@datafinder/embed-sdk
Version:
Embed SDK for DataFinder
839 lines (813 loc) • 36.3 kB
JavaScript
import * as Comlink from 'comlink';
import { v4 } from 'uuid';
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
// 私有化里需要通过跳转来实现嵌出
var DIRECT_PATH = '/minibase/fronted-check/iframe';
/**
* 允许嵌出的页面列表
*/
var ALLOW_EMBED_PAGES = [
// 看板页
'dashboard',
// 图表页
'report',
// 行为细查
'behavior-detail',
// TODO: 用户分群编辑页
'user-cohort/edit-cohort/:type/:id?',
// 融合看板页
'fusion-dashboard',
// 事件分析
'event-analysis',
// 留存分析
'retention-analysis',
// 转化分析
'funnel-analysis',
];
var DEFAULT_IFRAME_ATTRIBUTES = {
width: '100%',
height: '100%',
frameBorder: '0',
};
function createSearchParams(input) {
var i = Object.keys(input)
.filter(function (k) { return input[k] != null; })
.reduce(function (a, k) {
var _a;
return (__assign(__assign({}, a), (_a = {}, _a[k] = input[k], _a)));
}, {});
return new URLSearchParams(i);
}
// 把对象转化成 url search
var joinQuery = function (query) {
return Object.entries(query)
.map(function (_a) {
var key = _a[0], value = _a[1];
return value === undefined || value === false ? '' : "".concat(key, "=").concat(value);
})
.filter(Boolean)
.join('&');
};
var handleQuery = function (options) {
var dashboardId = options.dashboardId, filterId = options.filterId, crossOrigin = options.crossOrigin, proxyPath = options.proxyPath, dorToken = options.dorToken, from = options.from, customRequestHeaders = options.customRequestHeaders, locale = options.locale, embedQueryParams = options.embedQueryParams;
var query = __assign({ filter_id: filterId, dashboardId: dashboardId, crossOrigin: crossOrigin, proxyPath: proxyPath, dorToken: dorToken, from: from, locale: locale, crh: customRequestHeaders
? JSON.stringify(customRequestHeaders)
: undefined }, embedQueryParams);
return query;
};
var handleAnalysis = function (options, baseUrl) {
var resultId = options.resultId, reportId = options.reportId;
var query = handleQuery(options);
if (resultId) {
return "".concat(baseUrl, "/result/").concat(resultId, "?").concat(joinQuery(query));
}
if (reportId) {
return "".concat(baseUrl, "/").concat(reportId, "?").concat(joinQuery(query));
}
return "".concat(baseUrl, "?").concat(joinQuery(query));
};
var handleRetentionAnalysis = function (options, baseUrl) {
var resultId = options.resultId, reportId = options.reportId;
var query = handleQuery(options);
if (resultId) {
return "".concat(baseUrl, "/result/").concat(resultId, "?").concat(joinQuery(query));
}
if (reportId) {
return "".concat(baseUrl, "/").concat(reportId, "?").concat(joinQuery(query));
}
return baseUrl;
};
/**
* @deprecated 旧版本的 API
*
* 根据指定的选项将 Finder 嵌出页面以 iframe 形式渲染至目标节点
*/
function render(options) {
var targetNode = options.targetNode;
if (!isOptionsValid(options)) {
return;
}
options.proxyPath; var _a = options.iframeOptions, iframeOptions = _a === void 0 ? DEFAULT_IFRAME_ATTRIBUTES : _a, onSuccess = options.onSuccess, onError = options.onError;
try {
var iframe = document.createElement('iframe');
Object.assign(iframe, __assign({ src: getFinderIFrameURL(options) }, iframeOptions));
targetNode.appendChild(iframe);
onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess();
return iframe;
}
catch (err) {
onError === null || onError === void 0 ? void 0 : onError(err.message);
console.error(err);
}
}
function getFinderIFrameURL(options) {
var _a = options.basePath, basePath = _a === void 0 ? '/datafinder' : _a, _b = options.needsMinibaseRedirect, needsMinibaseRedirect = _b === void 0 ? false : _b, host = options.host, proxyPath = options.proxyPath, appId = options.appId, projectId = options.projectId, dashboardId = options.dashboardId, reportId = options.reportId, filterId = options.filterId, _c = options.crossOrigin, crossOrigin = _c === void 0 ? true : _c, customRequestHeaders = options.customRequestHeaders, dorToken = options.dorToken, from = options.from, locale = options.locale, embedQueryParams = options.embedQueryParams, _d = options.showOriginUrl, showOriginUrl = _d === void 0 ? false : _d;
// TODO: 修复默认逻辑
var iframeHost = host ? host.replace(/\/*$/, '') : ''; // 去除 host 参数末尾的斜杠
var page = getEmbedPage(options);
// 如果用户传了 object,则将 object 转换为 string,并且无论如何都 encode 处理一下
var localQueryParams = embedQueryParams || {};
Object.entries(localQueryParams).forEach(function (_a) {
var key = _a[0], value = _a[1];
if (value && typeof value === 'object') {
localQueryParams[key] = encodeURIComponent(JSON.stringify(value));
}
else {
localQueryParams[key] = encodeURIComponent(value);
}
});
var query = __assign({ dashboardId: dashboardId, reportId: reportId, filter_id: filterId, crossOrigin: crossOrigin, proxyPath: proxyPath, dorToken: dorToken, from: from,
// TODO: 寻找更好的传递参数的方式
crh: customRequestHeaders
? JSON.stringify(customRequestHeaders)
: undefined,
// 嵌出的是融合分析看板时,是 false,其他 case 为 true
hideBelongTo: page === ALLOW_EMBED_PAGES[4] ? false : true, locale: locale }, localQueryParams);
var projectIdIsEmpty = projectId === undefined || projectId == null;
var appIdIsEmpty = appId === undefined || appId == null;
if (projectIdIsEmpty && appIdIsEmpty) {
throw new Error('At least one argument must be proviced in appId or projectId');
}
var appURL = (function () {
var baseUrl = '';
if (!projectIdIsEmpty) {
baseUrl = "".concat(iframeHost).concat(basePath, "/project/").concat(projectId, "/").concat(showOriginUrl ? '' : 'embed-').concat(page);
}
else {
baseUrl = "".concat(iframeHost).concat(basePath, "/app/").concat(appId, "/").concat(showOriginUrl ? '' : 'embed-').concat(page);
}
switch (page) {
// 事件分析
case ALLOW_EMBED_PAGES[5]:
return handleAnalysis(options, baseUrl);
// 留存分析
case ALLOW_EMBED_PAGES[6]:
return handleAnalysis(options, "".concat(baseUrl, "/custom"));
default:
return "".concat(baseUrl, "?").concat(joinQuery(query));
}
})();
if (!needsMinibaseRedirect) {
return appURL;
}
return "".concat(iframeHost).concat(DIRECT_PATH, "?app=datafinder&redirectURI=").concat(encodeURIComponent(appURL));
}
function getEmbedPage(options) {
if (options.page) {
return options.page;
}
if (options.reportId) {
return 'report';
}
return 'dashboard';
}
function isOptionsValid(options) {
if (!(options.targetNode instanceof HTMLElement)) {
console.error("Given targetNode is not a valid HTMLElement.");
return false;
}
// TODO: 重新设计传入参数中 page 的协议,更新校验 page 的逻辑
// if (options.page && !ALLOW_EMBED_PAGES.includes(options.page)) {
// console.error(`"${options.page}" is not a valid finder embed page.`);
// }
return true;
}
var PostDataType;
(function (PostDataType) {
PostDataType["ExtensionInit"] = "__uba_extension_init__";
PostDataType["SendReportData"] = "__uba_dash_report_data__";
PostDataType["ExtensionLoaded"] = "__uba_dash_extension_loaded__";
})(PostDataType || (PostDataType = {}));
var ExtensionClient = {
init: function () {
var _a;
(_a = window.parent) === null || _a === void 0 ? void 0 : _a.postMessage({ type: PostDataType.ExtensionInit, data: {} }, '*');
return {
// 获取数据
fetchData: function () {
return new Promise(function (resolve) {
var receiver = function (ev) {
var data = ev.data;
var type = data.type;
if (type === PostDataType.SendReportData) {
resolve === null || resolve === void 0 ? void 0 : resolve(data);
}
window.removeEventListener('message', receiver);
};
window.addEventListener('message', receiver);
});
},
// 通知父页面已经加载完成
loaded: function () {
var _a;
(_a = window.parent) === null || _a === void 0 ? void 0 : _a.postMessage({
type: PostDataType.ExtensionLoaded,
data: {},
}, '*');
},
};
},
};
var ExtensionContainer = {
iframe: null,
};
var BaseAnalysisController = /** @class */ (function () {
function BaseAnalysisController() {
var _this = this;
/** 打开嵌出页面 */
this.openPage = function (customeIframe) { return __awaiter(_this, void 0, void 0, function () {
var _a, state, eventTrace, targetNode, _b, iframeOptions, onSuccess, iframe, comlinkController;
var _this = this;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_a = this, state = _a.state, eventTrace = _a.eventTrace;
state.proxyPath, targetNode = state.targetNode, _b = state.iframeOptions, iframeOptions = _b === void 0 ? DEFAULT_IFRAME_ATTRIBUTES : _b, onSuccess = state.onSuccess, state.onError;
return [4 /*yield*/, new Promise(function (resolve) {
_this.iframe = customeIframe || document.createElement('iframe');
Object.assign(_this.iframe, __assign({ src: getFinderIFrameURL(state) }, iframeOptions));
targetNode.appendChild(_this.iframe);
_this.iframe.onload = function () {
console.log('iframe init success');
onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess();
resolve();
};
})];
case 1:
_c.sent();
iframe = this.iframe;
this.comlinkController = Comlink.wrap(Comlink.windowEndpoint(iframe.contentWindow, self, '*'), self);
comlinkController = this.comlinkController;
return [2 /*return*/, new Promise(function (resolve, reject) {
Comlink.expose(Comlink.proxy({
onReady: function (iframeName) {
return __awaiter(this, void 0, void 0, function () {
var initState, err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (iframeName !== iframe.name) {
console.log("iframeName ".concat(iframeName, " not equals iframe.name ").concat(iframe === null || iframe === void 0 ? void 0 : iframe.name));
return [2 /*return*/];
}
_a.label = 1;
case 1:
_a.trys.push([1, 5, , 6]);
console.log('tea-next init ready', comlinkController);
return [4 /*yield*/, comlinkController.setSdkState()];
case 2:
_a.sent();
// 更新嵌出需要的配置
return [4 /*yield*/, comlinkController.updateInterfaceConfig(state.interfaceSetting)];
case 3:
// 更新嵌出需要的配置
_a.sent();
return [4 /*yield*/, comlinkController.getSdkState()];
case 4:
initState = _a.sent();
if (!initState) {
throw new Error('tea-embed-sdk init failed');
}
console.log('update interface setting end', state.interfaceSetting);
console.log('iframe src:', iframe === null || iframe === void 0 ? void 0 : iframe.src);
// 埋点
eventTrace();
resolve();
return [3 /*break*/, 6];
case 5:
err_1 = _a.sent();
console.log(err_1);
reject();
return [3 /*break*/, 6];
case 6: return [2 /*return*/];
}
});
});
},
}), Comlink.windowEndpoint(iframe.contentWindow, self, state.host));
})];
}
});
}); };
/** 获取查询dsl,包含时间、事件 */
this.getDsl = function () {
var _a;
return (_a = _this.comlinkController) === null || _a === void 0 ? void 0 : _a.getDsl();
};
/** 获取当前的resultId */
this.getResultId = function () {
var _a;
return (_a = _this.comlinkController) === null || _a === void 0 ? void 0 : _a.getResultId();
};
/** 获取当前嵌出页的url */
this.getCurrentUrl = function () {
var _a;
return (_a = _this.comlinkController) === null || _a === void 0 ? void 0 : _a.getCurrentUrl();
};
/** 获取当前嵌出页对应的tea页面url */
this.getTeaUrl = function () {
var _a;
return (_a = _this.comlinkController) === null || _a === void 0 ? void 0 : _a.getTeaUrl();
};
/** 更新resultId内容 */
this.updateResultId = function (resultId, source) {
var _a;
return (_a = _this.comlinkController) === null || _a === void 0 ? void 0 : _a.updateResultId(resultId, source);
};
/** 更新细分筛选内容 */
this.setFilters = function (filters) {
var _a;
console.log(filters, 'setFilters by custom');
return (_a = _this.comlinkController) === null || _a === void 0 ? void 0 : _a.setFilters(filters);
};
/** 复制 resultId */
this.copyResultId = function (resultId) {
var _a;
return (_a = _this.comlinkController) === null || _a === void 0 ? void 0 : _a.copyResultId(resultId);
};
}
return BaseAnalysisController;
}());
var EventAnalysisController = /** @class */ (function (_super) {
__extends(EventAnalysisController, _super);
function EventAnalysisController(props) {
var _this = _super.call(this) || this;
_this.eventTrace = function () {
var _a = _this, comlinkController = _a.comlinkController; _a.state;
comlinkController === null || comlinkController === void 0 ? void 0 : comlinkController.eventTracer();
};
/** 获取查询dsl,包含时间、事件 */
_this.getDsl = function () {
var _a;
return (_a = _this.comlinkController) === null || _a === void 0 ? void 0 : _a.getDsl();
};
_this.state = __assign(__assign({}, props), { page: 'event-analysis' });
return _this;
}
return EventAnalysisController;
}(BaseAnalysisController));
var RetentionAnalysisController = /** @class */ (function (_super) {
__extends(RetentionAnalysisController, _super);
function RetentionAnalysisController(props) {
var _this = _super.call(this) || this;
_this.eventTrace = function () {
var _a = _this, comlinkController = _a.comlinkController; _a.state;
comlinkController === null || comlinkController === void 0 ? void 0 : comlinkController.eventTracer();
};
/** 获取查询dsl,包含时间、事件 */
_this.getDsl = function () {
var _a;
return (_a = _this.comlinkController) === null || _a === void 0 ? void 0 : _a.getDsl();
};
_this.state = __assign(__assign({}, props), { page: 'retention-analysis' });
return _this;
}
return RetentionAnalysisController;
}(BaseAnalysisController));
var FunnelAnalysisController = /** @class */ (function (_super) {
__extends(FunnelAnalysisController, _super);
function FunnelAnalysisController(props) {
var _this = _super.call(this) || this;
_this.eventTrace = function () {
var _a = _this, comlinkController = _a.comlinkController; _a.state;
comlinkController === null || comlinkController === void 0 ? void 0 : comlinkController.eventTracer();
};
/** 获取查询dsl,包含时间、事件 */
_this.getDsl = function () {
var _a;
return (_a = _this.comlinkController) === null || _a === void 0 ? void 0 : _a.getDsl();
};
_this.state = __assign(__assign({}, props), { page: 'funnel-analysis' });
return _this;
}
return FunnelAnalysisController;
}(BaseAnalysisController));
/**
* 比较关系
*/
var EAttrOp;
(function (EAttrOp) {
EAttrOp["EQ"] = "=";
/**
* 不等于不含 null
*/
EAttrOp["NE"] = "!=";
/**
* 不等于含 null
*/
EAttrOp["NEQ_CONTAIN_NULL"] = "not_equal_contain_null";
/**
* 历史原因:string类型要新增一个 不等于不含null
* 不等于不含 null(analysis base string 的 != 是含null的,因此需要增加一个 not_equal_not_contain_null)
*/
EAttrOp["NEQ_NOT_CONTAIN_NULL"] = "not_equal_not_contain_null";
EAttrOp["GT"] = ">";
EAttrOp["LT"] = "<";
EAttrOp["GE"] = ">=";
EAttrOp["LE"] = "<=";
/**
* 包含
*/
EAttrOp["CONTAIN"] = "contain";
/**
* 自定义包含
*/
EAttrOp["CUSTOM_CONTAIN"] = "custom_contain";
/**
* 不包含
* sass 中的语义是 不包含(含null)
* 私有化 中的语义是 不包含(不含null)
*/
EAttrOp["NOT_CONTAIN"] = "not_contain";
/**
* 不包含不含null
* sass 环境
*/
EAttrOp["NOT_CONTAIN_NOT_CONTAIN_NULL"] = "not_contain_not_contain_null";
/**
* 不包含含null
* 私有化环境,NOT_CONTAIN
*/
EAttrOp["NOT_CONTAIN_CONTAIN_NULL"] = "not_contain_contain_null";
/**
* 包含
*/
EAttrOp["LIST_CONTAIN"] = "list_contain";
/**
* 不包含
*/
EAttrOp["LIST_NOT_CONTAIN"] = "list_not_contain";
/**
* 范围
*/
EAttrOp["BETWEEN"] = "between";
/**
* 固定范围
*/
EAttrOp["TIME_FIXED"] = "time_fixed";
/**
* 不在固定范围
*/
EAttrOp["TIME_NOT_FIXED"] = "time_not_fixed";
/**
* 在当前时间
*/
EAttrOp["TIME_RELATIVE_TO_TODAY"] = "time_relative_to_today";
/**
* 不在当前时间
*/
EAttrOp["TIME_NOT_RELATIVE_TO_TODAY"] = "time_not_relative_to_today";
/**
* 在今天和
*/
EAttrOp["TIME_WITH_TODAY"] = "time_with_today";
/**
* 不在今天和
*/
EAttrOp["TIME_NOT_WITH_TODAY"] = "time_not_with_today";
/**
* 在事件发生(仅作为事件过滤条件时才有)
*/
EAttrOp["TIME_RELATIVE_TO_EVENT"] = "time_relative_to_event";
/**
* 不在事件发生(仅作为事件过滤条件时才有)
*/
EAttrOp["TIME_NOT_RELATIVE_TO_EVENT"] = "time_not_relative_to_event";
/**
* 为空
*/
EAttrOp["IS_NULL"] = "is_null";
/**
* 不为空
*/
EAttrOp["IS_NOT_NULL"] = "is_not_null";
/**
* 正则匹配
*/
EAttrOp["MATCH"] = "match";
/**
* 正则不匹配
*/
EAttrOp["NOT_MATCH"] = "not_match";
/**
* 时间
*/
EAttrOp["TIME"] = "time";
})(EAttrOp || (EAttrOp = {}));
var MetaPropertyType;
(function (MetaPropertyType) {
/**
* 用户属性
*/
MetaPropertyType["PROFILE"] = "profile";
/**
* 事件公共属性
*/
MetaPropertyType["COMMON_PARAM"] = "common_param";
/**
* 事件一般属性
*/
MetaPropertyType["EVENT_PARAM"] = "event_param";
/**
* 业务维度属性
*/
MetaPropertyType["ITEM_PARAM"] = "item_param";
/**
* 用户标签
*/
MetaPropertyType["USER_TAG"] = "user_tag";
/**
* CDP 的用户标签,私有化联合部署时用到。
* 对于调用方来说无感知,会和 user_tag 一起请求。
*/
MetaPropertyType["CDP_TAG"] = "cdp_tag";
/**
* 用户分群。
* 注意,通常要和 CDP_COHORT 一起使用
*/
MetaPropertyType["COHORT"] = "cohort";
/**
* 私有化的用户属性。
* 一个坑点。
* TODO:给它抹平干掉 @huangtianyu
*/
MetaPropertyType["USER_PROFILE"] = "user_profile";
/**
* 脱离事件的属性
*/
MetaPropertyType["PARAM"] = "param";
/**
* CDP 的用户分群,私有化联合部署时用到。
*/
MetaPropertyType["CDP_COHORT"] = "cdp_cohort";
/**
* 自定义属性分组
*/
MetaPropertyType["CUSTOM_PROPERTY_GROUP"] = "custom_property_group";
})(MetaPropertyType || (MetaPropertyType = {}));
var MetaPropertyComposeType;
(function (MetaPropertyComposeType) {
MetaPropertyComposeType["ORIGIN"] = "origin";
/**
* 表示是虚拟属性,虚拟属性在属性列表中需要加个 ICON 区分
*/
MetaPropertyComposeType["VIRTUAL"] = "virtual";
/**
* 仅 Tea-next 使用的
*/
MetaPropertyComposeType["PROFILE"] = "profile";
/**
* 仅维度表使用
*/
MetaPropertyComposeType["ITEM"] = "item";
})(MetaPropertyComposeType || (MetaPropertyComposeType = {}));
var AbstractViewManager = /** @class */ (function () {
function AbstractViewManager(_targetNode, _options) {
var _a;
this._targetNode = _targetNode;
this._options = _options;
this._createIframe();
if ((_a = this._iframeElement) === null || _a === void 0 ? void 0 : _a.contentWindow) {
this._endpoint = Comlink.windowEndpoint(this._iframeElement.contentWindow);
this._remote = Comlink.wrap(this._endpoint);
}
this.exposeFunction('onReady', this._options.onReady);
}
/**
* 销毁当前视图
*/
AbstractViewManager.prototype.destroy = function () {
var _a;
(_a = this._iframeElement) === null || _a === void 0 ? void 0 : _a.remove();
};
Object.defineProperty(AbstractViewManager.prototype, "iframe", {
get: function () {
return this._iframeElement;
},
enumerable: false,
configurable: true
});
/**
* 暴露一个命名方法
*/
AbstractViewManager.prototype.exposeFunction = function (funcName, func) {
var _a;
if (func) {
Comlink.expose(Comlink.proxy((_a = {}, _a[funcName] = func, _a)), this._endpoint);
}
};
/**
* 创建一个渲染 DataFinder 页面的 IFrame
*/
AbstractViewManager.prototype._createIframe = function () {
var _a = this._options.iframeAttrs, iframeAttrs = _a === void 0 ? DEFAULT_IFRAME_ATTRIBUTES : _a;
var iframeElement = document.createElement('iframe');
// TODO: 设置 iframe 相关参数
Object.assign(iframeElement, __assign({ src: this._getIFrameURL() }, iframeAttrs));
this._targetNode.appendChild(iframeElement);
this._iframeElement = iframeElement;
};
AbstractViewManager.prototype._getIFrameURL = function () {
var _a = this._options, _b = _a.basePath, basePath = _b === void 0 ? '/datafinder' : _b, appId = _a.appId, dorToken = _a.dorToken, from = _a.from, customSearchParams = _a.customSearchParams, customRequestHeaders = _a.customRequestHeaders;
var searchParams = __assign(__assign({ dorToken: dorToken, from: from,
// TODO: 寻找更好的传递参数的方式
crh: customRequestHeaders
? JSON.stringify(customRequestHeaders)
: undefined }, this.getViewSearchParams()), customSearchParams);
var url = [
this._getIFrameOrigin(),
basePath,
"/app/".concat(appId),
this.getViewPath(),
"?".concat(createSearchParams(searchParams)),
].join('');
return url;
};
/**
* 返回当前视图的 URL Origin
*/
AbstractViewManager.prototype._getIFrameOrigin = function () {
var customDomain = this._options.customDomain;
if (customDomain) {
return customDomain;
}
return '';
};
return AbstractViewManager;
}());
var CohortEditor = /** @class */ (function (_super) {
__extends(CohortEditor, _super);
function CohortEditor(_targetNode, _options) {
var _this = _super.call(this, _targetNode, _options) || this;
_this._targetNode = _targetNode;
_this._options = _options;
_this.exposeFunction('onCohortCreate', _this._options.onCohortCreate);
return _this;
}
CohortEditor.prototype.setTitle = function (title) {
var _a;
(_a = this._remote) === null || _a === void 0 ? void 0 : _a.setTitle(title);
};
CohortEditor.prototype.getViewPath = function () {
var _a = this._options, cohortType = _a.cohortType, cohortId = _a.cohortId;
if (cohortId == null) {
return "/embed-user-cohort/edit-cohort/".concat(cohortType);
}
return "/embed-user-cohort/edit-cohort/".concat(cohortType, "/").concat(cohortId);
};
CohortEditor.prototype.getViewSearchParams = function () {
return null;
};
return CohortEditor;
}(AbstractViewManager));
/**
* 老的就是使用的字符串,没啥不好,保留吧
*/
var FunnelEventType;
(function (FunnelEventType) {
FunnelEventType["SINGLETON"] = "singleton";
FunnelEventType["PARALLEL"] = "parallel";
})(FunnelEventType || (FunnelEventType = {}));
/**
* 逻辑关系
*/
var ELogic;
(function (ELogic) {
ELogic["AND"] = "and";
ELogic["OR"] = "or";
})(ELogic || (ELogic = {}));
var generateFunnelQueryEvents = function (events) {
return events.map(function (event, index) {
var _a;
return {
label: "".concat(index + 1),
type: FunnelEventType.SINGLETON,
uuid: v4(),
events: [
{
label: "".concat(index + 1),
label_alias: event.eventName,
uuid: v4(),
data_archive_id: event.dataArchiveId,
event: {
event_name: event.eventName,
show_name: event.showName,
event_type: event.eventType,
data_archive_id: event.dataArchiveId,
},
conditions: {
logic: ELogic.AND,
conditions: ((_a = event.paramFilters) === null || _a === void 0 ? void 0 : _a.map(function (filter) {
var _a;
var operation = filter.operation || '=';
return {
logic: ELogic.OR,
uuid: v4(),
data_archive_id: event.dataArchiveId,
conditions: [
{
uuid: v4(),
filter: {
property_type: filter.propertyType,
property_compose_type: filter.propertyComposeType,
name: filter.name,
data_archive_id: event.dataArchiveId,
},
operation: {
label: operation,
value: operation,
},
operationValues: (_a = filter.propertyValues) === null || _a === void 0 ? void 0 : _a.map(function (va) { return ({
value: va,
label: va,
}); }),
},
],
};
})) || [],
},
},
],
};
});
};
var index = {
render: render,
getFinderIFrameURL: getFinderIFrameURL,
ExtensionClient: ExtensionClient,
ExtensionContainer: ExtensionContainer,
PostDataType: PostDataType,
};
export { CohortEditor, EAttrOp, EventAnalysisController, ExtensionClient, ExtensionContainer, FunnelAnalysisController, MetaPropertyComposeType, MetaPropertyType, PostDataType, RetentionAnalysisController, index as default, generateFunnelQueryEvents, getFinderIFrameURL, handleAnalysis, handleRetentionAnalysis, render };
//# sourceMappingURL=index.esm.js.map