@cowprotocol/widget-react 0.2.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("react/jsx-runtime"),i=require("react"),m="2.0",E="*",W=["connect","disconnect","close","chainChanged","accountsChanged"];class y{constructor(e){this.contentWindow=e,window.addEventListener("message",this.processEvent)}ethereumProvider=null;requests={};disconnect(){this.ethereumProvider=null,window.removeEventListener("message",this.processEvent)}onConnect(e){this.ethereumProvider=e,Object.keys(this.requests).forEach(s=>{this.processRequest(this.requests[s])}),this.requests={},W.forEach(s=>{e.on(s,n=>{this.postMessage({method:s,params:[n]})})})}processRequest(e){if(!this.ethereumProvider)return;(e.method==="enable"?this.ethereumProvider.enable():this.ethereumProvider.request(e)).then(n=>{this.postMessage({id:e.id,result:n})}).catch(n=>{this.postMessage({id:e.id,error:n})})}processEvent=e=>{e.data.jsonrpc==="2.0"&&(this.ethereumProvider?this.processRequest(e.data):this.requests[e.data.id]=e.data)};postMessage(e){this.contentWindow.postMessage({jsonrpc:m,...e},E)}}function R(){return typeof window>"u"||!window?"":`https://swap-dev-git-${window.location.hostname.replace("widget-configurator-git-","").replace("-cowswap.vercel.app","")}-cowswap.vercel.app`}const h={local:"http://localhost:3000",prod:"https://swap.cow.fi",dev:"https://dev.swap.cow.fi",pr:R()};var a=(t=>(t.SWAP="swap",t.LIMIT="limit",t.ADVANCED="advanced",t))(a||{});const d="_";function P(t){const e=h[t.env||"prod"],s=p(t),n=f(t);return e+"/#"+s+"?"+n}function p(t){const{chainId:e=1,sell:s,buy:n,tradeType:o=a.SWAP}=t,r=[s?.asset||d,n?.asset||d].map(encodeURIComponent).join("/");return`/${e}/widget/${o}/${r}`}function f(t){const{sell:e,buy:s,theme:n}=t,o=new URLSearchParams;return e?.amount&&o.append("sellAmount",e.amount),s?.amount&&o.append("buyAmount",s.amount),n&&o.append("theme",typeof n=="string"?n:n.baseTheme),o}const c="cowSwapWidget",w="640px",v="450px",S=20;function l(t,e={}){const{provider:s}=e,n=T(e);t.innerHTML="",t.appendChild(n);const{contentWindow:o}=n;if(!o)throw new Error("Iframe does not contain a window!");return C(o,e.appCode),A(n,e.height),s&&new y(o).onConnect(s),n.addEventListener("load",()=>{u(e,o)}),r=>u(r,o)}function T(t){const{width:e=v,height:s=w}=t,n=document.createElement("iframe");return n.src=P(t),n.width=e,n.height=s,n.style.border="0",n}function u(t,e){const s=p(t),n=f(t).toString();e.postMessage({key:c,method:"update",urlParams:{pathname:s,search:n},appParams:{...t,provider:void 0}},"*")}function C(t,e){window.addEventListener("message",s=>{s.data.key!==c||s.data.method!=="activate"||t.postMessage({key:c,method:"metaData",metaData:e?{appCode:e}:void 0},"*")})}function A(t,e=w){window.addEventListener("message",s=>{s.data.key!==c||s.data.method!=="iframeHeight"||(t.style.height=s.data.height?`${s.data.height+S}px`:e)})}function M({params:t,provider:e}){const s=i.useRef(),n=i.useRef(null),o=i.useRef(null);return i.useEffect(()=>{n.current&&(e&&s.current!==e&&(o.current=null),o.current?o.current(t):o.current=l(n.current,t))},[e,t]),i.useEffect(()=>{s.current=e},[e]),g.jsx("div",{ref:n})}exports.COWSWAP_URLS=h;exports.CowSwapWidget=M;exports.TradeType=a;exports.cowSwapWidget=l;
1
+ "use strict";var N=Object.defineProperty;var H=(n,e,t)=>e in n?N(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var h=(n,e,t)=>(H(n,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("react/jsx-runtime"),u=require("react"),D="cowSwapWidget";function R(n,e,t){const s={key:D,method:e,...typeof t=="object"?t:{}};n.postMessage(s,"*")}function P(n,e,t){const r=s=>{!b(s.data)||s.data.key!==D||s.data.method!==e||t(s.data)};return n.addEventListener("message",r),r}function b(n){return typeof n=="object"&&n!==null&&"key"in n&&"method"in n&&typeof n.key=="string"&&typeof n.method=="string"}function O(n,e,t){n.removeEventListener("message",t)}function _(n,e){n.removeEventListener("message",e)}var l=(n=>(n.ACTIVATE="ACTIVATE",n.UPDATE_HEIGHT="UPDATE_HEIGHT",n.EMIT_COW_EVENT="EMIT_COW_EVENT",n.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",n))(l||{}),m=(n=>(n.UPDATE_PARAMS="UPDATE_PARAMS",n.UPDATE_APP_DATA="UPDATE_APP_DATA",n.PROVIDER_RPC_RESPONSE="PROVIDER_RPC_RESPONSE",n.PROVIDER_ON_EVENT="PROVIDER_ON_EVENT",n))(m||{}),v=(n=>(n.SWAP="swap",n.LIMIT="limit",n.ADVANCED="advanced",n))(v||{});const F=["connect","disconnect","close","chainChanged","accountsChanged"];class M{constructor(e){h(this,"ethereumProvider",null);h(this,"requestWaitingForConnection",{});h(this,"processRpcCallFromWindow",({rpcRequest:e})=>{if(!this.ethereumProvider){e.id&&(this.requestWaitingForConnection[e.id]=e);return}this.processRpcRequest(e)});this.iframeWidow=e}disconnect(){this.ethereumProvider=null,O(window,l.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow)}onConnect(e){this.ethereumProvider?this.disconnect():P(window,l.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=e,this.processPendingRequests(),F.forEach(t=>{e.on(t,r=>this.onProviderEvent(t,r))})}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(e=>{this.processRpcRequest(this.requestWaitingForConnection[e])}),this.requestWaitingForConnection={}}processRpcRequest(e){const{id:t,jsonrpc:r,method:s}=e;if(!this.ethereumProvider||!t)return;(s==="enable"?this.ethereumProvider.enable():this.ethereumProvider.request({...e,id:t})).then(o=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:t,result:o}})).catch(o=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:t,error:o}}))}onProviderEvent(e,t){R(this.iframeWidow,m.PROVIDER_ON_EVENT,{event:e,params:t})}forwardRpcResponseToIframe(e){R(this.iframeWidow,m.PROVIDER_RPC_RESPONSE,e)}}function q(){return typeof window>"u"||!window?"":`https://swap-dev-git-${window.location.hostname.replace("widget-configurator-git-","").replace("-cowswap.vercel.app","")}-cowswap.vercel.app`}const L={local:"http://localhost:3000",prod:"https://swap.cow.fi",dev:"https://dev.swap.cow.fi",pr:q()},W="_";function x(n){const e=L[n.env||"prod"],t=y(n),r=U(n);return e+"/#"+t+"?"+r}function y(n){const{chainId:e=1,sell:t,buy:r,tradeType:s=v.SWAP}=n,c=[(t==null?void 0:t.asset)||W,(r==null?void 0:r.asset)||W].map(encodeURIComponent).join("/");return`/${e}/widget/${s}/${c}`}function U(n){const{sell:e,buy:t,theme:r}=n,s=new URLSearchParams;return e!=null&&e.amount&&s.append("sellAmount",e.amount),t!=null&&t.amount&&s.append("buyAmount",t.amount),r&&s.append("theme",typeof r=="string"?r:r.baseTheme),s}class G{constructor(){h(this,"subscriptions",{})}on(e){const{event:t,handler:r}=e;this.subscriptions[t]||(this.subscriptions[t]=[]),this.subscriptions[t].push(r)}off(e){const{event:t,handler:r}=e;this.subscriptions[t]&&(this.subscriptions[t]=this.subscriptions[t].filter(s=>s!==r))}emit(e,t){this.subscriptions[e]&&this.subscriptions[e].forEach(r=>r(t))}}let $=1;class k{constructor(e,t=[]){h(this,"eventEmitter",new G);h(this,"listeners",[]);h(this,"widgetListener");h(this,"instanceNumber",$++);this.contentWindow=e,this.updateListeners(t),this.widgetListener=P(this.contentWindow,l.EMIT_COW_EVENT,r=>this.eventEmitter.emit(r.event,r.payload))}stopListeningIframe(){_(this.contentWindow,this.widgetListener)}updateListeners(e){for(const t of this.listeners)this.eventEmitter.off(t);this.listeners=e||[];for(const t of this.listeners)this.eventEmitter.on(t)}}const V="640px",j="450px",Q=20;function T(n,e){const{params:t,provider:r,listeners:s}=e;let c=r;const o=K(t);n.innerHTML="",n.appendChild(o);const{contentWindow:a}=o;if(!a)throw console.error("Iframe does not contain a window",o),new Error("Iframe does not contain a window!");const w=[];w.push(J(a,t.appCode)),w.push(Y(o,t.height));const f=new k(window,s);let d=I(a,null,c);return o.addEventListener("load",()=>S(a,t,c)),{updateParams:i=>S(a,i,c),updateListeners:i=>f.updateListeners(i),updateProvider:i=>{c=i,d=I(a,d,i)},destroy:()=>{f.stopListeningIframe(),w.forEach(i=>window.removeEventListener("message",i)),n.removeChild(o)}}}function I(n,e,t){e&&e.disconnect();const r=e||new M(n);return t&&r.onConnect(t),r}function K(n){const{width:e=j,height:t=V}=n,r=document.createElement("iframe");return r.src=x(n),r.width=e,r.height=t,r.style.border="0",r}function S(n,e,t){const r=!!t,s=y(e),c=U(e).toString();R(n,m.UPDATE_PARAMS,{urlParams:{pathname:s,search:c},appParams:{...e},hasProvider:r})}function J(n,e){const t=P(window,l.ACTIVATE,()=>{_(window,t),R(n,m.UPDATE_APP_DATA,{metaData:e?{appCode:e}:void 0})});return t}function Y(n,e=V){return P(window,l.UPDATE_HEIGHT,t=>{n.style.height=t.height?`${t.height+Q}px`:e})}function z(n){const{params:e,provider:t,listeners:r}=n,[s,c]=u.useState(null),o=u.useRef(null),a=u.useRef(t),w=u.useRef(r),f=u.useRef(null),d=u.useRef(null),i=u.useCallback((p,E)=>{try{console.log(`[WIDGET] ${p}`),E()}catch(A){const C=`Error ${p.toLowerCase()}`;console.error(`[WIDGET] ${C}`,A),c({message:C,error:A})}},[c]);return u.useEffect(()=>{if(!f.current||JSON.stringify(o.current)===JSON.stringify(e))return;const p=f.current,E=d.current;o.current=e,E===null?i("Creating a new widget",()=>{d.current=T(p,{params:e,provider:a.current,listeners:r}),w.current=r}):i("Updating the widget",()=>E.updateParams(e))},[e]),u.useEffect(()=>{if(!d.current||a.current===t)return;a.current=t;const p=f.current;p&&i("Updating the provider",()=>{var E;(E=d.current)==null||E.destroy(),d.current=T(p,{params:e,provider:a.current,listeners:r})})},[t]),u.useEffect(()=>{if(!d.current||w.current===r)return;const p=d.current;i("Updating the listeners",()=>p.updateListeners(r))},[r]),s?g.jsxs("div",{style:{color:"#ff3a3a"},children:[s.message,s.error.message&&g.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:"0.75em"},children:s.error.message})]}):g.jsx("div",{ref:f})}exports.COWSWAP_URLS=L;exports.CowSwapWidget=z;exports.TradeType=v;exports.WidgetMethodsEmit=l;exports.WidgetMethodsListen=m;exports.createCowSwapWidget=T;exports.listenToMessageFromWindow=P;exports.postMessageToWindow=R;exports.stopListeningToMessageFromWindow=O;exports.stopListeningWindowListener=_;
package/index.mjs CHANGED
@@ -1,150 +1,279 @@
1
- import { jsx as w } from "react/jsx-runtime";
2
- import { useRef as c, useEffect as a } from "react";
3
- const m = "2.0", g = "*", E = ["connect", "disconnect", "close", "chainChanged", "accountsChanged"];
4
- class v {
1
+ var V = Object.defineProperty;
2
+ var N = (n, e, t) => e in n ? V(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
3
+ var p = (n, e, t) => (N(n, typeof e != "symbol" ? e + "" : e, t), t);
4
+ import { jsxs as H, jsx as v } from "react/jsx-runtime";
5
+ import { useState as b, useRef as m, useCallback as F, useEffect as g } from "react";
6
+ const W = "cowSwapWidget";
7
+ function P(n, e, t) {
8
+ const s = {
9
+ key: W,
10
+ method: e,
11
+ ...typeof t == "object" ? t : {}
12
+ };
13
+ n.postMessage(
14
+ s,
15
+ "*"
16
+ // TODO: Change to CoW specific origin in production. https://github.com/cowprotocol/cowswap/issues/3828
17
+ );
18
+ }
19
+ function R(n, e, t) {
20
+ const r = (s) => {
21
+ !q(s.data) || s.data.key !== W || s.data.method !== e || t(s.data);
22
+ };
23
+ return n.addEventListener("message", r), r;
24
+ }
25
+ function q(n) {
26
+ return typeof n == "object" && n !== null && "key" in n && "method" in n && typeof n.key == "string" && typeof n.method == "string";
27
+ }
28
+ function M(n, e, t) {
29
+ n.removeEventListener("message", t);
30
+ }
31
+ function O(n, e) {
32
+ n.removeEventListener("message", e);
33
+ }
34
+ var l = /* @__PURE__ */ ((n) => (n.ACTIVATE = "ACTIVATE", n.UPDATE_HEIGHT = "UPDATE_HEIGHT", n.EMIT_COW_EVENT = "EMIT_COW_EVENT", n.PROVIDER_RPC_REQUEST = "PROVIDER_RPC_REQUEST", n))(l || {}), w = /* @__PURE__ */ ((n) => (n.UPDATE_PARAMS = "UPDATE_PARAMS", n.UPDATE_APP_DATA = "UPDATE_APP_DATA", n.PROVIDER_RPC_RESPONSE = "PROVIDER_RPC_RESPONSE", n.PROVIDER_ON_EVENT = "PROVIDER_ON_EVENT", n))(w || {}), S = /* @__PURE__ */ ((n) => (n.SWAP = "swap", n.LIMIT = "limit", n.ADVANCED = "advanced", n))(S || {});
35
+ const G = ["connect", "disconnect", "close", "chainChanged", "accountsChanged"];
36
+ class $ {
5
37
  /**
6
- * Creates an instance of JsonRpcManager.
7
- * @param contentWindow - The window for handling events.
38
+ * Creates an instance of IframeRpcProviderBridge.
39
+ * @param iframeWidow - The iFrame window that will post up general RPC messages and to which the IframeRpcProviderBridge will forward the RPC result.
40
+ * Also it will receive some special RPC events coming from the wallet, like connect/chainChanged,accountChanged
8
41
  */
9
42
  constructor(e) {
10
- this.contentWindow = e, window.addEventListener("message", this.processEvent);
43
+ /**
44
+ * The Ethereum provider instance.
45
+ * When is null the JSON-RPC bridge is disconnected from the Ethereum provider.
46
+ * */
47
+ p(this, "ethereumProvider", null);
48
+ /** Stored JSON-RPC requests, to queue them when disconnected. */
49
+ p(this, "requestWaitingForConnection", {});
50
+ p(this, "processRpcCallFromWindow", ({ rpcRequest: e }) => {
51
+ if (!this.ethereumProvider) {
52
+ e.id && (this.requestWaitingForConnection[e.id] = e);
53
+ return;
54
+ }
55
+ this.processRpcRequest(e);
56
+ });
57
+ this.iframeWidow = e;
11
58
  }
12
59
  /**
13
- * The Ethereum provider instance.
14
- * When is null the JSON-RPC manager is disconnected from the Ethereum provider.
15
- * */
16
- ethereumProvider = null;
17
- /** Stored JSON-RPC requests. */
18
- requests = {};
19
- /**
20
- * Disconnects the JSON-RPC manager from the Ethereum provider.
60
+ * Disconnects the JSON-RPC bridge from the Ethereum provider.
21
61
  */
22
62
  disconnect() {
23
- this.ethereumProvider = null, window.removeEventListener("message", this.processEvent);
63
+ this.ethereumProvider = null, M(window, l.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow);
24
64
  }
25
65
  /**
26
66
  * Handles the 'connect' event and sets up event listeners for Ethereum provider events.
27
- * @param ethereumProvider - The Ethereum provider to connect.
67
+ * @param newProvider - The Ethereum provider to connect.
28
68
  */
29
69
  onConnect(e) {
30
- this.ethereumProvider = e, Object.keys(this.requests).forEach((s) => {
31
- this.processRequest(this.requests[s]);
32
- }), this.requests = {}, E.forEach((s) => {
33
- e.on(s, (n) => {
34
- this.postMessage({ method: s, params: [n] });
35
- });
70
+ this.ethereumProvider ? this.disconnect() : R(window, l.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow), this.ethereumProvider = e, this.processPendingRequests(), G.forEach((t) => {
71
+ e.on(t, (r) => this.onProviderEvent(t, r));
36
72
  });
37
73
  }
74
+ processPendingRequests() {
75
+ Object.keys(this.requestWaitingForConnection).forEach((e) => {
76
+ this.processRpcRequest(this.requestWaitingForConnection[e]);
77
+ }), this.requestWaitingForConnection = {};
78
+ }
38
79
  /**
39
80
  * Processes a JSON-RPC request and sends appropriate response or error via the content window.
40
81
  * @param request - The JSON-RPC request to be processed.
41
82
  */
42
- processRequest(e) {
43
- if (!this.ethereumProvider)
83
+ processRpcRequest(e) {
84
+ const { id: t, jsonrpc: r, method: s } = e;
85
+ if (!this.ethereumProvider || !t)
44
86
  return;
45
- (e.method === "enable" ? this.ethereumProvider.enable() : this.ethereumProvider.request(e)).then((n) => {
46
- this.postMessage({ id: e.id, result: n });
47
- }).catch((n) => {
48
- this.postMessage({ id: e.id, error: n });
87
+ (s === "enable" ? this.ethereumProvider.enable() : this.ethereumProvider.request({ ...e, id: t })).then(
88
+ (o) => this.forwardRpcResponseToIframe({
89
+ rpcResponse: { jsonrpc: r, id: t, result: o }
90
+ })
91
+ ).catch(
92
+ (o) => this.forwardRpcResponseToIframe({
93
+ rpcResponse: { jsonrpc: r, id: t, error: o }
94
+ })
95
+ );
96
+ }
97
+ onProviderEvent(e, t) {
98
+ P(this.iframeWidow, w.PROVIDER_ON_EVENT, {
99
+ event: e,
100
+ params: t
49
101
  });
50
102
  }
51
- processEvent = (e) => {
52
- e.data.jsonrpc === "2.0" && (this.ethereumProvider ? this.processRequest(e.data) : this.requests[e.data.id] = e.data);
53
- };
54
- postMessage(e) {
55
- this.contentWindow.postMessage(
56
- {
57
- jsonrpc: m,
58
- ...e
59
- },
60
- g
61
- );
103
+ /**
104
+ * Forward a JSON-RPC message to the content window.
105
+ */
106
+ forwardRpcResponseToIframe(e) {
107
+ P(this.iframeWidow, w.PROVIDER_RPC_RESPONSE, e);
62
108
  }
63
109
  }
64
- function y() {
110
+ function x() {
65
111
  return typeof window > "u" || !window ? "" : `https://swap-dev-git-${window.location.hostname.replace("widget-configurator-git-", "").replace("-cowswap.vercel.app", "")}-cowswap.vercel.app`;
66
112
  }
67
- const P = {
113
+ const k = {
68
114
  local: "http://localhost:3000",
69
115
  prod: "https://swap.cow.fi",
70
116
  dev: "https://dev.swap.cow.fi",
71
- pr: y()
72
- };
73
- var h = /* @__PURE__ */ ((t) => (t.SWAP = "swap", t.LIMIT = "limit", t.ADVANCED = "advanced", t))(h || {});
74
- const d = "_";
75
- function W(t) {
76
- const e = P[t.env || "prod"], s = p(t), n = f(t);
77
- return e + "/#" + s + "?" + n;
78
- }
79
- function p(t) {
80
- const { chainId: e = 1, sell: s, buy: n, tradeType: o = h.SWAP } = t, i = [s?.asset || d, n?.asset || d].map(encodeURIComponent).join("/");
81
- return `/${e}/widget/${o}/${i}`;
82
- }
83
- function f(t) {
84
- const { sell: e, buy: s, theme: n } = t, o = new URLSearchParams();
85
- return e?.amount && o.append("sellAmount", e.amount), s?.amount && o.append("buyAmount", s.amount), n && o.append("theme", typeof n == "string" ? n : n.baseTheme), o;
86
- }
87
- const r = "cowSwapWidget", l = "640px", R = "450px", T = 20;
88
- function A(t, e = {}) {
89
- const { provider: s } = e, n = C(e);
90
- t.innerHTML = "", t.appendChild(n);
91
- const { contentWindow: o } = n;
92
- if (!o)
93
- throw new Error("Iframe does not contain a window!");
94
- return M(o, e.appCode), S(n, e.height), s && new v(o).onConnect(s), n.addEventListener("load", () => {
95
- u(e, o);
96
- }), (i) => u(i, o);
97
- }
98
- function C(t) {
99
- const { width: e = R, height: s = l } = t, n = document.createElement("iframe");
100
- return n.src = W(t), n.width = e, n.height = s, n.style.border = "0", n;
101
- }
102
- function u(t, e) {
103
- const s = p(t), n = f(t).toString();
104
- e.postMessage(
105
- {
106
- key: r,
107
- method: "update",
108
- urlParams: {
109
- pathname: s,
110
- search: n
111
- },
112
- appParams: {
113
- ...t,
114
- provider: void 0
115
- }
116
- },
117
- "*"
118
- );
117
+ pr: x()
118
+ }, A = "_";
119
+ function Q(n) {
120
+ const e = k[n.env || "prod"], t = y(n), r = L(n);
121
+ return e + "/#" + t + "?" + r;
122
+ }
123
+ function y(n) {
124
+ const { chainId: e = 1, sell: t, buy: r, tradeType: s = S.SWAP } = n, c = [(t == null ? void 0 : t.asset) || A, (r == null ? void 0 : r.asset) || A].map(encodeURIComponent).join("/");
125
+ return `/${e}/widget/${s}/${c}`;
126
+ }
127
+ function L(n) {
128
+ const { sell: e, buy: t, theme: r } = n, s = new URLSearchParams();
129
+ return e != null && e.amount && s.append("sellAmount", e.amount), t != null && t.amount && s.append("buyAmount", t.amount), r && s.append("theme", typeof r == "string" ? r : r.baseTheme), s;
119
130
  }
120
- function M(t, e) {
121
- window.addEventListener("message", (s) => {
122
- s.data.key !== r || s.data.method !== "activate" || t.postMessage(
123
- {
124
- key: r,
125
- method: "metaData",
126
- metaData: e ? { appCode: e } : void 0
127
- },
128
- "*"
131
+ class K {
132
+ constructor() {
133
+ p(this, "subscriptions", {});
134
+ }
135
+ on(e) {
136
+ const { event: t, handler: r } = e;
137
+ this.subscriptions[t] || (this.subscriptions[t] = []), this.subscriptions[t].push(r);
138
+ }
139
+ off(e) {
140
+ const { event: t, handler: r } = e;
141
+ this.subscriptions[t] && (this.subscriptions[t] = this.subscriptions[t].filter((s) => s !== r));
142
+ }
143
+ emit(e, t) {
144
+ this.subscriptions[e] && this.subscriptions[e].forEach((r) => r(t));
145
+ }
146
+ }
147
+ let j = 1;
148
+ class J {
149
+ constructor(e, t = []) {
150
+ p(this, "eventEmitter", new K());
151
+ p(this, "listeners", []);
152
+ p(this, "widgetListener");
153
+ p(this, "instanceNumber", j++);
154
+ this.contentWindow = e, this.updateListeners(t), this.widgetListener = R(
155
+ this.contentWindow,
156
+ l.EMIT_COW_EVENT,
157
+ (r) => this.eventEmitter.emit(r.event, r.payload)
129
158
  );
159
+ }
160
+ stopListeningIframe() {
161
+ O(this.contentWindow, this.widgetListener);
162
+ }
163
+ updateListeners(e) {
164
+ for (const t of this.listeners)
165
+ this.eventEmitter.off(t);
166
+ this.listeners = e || [];
167
+ for (const t of this.listeners)
168
+ this.eventEmitter.on(t);
169
+ }
170
+ }
171
+ const U = "640px", Y = "450px", z = 20;
172
+ function C(n, e) {
173
+ const { params: t, provider: r, listeners: s } = e;
174
+ let c = r;
175
+ const o = B(t);
176
+ n.innerHTML = "", n.appendChild(o);
177
+ const { contentWindow: a } = o;
178
+ if (!a)
179
+ throw console.error("Iframe does not contain a window", o), new Error("Iframe does not contain a window!");
180
+ const E = [];
181
+ E.push(X(a, t.appCode)), E.push(Z(o, t.height));
182
+ const h = new J(window, s);
183
+ let d = I(a, null, c);
184
+ return o.addEventListener("load", () => D(a, t, c)), {
185
+ updateParams: (i) => D(a, i, c),
186
+ updateListeners: (i) => h.updateListeners(i),
187
+ updateProvider: (i) => {
188
+ c = i, d = I(a, d, i);
189
+ },
190
+ destroy: () => {
191
+ h.stopListeningIframe(), E.forEach((i) => window.removeEventListener("message", i)), n.removeChild(o);
192
+ }
193
+ };
194
+ }
195
+ function I(n, e, t) {
196
+ e && e.disconnect();
197
+ const r = e || new $(n);
198
+ return t && r.onConnect(t), r;
199
+ }
200
+ function B(n) {
201
+ const { width: e = Y, height: t = U } = n, r = document.createElement("iframe");
202
+ return r.src = Q(n), r.width = e, r.height = t, r.style.border = "0", r;
203
+ }
204
+ function D(n, e, t) {
205
+ const r = !!t, s = y(e), c = L(e).toString();
206
+ P(n, w.UPDATE_PARAMS, {
207
+ urlParams: {
208
+ pathname: s,
209
+ search: c
210
+ },
211
+ appParams: {
212
+ ...e
213
+ },
214
+ hasProvider: r
130
215
  });
131
216
  }
132
- function S(t, e = l) {
133
- window.addEventListener("message", (s) => {
134
- s.data.key !== r || s.data.method !== "iframeHeight" || (t.style.height = s.data.height ? `${s.data.height + T}px` : e);
217
+ function X(n, e) {
218
+ const t = R(window, l.ACTIVATE, () => {
219
+ O(window, t), P(n, w.UPDATE_APP_DATA, {
220
+ metaData: e ? { appCode: e } : void 0
221
+ });
135
222
  });
223
+ return t;
136
224
  }
137
- function L({ params: t, provider: e }) {
138
- const s = c(), n = c(null), o = c(null);
139
- return a(() => {
140
- n.current && (e && s.current !== e && (o.current = null), o.current ? o.current(t) : o.current = A(n.current, t));
141
- }, [e, t]), a(() => {
142
- s.current = e;
143
- }, [e]), /* @__PURE__ */ w("div", { ref: n });
225
+ function Z(n, e = U) {
226
+ return R(window, l.UPDATE_HEIGHT, (t) => {
227
+ n.style.height = t.height ? `${t.height + z}px` : e;
228
+ });
229
+ }
230
+ function re(n) {
231
+ const { params: e, provider: t, listeners: r } = n, [s, c] = b(null), o = m(null), a = m(t), E = m(r), h = m(null), d = m(null), i = F(
232
+ (u, f) => {
233
+ try {
234
+ console.log(`[WIDGET] ${u}`), f();
235
+ } catch (T) {
236
+ const _ = `Error ${u.toLowerCase()}`;
237
+ console.error(`[WIDGET] ${_}`, T), c({ message: _, error: T });
238
+ }
239
+ },
240
+ [c]
241
+ );
242
+ return g(() => {
243
+ if (!h.current || JSON.stringify(o.current) === JSON.stringify(e))
244
+ return;
245
+ const u = h.current, f = d.current;
246
+ o.current = e, f === null ? i("Creating a new widget", () => {
247
+ d.current = C(u, { params: e, provider: a.current, listeners: r }), E.current = r;
248
+ }) : i("Updating the widget", () => f.updateParams(e));
249
+ }, [e]), g(() => {
250
+ if (!d.current || a.current === t)
251
+ return;
252
+ a.current = t;
253
+ const u = h.current;
254
+ u && i("Updating the provider", () => {
255
+ var f;
256
+ (f = d.current) == null || f.destroy(), d.current = C(u, { params: e, provider: a.current, listeners: r });
257
+ });
258
+ }, [t]), g(() => {
259
+ if (!d.current || E.current === r)
260
+ return;
261
+ const u = d.current;
262
+ i("Updating the listeners", () => u.updateListeners(r));
263
+ }, [r]), s ? /* @__PURE__ */ H("div", { style: { color: "#ff3a3a" }, children: [
264
+ s.message,
265
+ s.error.message && /* @__PURE__ */ v("pre", { style: { whiteSpace: "pre-wrap", fontSize: "0.75em" }, children: s.error.message })
266
+ ] }) : /* @__PURE__ */ v("div", { ref: h });
144
267
  }
145
268
  export {
146
- P as COWSWAP_URLS,
147
- L as CowSwapWidget,
148
- h as TradeType,
149
- A as cowSwapWidget
269
+ k as COWSWAP_URLS,
270
+ re as CowSwapWidget,
271
+ S as TradeType,
272
+ l as WidgetMethodsEmit,
273
+ w as WidgetMethodsListen,
274
+ C as createCowSwapWidget,
275
+ R as listenToMessageFromWindow,
276
+ P as postMessageToWindow,
277
+ M as stopListeningToMessageFromWindow,
278
+ O as stopListeningWindowListener
150
279
  };
@@ -1,6 +1,2 @@
1
- import { CowSwapWidgetParams, EthereumProvider } from '@cowprotocol/widget-lib';
2
- export interface CowSwapWidgetProps {
3
- params: CowSwapWidgetParams;
4
- provider?: EthereumProvider;
5
- }
6
- export declare function CowSwapWidget({ params, provider }: CowSwapWidgetProps): import("react/jsx-runtime").JSX.Element;
1
+ import { CowSwapWidgetProps } from '@cowprotocol/widget-lib';
2
+ export declare function CowSwapWidget(props: CowSwapWidgetProps): import("react/jsx-runtime").JSX.Element;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cowprotocol/widget-react",
3
- "version": "0.2.3",
3
+ "version": "0.4.0",
4
4
  "type": "commonjs",
5
5
  "description": "CoW Swap Widget Library. Allows you to easily embed a CoW Swap widget on your React application.",
6
6
  "main": "index.js",
@@ -22,6 +22,6 @@
22
22
  "react"
23
23
  ],
24
24
  "dependencies": {
25
- "@cowprotocol/widget-lib": "^0.2.1"
25
+ "@cowprotocol/widget-lib": "^0.3.0"
26
26
  }
27
27
  }