### Clone and Set Up zoid Repository
Source: https://github.com/krakenjs/zoid/blob/main/CONTRIBUTING.md
Commands to clone the zoid repository, add the upstream remote, pull latest changes, and install dependencies.
```bash
git clone git@github.com:me/zoid.git
cd zoid
git remote add upstream git://github.com/krakenjs/zoid.git
git pull upstream
npm install
```
--------------------------------
### Run zoid Project Scripts
Source: https://github.com/krakenjs/zoid/blob/main/CONTRIBUTING.md
Scripts to verify installation and check code quality for the zoid project.
```bash
npm test
npm run-script lint
npm run-script cover
```
--------------------------------
### Angular Zoid Component Setup
Source: https://github.com/krakenjs/zoid/blob/main/demo/frameworks/angular/index.htm
Set up an Angular Zoid component by using the driver and registering it with an Angular module. This is useful for embedding Zoid components in Angular applications.
```javascript
var MyLoginAngularZoidComponent = MyLoginZoidComponent.driver( "angular", window.angular ); angular .module("app", [MyLoginAngularZoidComponent.name]) .controller("appController", function ($scope) { $scope.userLoggedIn = false; $scope.email = "foo@bar.com"; $scope.onLogin = function onLogin(email) { console.log("User logged in with email:", email); $scope.userLoggedIn = true; $scope.email = email; }; });
```
--------------------------------
### Vue 3 Zoid Integration Example
Source: https://github.com/krakenjs/zoid/blob/main/demo/frameworks/vue3/index.htm
This snippet demonstrates setting up a Vue 3 application to use a Zoid component. It defines a root component with a login form and integrates a Zoid login component using the 'vue3' driver.
```javascript
const RootComponent = { template:
`
Log in on xyz.com
{{ this.userLoggedIn ? 'User logged in with email: ' + email : '' }}
`,
data() {
return {
userLoggedIn: false,
email: "foo@bar.com",
};
},
computed: {
onLogin: function (email) {
return (email) => {
this.userLoggedIn = true;
this.email = email;
};
},
},
};
const vueAppp = Vue.createApp(RootComponent);
const MyVueLoginZoidComponent = MyLoginZoidComponent.driver("vue3");
vueAppp.component("app", MyVueLoginZoidComponent);
vueAppp.mount("#container");
```
--------------------------------
### Get Parent Window Reference with `xprops.getParent`
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/xprops.md
Obtain a reference to the parent window using `window.xprops.getParent()`. This reference can then be used to communicate with the parent, for example, by using `postMessage`.
```javascript
const parentWindow = window.xprops.getParent();
parentWindow.postMessage("hello!", "*");
```
--------------------------------
### Main Application Component
Source: https://github.com/krakenjs/zoid/blob/main/demo/advanced/react-end-to-end/login.htm
The main React component that utilizes the `useXProps` hook to get `prefilledEmail` and `onLogin` props, then renders the `Login` component with these props. Requires `React` and the `Login` component.
```javascript
function App() {
const { prefilledEmail, onLogin } = useXProps();
return ;
}
```
--------------------------------
### Listen to Zoid Events in containerTemplate
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/create.md
Attach functions to zoid lifecycle events within the containerTemplate or prerenderTemplate. This example shows how to handle the RENDERED event to manage the visibility of prerender and actual frames.
```javascript
event.on(EVENT.RENDERED, () => {
prerenderFrame.classList.remove(CLASS.VISIBLE);
prerenderFrame.classList.add(CLASS.INVISIBLE);
frame.classList.remove(CLASS.INVISIBLE);
frame.classList.add(CLASS.VISIBLE);
setTimeout(() => {
destroyElement(prerenderFrame);
}, 1);
});
```
--------------------------------
### Export Functionality from Child to Parent
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/xprops.md
In the child window, use `window.xprops.parent.export` to make functions available to the parent component. This example exports a `sayHello` function that logs a message.
```javascript
window.xprops.parent.export({
sayHello: () => {
console.log("hello world!");
},
});
```
--------------------------------
### Check Component Eligibility
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/instance.md
Determine if the component is eligible to be rendered. This requires an `eligible` handler to be defined during component setup.
```javascript
const myComponent = MyComponent();
if (myComponent.isEligible()) {
myComponent.render("#my-container");
}
```
--------------------------------
### Define Component Eligibility Handler
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/instance.md
Example of defining an `eligible` handler when creating a Zoid component. This handler should return `true` if the component is eligible to render, and `false` otherwise.
```javascript
const FirefoxOnlyButton = zoid.create({
tag: "my-component",
url: "https://my-site.com/my-component",
eligible: () => {
if (isFireFox()) {
return true;
} else {
return false;
}
},
});
```
--------------------------------
### Get Parent Domain with `xprops.getParentDomain`
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/xprops.md
Retrieve the domain of the parent window using `window.xprops.getParentDomain()`. This is useful for security checks or logging.
```javascript
console.log("The current parent window domain is:", window.xprops.getParentDomain());
```
--------------------------------
### Component Instantiation
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/component.md
Create a new Zoid component and instantiate it with initial props.
```APIDOC
## Instantiate Component
### Description
Instantiate a component and pass in props.
### Method
`zoid.create(options).`
### Parameters
#### Options
- **tag** (string) - Required - The HTML tag name for the component.
- **url** (string) - Required - The URL of the component's content.
#### Props
- **[string]** (any) - Optional - Any props to pass to the component instance.
### Request Example
```javascript
const Component = zoid.create({
tag: "my-component",
url: "https://my-site.com/my-component",
});
const componentInstance = Component({
foo: "bar",
onSomething: () => {
console.log("Something happened!");
},
});
```
### Response
Returns a `ZoidComponentInstance` object.
```
--------------------------------
### Basic Component Creation
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/create.md
Use `zoid.create` to define a new component. The `tag` option is required for identifying the component.
```javascript
zoid.create({ ...options });
```
```javascript
const MyComponent = zoid.create({
tag: 'my-component-tag',
...
});
```
--------------------------------
### Get Number of Active Zoid Component Instances
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/component.md
Retrieve the count of currently active instances of a Zoid component. This can be used for monitoring or debugging purposes.
```javascript
const MyComponent = zoid.create({ ... });
console.log(`There are currently ${ MyComponent.instances.length } active instances of MyComponent`);
```
--------------------------------
### Create and Instantiate a Zoid Component
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/component.md
Create a new Zoid component and then instantiate it, passing initial props. Ensure the component is created with a tag and URL before instantiation.
```javascript
const Component = zoid.create({
tag: "my-component",
url: "https://my-site.com/my-component",
});
const componentInstance = Component({
foo: "bar",
onSomething: () => {
console.log("Something happened!");
},
});
```
--------------------------------
### Parent Component Updating Props
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/xprops.md
Example of how a parent component can update the props of a child component using `componentInstance.setProps()`. This triggers the `onProps` listener in the child.
```javascript
const component = MyComponent({
color: "red",
});
component.render("#container").then(() => {
component.setProps({
color: "blue",
});
});
```
--------------------------------
### Show Component with `xprops.show`
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/xprops.md
Use `xprops.show()` to make the component visible. This method is applicable only to iframes; popups cannot be shown or hidden after initialization.
```javascript
document.querySelector("button#show").addEventListener("click", () => {
window.xprops.show();
});
```
--------------------------------
### Establish Zoid Parent Window Communication
Source: https://github.com/krakenjs/zoid/blob/main/test/windows/child/index.htm
This script initializes Zoid in a child window by finding the Zoid-enabled parent window. It copies coverage data, sets up mock domain and console/navigator properties, and evaluates the parent's component code.
```javascript
var parentWindow = window;
while (true) {
const ancestor = getAncestor(parentWindow);
if (!ancestor) {
break;
}
if (ancestor.zoid || getAncestor(ancestor)) {
parentWindow = ancestor;
} else {
break;
}
}
window.__coverage__ = parentWindow.__coverage__;
const query = Object.fromEntries( location.search
.replace(/^\?/, "")
.split("&")
.filter(Boolean)
.map((entry) => entry.split("="))
);
window.zoid = __zoid__;
window.mockDomain = query.mockDomain || "mock://www.child.com";
window.console.karma = parentWindow.console.karma;
window.navigator.mockUserAgent = parentWindow.navigator.mockUserAgent;
if (parentWindow.__component__) {
const parentComponent = parentWindow.__component__
.toString()
.replace(/zoid\.zoid/g, "window.zoid");
window.__component__ = eval(`(${parentComponent})`);
}
```
--------------------------------
### React Zoid Component Integration
Source: https://github.com/krakenjs/zoid/blob/main/demo/frameworks/react/index.htm
Integrates a Zoid component with React using the driver. This setup is useful for embedding cross-origin components within a React application.
```javascript
let MyLoginReactZoidComponent = MyLoginZoidComponent.driver("react", { React: window.React, ReactDOM: window.ReactDOM, });
```
--------------------------------
### Initialize Zoid Parent Window Communication in JavaScript
Source: https://github.com/krakenjs/zoid/blob/main/test/windows/bridge/index.htm
This script initializes the parent window for Zoid communication by finding the closest ancestor that meets Zoid's criteria. It then synchronizes coverage data, mock domain, and console/navigator properties from the parent to the current window. Ensure the ancestor window has the necessary Zoid properties or can be reached via `getAncestor`.
```javascript
var parentWindow = window;
while (true) {
const ancestor = getAncestor(parentWindow);
if (!ancestor) {
break;
}
if (ancestor.zoid || getAncestor(ancestor)) {
parentWindow = ancestor;
} else {
break;
}
}
window.__coverage__ = parentWindow.__coverage__;
window.mockDomain = "mock://www.child.com";
window.console.karma = parentWindow.console.karma;
window.navigator.mockUserAgent = parentWindow.navigator.mockUserAgent;
```
--------------------------------
### Component Instance Rendering
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/instance.md
Methods for rendering a component instance into a specified container and context.
```APIDOC
## POST /api/users
### Description
This endpoint allows for the creation of a new user.
### Method
POST
### Endpoint
/api/users
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **username** (string) - Required - The desired username for the new user.
- **email** (string) - Required - The email address of the new user.
- **password** (string) - Required - The password for the new user.
### Request Example
```json
{
"username": "johndoe",
"email": "john.doe@example.com",
"password": "securepassword123"
}
```
### Response
#### Success Response (201)
- **id** (string) - The unique identifier for the newly created user.
- **username** (string) - The username of the created user.
- **email** (string) - The email address of the created user.
#### Response Example
```json
{
"id": "user-12345",
"username": "johndoe",
"email": "john.doe@example.com"
}
```
```
```APIDOC
## GET /api/users/{userId}
### Description
Retrieves the details of a specific user based on their ID.
### Method
GET
### Endpoint
/api/users/{userId}
### Parameters
#### Path Parameters
- **userId** (string) - Required - The unique identifier of the user to retrieve.
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **id** (string) - The unique identifier for the user.
- **username** (string) - The username of the user.
- **email** (string) - The email address of the user.
- **createdAt** (string) - The timestamp when the user was created.
#### Response Example
```json
{
"id": "user-12345",
"username": "johndoe",
"email": "john.doe@example.com",
"createdAt": "2023-10-27T10:00:00Z"
}
```
```
--------------------------------
### Get Ancestor Window in JavaScript
Source: https://github.com/krakenjs/zoid/blob/main/test/windows/basicchild/index.htm
This function recursively finds the ancestor window that contains zoid or has a zoid ancestor. It's useful for establishing communication between nested windows or iframes.
```javascript
function getAncestor(win) { if (win.opener) { return win.opener; } if (win.parent !== win) { return win.parent; } }
```
```javascript
window.mockDomain = getAncestor(window).mockDomain; var parentWindow = window; while (true) { const ancestor = getAncestor(parentWindow); if (!ancestor) { break; } if (ancestor.zoid || getAncestor(ancestor)) { parentWindow = ancestor; } else { break; } } window.console.karma = parentWindow.console.karma; window.navigator.mockUserAgent = parentWindow.navigator.mockUserAgent; window."".__coverage__"" = parentWindow.__coverage__; window.zoid = __zoid__;
```
--------------------------------
### Show a Component Instance
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/instance.md
Show the component instance. This method is only applicable to iframe windows; popups cannot be hidden or shown after opening.
```javascript
const myComponent = MyComponent();
myComponent.render("#container");
document
.querySelector("button#show-component")
.addEventListener("click", () => {
myComponent.show().then(() => {
console.log("Component is now visible");
});
});
```
--------------------------------
### Zoid onDisplay Callback
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/parent-props.md
Execute a function when the component has completed its initial prerender phase. This indicates the component is ready to be displayed.
```javascript
MyComponent({
onDisplay: () => {
console.log("The component was displayed!");
},
}).render("#container");
```
--------------------------------
### Basic Render (same window)
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/render.md
Renders the component to a specified container element within the same window. Supports user-defined and built-in props.
```APIDOC
## Component().render(container, ?context)
### Description
Render the component to the given container element within the same window.
### Method
`render`
### Endpoint
N/A (Client-side method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Props
- **props** (object) - Required - Object containing all of the props required by the given component. These can be user-defined props, or pre-defined built-in props.
- **container** (string | HTMLElement) - Required - Element selector, or element, into which the component should be rendered. Defaults to `document.body`.
- **context** (iframe | popup) - Optional - The context to render to. Defaults to `defaultContext`, or if `defaultContext` is not set, `iframe`.
### Request Example
```javascript
MyComponent({
foo: "bar",
onBaz: () => {
console.log("Baz happened");
},
}).render("#container");
```
### Response
#### Success Response (200)
N/A (This is a client-side rendering method, not an API endpoint)
#### Response Example
None
```
--------------------------------
### driver(frameworkName, dependencies)
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/component.md
Register a Zoid component with a specific framework for native rendering.
```APIDOC
## driver(frameworkName, dependencies)
### Description
Register a component with your framework of choice, so it can be rendered natively in your app.
### Method
`ZoidComponent.driver(frameworkName, dependencies)`
### Parameters
#### Path Parameters
- **frameworkName** (string) - Required - The name of the framework (e.g., 'react', 'vue', 'angular').
- **dependencies** ({ [string] : any }) - Optional - Framework-specific dependencies required for integration.
### Request Example (React)
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
let MyReactZoidComponent = MyZoidComponent.driver("react", {
React: React,
ReactDOM: ReactDOM,
});
// Usage in a React component:
// render() {
// return (
//
// );
// }
```
### Request Example (Angular 1)
```javascript
MyZoidComponent.driver('angular', angular);
// Usage in HTML:
//
```
### Request Example (Angular 2)
```javascript
@ng.core.NgModule({
imports: [
ng.platformBrowser.BrowserModule,
MyZoidComponent.driver('angular2', ng.core)
]
});
// Usage in HTML:
//
```
### Request Example (Glimmer)
```javascript
import Component from "@glimmer/component";
export default MyZoidComponent.driver("glimmer", Component);
// Usage in HTML:
//
```
### Request Example (Vue)
```javascript
Vue.component('app', {
components: {
'my-zoid': MyZoidComponent.driver('vue')
}
}
// Usage in HTML:
//
```
### Request Example (Vue 3)
```javascript
// Create Vue application
const app = Vue.createApp(...)
// Define a new component called my-zoid
app.component('my-zoid', MyZoidComponent.driver('vue3'))
// Mount Vue application
app.mount(...)
// Usage in HTML:
//
```
### Response
Returns a framework-specific component wrapper.
```
--------------------------------
### Get Ancestor Window in JavaScript
Source: https://github.com/krakenjs/zoid/blob/main/test/windows/bridge/index.htm
This function recursively finds the closest ancestor window that is either the opener or the parent, stopping when no further ancestor can be found or when a specific condition is met. It's crucial for establishing communication channels between frames or windows.
```javascript
function getAncestor(win) { if (win.opener) { return win.opener; } if (win.parent !== win) { return win.parent; } }
```
--------------------------------
### Render Component to Another Window as a Popup
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/instance.md
Render the component instance to a specified window and container as a popup. The target window must have Zoid loaded and the component registered.
```javascript
const component = MyComponent();
component.renderTo(window.parent, "#my-container", "popup").then(() => {
console.info("The component was successfully rendered");
});
```
--------------------------------
### Instantiate a Zoid Component
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/instance.md
Create a Zoid component and then instantiate it with props. The `url` property is required to specify the component's location.
```javascript
const MyComponent = zoid.create({
tag: "my-component",
url: "https://my-site.com/my-component",
});
const component = MyComponent({
foo: "bar",
onSomething: () => {
console.log("Something happened!");
},
});
```
--------------------------------
### Component Instance Lifecycle Management
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/instance.md
Methods for managing the lifecycle of a component instance, including cloning, checking eligibility, closing, focusing, resizing, and showing.
```APIDOC
## PUT /api/users/{userId}
### Description
Updates an existing user's information.
### Method
PUT
### Endpoint
/api/users/{userId}
### Parameters
#### Path Parameters
- **userId** (string) - Required - The unique identifier of the user to update.
#### Query Parameters
None
#### Request Body
- **email** (string) - Optional - The new email address for the user.
- **password** (string) - Optional - The new password for the user.
### Request Example
```json
{
"email": "john.doe.updated@example.com"
}
```
### Response
#### Success Response (200)
- **id** (string) - The unique identifier for the user.
- **username** (string) - The username of the user.
- **email** (string) - The updated email address of the user.
- **updatedAt** (string) - The timestamp when the user was last updated.
#### Response Example
```json
{
"id": "user-12345",
"username": "johndoe",
"email": "john.doe.updated@example.com",
"updatedAt": "2023-10-27T11:00:00Z"
}
```
```
```APIDOC
## DELETE /api/users/{userId}
### Description
Deletes a specific user based on their ID.
### Method
DELETE
### Endpoint
/api/users/{userId}
### Parameters
#### Path Parameters
- **userId** (string) - Required - The unique identifier of the user to delete.
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (204)
No content is returned upon successful deletion.
#### Response Example
None
```
--------------------------------
### Basic Component Render
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/render.md
Render a component to a specified container element within the same window. Ensure the component is registered and all required props are provided.
```javascript
Component(props).render(container, ?context)
```
```javascript
MyComponent({
foo: "bar",
onBaz: () => {
console.log("Baz happened");
},
}).render("#container");
```
--------------------------------
### xprops.show
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/xprops.md
Shows the component. This is applicable only to iframe windows; popups cannot be shown or hidden after opening.
```APIDOC
## xprops.show
### Description
Show the component. Works on iframe windows only, popups can not be shown/hidden after opening.
### Method
`() => Promise`
### Parameters
None
### Request Example
```javascript
document.querySelector("button#show").addEventListener("click", () => {
window.xprops.show();
});
```
### Response
#### Success Response (200)
Resolves a Promise when the component is shown.
#### Response Example
None
```
--------------------------------
### Open Zoid Login Component
Source: https://github.com/krakenjs/zoid/blob/main/demo/advanced/remote/login-button.htm
This snippet demonstrates how to open a Zoid login component when a button is clicked. It includes passing initial data and handling the login callback. Ensure the Zoid component is defined and the target container is available.
```javascript
document.querySelector("#openLoginButton").addEventListener("click", function () {
// document.querySelector('#openLoginButton').style.display = 'none';
MyLoginZoidComponent({
prefilledEmail: "foo@bar.com",
onLogin: function (email) {
console.log("User logged in with email:", email);
document.querySelector("#result").innerText = email + " logged in!";
},
}).renderTo(window.parent, window.xprops.loginContainer);
});
```
--------------------------------
### Implement Zoid Component Logic
Source: https://github.com/krakenjs/zoid/blob/main/docs/example.md
Implement the component's business logic within the iframe using `window.xprops` to access passed-down props and handle user interactions.
```html
```
--------------------------------
### Render Component to Another Window
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/instance.md
Render the component instance to a specified window and container using a CSS selector. The target window must have Zoid loaded and the component registered.
```javascript
const component = MyComponent();
component.renderTo(window.parent, "#my-container").then(() => {
console.info("The component was successfully rendered");
});
```
--------------------------------
### Render Login Component on xyz.com
Source: https://github.com/krakenjs/zoid/blob/main/demo/advanced/props/index.htm
Renders a Zoid component for login on xyz.com, passing initial props and handling login events. It also updates the component's props based on user input in an email field.
```javascript
// Render the component
var instance = MyLoginZoidComponent({
prefilledEmail: "foo@bar.com",
onLogin: function (email) {
console.log("User logged in with email:", email);
document.querySelector("#result").innerText = email + " logged in!";
},
});
instance.render("#container");
document.querySelector("#email").addEventListener("keyup", function (event) {
instance.updateProps({
prefilledEmail: event.target.value,
});
});
```
--------------------------------
### Render Zoid Child Components
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/create.md
Instantiate the parent component and then render its child components into specified DOM elements. Ensure the target container IDs exist on the page.
```javascript
const cardFields = CardFields({
style: {
borderColor: "red",
},
});
cardFields.NumberField().render("#card-number-field-container");
cardFields.CVVField().render("#card-cvv-field-container");
cardFields.ExpiryField().render("#card-expiry-field-container");
```
--------------------------------
### Render Parent and Child Components in Parent Window
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/xprops.md
Instantiate and render the parent component, then render its child component within a specified container. An event listener is attached to a button to trigger a method exposed by the parent.
```javascript
const parent = ParentComponent({
color: "blue",
});
const child = parent.Child();
child.render("#child-container");
document.querySelector("button#doSomething").addEventListener("click", () => {
parent.sayHello(); // Should log 'hello world!'
});
```
--------------------------------
### React DOM Rendering
Source: https://github.com/krakenjs/zoid/blob/main/demo/advanced/react-end-to-end/login.htm
Renders the main `App` component into the DOM element with the ID 'container'. This is the entry point for the React application.
```javascript
ReactDOM.render(, document.querySelector("#container"));
```
--------------------------------
### Render MyLoginZoidComponent
Source: https://github.com/krakenjs/zoid/blob/main/demo/basic/iframe/index.htm
Renders the MyLoginZoidComponent with prefilled email and an onLogin callback. Ensure the target container element exists.
```javascript
// Render the component MyLoginZoidComponent({ prefilledEmail: "foo@bar.com", onLogin: function (email) { console.log("User logged in with email:", email); document.querySelector("#result").innerText = email + " logged in!"; }, }).render("#container");
```
--------------------------------
### Render Login Button Component
Source: https://github.com/krakenjs/zoid/blob/main/demo/advanced/remote-popup/index.htm
Renders the login button component on xyz.com. Ensure the login container and render target IDs are correctly specified.
```javascript
MyLoginButtonComponent({
loginContainer: "#loginContainer",
}).render("#container");
```
--------------------------------
### Push Topic Branch
Source: https://github.com/krakenjs/zoid/blob/main/CONTRIBUTING.md
Command to push your topic branch to your fork on origin.
```bash
git push origin
```
--------------------------------
### Focus a Component Instance
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/instance.md
Focus the component instance. This method is only effective for popup windows and should be triggered by a user action, such as a click event.
```javascript
const myComponent = MyComponent();
myComponent.render("#container");
document
.querySelector("button#focus-component")
.addEventListener("click", () => {
myComponent.focus().then(() => {
console.log("Component is now focused");
});
});
```
--------------------------------
### Define prerenderTemplate with JSX
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/create.md
Use JSX with jsx-pragmatic to define a template for content displayed while the Zoid component is loading. The template should be rendered using dom({ doc }). Requires babel with a \"@jsx node\" comment.
```javascript
/* @jsx node */
import { node, dom } from "jsx-pragmatic";
var MyLoginZoidComponent = zoid.create({
tag: "my-login",
url: "https://www.mysite.com/login",
prerenderTemplate: function ({ doc }) {
return (Please wait while the component loads...
).render(
dom({ doc })
);
},
});
```
--------------------------------
### Retrieve Sibling Components from Any Parent
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/xprops.md
Retrieve sibling components regardless of their parent context by passing `{ anyParent: true }` to `window.xprops.getSiblings()`. This is useful for discovering components across different parent applications.
```javascript
for (const sibling of window.xprops.getSiblings({ anyParent: true })) {
console.log("Found sibling from any parent!", sibling.tag);
}
```
--------------------------------
### Render Component to a Container as a Popup
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/instance.md
Render the component instance to a specified container and explicitly set the rendering context to 'popup'.
```javascript
const component = MyComponent();
component.render("#my-container", "popup").then(() => {
console.info("The component was successfully rendered");
});
```
--------------------------------
### Rendering Child Component from Parent
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/xprops.md
Illustrates how to instantiate and render a `ChildComponent` from within a `ParentComponent`. The `ParentComponent` instance is created with props, and then its `Child` property is used to create and render the `ChildComponent` instance.
```javascript
const parent = ParentComponent({
color: "blue",
});
const child = parent.Child();
child.render("#child-container");
```
--------------------------------
### zoid.create Component Definition
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/create.md
Defines a new Zoid component using `zoid.create` with essential configuration options.
```APIDOC
## POST /api/components
### Description
Creates a new component definition that can be loaded in parent and child windows.
### Method
POST
### Endpoint
/api/components
### Parameters
#### Request Body
- **tag** (string) - Required - A tag-name for the component, used for loading the correct component in the child window or frame, generating framework drivers, and logging.
- **url** (string | ({ props }) => string) - Required - The full URL that will be loaded when your component is rendered, or a function returning the URL. Must include a protocol (http:, https:, or about:).
- **dimensions** ({ width : string, height : string }) - Optional - The dimensions for your component, in CSS-style units, with support for `px` or `%`.
- **props** ({ [string] : PropDefinition }) - Optional - A mapping of prop name to prop settings. Helpful for setting default values, decorating values, adding props to the query string of your component URL, and more.
### Request Example
```json
{
"tag": "my-component-tag",
"url": "https://my-site.com/my-component",
"dimensions": {
"width": "300px",
"height": "200px"
},
"props": {
"onLogin": {
"type": "function"
},
"prefilledEmail": {
"type": "string",
"required": false
}
}
}
```
### Response
#### Success Response (200)
- **component_id** (string) - The unique identifier for the created component.
#### Response Example
```json
{
"component_id": "comp_12345"
}
```
```
--------------------------------
### Listen for Prop Updates with `xprops.onProps`
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/xprops.md
Set up a listener in the child component using `window.xprops.onProps()` to react to prop changes initiated by the parent via `componentInstance.setProps()`. The callback function receives the updated props.
```javascript
console.log("The current color is", window.xprops.color); // red
window.xprops.onProps(() => {
console.log("The current color is", window.xprops.color); // blue
});
```
--------------------------------
### Render Component to a Container (DOM Element)
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/instance.md
Render the component instance to a specified container using a DOM element. The rendering context defaults to 'iframe'.
```javascript
const component = MyComponent();
component.render(document.body).then(() => {
console.info("The component was successfully rendered");
});
```
--------------------------------
### Focus Component with `xprops.focus`
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/xprops.md
Use `xprops.focus()` to refocus the component. This method is only effective on popup windows and must be triggered by a user interaction to comply with browser security policies.
```javascript
document.querySelector("button#focus").addEventListener("click", () => {
window.xprops.focus();
});
```
--------------------------------
### Define a Zoid Component
Source: https://github.com/krakenjs/zoid/blob/main/README.md
Use `zoid.create` to define a reusable cross-domain component. Specify a unique tag and the URL where the component will be hosted.
```javascript
var MyLoginComponent = zoid.create({
tag: "my-login-component",
url: "http://www.my-site.com/my-login-component"
});
```
--------------------------------
### Clone a Component Instance
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/instance.md
Create an exact copy of an existing component instance with the same props. This is useful for rendering the same component multiple times with identical configurations.
```javascript
const button1 = ButtonComponent({
color: "red",
});
const button2 = button1.clone();
button1.render("#first-button-container"); // First red button
button2.render("#first-button-container"); // Second red button
```
--------------------------------
### Render Component to a Container (Selector)
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/instance.md
Render the component instance to a specified container using a CSS selector. The rendering context defaults to 'iframe'.
```javascript
const component = MyComponent();
component.render("#my-container").then(() => {
console.info("The component was successfully rendered");
});
```
--------------------------------
### Render Login Button Component
Source: https://github.com/krakenjs/zoid/blob/main/demo/advanced/redirect-different-domain/index.htm
Renders the MyLoginButtonComponent into the '#container' element. Ensure the loginContainer option is correctly configured.
```javascript
MyLoginButtonComponent({ loginContainer: "#loginContainer", }).render("#container");
```
--------------------------------
### Zoid Component Options
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/create.md
Details on the options available when creating a Zoid component, including `opts`, `autoResize`, `allowedParentDomains`, `domain`, `defaultContext`, and `validate`.
```APIDOC
## Zoid Component Configuration Options
### opts
Data automatically passed to `containerTemplate` and `prerenderTemplate`, used to help render and customize the template.
- `uid` (string) - Unique id automatically generated by zoid on render, unique to the instantiation of the given component
- `props` (object) - Props passed to the component in `render()`
- `doc` (Document) - The appropriate document used to render dom elements
- `container` (HTMLElement) - The element into which the generated element will be inserted
- `dimensions` (object) - The dimensions for the component
- `tag` (string) - Tag name of the component
- `context` (string) - Context type of the component (`iframe` or `popup`)
- `frame` (HTMLIFrameElement) - Frame element that will be rendered into. Only applies to `containerTemplate` when rendering an iframe
- `prerenderFrame` (HTMLIFrameElement) - Frame element that will be pre-rendered into. Only applies to `containerTemplate` when rendering an iframe using `prerenderTemplate`
- `close` (function) - Close the component. Useful if you want to render a close button outside the component
- `focus` (function) - Focus the component. Valid for popup components only. Useful if you want a clickable background overlay to re-focus the popup window.
- `event` (object) - Object that can be used to listen for the following events: `RENDER`, `RENDERED`, `DISPLAY`, `ERROR`, `CLOSED`, `PROPS`, `RESIZE`
### Listening to zoid events
In the `containerTemplate` and `prerenderFunctions`, it is possible to attach functions that fire at events in the zoid lifecycle:
```javascript
// Example of listening to the RENDERED event
event.on(EVENT.RENDERED, () => {
prerenderFrame.classList.remove(CLASS.VISIBLE);
prerenderFrame.classList.add(CLASS.INVISIBLE);
frame.classList.remove(CLASS.INVISIBLE);
frame.classList.add(CLASS.VISIBLE);
setTimeout(() => {
destroyElement(prerenderFrame);
}, 1);
});
```
## autoResize `{ height: boolean, width: boolean, element: string }`
Makes the iframe resize automatically when the child window size changes.
### Example Usage
```javascript
const MyComponent = zoid.create({
tag: "my-component",
url: "https://my-site.com/my-component",
autoResize: {
width: false,
height: true,
},
});
```
Note that by default it matches the `body` element of your content. You can override this setting by specifying a custom selector as an `element` property.
```javascript
const MyComponent = zoid.create({
tag: "my-component",
url: "https://my-site.com/my-component",
autoResize: {
width: false,
height: true,
element: ".my-selector",
},
});
```
Recommended to only use `autoResize` for height. Width has some strange effects, especially when scroll bars are present.
## allowedParentDomains `string | Array`
A string, array of strings or regular expressions to be used to validate the parent domain. If the parent domain doesn't match any item, communication from child to parent will be prevented. The default value is `*` which matches any domain.
### Example Usage
```javascript
const MyComponent = zoid.create({
tag: "my-component",
url: "https://my-site.com/my-component",
allowedParentDomains: ["http://localhost", /^http:\/\/www\.mydomain\.com$/],
});
```
## domain `string`
A string, or map of env to strings, for the domain which will be loaded in the iframe or popup. Only required if the domain which will be rendered is different to the domain specified in the `url` setting - for example, if the original url does a 302 redirect to a different domain or subdomain.
### Example Usage
```javascript
const MyComponent = zoid.create({
tag: "my-component",
url: "https://foo.com/login",
domain: "https://subdomain.foo.com",
});
```
## defaultContext `string`
Determines which context should be picked by default when `render()` is called. Defaults to `iframe`.
### Example Usage
```javascript
const MyComponent = zoid.create({
tag: "my-component",
url: "https://my-site.com/my-component",
defaultContext: "popup",
});
```
## validate `({ props }) => void`
Function which is passed all of the props at once and may validate them. Useful for validating inter-dependant props.
### Example Usage
```javascript
const MyComponent = zoid.create({
tag: "my-component",
url: "https://my-site.com/my-component",
validate: function ({ props }) {
if (props.name === "Batman" && props.strength < 10) {
throw new Error(`Batman must have at least 10 strength`);
}
},
});
```
```
--------------------------------
### Define prerenderTemplate with native DOM methods
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/create.md
Create a prerender template for your Zoid component using native browser DOM methods. Use the 'doc' object passed to the function to create elements within the target document. This is crucial for cross-origin compatibility.
```javascript
import { node, dom } from "jsx-pragmatic";
var MyLoginZoidComponent = zoid.create({
tag: "my-login",
url: "https://www.mysite.com/login",
prerenderTemplate: function containerTemplate({ doc }) {
const p = doc.createElement("p");
p.innerText = "Please wait while the component loads...";
return p;
},
});
```
--------------------------------
### Register Zoid Component Driver for Frameworks
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/component.md
Register a Zoid component with a specific framework using the `driver` method. This allows the component to be rendered natively within that framework's ecosystem.
```javascript
import FooFramework from 'foo-framework';
const Component = zoid.create({ ... });
const FooComponent = Component.driver('foo', { FooFramework });
// Now `FooComponent` is natively renderable inside a `FooFramework` app.
```
--------------------------------
### Open Login Zoid Component
Source: https://github.com/krakenjs/zoid/blob/main/demo/advanced/redirect-different-domain/login-button.htm
Attaches an event listener to a button to open a Zoid login component. The component is configured with pre-filled data and an onLogin callback to handle user authentication results. It is rendered into the parent window's context.
```javascript
document.querySelector("#openLoginButton").addEventListener("click", function () {
// document.querySelector('#openLoginButton').style.display = 'none';
MyLoginZoidComponent({
prefilledEmail: "foo@bar.com",
onLogin: function (email) {
console.log("User logged in with email:", email);
document.querySelector("#result").innerText = email + " logged in!";
},
}).renderTo(window.parent, window.xprops.loginContainer, zoid.CONTEXT.POPUP);
});
```
--------------------------------
### Retrieve Sibling Components
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/xprops.md
Iterate over sibling components found on the same domain using `window.xprops.getSiblings()`. This can be used to interact with other components rendered within the same context.
```javascript
for (const sibling of window.xprops.getSiblings()) {
console.log("Found sibling!", sibling.tag);
}
```
--------------------------------
### Resize a Component Instance
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/instance.md
Resize the component instance. This method is only applicable to iframe windows; popups cannot be resized after opening.
```javascript
const myComponent = MyComponent();
myComponent.render("#container");
document
.querySelector("button#resize-component")
.addEventListener("click", () => {
myComponent.resize({ width: 500, height: 800 }).then(() => {
console.log("Component is now resized");
});
});
```
--------------------------------
### Register Zoid Component in Vue
Source: https://github.com/krakenjs/zoid/blob/main/demo/frameworks/vue/index.htm
Register a Zoid component as a Vue component. Ensure the Zoid component is initialized with the correct driver (e.g., 'vue').
```javascript
var MyLoginVueZoidComponent = MyLoginZoidComponent.driver("vue", Vue);
Vue.component("app", {
data: function () {
return {
userLoggedIn: false,
email: "foo@bar.com",
};
},
template:
`
Log in on xyz.com
{{ this.userLoggedIn ? 'User logged in with email: ' + email : '' }}
`,
components: {
"my-component": MyLoginVueZoidComponent,
},
computed: {
onLogin: function (email) {
return (email) => {
this.userLoggedIn = true;
this.email = email;
};
},
},
});
var vm = new Vue({
el: "#container",
});
```
--------------------------------
### xprops
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/component.md
Access props passed down to the child window or iframe.
```APIDOC
## xprops
### Description
Similar to `window.xprops` -- gives you access to the props passed down to the child window or iframe.
### Method
`ZoidComponent.xprops`
### Parameters
None
### Request Example
```javascript
const MyComponent = zoid.create({ ... });
console.log(MyComponent.xprops.message);
```
### Response
- **{ [string] : any }** - An object containing the props passed to the child.
```
--------------------------------
### xprops.tag
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/xprops.md
Provides the tag name associated with the current component instance.
```APIDOC
## xprops.tag
### Description
Tag for the component instance
### Method
`string`
### Parameters
None
### Request Example
```javascript
console.log("The current component is:", window.xprops.tag);
```
### Response
#### Success Response (200)
- **tag** (string) - The tag name of the component instance.
#### Response Example
```json
{
"tag": "my-component-tag"
}
```
```
--------------------------------
### xprops.getSiblings
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/xprops.md
Retrieves an array of sibling components that are on the same domain. This can be filtered to include siblings from any parent.
```APIDOC
## xprops.getSiblings
### Description
Gets an array of sibling components that are on the same domain. This function is useful for inter-component communication or discovery within the same application context.
### Method
`xprops.getSiblings`
### Parameters
#### Query Parameters
- **anyParent** (boolean) - Optional - If set to `true`, it will include siblings from any parent domain, not just the current one.
### Response
- **Array<{ tag : string, xprops : XProps, exports : Exports }>** - An array of sibling component objects. Each object contains:
- **tag** (string): The tag name of the sibling component.
- **xprops** (XProps): The props associated with the sibling component.
- **exports** (Exports): The exported values from the sibling component.
### Request Example
```javascript
// Get siblings on the same domain
for (const sibling of window.xprops.getSiblings()) {
console.log("Found sibling!", sibling.tag);
}
// Get siblings from any parent domain
for (const sibling of window.xprops.getSiblings({ anyParent: true })) {
console.log("Found sibling from any parent!", sibling.tag);
}
```
```
--------------------------------
### xprops.uid
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/xprops.md
Provides the unique identifier for the current component instance.
```APIDOC
## xprops.uid
### Description
Unique ID for the component instance
### Method
`string`
### Parameters
None
### Request Example
```javascript
console.log("The current component uid is:", window.xprops.uid);
```
### Response
#### Success Response (200)
- **uid** (string) - The unique identifier for the component instance.
#### Response Example
```json
{
"uid": "some-unique-id"
}
```
```
--------------------------------
### Define containerTemplate with native DOM methods
Source: https://github.com/krakenjs/zoid/blob/main/docs/api/create.md
Create a custom container for your Zoid component using native browser DOM methods like document.createElement. Ensure the frame and prerenderFrame elements are appended to the container. Requires imports from jsx-pragmatic.
```javascript
import { node, dom } from "jsx-pragmatic";
var MyLoginZoidComponent = zoid.create({
tag: "my-login",
url: "https://www.mysite.com/login",
containerTemplate: function containerTemplate({
doc,
uid,
frame,
prerenderFrame,
}) {
let container = doc.createElement("div");
container.id = uid;
container.appendChild(frame);
container.appendChild(prerenderFrame);
return container;
},
});
```