[Feature]Booking Embed (#2227)
This commit is contained in:
1 parent
4e9c3be598
commit
4a58da62d6
39 files changed
+1740
-22
No files matched your search
@@ -0,0 +1,78 @@
|
||||
export class ModalBox extends HTMLElement {
|
||||
connectedCallback() {
|
||||
const closeEl = this.shadowRoot!.querySelector(".close") as HTMLElement;
|
||||
closeEl.onclick = () => {
|
||||
this.shadowRoot!.host.remove();
|
||||
};
|
||||
}
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
//FIXME: this styling goes as is as it's a JS string. That's a lot of unnecessary whitespaces over the wire.
|
||||
const modalHtml = `
|
||||
<style>
|
||||
.backdrop {
|
||||
position:fixed;
|
||||
width:100%;
|
||||
height:100%;
|
||||
top:0;
|
||||
left:0;
|
||||
z-index:99999999;
|
||||
display:block;
|
||||
background-color:rgb(5,5,5, 0.8)
|
||||
}
|
||||
@media only screen and (min-width:600px) {
|
||||
.modal-box {
|
||||
margin:0 auto;
|
||||
margin-top:20px;
|
||||
margin-bottom:20px;
|
||||
position:absolute;
|
||||
width:50%;
|
||||
height: 80%;
|
||||
top:50%;
|
||||
left:50%;
|
||||
transform: translateY(-50%) translateX(-50%);
|
||||
overflow: scroll;
|
||||
}
|
||||
}
|
||||
|
||||
@media only screen and (max-width:600px) {
|
||||
.modal-box {
|
||||
width: 100%;
|
||||
height: 80%;
|
||||
position:fixed;
|
||||
top:50px;
|
||||
left:0;
|
||||
right: 0;
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.header {
|
||||
position: relative;
|
||||
float:right;
|
||||
top: 10px;
|
||||
}
|
||||
.close {
|
||||
font-size: 30px;
|
||||
left: -20px;
|
||||
position: relative;
|
||||
color:white;
|
||||
cursor: pointer;
|
||||
}
|
||||
</style>
|
||||
<div class="backdrop">
|
||||
<div class="header">
|
||||
<span class="close">×</span>
|
||||
</div>
|
||||
<div class="modal-box">
|
||||
<div class="body">
|
||||
<slot></slot>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
this.attachShadow({ mode: "open" });
|
||||
this.shadowRoot!.innerHTML = modalHtml;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { useState, useEffect, CSSProperties } from "react";
|
||||
|
||||
import { sdkActionManager } from "./sdk-event";
|
||||
|
||||
// Only allow certain styles to be modified so that when we make any changes to HTML, we know what all embed styles might be impacted.
|
||||
// Keep this list to minimum, only adding those styles which are really needed.
|
||||
interface EmbedStyles {
|
||||
body?: Pick<CSSProperties, "background" | "backgroundColor">;
|
||||
eventTypeListItem?: Pick<CSSProperties, "background" | "color" | "backgroundColor">;
|
||||
enabledDateButton?: Pick<CSSProperties, "background" | "color" | "backgroundColor">;
|
||||
disabledDateButton?: Pick<CSSProperties, "background" | "color" | "backgroundColor">;
|
||||
}
|
||||
|
||||
type ElementName = keyof EmbedStyles;
|
||||
|
||||
type ReactEmbedStylesSetter = React.Dispatch<React.SetStateAction<EmbedStyles>>;
|
||||
|
||||
export interface UiConfig {
|
||||
theme: string;
|
||||
styles: EmbedStyles;
|
||||
}
|
||||
|
||||
const embedStore = {
|
||||
// Store all embed styles here so that as and when new elements are mounted, styles can be applied to it.
|
||||
styles: {},
|
||||
// Store all React State setters here.
|
||||
reactStylesStateSetters: {} as Record<ElementName, ReactEmbedStylesSetter>,
|
||||
};
|
||||
|
||||
const setEmbedStyles = (stylesConfig: UiConfig["styles"]) => {
|
||||
embedStore.styles = stylesConfig;
|
||||
for (let [, setEmbedStyle] of Object.entries(embedStore.reactStylesStateSetters)) {
|
||||
setEmbedStyle((styles) => {
|
||||
return {
|
||||
...styles,
|
||||
...stylesConfig,
|
||||
};
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const registerNewSetter = (elementName: ElementName, setStyles: ReactEmbedStylesSetter) => {
|
||||
embedStore.reactStylesStateSetters[elementName] = setStyles;
|
||||
// It's possible that 'ui' instruction has already been processed and the registration happened due to some action by the user in iframe.
|
||||
// So, we should call the setter immediately with available embedStyles
|
||||
setStyles(embedStore.styles);
|
||||
};
|
||||
|
||||
const removeFromEmbedStylesSetterMap = (elementName: ElementName) => {
|
||||
delete embedStore.reactStylesStateSetters[elementName];
|
||||
};
|
||||
|
||||
// TODO: Make it usable as an attribute directly instead of styles value. It would allow us to go beyond styles e.g. for debugging we can add a special attribute indentifying the element on which UI config has been applied
|
||||
export const useEmbedStyles = (elementName: ElementName) => {
|
||||
const [styles, setStyles] = useState({} as EmbedStyles);
|
||||
|
||||
useEffect(() => {
|
||||
registerNewSetter(elementName, setStyles);
|
||||
// It's important to have an element's embed style be required in only one component. If due to any reason it is required in multiple components, we would override state setter.
|
||||
return () => {
|
||||
// Once the component is unmounted, we can remove that state setter.
|
||||
removeFromEmbedStylesSetterMap(elementName);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return styles[elementName] || {};
|
||||
};
|
||||
|
||||
// If you add a method here, give type safety to parent manually by adding it to embed.ts. Look for "parentKnowsIframeReady" in it
|
||||
export const methods = {
|
||||
ui: function style(uiConfig: UiConfig) {
|
||||
// TODO: Create automatic logger for all methods. Useful for debugging.
|
||||
console.log("Method: ui called", uiConfig);
|
||||
const stylesConfig = uiConfig.styles;
|
||||
|
||||
// In case where parent gives instructions before setEmbedStyles is set.
|
||||
if (!setEmbedStyles) {
|
||||
return requestAnimationFrame(() => {
|
||||
style(uiConfig);
|
||||
});
|
||||
}
|
||||
|
||||
// body can't be styled using React state hook as it is generated by _document.tsx which doesn't support hooks.
|
||||
if (stylesConfig.body?.background) {
|
||||
document.body.style.background = stylesConfig.body.background as string;
|
||||
}
|
||||
|
||||
setEmbedStyles(stylesConfig);
|
||||
},
|
||||
parentKnowsIframeReady: () => {
|
||||
document.body.style.display = "block";
|
||||
sdkActionManager?.fire("linkReady", {});
|
||||
},
|
||||
};
|
||||
|
||||
const messageParent = (data: any) => {
|
||||
parent.postMessage(
|
||||
{
|
||||
originator: "CAL",
|
||||
...data,
|
||||
},
|
||||
"*"
|
||||
);
|
||||
};
|
||||
|
||||
function keepParentInformedAboutDimensionChanges() {
|
||||
let knownHiddenHeight: Number | null = null;
|
||||
let numDimensionChanges = 0;
|
||||
requestAnimationFrame(function informAboutScroll() {
|
||||
// Because of scroll="no", this much is hidden from the user.
|
||||
const hiddenHeight = document.documentElement.scrollHeight - window.innerHeight;
|
||||
// TODO: Handle width as well.
|
||||
if (knownHiddenHeight !== hiddenHeight) {
|
||||
knownHiddenHeight = hiddenHeight;
|
||||
numDimensionChanges++;
|
||||
// FIXME: This event shouldn't be subscribable by the user. Only by the SDK.
|
||||
sdkActionManager?.fire("dimension-changed", {
|
||||
hiddenHeight,
|
||||
});
|
||||
}
|
||||
// Parent Counterpart would change the dimension of iframe and thus page's dimension would be impacted which is recursive.
|
||||
// It should stop ideally by reaching a hiddenHeight value of 0.
|
||||
// FIXME: If 0 can't be reached we need to just abandon our quest for perfect iframe and let scroll be there. Such case can be logged in the wild and fixed later on.
|
||||
if (numDimensionChanges > 50) {
|
||||
console.warn("Too many dimension changes detected.");
|
||||
return;
|
||||
}
|
||||
requestAnimationFrame(informAboutScroll);
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined" && !location.search.includes("prerender=true")) {
|
||||
sdkActionManager?.on("*", (e) => {
|
||||
const detail = e.detail;
|
||||
//console.log(detail.fullType, detail.type, detail.data);
|
||||
messageParent(detail);
|
||||
});
|
||||
|
||||
window.addEventListener("message", (e) => {
|
||||
const data: Record<string, any> = e.data;
|
||||
if (!data) {
|
||||
return;
|
||||
}
|
||||
const method: keyof typeof methods = data.method;
|
||||
if (data.originator === "CAL" && typeof method === "string") {
|
||||
methods[method]?.(data.arg);
|
||||
}
|
||||
});
|
||||
|
||||
keepParentInformedAboutDimensionChanges();
|
||||
sdkActionManager?.fire("iframeReady", {});
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
/**
|
||||
These styles are applied to the entire page, so the selectors need to be specific
|
||||
*/
|
||||
.cal-embed {
|
||||
border: 0px;
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
import type { CalWindow } from "@calcom/embed-snippet";
|
||||
|
||||
import { ModalBox } from "./ModalBox";
|
||||
import { methods, UiConfig } from "./embed-iframe";
|
||||
import css from "./embed.css";
|
||||
import { SdkActionManager } from "./sdk-action-manager";
|
||||
|
||||
declare module "*.css";
|
||||
|
||||
type Namespace = string;
|
||||
type Config = Record<"origin", "string">;
|
||||
|
||||
const globalCal = (window as CalWindow).Cal;
|
||||
|
||||
if (!globalCal || !globalCal.q) {
|
||||
throw new Error("Cal is not defined. This shouldn't happen");
|
||||
}
|
||||
|
||||
document.head.appendChild(document.createElement("style")).innerHTML = css;
|
||||
|
||||
function log(...args: any[]) {
|
||||
console.log(...args);
|
||||
}
|
||||
/**
|
||||
* A very simple data validator written with intention of keeping payload size low.
|
||||
* Extend the functionality of it as required by the embed.
|
||||
* @param data
|
||||
* @param schema
|
||||
*/
|
||||
function validate(data: any, schema: Record<"props" | "required", any>) {
|
||||
function checkType(value: any, expectedType: any) {
|
||||
if (typeof expectedType === "string") {
|
||||
return typeof value == expectedType;
|
||||
} else {
|
||||
return value instanceof expectedType;
|
||||
}
|
||||
}
|
||||
|
||||
function isUndefined(data: any) {
|
||||
return typeof data === "undefined";
|
||||
}
|
||||
|
||||
if (schema.required && isUndefined(data)) {
|
||||
throw new Error("Argument is required");
|
||||
}
|
||||
|
||||
for (let [prop, propSchema] of Object.entries<Record<"type" | "required", any>>(schema.props)) {
|
||||
if (propSchema.required && isUndefined(data[prop])) {
|
||||
throw new Error(`"${prop}" is required`);
|
||||
}
|
||||
let typeCheck = true;
|
||||
if (propSchema.type && !isUndefined(data[prop])) {
|
||||
if (propSchema.type instanceof Array) {
|
||||
propSchema.type.forEach((type) => {
|
||||
typeCheck = typeCheck || checkType(data[prop], type);
|
||||
});
|
||||
} else {
|
||||
typeCheck = checkType(data[prop], propSchema.type);
|
||||
}
|
||||
}
|
||||
if (!typeCheck) {
|
||||
throw new Error(`"${prop}" is of wrong type.Expected type "${propSchema.type}"`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export type Instruction = [method: string, argument: any] | [method: string, argument: any][];
|
||||
export type InstructionQueue = Instruction[];
|
||||
|
||||
export class Cal {
|
||||
iframe?: HTMLIFrameElement;
|
||||
|
||||
__config: any;
|
||||
|
||||
namespace: string;
|
||||
|
||||
actionManager: SdkActionManager;
|
||||
|
||||
iframeReady!: boolean;
|
||||
|
||||
iframeDoQueue: { method: keyof typeof methods; arg: any }[] = [];
|
||||
|
||||
static actionsManagers: Record<Namespace, SdkActionManager>;
|
||||
|
||||
static getQueryObject(config: Record<string, string>) {
|
||||
config = config || {};
|
||||
return {
|
||||
...config,
|
||||
// guests is better for API but Booking Page accepts guest. So do the mapping
|
||||
guest: config.guests ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
processInstruction(instruction: Instruction) {
|
||||
instruction = [].slice.call(instruction, 0);
|
||||
if (instruction[0] instanceof Array) {
|
||||
// It is an instruction
|
||||
instruction.forEach((instruction) => {
|
||||
this.processInstruction(instruction);
|
||||
});
|
||||
return;
|
||||
}
|
||||
const [method, ...args] = instruction;
|
||||
if (!this[method]) {
|
||||
// Instead of throwing error, log and move forward in the queue
|
||||
log(`Instruction ${method} not FOUND`);
|
||||
}
|
||||
try {
|
||||
(this[method] as Function)(...args);
|
||||
} catch (e) {
|
||||
// Instead of throwing error, log and move forward in the queue
|
||||
log(`Instruction couldn't be executed`, e);
|
||||
}
|
||||
return instruction;
|
||||
}
|
||||
|
||||
processQueue(queue: InstructionQueue) {
|
||||
queue.forEach((instruction) => {
|
||||
this.processInstruction(instruction);
|
||||
});
|
||||
|
||||
queue.splice(0);
|
||||
|
||||
/** @ts-ignore */ // We changed the definition of push here.
|
||||
queue.push = (instruction) => {
|
||||
this.processInstruction(instruction);
|
||||
};
|
||||
}
|
||||
|
||||
createIframe({
|
||||
calLink,
|
||||
queryObject = {},
|
||||
}: {
|
||||
calLink: string;
|
||||
queryObject?: Record<string, string | string[]>;
|
||||
}) {
|
||||
const iframe = (this.iframe = document.createElement("iframe"));
|
||||
// FIXME: scrolling seems deprecated, though it works on Chrome. What's the recommended way to do it?
|
||||
iframe.scrolling = "no";
|
||||
iframe.className = "cal-embed";
|
||||
const config = this.getConfig();
|
||||
|
||||
// Prepare searchParams from config
|
||||
const searchParams = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(queryObject)) {
|
||||
if (value instanceof Array) {
|
||||
value.forEach((val) => searchParams.append(key, val));
|
||||
} else {
|
||||
searchParams.set(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
const urlInstance = new URL(`${config.origin}/${calLink}`);
|
||||
urlInstance.searchParams.set("embed", this.namespace);
|
||||
|
||||
// Merge searchParams from config onto the URL which might have query params already
|
||||
//@ts-ignore
|
||||
for (let [key, value] of searchParams) {
|
||||
urlInstance.searchParams.append(key, value);
|
||||
}
|
||||
iframe.src = urlInstance.toString();
|
||||
return iframe;
|
||||
}
|
||||
|
||||
init(namespaceOrConfig: string | Config, config: Config = {} as Config) {
|
||||
if (namespaceOrConfig.hasOwnProperty("origin")) {
|
||||
config = namespaceOrConfig as Config;
|
||||
}
|
||||
if (config?.origin) {
|
||||
this.__config.origin = config.origin;
|
||||
}
|
||||
}
|
||||
|
||||
getConfig() {
|
||||
return this.__config;
|
||||
}
|
||||
|
||||
// TODO: Maintain exposed methods in a separate namespace, so that unexpected methods don't become instructions
|
||||
|
||||
/**
|
||||
* It is an instruction that adds embed iframe inline as last child of the element
|
||||
*/
|
||||
inline({
|
||||
calLink,
|
||||
elementOrSelector,
|
||||
config,
|
||||
}: {
|
||||
calLink: string;
|
||||
elementOrSelector: string | HTMLElement;
|
||||
config: Record<string, string>;
|
||||
}) {
|
||||
validate(arguments[0], {
|
||||
required: true,
|
||||
props: {
|
||||
calLink: {
|
||||
required: true,
|
||||
type: "string",
|
||||
},
|
||||
elementOrSelector: {
|
||||
required: true,
|
||||
type: ["string", HTMLElement],
|
||||
},
|
||||
config: {
|
||||
required: false,
|
||||
type: Object,
|
||||
},
|
||||
},
|
||||
});
|
||||
const iframe = this.createIframe({ calLink, queryObject: Cal.getQueryObject(config) });
|
||||
iframe.style.height = "100%";
|
||||
iframe.style.width = "100%";
|
||||
let element =
|
||||
elementOrSelector instanceof HTMLElement
|
||||
? elementOrSelector
|
||||
: document.querySelector(elementOrSelector);
|
||||
if (!element) {
|
||||
throw new Error("Element not found");
|
||||
}
|
||||
element.appendChild(iframe);
|
||||
}
|
||||
|
||||
modal({ calLink }: { calLink: string }) {
|
||||
const iframe = this.createIframe({ calLink });
|
||||
iframe.style.height = "100%";
|
||||
iframe.style.width = "100%";
|
||||
const template = document.createElement("template");
|
||||
template.innerHTML = `<cal-modal-box></cal-modal-box>`;
|
||||
template.content.children[0].appendChild(iframe);
|
||||
document.body.appendChild(template.content);
|
||||
}
|
||||
|
||||
on({
|
||||
action,
|
||||
callback,
|
||||
}: {
|
||||
action: Parameters<SdkActionManager["on"]>[0];
|
||||
callback: Parameters<SdkActionManager["on"]>[1];
|
||||
}) {
|
||||
validate(arguments[0], {
|
||||
required: true,
|
||||
props: {
|
||||
action: {
|
||||
required: true,
|
||||
type: "string",
|
||||
},
|
||||
callback: {
|
||||
required: true,
|
||||
type: Function,
|
||||
},
|
||||
},
|
||||
});
|
||||
this.actionManager.on(action, callback);
|
||||
}
|
||||
|
||||
preload({ calLink }: { calLink: string }) {
|
||||
validate(arguments[0], {
|
||||
required: true,
|
||||
props: {
|
||||
calLink: {
|
||||
type: "string",
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
const iframe = document.body.appendChild(document.createElement("iframe"));
|
||||
const config = this.getConfig();
|
||||
|
||||
const urlInstance = new URL(`${config.origin}/${calLink}`);
|
||||
urlInstance.searchParams.set("prerender", "true");
|
||||
iframe.src = urlInstance.toString();
|
||||
iframe.style.width = "0";
|
||||
iframe.style.height = "0";
|
||||
iframe.style.display = "none";
|
||||
}
|
||||
|
||||
ui(uiConfig: UiConfig) {
|
||||
validate(uiConfig, {
|
||||
required: true,
|
||||
props: {
|
||||
theme: {
|
||||
required: false,
|
||||
type: "string",
|
||||
},
|
||||
styles: {
|
||||
required: false,
|
||||
type: Object,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
this.doInIframe({ method: "ui", arg: uiConfig });
|
||||
}
|
||||
|
||||
doInIframe({
|
||||
method,
|
||||
arg,
|
||||
}: // TODO: Need some TypeScript magic here to remove hardcoded types
|
||||
| { method: "ui"; arg: Parameters<typeof methods["ui"]>[0] }
|
||||
| { method: "parentKnowsIframeReady"; arg: undefined }) {
|
||||
if (!this.iframeReady) {
|
||||
this.iframeDoQueue.push({ method, arg });
|
||||
return;
|
||||
}
|
||||
// TODO: Ensure that origin is as defined by user. Generally it would be cal.com but in case of self hosting it can be anything.
|
||||
this.iframe!.contentWindow!.postMessage({ originator: "CAL", method, arg }, "*");
|
||||
}
|
||||
|
||||
constructor(namespace: string, q: InstructionQueue) {
|
||||
this.__config = {
|
||||
origin: import.meta.env.NEXT_PUBLIC_WEBSITE_URL || "https://cal.com",
|
||||
};
|
||||
this.namespace = namespace;
|
||||
this.actionManager = new SdkActionManager(namespace);
|
||||
|
||||
Cal.actionsManagers = Cal.actionsManagers || {};
|
||||
Cal.actionsManagers[namespace] = this.actionManager;
|
||||
|
||||
this.processQueue(q);
|
||||
|
||||
// 1. Initial iframe width and height would be according to 100% value of the parent element
|
||||
// 2. Once webpage inside iframe renders, it would tell how much iframe height should be increased so that my entire content is visible without iframe scroll
|
||||
// 3. Parent window would check what iframe height can be set according to parent Element
|
||||
this.actionManager.on("dimension-changed", (e) => {
|
||||
const { data } = e.detail;
|
||||
const iframe = this.iframe!;
|
||||
if (!iframe) {
|
||||
// Iframe might be pre-rendering
|
||||
return;
|
||||
}
|
||||
let proposedHeightByIframeWebsite = parseFloat(getComputedStyle(iframe).height) + data.hiddenHeight;
|
||||
iframe.style.height = proposedHeightByIframeWebsite;
|
||||
});
|
||||
|
||||
this.actionManager.on("iframeReady", (e) => {
|
||||
this.iframeReady = true;
|
||||
this.doInIframe({ method: "parentKnowsIframeReady", arg: undefined });
|
||||
this.iframeDoQueue.forEach(({ method, arg }) => {
|
||||
this.doInIframe({ method, arg });
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
globalCal.instance = new Cal("", globalCal.q!);
|
||||
|
||||
for (let [ns, api] of Object.entries(globalCal.ns!)) {
|
||||
api.instance = new Cal(ns, api.q!);
|
||||
}
|
||||
|
||||
/**
|
||||
* Intercepts all postmessages and fires action in corresponding actionManager
|
||||
*/
|
||||
window.addEventListener("message", (e) => {
|
||||
const detail = e.data;
|
||||
const fullType = detail.fullType;
|
||||
const parsedAction = SdkActionManager.parseAction(fullType);
|
||||
if (!parsedAction) {
|
||||
return;
|
||||
}
|
||||
const actionManager = Cal.actionsManagers[parsedAction.ns];
|
||||
if (!actionManager) {
|
||||
throw new Error("Unhandled Action" + parsedAction);
|
||||
}
|
||||
actionManager.fire(parsedAction.type, detail.data);
|
||||
});
|
||||
|
||||
document.addEventListener("click", (e) => {
|
||||
const htmlElement = e.target;
|
||||
if (!(htmlElement instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
const path = htmlElement.dataset.calLink;
|
||||
if (!path) {
|
||||
return;
|
||||
}
|
||||
// TODO: Add an option to check which cal instance should be used for this.
|
||||
globalCal("modal", {
|
||||
calLink: path,
|
||||
});
|
||||
});
|
||||
|
||||
customElements.define("cal-modal-box", ModalBox);
|
||||
@@ -0,0 +1,58 @@
|
||||
type Namespace = string;
|
||||
type CustomEventDetail = Record<string, any>;
|
||||
|
||||
function _fireEvent(fullName: string, detail: CustomEventDetail) {
|
||||
const event = new window.CustomEvent(fullName, {
|
||||
detail: detail,
|
||||
});
|
||||
|
||||
window.dispatchEvent(event);
|
||||
}
|
||||
|
||||
export class SdkActionManager {
|
||||
namespace: Namespace;
|
||||
|
||||
static parseAction(fullType: string) {
|
||||
if (!fullType) {
|
||||
return null;
|
||||
}
|
||||
//FIXME: Ensure that any action if it has :, it is properly encoded.
|
||||
const [cal, calNamespace, type] = fullType.split(":");
|
||||
if (cal !== "CAL") {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
ns: calNamespace,
|
||||
type,
|
||||
};
|
||||
}
|
||||
|
||||
getFullActionName(name: string) {
|
||||
return this.namespace ? `CAL:${this.namespace}:${name}` : `CAL::${name}`;
|
||||
}
|
||||
|
||||
fire(name: string, data: CustomEventDetail) {
|
||||
const fullName = this.getFullActionName(name);
|
||||
const detail = {
|
||||
type: name,
|
||||
namespace: this.namespace,
|
||||
fullType: fullName,
|
||||
data,
|
||||
};
|
||||
|
||||
_fireEvent(fullName, detail);
|
||||
|
||||
// Wildcard Event
|
||||
_fireEvent(this.getFullActionName("*"), detail);
|
||||
}
|
||||
|
||||
on(name: string, callback: (arg0: CustomEvent<CustomEventDetail>) => void) {
|
||||
const fullName = this.getFullActionName(name);
|
||||
window.addEventListener(fullName, callback as EventListener);
|
||||
}
|
||||
|
||||
constructor(ns: string | null) {
|
||||
ns = ns || "";
|
||||
this.namespace = ns;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* @file
|
||||
* This module is supposed to instantiate the SDK with appropriate namespace
|
||||
*/
|
||||
import { SdkActionManager } from "./sdk-action-manager";
|
||||
|
||||
export let sdkActionManager: SdkActionManager | null = null;
|
||||
if (typeof window !== "undefined") {
|
||||
sdkActionManager = new SdkActionManager(new URL(document.URL).searchParams.get("embed"));
|
||||
}
|
||||
Reference in new issue
Block a user