Commit 9be328f6 by 胡悦

修改

1 parent c08ed7d7

13.1 KB | W: | H:

10.2 KB | W: | H:

css/img/zTreeStandard.png
css/img/zTreeStandard.png
css/img/zTreeStandard.png
css/img/zTreeStandard.png
  • 2-up
  • Swipe
  • Onion skin
......@@ -103,7 +103,7 @@ main {
/* padding: 8px 20px; */
position: relative;
background-color: #fff;
margin: 8px 20px 0;
/* margin: 8px 20px 0; */
padding: 0 20px 0;
}
main .table-page{
......
......@@ -218,11 +218,11 @@
<label class="layui-form-label required">选择开通模式:</label>
<!-- <div class="layui-input-inline"> -->
<div class="layuui-radio">
<input type="radio" name="merchantModel" value="男" title="单店企微版" />
<input type="radio" name="merchantModel" required lay-verify="otherReq" value="男" title="单店企微版" />
<span>(一个门店一个企微账户授权)</span>
</div>
<div class="layuui-radio">
<input type="radio" name="merchantModel" value="女" title="集团企微版" />
<input type="radio" name="merchantModel" required lay-verify="otherReq" value="女" title="集团企微版" />
<span>(集团多个企微共用一个企微账户授权)</span>
</div>
......@@ -490,7 +490,7 @@
<label class="layui-form-label required">账户类型:</label>
<div class="layui-input-inline w-70" id="accountTypeEl"></div>
</div>
<div class="layui-form-item" style="text-align: center">
<div class="footer-close">
<button id="firstBtn" class="layui-btn" lay-submit lay-filter="handleFirstSubmit">下一步</button>
<button type="reset" class="layui-btn" data-type="handleCancel">取消</button>
</div>
......@@ -513,13 +513,13 @@
<ul class="layui-tab-title"></ul>
<div class="layui-tab-content"></div>
</div>
<button id="draft" class="layui-btn">存草稿</button>
<button id="preStep" class="layui-btn">上一步</button>
<button id="confirm" class="layui-btn">确定</button>
<button class="layui-btn" data-type="handleCancel">取消</button>
<div class="footer-close">
<button id="draft" class="layui-btn">存草稿</button>
<button id="preStep" class="layui-btn">上一步</button>
<button id="confirm" class="layui-btn">确定</button>
<button class="layui-btn" data-type="handleCancel">取消</button>
</div>
</div>
</div>
</div>
</main>
</div>
......@@ -672,6 +672,23 @@
if (value && !validator.checkPhoneNumber(value)) {
return '请填入正确的驻店电话'
}
},
otherReq: function(value,item){
var verifyName=$(item).attr('name')
, verifyType=$(item).attr('type')
,formElem=$(item).parents('.layui-form')//获取当前所在的form元素,如果存在的话
,verifyElem=formElem.find('input[name='+verifyName+']')//获取需要校验的元素
,isTrue= verifyElem.is(':checked')//是否命中校验
,focusElem = verifyElem.next().find('i.layui-icon');//焦点元素
if(!isTrue || !value){
//定位焦点
focusElem.css(verifyType=='radio'?{"color":"#FF5722"}:{"border-color":"#FF5722"});
//对非输入框设置焦点
focusElem.first().attr("tabIndex","1").css("outline","0").blur(function() {
focusElem.css(verifyType=='radio'?{"color":""}:{"border-color":""});
}).focus();
return '必填项不能为空';
}
}
})
......
......@@ -22,11 +22,15 @@
.merchant #searchForm .layui-inline {
margin-bottom: 5px;
vertical-align: top;
}
.layui-btn-xs {
cursor: pointer;
}
.layui-form-label {
width: 130px;
}
.channel,
.accountLevel,
......@@ -35,6 +39,21 @@
.searchInputBtn {
margin-left: 20px;
}
#relevancyBtn {
display: flex;
align-items: center;
}
.relevancyImg {
width: 20px;
height: 20px;
margin-right: 5px;
}
.hide {
display: none;
}
.show {
display: inline-block;
}
</style>
<title>商户管理</title>
</head>
......@@ -46,12 +65,34 @@
<div class="search-block">
<div class="h20"></div>
<form class="layui-form" lay-filter="searchFilter" id="searchForm">
<div class="layui-inline" id="operateEl">
<div class="layui-inline hide" id="operateEl">
<button class="layui-btn mb5" id="addBtn">
<i class="layui-icon layui-icon-addition"></i>
创建商户
</button>
</div>
<div id="relevancyEl" class="hide">
<div class="layui-inline">
<div class="layui-inline channel">
<label class="layui-form-label">是否已关联企微:</label>
<div class="layui-input-inline">
<select name="channelId">
<option value="">全部</option>
<option value="1">已关联</option>
<option value="2">未关联</option>
</select>
</div>
</div>
</div>
<div class="layui-inline">
<button class="layui-btn mb5" id="relevancyBtn">
<img class="relevancyImg" src="../../css/img/relevancy.png" alt="" />
<!-- <i class="layui-icon layui-icon-addition"></i> -->
门店账户关联企微
</button>
</div>
</div>
<div id="channelBox" class="hide" style="display: inline-block;">
<div class="layui-inline channel">
<label class="layui-form-label">渠道:</label>
<div class="layui-input-inline">
......@@ -60,22 +101,23 @@
</select>
</div>
</div>
<div class="layui-inline accountLevel">
<label class="layui-form-label">账户等级:</label>
<div class="layui-input-inline">
<select name="merchantAccountLevel" id="accountLevelEl">
<option value="">全部</option>
</select>
</div>
</div>
<div class="layui-inline accountLevel">
<label class="layui-form-label">账户等级:</label>
<div class="layui-input-inline">
<select name="merchantAccountLevel" id="accountLevelEl">
<option value="">全部</option>
</select>
</div>
<div class="layui-inline accountType">
<label class="layui-form-label">账户类型:</label>
<div class="layui-input-inline">
<select name="accounttypeId" id="accountTypeIdEl">
<option value="">全部</option>
</select>
</div>
</div>
<div class="layui-inline customerStatus">
<label class="layui-form-label">账户状态:</label>
<div class="layui-input-inline">
<select name="status" id="searchStatusEl">
<option value="">全部</option>
</select>
</div>
</div>
<div class="layui-inline loginName">
<div class="layui-input-inline" style="width: 120px">
<select name="accountOrPhone" lay-filter="nameFilter">
......@@ -87,30 +129,32 @@
<input class="layui-input" placeholder="请输入" name="merchantLoginAccount" />
</div>
</div>
<div class="layui-inline customerStatus">
<label class="layui-form-label">账户状态:</label>
<div class="layui-input-inline">
<select name="status" id="searchStatusEl">
<option value="">全部</option>
</select>
</div>
</div>
<div class="layui-inline customerStatus">
<label class="layui-form-label">模式:</label>
<div id="model">
<div class="layui-inline accountType">
<label class="layui-form-label">账户类型:</label>
<div class="layui-input-inline">
<select name="status" id="searchModelEl">
<select name="accounttypeId" id="accountTypeIdEl">
<option value="">全部</option>
</select>
</div>
</div>
<div class="layui-inline customerStatus">
<label class="layui-form-label">模式:</label>
<div class="layui-input-inline">
<input class="layui-input" style="width: 380px;" name="merchantName" placeholder="请输入商户名称/关联的企业微信名" />
<select name="status" id="searchModelEl">
<option value="">全部</option>
</select>
</div>
</div>
<div class="layui-inline searchInputBtn">
<button class="layui-btn" lay-submit lay-filter="searchSubmit">查询</button>
</div>
<div class="layui-inline customerStatus">
<div class="layui-input-inline">
<input class="layui-input" style="width: 380px;" name="merchantName" placeholder="请输入商户名称/关联的企业微信名" />
</div>
</div>
<div class="layui-inline searchInputBtn">
<button class="layui-btn" lay-submit lay-filter="searchSubmit">查询</button>
</div>
</form>
<div class="table-page">
<table class="layui-table" id="merchantTable" lay-filter="merchant-table-filter"></table>
......@@ -135,34 +179,26 @@
</ul>
</script>
<script type="text/html" id="merchantBtns">
<div>
<a class="layui-btn-xs" lay-event="handleDetail">查看</a>
{{# if((d.btn.edit)){ }}
<!-- <a class="layui-btn-xs" lay-event="handleEdit">修改基本信息</a> -->
<a class="layui-btn-xs" lay-event="handleEdit">修改</a>
{{# } }}
</div>
<!-- <div>
{{# if((d.btn.edit)){ }}
<a class="layui-btn-xs" lay-event="handleAuthority">修改权限</a>
{{# } }}
{{# if((d.btn.editPeriod)){ }}
<a class="layui-btn-xs" lay-event="handleVaildPeriod">修改账户有效期</a>
{{# } }}
</div> -->
<div>
{{# if((d.btn.createStaff)){ }}
<a class="layui-btn-xs" lay-event="handleAddStaff">创建员工</a>
{{# } }} {{# if((d.btn.createSubMerchant)){ }}
<a class="layui-btn-xs" lay-event="handleAddMerchant">创建子商户/门店</a>
{{# } }}
{{# if((d.btn.editPeriod)){ }}
<a class="layui-btn-xs" lay-event="handleVaildPeriod">修改账户有效期</a>
{{# } }}
</div>
<div>
<a class="layui-btn-xs" lay-event="handleDetail">查看</a>
{{# if((d.btn.edit)){ }}
<!-- <a class="layui-btn-xs" lay-event="handleEdit">修改基本信息</a> -->
<a class="layui-btn-xs" lay-event="handleEdit">修改</a>
{{# } }}
</div>
<div>
{{# if((d.btn.createStaff && window.isDxternal !=1) ){ }}
<a class="layui-btn-xs" lay-event="handleAddStaff">创建员工</a>
{{# } }} {{# if((d.btn.createSubMerchant)){ }}
<a class="layui-btn-xs" lay-event="handleAddMerchant">创建子商户/门店</a>
{{# } }}
{{# if((d.btn.editPeriod && window.isDxternal !=1)){ }}
<a class="layui-btn-xs" lay-event="handleVaildPeriod">修改账户有效期</a>
{{# } }}
</div>
</script>
<script>
layui.use(['gtree', 'request', 'helper', 'table', 'laypage', 'layer'], function () {
layui.use(['gtree', 'request', 'helper', 'table', 'laypage', 'layer'], function() {
var tree = layui.gtree
var request = layui.request
var table = layui.table
......@@ -170,8 +206,13 @@
var form = layui.form
var $ = layui.$
var helper = layui.helper
var user = helper.store.get('user')
var isDxternal = isAppend()
// var user = helper.store.get('user')
var user = {
merchantId: 81
}
// var isDxternal = isAppend()
window.isDxternal = 1 // 1 SCRM, default 运营平台
var baseData = {
statusList: [],
channelList: [],
......@@ -188,7 +229,7 @@
elem: 'merchantPage',
groups: 5,
layout: ['count', 'page', 'skip'],
jump: function (obj, first) {
jump: function(obj, first) {
//obj包含了当前分页的所有参数,比如:
// console.log(obj.curr); //得到当前页,以便向服务端请求对应页的数据。
// console.log(obj.limit); //得到每页显示的条数
......@@ -285,13 +326,13 @@
toolbar: '#merchantBtns',
width: 220,
fixed: 'right'
// },
// {
// align: 'left',
// title: '账户开关',
// toolbar: '#vaildPeriod',
// width: 150,
// fixed: 'right'
// },
// {
// align: 'left',
// title: '账户开关',
// toolbar: '#vaildPeriod',
// width: 150,
// fixed: 'right'
}
]
var colums = [
......@@ -365,42 +406,41 @@
}
]
var gl = false
var merchantTable = table.render({
elem: '#merchantTable',
page: false,
skin: 'nob',
cols: gl ? [cols] : [colums],
done: function () {
cols: window.isDxternal != 1 ? [cols] : [colums],
done: function() {
$("[data-field='lowerHairPath']").css('display', 'none')
$('.layui-table-main tr').each(function (index, val) {
$('.layui-table-main tr').each(function(index, val) {
$($('.layui-table-fixed-l .layui-table-body tbody tr')[index]).height($(val).height())
$($('.layui-table-fixed-r .layui-table-body tbody tr')[index]).height($(val).height())
})
//动态监听表头高度变化,冻结行跟着改变高度
$('.layui-table-header tr').resize(function () {
$('.layui-table-header tr').each(function (index, val) {
$('.layui-table-header tr').resize(function() {
$('.layui-table-header tr').each(function(index, val) {
$($('.layui-table-fixed .layui-table-header table tr')[index]).height($(val).height())
})
})
//初始化高度,使得冻结行表头高度一致
$('.layui-table-header tr').each(function (index, val) {
$('.layui-table-header tr').each(function(index, val) {
$($('.layui-table-fixed .layui-table-header table tr')[index]).height($(val).height())
})
//动态监听表体高度变化,冻结行跟着改变高度
$('.layui-table-body tr').resize(function () {
$('.layui-table-body tr').each(function (index, val) {
$('.layui-table-body tr').resize(function() {
$('.layui-table-body tr').each(function(index, val) {
$($('.layui-table-fixed .layui-table-body table tr')[index]).height($(val).height())
})
})
//初始化高度,使得冻结行表体高度一致
$('.layui-table-body tr').each(function (index, val) {
$('.layui-table-body tr').each(function(index, val) {
$($('.layui-table-fixed .layui-table-body table tr')[index]).height($(val).height())
})
}
})
table.on('tool(merchant-table-filter)', function (obj) {
table.on('tool(merchant-table-filter)', function(obj) {
// console.log(obj)
var eventName = obj.event
var row = obj.data
......@@ -459,7 +499,7 @@
case 'handleVaildPeriod':
// console.log(row)
var area = ['500px', '180px']
if (row.merchantAccountLevel != 4) {
if (row.merchantAccountLevel == 4) {
area = ['900px', '480px']
}
layer.open({
......@@ -471,12 +511,12 @@
// maxmin: true,
btn: ['确定', '取消'],
content: 'validPeriodForm.html?id=' + row.id + '&effectiveTime=' + row.effectiveTime + '&status=' + row.status + '&merchantAccountLevel=' + row.merchantAccountLevel,
yes: function (index, layero) {
yes: function(index, layero) {
var body = layer.getChildFrame('body', index)
helper.store.set('isRefresh', false)
body.find('#periodVerifyBtn').click()
},
end: function () {
end: function() {
var isRefresh = helper.store.get('isRefresh')
if (isRefresh) {
getTabelList()
......@@ -493,7 +533,7 @@
init()
$('#addBtn').on('click', function () {
$('#addBtn').on('click', function() {
// 1-创建新商户;2-创建子商户;3-修改
go('merchant', 'add', {
editLevel: 1,
......@@ -502,8 +542,12 @@
})
return false
})
$('#relevancyBtn').on('click', function() {
$messenger.emit('route-to', { path: '/baseInfo', params: { a: 111 } })
})
// 搜索绑定事件
form.on('submit(searchSubmit)', function () {
form.on('submit(searchSubmit)', function() {
getTabelList(true)
return false
})
......@@ -522,7 +566,7 @@
}
var searchData = $('#searchForm [name]').serializeArray()
// console.log(searchData)
$.each(searchData, function () {
$.each(searchData, function() {
if (this.name == 'merchantLoginAccount') {
var attrName = params.accountOrPhone == '0' ? 'merchantLoginAccount' : 'merchantLegalPersonPhone'
params[attrName] = this.value
......@@ -531,9 +575,9 @@
}
})
// console.log(params)
request(params, function (res) {
request(params, function(res) {
var data = helper.formateNullFieldData(res.data)
$.each(data.data, function (index, item) {
$.each(data.data, function(index, item) {
item.index = index + 1 + page.pageSize * (page.pageNum - 1)
item.btn = {
edit: false,
......@@ -551,50 +595,94 @@
// status(账户状态 - 列表):1-草稿;2-正常;3-注销;4-过期
// merchantAccountLevel(账户等级 - 列表):1-工厂;2-省代;3-市代;4-门店
// 外部系统
if (isDxternal) {
// 状态 - 正常
if (item.status == 2) {
// 本身
if (item.id == user.merchantId) {
item.btn.createStaff = true
if (item.merchantAccountLevel != 4) {
item.btn.createSubMerchant = true
}
} else {
// 下级商户
// console.log(item)
item.btn.edit = true
item.btn.editPeriod = true
// 直属门店
if (item.merchantAccountLevel == 4) {
if (item.parentId == user.merchantId) {
item.btn.createStaff = true
switch (window.isDxternal) {
case 1:
if (item.status == 2) {
// 本身
if (item.id == user.merchantId) {
item.btn.createStaff = true
if (item.merchantAccountLevel != 4) {
item.btn.createSubMerchant = true
}
} else {
// 下级商户
// console.log(item)
item.btn.edit = true
item.btn.editPeriod = true
// 直属门店
if (item.merchantAccountLevel == 4) {
if (item.parentId == user.merchantId) {
item.btn.createStaff = true
}
} else {
item.btn.createSubMerchant = true
}
}
} else if (item.status != 3) {
item.btn.edit = true
if (item.status == 4) {
item.btn.editPeriod = true
}
}
break
default:
if (item.status != 3) {
item.btn.edit = true
}
if (item.status == 2) {
item.btn.createStaff = true
if (item.merchantAccountLevel != 4) {
item.btn.createSubMerchant = true
}
}
} else if (item.status != 3) {
item.btn.edit = true
if (item.status == 4) {
if (item.status != 1) {
item.btn.editPeriod = true
}
}
} else {
// 超管登录
if (item.status != 3) {
item.btn.edit = true
}
if (item.status == 2) {
item.btn.createStaff = true
if (item.merchantAccountLevel != 4) {
item.btn.createSubMerchant = true
}
}
if (item.status != 1) {
item.btn.editPeriod = true
}
}
// if (isDxternal) {
// // 状态 - 正常
// if (item.status == 2) {
// // 本身
// if (item.id == user.merchantId) {
// item.btn.createStaff = true
// if (item.merchantAccountLevel != 4) {
// item.btn.createSubMerchant = true
// }
// } else {
// // 下级商户
// // console.log(item)
// item.btn.edit = true
// item.btn.editPeriod = true
// // 直属门店
// if (item.merchantAccountLevel == 4) {
// if (item.parentId == user.merchantId) {
// item.btn.createStaff = true
// }
// } else {
// item.btn.createSubMerchant = true
// }
// }
// } else if (item.status != 3) {
// item.btn.edit = true
// if (item.status == 4) {
// item.btn.editPeriod = true
// }
// }
// } else {
// // 超管登录
// if (item.status != 3) {
// item.btn.edit = true
// }
// if (item.status == 2) {
// item.btn.createStaff = true
// if (item.merchantAccountLevel != 4) {
// item.btn.createSubMerchant = true
// }
// }
// if (item.status != 1) {
// item.btn.editPeriod = true
// }
// }
})
var options = {
data: data.data
......@@ -615,7 +703,7 @@
method: 'cn.com.glsx.merchants.menu.findAllDictData',
dictType: dictType
},
function (res) {
function(res) {
fn && fn(res)
}
)
......@@ -624,7 +712,7 @@
// 设置option
function setSelectOption(elName, listName, optionId, optionLabel) {
var el = $(elName)
$.each(baseData[listName], function (index, item) {
$.each(baseData[listName], function(index, item) {
el.append(new Option(item[optionLabel], item[optionId]))
})
form.render('select')
......@@ -632,7 +720,7 @@
// 获取有效期
function getVaildPeriod() {
getDictData('merchant_status', function (res) {
getDictData('merchant_status', function(res) {
baseData.statusList = res.data
setSelectOption('#searchStatusEl', 'statusList', 'dictValue', 'dictLabel')
})
......@@ -640,7 +728,7 @@
// 获取渠道
function getChannel() {
getDictData('channel', function (res) {
getDictData('channel', function(res) {
baseData.channelList = res.data
setSelectOption('#channelIdEl', 'channelList', 'dictValue', 'dictLabel')
})
......@@ -648,7 +736,7 @@
// 获取账户等级
function getAccountLevel() {
getDictData('account_level', function (res) {
getDictData('account_level', function(res) {
baseData.accountLevelList = res.data
setSelectOption('#accountLevelEl', 'accountLevelList', 'dictValue', 'dictLabel')
})
......@@ -656,7 +744,7 @@
// 获取账户类型
function getAccountType() {
getDictData('account_type', function (res) {
getDictData('account_type', function(res) {
baseData.accountTypeList = res.data
setSelectOption('#accountTypeIdEl', 'accountTypeList', 'dictValue', 'dictLabel')
})
......@@ -664,7 +752,7 @@
// 获取模式
function getModel() {
getDictData('merchant_model', function (res) {
getDictData('merchant_model', function(res) {
baseData.modelList = res.data
setSelectOption('#searchModelEl', 'modelList', 'dictValue', 'dictLabel')
})
......@@ -673,18 +761,42 @@
// 功能点按需出现
function elRemove() {
$('#operateEl').remove()
$('#channelBox').remove()
$('#relevancyEl').addClass('show')
$('#model').remove()
}
// SCRM系统 搜索加按钮
function hideSearch() {
// $('#channelBox').remove()
$('#operateEl').addClass('show')
$('#channelBox').addClass('show')
$('#relevancyEl').remove()
$('#model').addClass('show')
}
// 运营平台
function init() {
// 运营系统
if (!isDxternal) {
getChannel()
getAccountLevel()
getAccountType()
getModel()
} else {
elRemove()
switch (window.isDxternal) {
case 1:
elRemove()
break
default:
getChannel()
getModel()
hideSearch()
}
// if (!isDxternal) {
// getChannel()
// getAccountLevel()
// getAccountType()
// getModel()
// } else {
// elRemove()
// }
getAccountLevel()
getAccountType()
getVaildPeriod()
getTabelList()
}
......
......@@ -75,7 +75,7 @@
var vaildData = {
id: getQueryString('id')
}
if (merchantAccountLevel != 4) {
if (merchantAccountLevel == 4) {
$('#storeEl').show()
$('#merchantEl').hide()
} else {
......@@ -131,13 +131,15 @@
// 1-草稿;2-正常;3-注销;4-过期
form.on('submit(periodSubmit)', function (data) {
console.log(data)
if (merchantAccountLevel != 4) {
if (data.field.effectiveTime) {
console.log(data, merchantAccountLevel)
if (merchantAccountLevel == 4) {
console.log('2222222222')
if (data.field.effectiveStarttime && data.field.expireDate) {
var params = {
method: 'cn.com.glsx.merchants.merchant.updateMerchant',
method: 'cn.com.glsx.merchants.merchant.updateValPerByMerId',
id: vaildData.id,
effectiveTime: data.field.effectiveTime
effectiveStarttime: new Date(data.field.effectiveStarttime),
expireDate: new Date(data.field.expireDate)
}
request(params, function (res) {
if (res.code == '0') {
......@@ -146,18 +148,18 @@
}
})
} else {
layer.msg('请选择账户有效期', {
layer.msg('请选择账户有效期2', {
icon: 5,
anim: 6
})
}
} else {
if (data.field.effectiveStarttime && data.field.expireDate) {
if (data.field.effectiveTime) {
console.log('11111111')
var params = {
method: 'cn.com.glsx.merchants.merchant.updateMerchant',
method: 'cn.com.glsx.merchants.merchant.updateValPerByMerId',
id: vaildData.id,
effectiveStarttime: data.field.effectiveStarttime,
expireDate: data.field.expireDate
effectiveTime: data.field.effectiveTime
}
request(params, function (res) {
if (res.code == '0') {
......@@ -166,7 +168,7 @@
}
})
} else {
layer.msg('请选择账户有效期', {
layer.msg('请选择账户有效期1', {
icon: 5,
anim: 6
})
......
......@@ -11,6 +11,7 @@
loadLayConfig()
loadConfig()
loadHeaderFooter()
connect()
})()
/**
* 跳转方法 TODO
......@@ -118,3 +119,18 @@ function qs(name) {
}
return null
}
function connect() {
layui.use(['postmate'], function () {
var Postmate = layui.postmate
new Postmate.Model({
height: () => {
console.log('clientHeight', document.body.clientHeight, 'document.height ', document.height || document.body.offsetHeight)
return document.height || document.body.offsetHeight
},
push: data => {
console.log(data)
}
}).then(parent => (window.$messenger = parent))
})
}
/**
postmate - A powerful, simple, promise-based postMessage library
@version v1.5.2
@link https://github.com/dollarshaveclub/postmate
@author Jacob Kelley <jakie8@gmail.com>
@license MIT
**/
layui.define(function (exports) {
'use strict'
/**
* The type of messages our frames our sending
* @type {String}
*/
var messageType = 'application/x-postmate-v1+json'
/**
* The maximum number of attempts to send a handshake request to the parent
* @type {Number}
*/
var maxHandshakeRequests = 5
/**
* A unique message ID that is used to ensure responses are sent to the correct requests
* @type {Number}
*/
var _messageId = 0
/**
* Increments and returns a message ID
* @return {Number} A unique ID for a message
*/
var generateNewMessageId = function generateNewMessageId() {
return ++_messageId
}
/**
* Postmate logging function that enables/disables via config
* @param {Object} ...args Rest Arguments
*/
var log = function log() {
var _console
return Postmate.debug ? (_console = console).log.apply(_console, arguments) : null
} // eslint-disable-line no-console
/**
* Takes a URL and returns the origin
* @param {String} url The full URL being requested
* @return {String} The URLs origin
*/
var resolveOrigin = function resolveOrigin(url) {
var a = document.createElement('a')
a.href = url
var protocol = a.protocol.length > 4 ? a.protocol : window.location.protocol
var host = a.host.length ? (a.port === '80' || a.port === '443' ? a.hostname : a.host) : window.location.host
return a.origin || protocol + '//' + host
}
var messageTypes = {
handshake: 1,
'handshake-reply': 1,
call: 1,
emit: 1,
reply: 1,
request: 1
/**
* Ensures that a message is safe to interpret
* @param {Object} message The postmate message being sent
* @param {String|Boolean} allowedOrigin The whitelisted origin or false to skip origin check
* @return {Boolean}
*/
}
var sanitize = function sanitize(message, allowedOrigin) {
if (typeof allowedOrigin === 'string' && message.origin !== allowedOrigin) return false
if (!message.data) return false
if (typeof message.data === 'object' && !('postmate' in message.data)) return false
if (message.data.type !== messageType) return false
if (!messageTypes[message.data.postmate]) return false
return true
}
/**
* Takes a model, and searches for a value by the property
* @param {Object} model The dictionary to search against
* @param {String} property A path within a dictionary (i.e. 'window.location.href')
* @param {Object} data Additional information from the get request that is
* passed to functions in the child model
* @return {Promise}
*/
var resolveValue = function resolveValue(model, property) {
var unwrappedContext = typeof model[property] === 'function' ? model[property]() : model[property]
return Postmate.Promise.resolve(unwrappedContext)
}
/**
* Composes an API to be used by the parent
* @param {Object} info Information on the consumer
*/
var ParentAPI =
/*#__PURE__*/
(function () {
function ParentAPI(info) {
var _this = this
this.parent = info.parent
this.frame = info.frame
this.child = info.child
this.childOrigin = info.childOrigin
this.events = {}
// if (process.env.NODE_ENV !== 'production') {
// log('Parent: Registering API')
// log('Parent: Awaiting messages...')
// }
this.listener = function (e) {
if (!sanitize(e, _this.childOrigin)) return false
/**
* the assignments below ensures that e, data, and value are all defined
*/
var _ref = ((e || {}).data || {}).value || {},
data = _ref.data,
name = _ref.name
if (e.data.postmate === 'emit') {
// if (process.env.NODE_ENV !== 'production') {
// log('Parent: Received event emission: ' + name)
// }
if (name in _this.events) {
_this.events[name].call(_this, data)
}
}
}
this.parent.addEventListener('message', this.listener, false)
// if (process.env.NODE_ENV !== 'production') {
// log('Parent: Awaiting event emissions from Child')
// }
}
var _proto = ParentAPI.prototype
_proto.get = function get(property) {
var _this2 = this
return new Postmate.Promise(function (resolve) {
// Extract data from response and kill listeners
var uid = generateNewMessageId()
var transact = function transact(e) {
if (e.data.uid === uid && e.data.postmate === 'reply') {
_this2.parent.removeEventListener('message', transact, false)
resolve(e.data.value)
}
} // Prepare for response from Child...
_this2.parent.addEventListener('message', transact, false) // Then ask child for information
_this2.child.postMessage(
{
postmate: 'request',
type: messageType,
property: property,
uid: uid
},
_this2.childOrigin
)
})
}
_proto.call = function call(property, data) {
// Send information to the child
this.child.postMessage(
{
postmate: 'call',
type: messageType,
property: property,
data: data
},
this.childOrigin
)
}
_proto.on = function on(eventName, callback) {
this.events[eventName] = callback
}
_proto.destroy = function destroy() {
// if (process.env.NODE_ENV !== 'production') {
// log('Parent: Destroying Postmate instance')
// }
window.removeEventListener('message', this.listener, false)
this.frame.parentNode.removeChild(this.frame)
}
return ParentAPI
})()
/**
* Composes an API to be used by the child
* @param {Object} info Information on the consumer
*/
var ChildAPI =
/*#__PURE__*/
(function () {
function ChildAPI(info) {
var _this3 = this
this.model = info.model
this.parent = info.parent
this.parentOrigin = info.parentOrigin
this.child = info.child
// if (process.env.NODE_ENV !== 'production') {
// log('Child: Registering API')
// log('Child: Awaiting messages...')
// }
this.child.addEventListener('message', function (e) {
if (!sanitize(e, _this3.parentOrigin)) return
// if (process.env.NODE_ENV !== 'production') {
// log('Child: Received request', e.data)
// }
var _e$data = e.data,
property = _e$data.property,
uid = _e$data.uid,
data = _e$data.data
if (e.data.postmate === 'call') {
if (property in _this3.model && typeof _this3.model[property] === 'function') {
_this3.model[property](data)
}
return
} // Reply to Parent
resolveValue(_this3.model, property).then(function (value) {
return e.source.postMessage(
{
property: property,
postmate: 'reply',
type: messageType,
uid: uid,
value: value
},
e.origin
)
})
})
}
var _proto2 = ChildAPI.prototype
_proto2.emit = function emit(name, data) {
// if (process.env.NODE_ENV !== 'production') {
// log('Child: Emitting Event "' + name + '"', data)
// }
this.parent.postMessage(
{
postmate: 'emit',
type: messageType,
value: {
name: name,
data: data
}
},
this.parentOrigin
)
}
return ChildAPI
})()
/**
* The entry point of the Parent.
* @type {Class}
*/
var Postmate =
/*#__PURE__*/
(function () {
// eslint-disable-line no-undef
// Internet Explorer craps itself
/**
* Sets options related to the Parent
* @param {Object} object The element to inject the frame into, and the url
* @return {Promise}
*/
function Postmate(_ref2) {
var _ref2$container = _ref2.container,
container = _ref2$container === void 0 ? (typeof container !== 'undefined' ? container : document.body) : _ref2$container,
model = _ref2.model,
url = _ref2.url,
name = _ref2.name,
_ref2$classListArray = _ref2.classListArray,
classListArray = _ref2$classListArray === void 0 ? [] : _ref2$classListArray
// eslint-disable-line no-undef
this.parent = window
this.frame = document.createElement('iframe')
this.frame.name = name || ''
this.frame.classList.add.apply(this.frame.classList, classListArray)
container.appendChild(this.frame)
this.child = this.frame.contentWindow || this.frame.contentDocument.parentWindow
this.model = model || {}
return this.sendHandshake(url)
}
/**
* Begins the handshake strategy
* @param {String} url The URL to send a handshake request to
* @return {Promise} Promise that resolves when the handshake is complete
*/
var _proto3 = Postmate.prototype
_proto3.sendHandshake = function sendHandshake(url) {
var _this4 = this
var childOrigin = resolveOrigin(url)
var attempt = 0
var responseInterval
return new Postmate.Promise(function (resolve, reject) {
var reply = function reply(e) {
if (!sanitize(e, childOrigin)) return false
if (e.data.postmate === 'handshake-reply') {
clearInterval(responseInterval)
// if (process.env.NODE_ENV !== 'production') {
// log('Parent: Received handshake reply from Child')
// }
_this4.parent.removeEventListener('message', reply, false)
_this4.childOrigin = e.origin
if (process.env.NODE_ENV !== 'production') {
log('Parent: Saving Child origin', _this4.childOrigin)
}
return resolve(new ParentAPI(_this4))
} // Might need to remove since parent might be receiving different messages
// from different hosts
if (process.env.NODE_ENV !== 'production') {
log('Parent: Invalid handshake reply')
}
return reject('Failed handshake')
}
_this4.parent.addEventListener('message', reply, false)
var doSend = function doSend() {
attempt++
// if (process.env.NODE_ENV !== 'production') {
// log('Parent: Sending handshake attempt ' + attempt, {
// childOrigin: childOrigin
// })
// }
_this4.child.postMessage(
{
postmate: 'handshake',
type: messageType,
model: _this4.model
},
childOrigin
)
if (attempt === maxHandshakeRequests) {
clearInterval(responseInterval)
}
}
var loaded = function loaded() {
doSend()
responseInterval = setInterval(doSend, 500)
}
if (_this4.frame.attachEvent) {
_this4.frame.attachEvent('onload', loaded)
} else {
_this4.frame.onload = loaded
}
// if (process.env.NODE_ENV !== 'production') {
// log('Parent: Loading frame', {
// url: url
// })
// }
_this4.frame.src = url
})
}
return Postmate
})()
/**
* The entry point of the Child
* @type {Class}
*/
Postmate.debug = false
Postmate.Promise = (function () {
try {
return window ? window.Promise : Promise
} catch (e) {
return null
}
})()
Postmate.Model =
/*#__PURE__*/
(function () {
/**
* Initializes the child, model, parent, and responds to the Parents handshake
* @param {Object} model Hash of values, functions, or promises
* @return {Promise} The Promise that resolves when the handshake has been received
*/
function Model(model) {
this.child = window
this.model = model
this.parent = this.child.parent
return this.sendHandshakeReply()
}
/**
* Responds to a handshake initiated by the Parent
* @return {Promise} Resolves an object that exposes an API for the Child
*/
var _proto4 = Model.prototype
_proto4.sendHandshakeReply = function sendHandshakeReply() {
var _this5 = this
return new Postmate.Promise(function (resolve, reject) {
var shake = function shake(e) {
if (!e.data.postmate) {
return
}
if (e.data.postmate === 'handshake') {
// if (process.env.NODE_ENV !== 'production') {
// log('Child: Received handshake from Parent')
// }
_this5.child.removeEventListener('message', shake, false)
// if (process.env.NODE_ENV !== 'production') {
// log('Child: Sending handshake reply to Parent')
// }
e.source.postMessage(
{
postmate: 'handshake-reply',
type: messageType
},
e.origin
)
_this5.parentOrigin = e.origin // Extend model with the one provided by the parent
var defaults = e.data.model
if (defaults) {
Object.keys(defaults).forEach(function (key) {
_this5.model[key] = defaults[key]
})
// if (process.env.NODE_ENV !== 'production') {
// log('Child: Inherited and extended model from Parent')
// }
}
// if (process.env.NODE_ENV !== 'production') {
// log('Child: Saving Parent origin', _this5.parentOrigin)
// }
return resolve(new ChildAPI(_this5))
}
return reject('Handshake Reply Failed')
}
_this5.child.addEventListener('message', shake, false)
})
}
return Model
})()
exports('postmate', Postmate)
})
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!