Commit 78ad3e8d by 胡悦

init

0 parents
Showing 60 changed files with 3135 additions and 0 deletions
.svn/
\ No newline at end of file \ No newline at end of file
const target = [
'ip',
'dev',
'uat',
'prod'
]
/**
*
0本地
1开发
2测试
3生产
*/
const index = 2
const secretKey = {
ip: {},
dev: {
sso: {
appKey: '8b31ae1009ccb0f96130ca4bd90e3d89',
secret: '02d60f17ae714872845d2aa9d3b087e109ccb0f96130ca4b',
},
},
uat: {},
prod: {},
} [target[index]]
const domain = {
ip: 'http://192.168.3.181:8394',
dev: 'https://scrm.dev.glsx.com.cn',
uat: 'https://scrm.test.glsx.com.cn',
prod: 'https://scrm.cgacar.com',
} [target[index]]
const pathEnum = {
sso: '/rop-scrm-sso/',
}
module.exports = {
index,
domain,
pathEnum,
secretKey,
}
\ No newline at end of file \ No newline at end of file
import sha1 from './sha1.js'
import qs from './qs'
import environment from './environment.js'
const sign = (params, secret, noSignAttr = []) => {
delete params.sign
var objStr = qs.stringify(params, {
arrayFormat: 'indices',
allowDots: true,
encodeValuesOnly: true
})
var objVal = objStr.split('&')
var realObj = {}
objVal.forEach(item => {
const idx = item.indexOf('=')
realObj[item.split('=')[0]] = decodeURIComponent(item.slice(idx + 1))
})
const keys = Object.keys(realObj).sort()
var str = []
var obj = null
for (const key in realObj) {
obj = realObj[key]
if (obj === null) {
obj = ''
} else if (typeof obj === 'object') {
obj = JSON.stringify(obj)
}
realObj[key] = obj
}
keys.forEach(e => {
!noSignAttr.includes(e) && str.push(e + realObj[e])
})
realObj.sign = sha1(secret + str.join('') + secret).toUpperCase()
return realObj
}
module.exports = {
...environment,
sign
}
\ No newline at end of file \ No newline at end of file
This diff is collapsed. Click to expand it.
import {
secretKey,
pathEnum,
domain,
index,
sign
} from './http.js'
import util from '../utils/util.js'
let INTERRUPT = false
/**接口 */
class Request {
get(params, returnAll = false) {
return this.request('GET', params, returnAll)
}
post(params, returnAll = false) {
return this.request('POST', params, returnAll)
}
reportTrack(params) {
return this.request('POST', params, true)
}
request(RequestMethods, params, returnAll) {
return new Promise((resolve, reject) => {
wx.showNavigationBarLoading()
let header = RequestMethods === 'POST' ? {
'content-type': 'application/x-www-form-urlencoded'
} : {}
let projectName = this.getRopProject(params.method)
if (!projectName) projectName = this.getRopProject(params.method)
const path = pathEnum[projectName]
params = this.getData(params)
wx.request({
url: `${domain}${path}router?method=${params.method}`,
data: params,
method: RequestMethods,
header,
dataType: 'json',
responseType: 'text',
success(response) {
/**业务代码 */
},
fail(error) {
wx.hideLoading()
console.error(`接口异常:`, error)
wx.showToast({
title: '系统异常',
icon: 'error'
})
reject(error)
},
complete() {
wx.stopPullDownRefresh()
wx.hideNavigationBarLoading()
}
})
})
}
getData(params) {
let projectName = params.projectName
if (!projectName) projectName = this.getRopProject(params.method)
else delete params.projectName
let appKey = '48e5e13229b82c1b4e6e8c96151f0637'
let secret = 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b'
if (secretKey[projectName]) {
appKey = secretKey[projectName].appKey
secret = secretKey[projectName].secret
}
const sessionId = util.getSessionId()
let noSignAttr = []
if (!params.sessionId && sessionId) params.sessionId = sessionId
if (params.noSignAttr) {
noSignAttr = params.noSignAttr
delete params.noSignAttr
}
params.v = '1.0.0'
params.format = 'json'
params.locale = 'zh_CN'
params.source = 'dj-wechat'
params.appKey = appKey
return sign(params, secret, noSignAttr)
}
getRopProject(method) {
const projectName = method.split('.')[2]
return projectName
}
}
export default new Request()
\ No newline at end of file \ No newline at end of file
function encodeUTF8(s) {
var i, r = [], c, x;
for (i = 0; i < s.length; i++)
if ((c = s.charCodeAt(i)) < 0x80) r.push(c);
else if (c < 0x800) r.push(0xC0 + (c >> 6 & 0x1F), 0x80 + (c & 0x3F));
else {
if ((x = c ^ 0xD800) >> 10 == 0) //对四字节UTF-16转换为Unicode
c = (x << 10) + (s.charCodeAt(++i) ^ 0xDC00) + 0x10000,
r.push(0xF0 + (c >> 18 & 0x7), 0x80 + (c >> 12 & 0x3F));
else r.push(0xE0 + (c >> 12 & 0xF));
r.push(0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
};
return r;
}
// 字符串加密成 hex 字符串
function sha1(s) {
var data = new Uint8Array(encodeUTF8(s))
var i, j, t;
var l = ((data.length + 8) >>> 6 << 4) + 16, s = new Uint8Array(l << 2);
s.set(new Uint8Array(data.buffer)), s = new Uint32Array(s.buffer);
for (t = new DataView(s.buffer), i = 0; i < l; i++)s[i] = t.getUint32(i << 2);
s[data.length >> 2] |= 0x80 << (24 - (data.length & 3) * 8);
s[l - 1] = data.length << 3;
var w = [], f = [
function () { return m[1] & m[2] | ~m[1] & m[3]; },
function () { return m[1] ^ m[2] ^ m[3]; },
function () { return m[1] & m[2] | m[1] & m[3] | m[2] & m[3]; },
function () { return m[1] ^ m[2] ^ m[3]; }
], rol = function (n, c) { return n << c | n >>> (32 - c); },
k = [1518500249, 1859775393, -1894007588, -899497514],
m = [1732584193, -271733879, null, null, -1009589776];
m[2] = ~m[0], m[3] = ~m[1];
for (i = 0; i < s.length; i += 16) {
var o = m.slice(0);
for (j = 0; j < 80; j++)
w[j] = j < 16 ? s[i + j] : rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1),
t = rol(m[0], 5) + f[j / 20 | 0]() + m[4] + w[j] + k[j / 20 | 0] | 0,
m[1] = rol(m[1], 30), m.pop(), m.unshift(t);
for (j = 0; j < 5; j++)m[j] = m[j] + o[j] | 0;
};
t = new DataView(new Uint32Array(m).buffer);
for (var i = 0; i < 5; i++)m[i] = t.getUint32(i << 2);
var hex = Array.prototype.map.call(new Uint8Array(new Uint32Array(m).buffer), function (e) {
return (e < 16 ? "0" : "") + e.toString(16);
}).join("");
return hex;
}
module.exports = sha1
//app.js
import router from './router/index.js'
import util from './utils/util.js'
App({
onLaunch: function () {
/**挂载到wx对象 */
wx.$util = util
wx.$router = router
},
globalData: {
}
})
\ No newline at end of file \ No newline at end of file
{
"pages": [
"pages/tab/index/index"
],
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "Weixin",
"navigationBarTextStyle": "black"
},
"usingComponents": {},
"sitemapLocation": "sitemap.json",
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序位置接口的效果展示"
}
},
"lazyCodeLoading": "requiredComponents"
}
\ No newline at end of file \ No newline at end of file
.box-center{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
// components/Authorize/Authorize.js
Component({
/**
* 组件的属性列表
*/
properties: {
scopeType: String,
checkSetting: {
type: Boolean,
value: false,
observer: function (newVal, oldVal) {
this.check()
}
}
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
/**
* 禁止滑动
*/
noScroll: wx.$util.noScroll(),
cancel() {
this.setData({
openSet: false
})
},
check() {
const _this = this
let {
scopeType
} = this.properties
let type = `scope.${scopeType}`
let buttonType = 'openSetting'
if (type === 'scope.userInfo') buttonType = 'getUserInfo'
this.setData({
buttonType
})
wx.getSetting({
success(res) {
if (!res.authSetting[type]) {
wx.authorize({
scope: type,
success() {
_this.triggerEvent('success',{
message:'授权成功'
})
},
fail() {
_this.setData({
openSet: true
})
}
})
} else {
_this.triggerEvent('success',{
message:'已授权'
})
}
}
})
}
}
})
\ No newline at end of file \ No newline at end of file
{
"component": true,
"usingComponents": {}
}
\ No newline at end of file \ No newline at end of file
<view class='open-seting-bg' wx:if='{{openSet}}' catchtap='cancel' catchtouchmove='noScroll'>
<view class='open-set-inner'>
<view class='set-title'>是否打开授权设置?</view>
<view class='btn-openset'>
<view catchtap='cancel' class='btn'>取消</view>
<view class='btn'>
确定
<button open-type='{{buttonType}}' class='button-style ' catchtap='cancel'></button>
</view>
</view>
</view>
</view>
\ No newline at end of file \ No newline at end of file
/* components/Authorize/Authorize.wxss */
.open-seting-bg {
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
background: rgba(0, 0, 0, 0.5);
z-index: 9999999999;
}
.open-set-inner {
width: 400rpx;
height: 220rpx;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background: #fff;
z-index: 9999999999;
}
.btn-openset {
display: flex;
font-size: 30rpx;
height: 100rpx;
}
.set-title {
font-size: 30rpx;
height: 120rpx;
display: flex;
align-items: center;
justify-content: center;
}
.btn{
flex: 1;
height: 100%;
position: relative;
display: flex;
align-items: center;
justify-content: center;
}
.button-style {
position: absolute;
width: 100%;
height: 100%;
box-sizing: border-box;
opacity: 0;
top: 0;
left: 0;
}
// components/Calendar/Calendar.js
import Calendar from './Calendar_Function'
import _component_ from './Static_Properties'
const CalendarFunction = Symbol('CalendarFunction')
Component({
/**
* 组件的属性列表
*/
properties: _component_.properties,
/**
* 组件的初始数据
*/
data: _component_.data,
/**
* 组件的方法列表
*/
methods: {
noScroll() {},
setCalenderBodyHeight() {
this[CalendarFunction].setCalenderBodyHeight()
},
showCalendar(e) {
let type = e && e.currentTarget && e.currentTarget.dataset.type || ''
let result = type === 'show'
if (!result) {
this.setData({
hideCalendar: true
})
setTimeout(() => {
this.setData({
show: result,
hideCalendar: false
})
}, 300)
} else {
this.setData({
show: result
})
if (!this.data.calenderBodyHeight) this[CalendarFunction].setCalenderBodyHeight()
}
},
dateChange(e) {
let {
current
} = e.detail
this.setData({
current
})
},
choose(e) {
let {
dateType,
minDate,
maxDate
} = this.data
let {
data
} = e.currentTarget.dataset
if ((minDate && Date.parse(minDate) > Date.parse(data)) || (maxDate && Date.parse(maxDate) < Date.parse(data))) return
this[CalendarFunction][dateType](e)
},
done() {
let {
dateType
} = this.data
this[CalendarFunction].done(dateType)
},
changeDate(e) {
let { value } = e.detail
this.setData({
current: value
})
},
showShortcutPicker() {
this.setData({
showShortcut: !this.data.showShortcut
})
},
chooseAll() {
this[CalendarFunction].chooseAll()
}
},
attached() {
this[CalendarFunction] = new Calendar(this)
}
})
\ No newline at end of file \ No newline at end of file
{
"component": true,
"usingComponents": {}
}
\ No newline at end of file \ No newline at end of file
<view class='calender-picker' bindtap="showCalendar" data-type='show'>
<slot></slot>
</view>
<!-- 弹框模式 -->
<view class='calender-box' hidden='{{!show}}' catchtouchmove="noScroll">
<view class='calender-bg' bindtap="showCalendar"></view>
<view class='calender-view {{hasRadius}} {{hideCalendar?"hideCalendar":""}} {{isFullSucreen&&!showConfirm?"isFullSucreen":""}}' style="height:{{height}}">
<view class='calender-header'>
<view class='calender-title' wx:if='{{showTitle}}'>
<block wx:if="{{rangeAll && dateType == 'range'}}">
<view class="calender-all" style="color:{{calenderColor}};" bindtap="chooseAll">全选</view>
</block>
{{title||'日期选择'}}
<view class='calender-close' bindtap="showCalendar">
<image src="../images/close.png" class='calender-close-image'></image>
</view>
</view>
<block wx:if='{{showSubTitle}}'>
<picker class='calender-subtitle' bindchange="changeDate" bindcancel='showShortcutPicker' value="{{current}}" range="{{dateList}}" wx:if='{{shortcut}}'>
<view class='calender-subtitle-text' bindtap="showShortcutPicker">
{{dateList[current]}}
<view class='arrow {{showShortcut}}'></view>
</view>
</picker>
<view class='calender-subtitle' wx:else>{{dateList[current]}}</view>
</block>
<view class='calendar-weekdays'>
<block wx:for='{{weekdays}}' wx:key='index'>
<view class='calendar-weekday'>{{item}}</view>
</block>
</view>
</view>
<view class='calender-body' style="height:calc(100% - {{calenderBodyHeight}})">
<swiper class='calender-swiper' bindchange='dateChange' current='{{current}}' vertical='{{vertical}}'>
<block wx:for='{{monthList}}' wx:key='index'>
<swiper-item>
<view class='calender-mark box-center' wx:if="{{!hideMark}}">{{item.mark}}</view>
<view class='calender-month'>
<block wx:for='{{item.data}}' wx:for-item='i' wx:for-index='ind' wx:key='ind'>
<view class='calender-day {{ind == 0?i.week:""}} {{i.active?"active":""}} {{i.disable?"disable":""}}' style="background:{{i.active?calenderColor:''}};color:{{i.middle?calenderColor:''}}" bindtap="choose" data-index='{{index}}' data-ind='{{ind}}' data-data='{{i.data}}'>
<view class='calender-middle' style="background:{{calenderColor}};" wx:if='{{i.middle}}'></view>
<view class='box-center text'>
{{i.day}}
<view wx:if='{{dateType==="range"}}' class='calender-tips'>
<view wx:if='{{i.start}}'>{{rangeText.start}}</view>
<view wx:if='{{i.end}}'>{{rangeText.end}}</view>
</view>
</view>
</view>
</block>
</view>
</swiper-item>
</block>
</swiper>
</view>
<view class='calender-footer {{isFullSucreen}}' wx:if='{{showConfirm}}'>
<view class='calender-btn {{dateType === "range" && !rangeDate.end ?"disable":""}} {{dateType === "multiple" && multipleDate.length < 1 ?"disable":""}}' style="background:{{calenderColor}}" bindtap="done">
{{confirmText||'确定'}}
</view>
</view>
</view>
</view>
\ No newline at end of file \ No newline at end of file
/* components/Calendar/Calendar.wxss */
.calender-box {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
z-index: 99;
}
.calender-bg {
position: absolute;
background: rgba(0, 0, 0, .5);
top: 0;
left: 0;
bottom: 0;
right: 0;
}
.calender-view {
position: absolute;
left: 0;
width: 100%;
background: #fff;
animation: show-calender .5s forwards;
color: #333;
}
.calender-view.true {
border-radius: 40rpx 40rpx 0 0;
}
.calender-view.isFullSucreen {
box-sizing: border-box;
padding-bottom: 34px !important;
}
@keyframes show-calender {
from {
bottom: -100%;
}
to {
bottom: 0;
}
}
.calender-view.hideCalendar {
animation: hide-calender .5s forwards;
}
@keyframes hide-calender {
from {
bottom: 0;
}
to {
bottom: -100%;
}
}
.calender-header {
box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.10);
}
.calender-title,
.calender-subtitle {
width: 100%;
height: 88rpx;
text-align: center;
position: relative;
font-size: 32rpx;
display: flex;
align-items: center;
justify-content: center;
}
.calender-all {
position: absolute;
top: 50%;
left: 24rpx;
transform: translateY(-50%);
font-size: 20rpx;
}
.calender-subtitle-text {
display: flex;
align-items: center;
justify-content: center;
}
.calender-subtitle {
font-size: 28rpx;
}
.calender-subtitle .arrow {
width: 14rpx;
height: 14rpx;
border-top: 2rpx solid transparent;
border-right: 2rpx solid #ccc;
border-bottom: 2rpx solid #ccc;
border-left: 2rpx solid transparent;
transform: rotate(45deg) translateY(-4rpx);
margin-left: 16rpx;
transition: all .3s;
}
.calender-subtitle .arrow.true {
transform: rotate(225deg) translateY(0) translateX(-4rpx);
}
.calender-close {
position: absolute;
width: 40rpx;
height: 40rpx;
top: 50%;
right: 24rpx;
transform: translateY(-50%);
display: flex;
align-items: center;
justify-content: center;
}
.calender-close-image {
width: 24rpx;
height: 24rpx;
}
.calendar-weekdays {
display: grid;
grid-template-columns: repeat(7, 1fr);
font-size: 24rpx;
line-height: 60rpx;
}
.calendar-weekday {
text-align: center;
}
.calender-body {
width: 100%;
padding: 20rpx 0;
box-sizing: border-box;
}
.calender-swiper {
height: 100%;
}
.calender-mark {
color: rgba(0, 0, 0, .1);
text-shadow: 0 4rpx 20rpx rgba(0, 0, 0, .1);
font-size: 320rpx;
width: 100%;
text-align: center;
}
.box-center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.calender-month {
height: 100%;
position: relative;
z-index: 1;
display: grid;
grid-template-rows: repeat(minmax(5, 6), 1fr);
grid-template-columns: repeat(7, 1fr);
}
.calender-day {
position: relative;
font-size: 32rpx;
display: flex;
}
.calender-day.active {
color: #fff;
border-radius: 8rpx;
}
.calender-day.disable {
opacity: .25;
}
.calender-day .calender-middle {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
opacity: 0.1;
}
.calender-day .text {
text-align: center;
width: 100%;
}
.calender-tips {
font-size: 14rpx;
}
.week-1 {
grid-column-start: 2;
}
.week-2 {
grid-column-start: 3;
}
.week-3 {
grid-column-start: 4;
}
.week-4 {
grid-column-start: 5;
}
.week-5 {
grid-column-start: 6;
}
.week-6 {
grid-column-start: 7;
}
.calender-footer {
position: absolute;
width: 100%;
left: 0;
bottom: 0;
padding: 14rpx 32rpx;
box-sizing: border-box;
}
.calender-footer.true {
padding-bottom: 34px !important;
}
.calender-footer .calender-btn {
width: 100%;
height: 72rpx;
font-size: 28rpx;
color: #fff;
border-radius: 999rpx;
display: flex;
justify-content: center;
align-items: center;
}
.calender-footer .calender-btn.disable {
opacity: .3;
}
\ No newline at end of file \ No newline at end of file
const _CalendarObject_ = Symbol('_CalendarObject_')
const _nowDate_ = Symbol('_nowDate_')
const _separator_ = Symbol('_separator_')
class Calendar {
[_CalendarObject_] = {};
[_nowDate_] = new Date();
[_separator_] = '-';
constructor(calendarObject) {
this[_CalendarObject_] = calendarObject
this[_separator_] = calendarObject.data.separator
this.setCalenderHeight()
this.setMonthList()
let {
weekdays,
firstDayOfWeek
} = calendarObject.data
let firstDay = weekdays[firstDayOfWeek - 1]
let [last, first] = weekdays.join('').split(firstDay)
calendarObject.setData({
weekdays: [firstDay, ...first, ...last]
})
}
/**设置日历高度 */
setCalenderHeight() {
let _this = this[_CalendarObject_]
let {
data: calenderHeight
} = _this
let height = '80%'
if (typeof calenderHeight === 'number') {
wx.$util.getPhoneInfo(res => {
let {
windowHeight
} = res
if (calenderHeight > windowHeight) calenderHeight = windowHeight
if (calenderHeight < windowHeight * 0.5) calenderHeight = windowHeight * 0.5
height = `${calenderHeight}px`
})
}
if (typeof calenderHeight === 'string') {
if (calenderHeight.includes('%')) {
height = calenderHeight
let [num] = calenderHeight.split('%')
if (num < 50) height = '50%'
if (num > 100) height = '80%'
} else {
if (calenderHeight < 50) calenderHeight = '50'
if (calenderHeight > 100) calenderHeight = '80'
height = `${calenderHeight}%`
}
}
_this.setData({
isFullSucreen: wx.$util.isFullSucreen(),
height
})
}
/**设置日期高度 */
setCalenderBodyHeight() {
let _this = this[_CalendarObject_]
wx.$util.getViewInfo('.calender-header', header => {
wx.$util.getViewInfo('.calender-footer', footer => {
let headerHeight = header.height
let footerHeight = footer && footer.height || 0
_this.setData({
calenderBodyHeight: `${headerHeight + footerHeight}px`
})
}, _this)
}, _this)
}
/**设置日期列表 */
setMonthList() {
let {
separator,
previous,
minDate,
maxDate,
next
} = this[_CalendarObject_].data
if (maxDate || minDate) {
if (!minDate) {
let nowMonth = new Date().getMonth()
minDate = new Date(new Date().setMonth(nowMonth - previous)).format(`yyyy${separator}MM${separator}dd`)
}
if (!maxDate) {
maxDate = this[_nowDate_].format(`yyyy${separator}MM${separator}dd`)
}
previous = this.getMonthDifference(minDate, this[_nowDate_].format(`yyyy${separator}MM${separator}dd`))
next = this.getMonthDifference(this[_nowDate_].format(`yyyy${separator}MM${separator}dd`), maxDate)
} else {
previous = previous < 0 ? 0 : previous
next = next < 0 ? 0 : next
}
let nowMonth = this[_nowDate_].getMonth()
let now = new Date().setDate(1)
for (let i = nowMonth - previous; i <= nowMonth + next; i++) {
this.init(new Date(now).setMonth(i))
}
}
/**初始化日期 */
init(date) {
let _this = this[_CalendarObject_]
let {
firstDayOfWeek,
allowSameDay,
multipleDate,
monthList,
rangeDate,
dateList,
dateType,
current,
minDate,
maxDate,
value,
} = _this.data
let separator = this[_separator_]
let [year, month] = new Date(date).format(`yyyy${separator}MM`).split(separator)
let days = this.getDayNumber(year, Number(month))
let week = new Date(year, Number(month) - 1, 1).getDay()
let dateFormat = `yyyy${separator}MM${separator}dd`
let today = value || this[_nowDate_].format(dateFormat)
let nextDay = ''
let arr = []
dateList.push(`${year}${separator}${month}`)
if (dateType === 'range') {
nextDay = new Date(new Date().setDate(new Date(new Date(today)).getDate() + 1)).format(dateFormat)
}
let [now_year, now_month, now_day] = today.split(separator)
let [next_year, next_month, next_day] = allowSameDay ? today.split(separator) : nextDay.split(separator)
for (let i = 1; i <= days; i++) {
let todayStr = `${year}${separator}${month}${separator}${now_day}`
let dayStr = `${year}${separator}${month}${separator}${i < 10 ? `0${i}`:i}`
let obj = {
day: i,
data: dayStr,
active: now_year == year && now_month == month && i == Number(now_day)
}
if ((minDate && Date.parse(minDate) > Date.parse(dayStr)) || (maxDate && Date.parse(maxDate) < Date.parse(dayStr))) obj.disable = true
if (dateType === 'multiple') multipleDate.push(todayStr)
if (nextDay) {
if (now_year == year && now_month == month && i == Number(now_day)) {
obj.start = true
rangeDate.start = todayStr
}
if (next_year == year && next_month == month && i == Number(next_day)) {
obj.active = true
obj.end = true
rangeDate.end = `${year}${separator}${next_month}${separator}${next_day}`
}
}
firstDayOfWeek = firstDayOfWeek == 7 ? 0 : firstDayOfWeek
if (i === 1) obj.week = `week-${week - firstDayOfWeek}`
arr.push(obj)
}
monthList.push({
data: arr,
mark: Number(month)
})
if (current <= 1) {
let [nowYear, nowMonth] = today.split(separator)
current = dateList.findIndex(e => e === `${nowYear}${separator}${nowMonth}`)
}
_this.setData({
multipleDate,
date: today,
rangeDate,
monthList,
dateList,
current
})
}
/**当设置最小日期或者最大日期时 自动设置前后月份 */
getMonthDifference(date1, date2) {
let separator = this[_separator_]
//获取年,月数
let [year1, month1] = date1.split(separator)
let [year2, month2] = date2.split(separator)
let months = (parseInt(year2) - parseInt(year1)) * 12 + (parseInt(month2) - parseInt(month1))
return months
}
/**单选 */
single(e) {
let _this = this[_CalendarObject_]
let {
index,
data,
ind
} = e.currentTarget.dataset
let {
showConfirm,
monthList
} = _this.data
monthList.map(x => {
x.data.map(i => i.active = false)
})
monthList[index].data[ind].active = true
_this.setData({
monthList,
date: data
})
if (!showConfirm) this.done()
}
/**多选 */
multiple(e) {
let _this = this[_CalendarObject_]
let {
index,
ind,
} = e.currentTarget.dataset
let {
monthList
} = _this.data
let arr = []
monthList[index].data[ind].active = !monthList[index].data[ind].active
monthList.map(x => x.data.map(i => {
if (i.active) arr.push(i.data)
}))
_this.setData({
[`monthList[${index}].data`]: monthList[index].data,
multipleDate: arr
})
}
/**范围选择 */
range(e) {
const _this = this[_CalendarObject_]
let {
index,
data,
ind
} = e.currentTarget.dataset
let {
allowSameDay,
showConfirm,
monthList,
rangeDate
} = _this.data
const start = Date.parse(rangeDate.start)
if (rangeDate.end || start > Date.parse(data)) {
monthList = this.clearStatus({
monthList,
index,
ind
})
rangeDate.start = data
rangeDate.end = ''
} else {
if (!allowSameDay && Date.parse(data) == Date.parse(rangeDate.start)) return
monthList[index].data[ind].active = true
monthList[index].data[ind].end = true
rangeDate.end = data
monthList.map(x => {
x.data.map(i => {
let day = Date.parse(i.data)
i.middle = day > start && day < Date.parse(data)
})
})
}
_this.setData({
monthList,
rangeDate
})
if (!showConfirm && rangeDate.end) this.done()
}
/**点击完成 */
done() {
let _this = this[_CalendarObject_]
let {
multipleDate,
rangeDate,
dateType,
date
} = _this.data
let targer = {
'single': date,
'multiple': multipleDate,
'range': rangeDate
}
if ((dateType === 'multiple' && multipleDate.length < 1) || (dateType === 'range' && !rangeDate.end)) return
_this.triggerEvent('select', {
date: targer[dateType]
})
_this.showCalendar()
}
/**清空范围选择状态 */
clearStatus(params) {
let {
monthList,
index,
ind
} = params
monthList.map(x => x.data.map(i => {
i.active = false
i.start = false
i.end = false
i.middle = false
}))
monthList[index].data[ind].active = true
monthList[index].data[ind].start = true
return monthList
}
/**
* 获取月份天数
*/
getDayNumber(year, month) {
let days = 31
switch (month) {
case 2:
days = (year % 4 == 0 && year % 100 !== 0) || year % 400 == 0 ? 29 : 28
break;
case 4:
case 6:
case 9:
case 11:
days = 30
break;
}
return days
}
/**日期范围 点击全选 */
chooseAll() {
let _this = this[_CalendarObject_]
let {
monthList,
minDate,
maxDate
} = _this.data
monthList.map((e, index) => {
e.data.map((i, ind) => {
let obj = {
currentTarget: {
dataset: {
index,
ind,
data: i.data
}
}
}
if (i.data == minDate) this.range(obj)
if(i.data == maxDate) this.range(obj)
})
})
}
}
export default Calendar
\ No newline at end of file \ No newline at end of file
export default {
properties: {
calenderHeight: {
type: [String, Number]
},
title: String, // 标题名称
hasRadius: {
type: Boolean,
value: true
}, // 是否圆角
showTitle: {
type: Boolean,
value: true
}, // 是否显示标题
showSubTitle: {
type: Boolean,
value: true
}, // 是否显示副标题
confirmText: String, // 确定按钮文本
showConfirm: {
type: Boolean,
value: true
}, // 是否显示确定按钮
calenderColor: {
type: String,
value: '#00A479'
}, // 日历主题色
previous: {
type: Number,
value: 3
}, // 当前月的前几个月 ,默认3个月
next: {
type: Number,
value: 3
}, // 当前月的后几个月 , 默认3个月
vertical: Boolean, //是否纵向滑动
/** 选择类型默认单选,single单选, multiple多个日期,range日期范围 */
dateType: {
type: String,
value: 'single'
},
value: String, //单选绑定数据
shortcut: Boolean, //日期快捷切换 默认为false
/** 分隔符,默认为 "-" */
separator: {
type: String,
value: '-'
},
/** 日期范围-开始结束文本 */
rangeText: {
type: Object,
value: {
start: '开始',
end: '结束'
}
},
/**是否显示日期范围 全选 */
rangeAll: Boolean,
/** 是否允许日期范围的起止时间为同一天, 默认为false */
allowSameDay: Boolean,
/** 周起始日,默认周日 */
firstDayOfWeek: {
type: [Number, String],
value: 7
},
/**
* 可选最小日期,不传则默认无限制。
* 格式yyyy-MM-dd, 需跟separator一致。 */
minDate: String,
/** 可选最大日期,不传则默认无限制。
* 格式yyyy-MM-dd, 需跟separator一致 */
maxDate: String,
/**隐藏水印 */
hideMark: Boolean
},
data: {
weekdays: ['一', '二', '三', '四', '五', '六', '日'],
monthList: [],
dateList: [],
current: 0,
height: '80%',
rangeDate: {},
multipleDate: []
}
}
\ No newline at end of file \ No newline at end of file
// components/GlCell/GlCell.js
Component({
/**
* 组件的属性列表
*/
properties: {
label:String,
labelWidth:String,
border:Boolean,
haveArrow:Boolean,
value:String,
valueAlign:String,
required:Boolean
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
click(e){
this.triggerEvent('click')
}
}
})
{
"component": true,
"usingComponents": {}
}
\ No newline at end of file \ No newline at end of file
<view class='cell-box'>
<view class='cell {{border?"border":""}}' bindtap="click">
<view class='cell-label' style="width:{{labelWidth}}">
<text wx:if='{{required}}' class='required'>*</text>{{label||'标题'}}
</view>
<view class='cell-value ' style="width:calc(100% - {{labelWidth}});">
<view class='value {{valueAlign}} {{haveArrow}}'>
<view class='slot'><slot></slot></view>
<view class='details'>{{value}}</view>
</view>
<image wx:if='{{haveArrow}}' class='arrow' src="../images/arrow-x.png"></image>
</view>
</view>
</view>
\ No newline at end of file \ No newline at end of file
/* components/GlCell/GlCell.wxss */
.cell-box {
background: #fff;
font-size: 28rpx;
color: #333333;
padding-left: 40rpx;
box-sizing: border-box;
}
.cell {
width: 100%;
height: 90rpx;
box-sizing: border-box;
display: flex;
align-items: center;
}
.cell.border {
border-bottom: 2rpx solid #eee;
}
.cell-label {
width: 25%;
}
.cell-value {
width: 75%;
position: relative;
height: 100%;
}
.cell-value .false {
padding-right: 40rpx !important;
}
.value {
width: 100%;
height: 100%;
display: flex;
align-items: center;
padding-right: 70rpx;
box-sizing: border-box;
}
.required{
color: #f00;
}
.details{
display: none;
}
.slot:empty + .details{
display: block;
}
.cell-value .right {
justify-content: flex-end;
height: 100%;
box-sizing: border-box;
}
.slot{
width: 100%;
}
.slot:empty{
display: none;
}
.arrow {
position: absolute;
right: 40rpx;
top: 50%;
transform: translateY(-50%);
width: 28rpx;
height: 26rpx;
}
// components/glTextarea/glTextarea.js
Component({
/**
* 组件的属性列表
*/
properties: {
maxlength: {
type: Number,
value: -1
},
placeholder: String,
showWordLimit: Boolean,
disabled: Boolean,
value: String,
filterEmoji:{
type:Boolean,
value:true
}
},
/**
* 组件的初始数据
*/
data: {
edit: true,
value: null
},
/**
* 组件的方法列表
*/
methods: {
/**
* 打开文本编辑器
*/
openTextarea() {
if (this.data.disabled) return
this.setData({
edit: false,
textareaFocus: true
})
},
setValue(value) {
if(this.properties.filterEmoji) {
if (wx.$util.haveEmoji(value)) value = wx.$util.replaceEmoji(value)
}
this.setData({
value
})
},
textareaInput(e) {
let {
value
} = e.detail
this.setValue(value)
this.triggerEvent('input', {
value
})
},
textareaBlur(e) {
let {
value
} = e.detail
this.setData({
edit: true
})
this.setValue(value)
this.triggerEvent('blur', {
value
})
},
}
})
\ No newline at end of file \ No newline at end of file
{
"component": true,
"usingComponents": {}
}
\ No newline at end of file \ No newline at end of file
<view class='textarea-box {{maxlength>0&&showWordLimit?"showWordLimit":""}}'>
<block wx:if='{{edit}}'>
<text class='textarea' bindtap="openTextarea" style="color:{{value?'#333':'#999'}}">{{value||placeholder||'请输入'}}</text>
</block>
<block wx:else>
<textarea class='_textarea_' maxlength="{{maxlength}}" value='{{value}}' bindinput='textareaInput' focus='{{textareaFocus}}' bindblur='textareaBlur' bindconfirm='textareaBlur' ></textarea>
</block>
<block wx:if='{{maxlength>0&&showWordLimit}}'>
<view class='wordLimit'>
{{value.length||0}} / {{maxlength}}
</view>
</block>
</view>
\ No newline at end of file \ No newline at end of file
/* components/glTextarea/glTextarea.wxss */
.textarea-box {
width: 100%;
height: 100%;
position: relative;
}
.textarea-box .textarea {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow-y: scroll;
}
._textarea_ {
width: 100%;
height: calc(100% - 40rpx);
}
.textarea-box.showWordLimit .textarea {
height: calc(100% - 40rpx);
}
.wordLimit {
position: absolute;
bottom: 0;
right: 0;
color: #999;
}
// components/share/share.js
import Draw_Function from './draw_function'
Component({
/**
* 组件的属性列表
*/
properties: {
show: {
type: Boolean,
value: false,
observer: function (newVal, oldVal) {
let {
wxShare
} = this.data
this.check(newVal)
if (!wxShare) {
this.setData({
_show: true
})
}
}
},
toast: {
type: String,
value: '生成中...'
},
canvasObject: Object,
hideCancel: Boolean,
diyDraw: Boolean,
hideWx: Boolean,
wxShare: Boolean
},
ready() {
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
/**
* 检查
*/
check(bool) {
if (bool) {
if (this.data.tempFilePath) return
this.getImgData(res => {
this.draw(res)
})
}
},
/**
* 禁止滑动
*/
noScroll: wx.$util.noScroll(),
/**
* 取消
*/
cancel() {
this.setData({
_show: false
})
},
saveImg() {
let _this = this
wx.saveImageToPhotosAlbum({
filePath: _this.data.tempFilePath,
success(e) {
wx.$util.showToast('保存成功')
_this.triggerEvent('callBack')
}
})
},
/**保存 */
save() {
this.saveImg()
wx.nextTick(() => this.cancel())
},
/**
* 检查
*/
checkSetting() {
this.setData({
settingStatus: !this.data.settingStatus
})
},
/**
* 开始生成
*/
draw(images) {
const {
canvasObject,
wxShare
} = this.__data__
let {
height,
width
} = canvasObject
width = width || 300
height = height || 150
wx.$util.getPhoneInfo(phoneInfo => {
wx.$util.getViewInfo('.choose-list', listInfo => {
wx.$util.getViewInfo('.bg', bgInfo => {
let {
windowWidth
} = phoneInfo
let pixelRatio = windowWidth / 750
let viewTop = !wxShare ? (bgInfo.height - listInfo.height - height * pixelRatio) / 2 : 0
this.setData({
canvasStyle: `width:${width * pixelRatio}px;height:${height * pixelRatio}px;top:${viewTop}px;`,
previewStyle: `width:${width * pixelRatio}px;height:${width * pixelRatio * 0.8}px;`,
pixelRatio,
viewTop,
height,
width
})
this.ctx = wx.createCanvasContext('canvasImg', this)
this.ctx.clearRect(0, 0, width, height)
this.draw_canvas({
canvasObject,
images,
width,
height
}, canvas => {
canvas.draw(false, setTimeout(() => {
this.getCanvasImg()
}, 500))
})
})
}, this)
}, this)
},
/**画布 */
draw_canvas(params, callBack) {
const {
canvasObject,
images,
height,
width
} = params
const {
backgroundColor,
textList,
lines
} = canvasObject
const draw_function = new Draw_Function(this)
this.ctx.setFillStyle(backgroundColor || '#fff')
this.ctx.fillRect(0, 0, width, height)
this.ctx.save()
if (this.__data__.diyDraw) {
this.triggerEvent('draw', {
ctx: this.ctx,
canvasObject,
callBack,
height,
images,
width
})
} else {
images && images.length > 0 && (images.map(e => {
draw_function.drawImages(e)
}))
textList && textList.length > 0 && (textList.map(e => {
e.width = canvasObject.width
draw_function.drawText(e)
}))
lines && lines.length > 0 && (lines.map(e => {
draw_function.drawLine(e)
}))
callBack(this.ctx)
}
},
/**
* 画布生成图片
*/
getCanvasImg() {
let _this = this
let {
pixelRatio,
wxShare,
height,
width
} = _this.data
wx.canvasToTempFilePath({
canvasId: 'canvasImg',
width: width * pixelRatio,
height: height * pixelRatio,
fileType: 'jpg',
quality: 1,
x: 0,
y: 0,
success(res) {
console.log(res)
let {
tempFilePath
} = res
if (wxShare) {
wx.hideLoading()
_this.checkSetting()
wx.showShareImageMenu({
path: tempFilePath,
success(res) {
console.log(res)
}
})
} else {
setTimeout(() => {
_this.createPreviewImg({
tempFilePath,
width
})
}, 300)
}
},
fail(err) {
console.error(err)
wx.hideLoading()
}
}, this)
},
/**生成预览图 */
createPreviewImg(params) {
const p_ctx = wx.createCanvasContext('preview', this)
let {
tempFilePath,
width
} = params
p_ctx.drawImage(tempFilePath, 0, 0, width, width * 0.8)
let _this = this
p_ctx.draw(false, setTimeout(() => {
wx.canvasToTempFilePath({
height: width * 1.6,
width: width * 2,
canvasId: 'preview',
fileType: 'jpg',
quality: 1,
x: 0,
y: 0,
success(preview) {
console.log(preview)
_this.setData({
tempFilePath
})
_this.triggerEvent('init', {
previewImg: preview.tempFilePath,
tempFilePath
})
wx.hideLoading()
},
fail(err) {
console.error(err)
wx.hideLoading()
}
}, this)
}, 500))
},
/**
* 批量转换图片
*/
getImgData(callBack) {
let _this = this
let {
canvasObject,
toast,
} = this.__data__
let {
imgList
} = canvasObject
wx.showLoading({
title: toast,
mask: true,
success() {
if (imgList.length > 0) {
_this.createLocalImg(imgList, 0, res => {
callBack(res)
})
} else {
callBack()
}
}
})
},
/**网络图片转成本地资源 */
createLocalImg(imgList, index = 0, callBack) {
if (index === imgList.length) return callBack(imgList)
wx.$util.promise(resolve => {
wx.getImageInfo({
src: imgList[index].url,
success(res) {
imgList[index].url = res.path
resolve()
},
fail() {
wx.$util.showToast('图片生成失败,请稍后再试')
wx.hideLoading()
console.error(`索引为:${index}的图片转换本地失败,${JSON.stringify(imgList[index].url)}`)
}
})
}).then(() => {
this.createLocalImg(imgList, index + 1, callBack)
})
}
}
})
\ No newline at end of file \ No newline at end of file
{
"component": true,
"usingComponents": {}
}
\ No newline at end of file \ No newline at end of file
<view class='share-box' catchtouchmove='noScroll' wx:if='{{_show}}'>
<view class='bg' bindtap='cancel'></view>
<view class='info {{flag?"flag":""}}' style="top:{{viewTop}}px;" hidden="{{canvasObject.showCanvas}}">
<slot></slot>
</view>
<view class='choose-list' style="height:{{hideCancel?'auto':'298rpx'}}">
<view class='list'>
<view class='list-btn' wx:if='{{!hideWx}}'>
<image src='../images/wx.png' class='image'></image>
<view>微信好友</view>
<button open-type='share' bindtap='cancel' class='button'></button>
</view>
<view class='list-btn' bindtap='checkSetting'>
<image src='../images/share.png' class='image'></image>
<view>保存分享</view>
</view>
</view>
<view wx:if='{{!hideCancel}}' class='cancel' bindtap='cancel'>取消</view>
</view>
</view>
<view class='canvas {{wxShare?"":"showCanvas"}}' style="{{canvasStyle}}">
<canvas canvas-id='canvasImg' style='width:100%;height:100%;'></canvas>
</view>
<view class='preview' style="{{previewStyle}}">
<canvas canvas-id="preview" style='width:100%;height:100%;'></canvas>
</view>
<authorize scopeType='writePhotosAlbum' checkSetting='{{settingStatus}}' bindsuccess='save'></authorize>
\ No newline at end of file \ No newline at end of file
.text-hide {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.share-box {
position: fixed;
z-index: 999999;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
}
.share-box .info {
width: auto;
height: auto;
position: absolute;
left: 1000%;
transform: translateX(-50%);
overflow: hidden;
}
.share-box .info.flag{
left: 50%;
animation: showInfo .5s forwards;
}
@keyframes showInfo{
0%{
opacity: 0;
}
100%{
opacity: 1;
}
}
.share-box .bg {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
background: rgba(0, 0, 0, 0.5);
}
.choose-list {
width: 100%;
position: absolute;
left: 0;
background: #f6f6f6;
animation: showChoose .4s forwards;
}
@keyframes showChoose{
0%{
bottom: -100%;
}
100%{
bottom: 0%;
}
}
.choose-list .cancel {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 96rpx;
line-height: 96rpx;
text-align: center;
font-size: 28rpx;
color: #333;
background: #fff;
}
.list {
width: 100%;
height: 182rpx;
background: #fff;
display: flex;
}
.list-btn {
flex: 1;
text-align: center;
font-size: 24rpx;
color: #333;
padding-top: 40rpx;
position: relative;
}
.list-btn .image {
width: 60rpx;
height: 60rpx;
margin-bottom: 10rpx;
}
.list-btn .button {
width: 100%;
height: 100%;
position: absolute;
opacity: 0;
top: 0;
left: 0;
}
.canvas {
position: fixed;
top: -1000%;
left: -1000%;
animation: canvasShow .5s forwards;
}
.preview{
position: fixed;
top: 1000%;
left: 1000%;
z-index: 999999999;
}
@keyframes canvasShow{
0%{
opacity: 0;
}
100%{
opacity: 1;
}
}
.showCanvas{
left: 50%;
transform: translateX(-50%);
z-index: 99999999999;
}
\ No newline at end of file \ No newline at end of file
const _ctx_ = Symbol('_ctx_')
const _pixelRatio_ = Symbol('_pixelRatio_')
class Draw_Function {
[_ctx_] = null;
[_pixelRatio_] = null;
constructor(_this_) {
this[_ctx_] = _this_.ctx
this[_pixelRatio_] = _this_.data.pixelRatio || 2
}
drawImages(imageParams) {
this[_ctx_].beginPath()
this[_ctx_].save()
let {
borderRadius,
height,
width,
url,
x,
y,
} = imageParams
height = this.toRpx(height)
width = this.toRpx(width)
x = this.toRpx(x)
y = this.toRpx(y)
if (borderRadius) {
this.drawRadiusRect({
borderRadius,
height,
width,
x,
y,
})
this[_ctx_].clip()
}
this[_ctx_].drawImage(url, x, y, width, height)
this[_ctx_].restore()
}
toRpx(val) {
return this[_pixelRatio_] * val
}
getTextWidth(text, fontSize) {
if (fontSize) this[_ctx_].setFontSize(fontSize)
return this[_ctx_].measureText(text).width
}
drawFill(x, y, width, height, color) {
this[_ctx_].beginPath()
this[_ctx_].setFillStyle(color || '#000')
this[_ctx_].fillRect(x, y, width, height)
this[_ctx_].stroke()
this[_ctx_].restore()
this[_ctx_].save()
}
drawText(textParams) {
let {
textDecoration,
textBaseline,
lineHeight,
fontWeight,
textAlign,
textWidth,
maxWidth,
fontSize,
opacity,
lineNum,
width,
color,
text,
x,
y,
} = textParams
let text_width = this.getTextWidth(text)
textAlign = textAlign || 'left'
textBaseline = textBaseline || 'normal'
opacity = typeof opacity === 'number' ? opacity : 1
lineHeight = this.toRpx(lineHeight || fontSize || 12)
textWidth = this.toRpx(textWidth || 0)
fontSize = this.toRpx(fontSize || 12)
maxWidth = this.toRpx(maxWidth || width)
width = this.toRpx(width)
x = this.toRpx(x)
y = this.toRpx(y)
let fontX = this.getFontWidth({
textAlign,
fontSize,
text,
x,
})
if (textParams.border) {
let boxX = this.toRpx(textParams.x - 4.5),
boxY = this.toRpx(textParams.y - 0.5),
boxWidth = text_width + this.toRpx(9),
boxHeight = lineHeight + this.toRpx(4)
if (boxWidth > width - fontX - this.getTextWidth('…') - fontSize) {
boxWidth = width - boxX + this.toRpx(9)
}
this.drawFill(boxX, boxY, boxWidth, boxHeight, textParams.border)
}
if (textParams.background) {
let boxX = this.toRpx(textParams.x - 4),
boxY = this.toRpx(textParams.y),
boxWidth = text_width + this.toRpx(8),
boxHeight = lineHeight + this.toRpx(3)
if (boxWidth > width - fontX - this.getTextWidth('…') - fontSize) {
boxWidth = width - boxX + this.toRpx(8)
}
this.drawFill(boxX, boxY, boxWidth, boxHeight, textParams.background)
}
this[_ctx_].beginPath()
this[_ctx_].setGlobalAlpha(opacity)
this[_ctx_].setFontSize(fontSize)
this[_ctx_].setFillStyle(color || '#000')
this[_ctx_].setStrokeStyle(color || '#000')
this[_ctx_].setTextBaseline(textBaseline)
this[_ctx_].setTextAlign(textAlign)
this[_ctx_].setLineWidth(this.toRpx(2))
const drawOneLineText = () => {
let textArr = text.split(''),
newText = '',
ellipsis = false
try {
textArr.map(e => {
newText += e
if (this.getTextWidth(newText) > width - fontX) throw true
})
} catch (error) {
ellipsis = error
}
if (ellipsis) newText += '…'
if (lastFont) newText += lastFont
this[_ctx_].fillText(newText, x, y, maxWidth)
if (checkFontWeight(fontWeight)) this[_ctx_].strokeText(newText, x, textHeight, maxWidth)
if (checkTextDecoration(textDecoration)) {
this.drawDecoration({
textDecoration,
textBaseline,
textAlign,
fontSize,
newText,
opacity,
text,
y,
x
})
}
}
if (lineNum > 1) {
let textArr = text.split(''),
textRowArr = [],
currentText = '',
viewWidth = width - fontX
if (text_width > viewWidth) {
textArr.map(e => {
currentText += e
if (this.getTextWidth(currentText) >= viewWidth && textRowArr.length < lineNum - 1) {
textRowArr.push(currentText)
currentText = ''
}
})
if (currentText.length) textRowArr.push(currentText)
textRowArr.map((e, index) => {
if (this.getTextWidth(e) > viewWidth && index == lineNum - 1) {
try {
let lastText = '',
lastArr = e.split('')
lastArr.map(i => {
lastText += i
if (this.getTextWidth(lastText) > width - fontX - this.getTextWidth('…')) throw lastText
})
} catch (error) {
if (lastFont) e = `${error.substring(0, error.length - lastFont.length)}…${lastFont}`
else e = `${error}…`
}
}
if (lastFont && e.indexOf(lastFont) == -1 && textRowArr.length < 2) e = `${e.substring(0, e.length - lastFont.length)}…${lastFont}`
let textHeight = y + index * (lineHeight || fontSize)
this[_ctx_].fillText(e, x, textHeight, maxWidth)
if (checkFontWeight(fontWeight)) this[_ctx_].strokeText(newText, x, textHeight, maxWidth)
if (checkTextDecoration(textDecoration)) {
this.drawDecoration({
y: textHeight,
textDecoration,
textBaseline,
textAlign,
fontSize,
newText: e,
opacity,
text,
x
})
}
})
} else {
drawOneLineText()
}
} else {
drawOneLineText()
}
this[_ctx_].stroke()
}
drawLine(lineParams) {
this[_ctx_].beginPath()
let {
opacity,
startX,
startY,
width,
color,
endX,
endY,
} = lineParams
startX = this.toRpx(startX)
startY = this.toRpx(startY)
width = this.toRpx(width)
endX = this.toRpx(endX)
endY = this.toRpx(endY)
this[_ctx_].setGlobalAlpha(typeof opacity === 'number' ? opacity : 1)
this[_ctx_].setStrokeStyle(color || '#000')
this[_ctx_].setLineWidth(width || this.toRpx(1))
this[_ctx_].moveTo(startX, startY)
this[_ctx_].lineTo(endX, endY)
this[_ctx_].stroke()
this[_ctx_].restore()
this[_ctx_].save()
}
setLineY = params => {
let {
textDecoration,
textBaseline,
fontSize,
y
} = params
let type = {
'underline': {
'top': y + fontSize,
'middle': y + fontSize / 2,
'bottom': y,
'normal': y,
},
'overline': {
'top': y,
'middle': y - fontSize / 2,
'bottom': y - fontSize,
'normal': y,
},
'line-through': {
'top': y + fontSize / 2,
'middle': y - fontSize / 2,
'bottom': y,
'normal': y,
}
}
return type[textDecoration][textBaseline]
}
setLineX(params) {
let {
textAlign,
text,
x
} = params
let textWidth = this[_ctx_].measureText(text).width
let type = {
'left': x,
'center': x - textWidth / 2,
'right': x - textWidth
}
return type[textAlign]
}
drawRadiusRect(params) {
let {
borderRadius,
height,
width,
x,
y,
} = params
let radius = typeof borderRadius === 'string' ? (Number(borderRadius.split('%')[0]) / 100 * width) / 2 : borderRadius / 2
radius = radius || 0
this[_ctx_].beginPath()
for (let i = 1; i < 5; i++) {
let arcX = i === 1 || i === 4 ? x + width - radius : x + radius
let arcY = i === 1 || i === 2 ? y + height - radius : y + radius
this[_ctx_].arc(arcX, arcY, radius, 2 * Math.PI * ((i - 1) / 4), 2 * Math.PI * (i / 4))
}
}
getFontWidth(params) {
let {
textAlign,
fontSize,
text,
x
} = params
let type = {
'left': x,
'center': x - fontSize * text.length / 2,
'right': x - fontSize * text.length
}
return type[textAlign] < 0 ? 0 : type[textAlign]
}
drawDecoration(params) {
let {
newText,
opacity,
y,
x
} = params
let lineX = x
let lineY = y
lineX = this.setLineX(params)
lineY = this.setLineY(params)
this[_ctx_].setGlobalAlpha(opacity)
this[_ctx_].moveTo(lineX, lineY)
this[_ctx_].lineTo(lineX + this[_ctx_].measureText(newText).width, lineY)
}
}
const checkFontWeight = (fontWeight = '0') => {
return (fontWeight && (typeof fontWeight === 'string' || typeof fontWeight === 'number') && (fontWeight == 'bold' || fontWeight >= 700))
}
const checkTextDecoration = textDecoration => {
return (textDecoration && (textDecoration === 'underline' || textDecoration === 'overline' || textDecoration === 'line-through'))
}
export default Draw_Function
\ No newline at end of file \ No newline at end of file
Component({
/**
* 组件的属性列表
*/
properties: {
tabList: {
type: Array,
value: []
},
height: {
type: String,
value: '100vh'
},
tagIndex: {
type: Number,
value: 0,
observer: function (n, o) {
this.setData({
count: n
})
}
},
key: {
type: String,
value: 'name'
},
showClickLoading:Boolean
},
/**
* 组件的初始数据
*/
data: {
count: 0,
scrollTop: 0
},
/**
* 组件的方法列表
*/
methods: {
click(e) {
let {
item,
index
} = e.currentTarget.dataset
if(this.data.count === index) return
if(this.properties.showClickLoading) wx.$util.showLoading('')
item.index = index
this.setData({
count: index,
scrollTop: 0
})
this.triggerEvent('click', item)
wx.nextTick(()=>{
wx.hideLoading()
})
},
tabScrollTolower(e) {
this.triggerEvent('tabScrollTolower')
},
viewScrollTolower(e) {
this.triggerEvent('viewScrollTolower')
}
},
ready() {
}
})
\ No newline at end of file \ No newline at end of file
{
"component": true,
"usingComponents": {}
}
\ No newline at end of file \ No newline at end of file
<view class='tab-box' id='tabView' style="height:{{height}}">
<scroll-view style="height:100%;" scroll-y class='tab' bindscrolltolower='tabScrollTolower'>
<view>
<block wx:for='{{tabList}}' wx:key='index'>
<view class='tab-item {{count==index?"active":""}}' bindtap="click" data-item='{{item}}' data-index='{{index}}'>{{item[key]}}</view>
</block>
</view>
</scroll-view>
<view class='view'>
<scroll-view style="height:100%" scroll-y scroll-top='{{scrollTop}}' bindscrolltolower='viewScrollTolower'>
<slot></slot>
</scroll-view>
</view>
</view>
\ No newline at end of file \ No newline at end of file
/* components/tabView/tabView.wxss */
.tab {
float: left;
width: 26.67%;
box-sizing: border-box;
text-align: center;
background: #f4f4f4;
}
.view {
float: left;
width: 73.33%;
height: 100%;
position: relative;
}
.tab-item {
width: 100%;
height: 96rpx;
line-height: 96rpx;
font-size: 24rpx;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
color: #333;
box-sizing: border-box;
padding: 0 10rpx;
}
.active {
font-weight: 700;
background: #fff;
position: sticky;
top: 0;
font-size: 28rpx;
}
// components/TimeHorizon/TimeHorizon.js
Component({
/**
* 组件的属性列表
*/
properties: {
config: {
type: Object,
observer: function (newVal, oldVal) {
let {
havehhmmss,
startData,
startTime,
startLabel,
valueAlign,
endData,
endLabel,
} = newVal
valueAlign = valueAlign || 'left'
this.setData({
havehhmmss,
startData,
startTime,
startLabel,
valueAlign,
endData,
endLabel
})
}
}
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
dateChange(e) {
let {
value
} = e.detail
let {
type
} = e.currentTarget.dataset
if (this.data.endData && type === 'start') {
this.setData({
endData: ''
})
}
let {
havehhmmss
} = this.data
if(havehhmmss)
value = havehhmmss ? type === 'start' ? `${value} 00:00:00` : `${value} 23:59:59` : value
this.setData({
[`${type}Data`]: value
})
let {
startData,
endData,
} = this.data
if (startData && endData) this.triggerEvent('change', {
startData,
endData
})
}
}
})
\ No newline at end of file \ No newline at end of file
{
"component": true,
"usingComponents": {}
}
\ No newline at end of file \ No newline at end of file
<view class='time-box'>
<picker class='time-picker' mode="date" value="{{startData}}" start="{{startTime}}" bindchange="dateChange" data-type='start'>
<view class='time-picker-view'>
<view class='time-picker-label'>{{startLabel||'开始时间'}}</view>
<view class='time-picker-value {{!startData?"no-data":""}} {{valueAlign}}'>
{{startData||'请选择'}}
<image class='arrow' src="../images/arrow-x.png"></image>
</view>
</view>
</picker>
<picker class='time-picker' mode="date" value="{{endData}}" start="{{startData}}" bindchange="dateChange" data-type='end'>
<view class='time-picker-view'>
<view class='time-picker-label'>{{endLabel||'结束时间'}}</view>
<view class='time-picker-value {{!endData?"no-data":""}} {{valueAlign}}'>
{{endData||'请选择'}}
<image class='arrow' src="../images/arrow-x.png"></image>
</view>
</view>
</picker>
</view>
\ No newline at end of file \ No newline at end of file
/* components/TimeHorizon/TimeHorizon.wxss */
.time-box {
background: #fff;
font-size: 28rpx;
color: #333333;
}
.time-picker {
padding-left: 40rpx;
}
.time-picker-view {
display: flex;
align-items: center;
width: 100%;
height: 90rpx;
box-sizing: border-box;
border-bottom: 2rpx solid #eee;
}
.time-picker-label{
width: 25%;
box-sizing: border-box;
}
.time-picker-value{
width: 75%;
display: flex;
align-items: center;
position: relative;
}
.time-picker-value.right{
justify-content: flex-end;
padding-right: 70rpx;
}
.no-data {
color: #999;
}
.arrow {
position: absolute;
right: 40rpx;
top: 50%;
transform: translateY(-50%);
width: 28rpx;
height: 26rpx;
}
// pages/tab/index/index.js
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {
}
})
\ No newline at end of file \ No newline at end of file
{
"usingComponents": {}
}
\ No newline at end of file \ No newline at end of file
<!--pages/tab/index/index.wxml-->
<text>pages/tab/index/index.wxml</text>
/* pages/tab/index/index.wxss */
\ No newline at end of file \ No newline at end of file
// pages/webView/webView.js
Page({
/**
* 页面的初始数据
*/
data: {
flag: true
},
getParams(str) {
let params = str.split('?')
if (params.length < 2) return {}
let param = params[1].split('&')
let obj = {}
for (let i = 0; i < param.length; i++) {
let paramsA = param[i].split('=')
let key = paramsA[0]
let value = paramsA[1]
obj[key] = value
}
return obj
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
wx.$util.showLoading('加载中...')
let decodeUrl = decodeURIComponent(options.url);
let param = this.getParams(decodeUrl)
if (param.urlParam) {
let query = JSON.parse(param.urlParam)
this.data.refresh = query.refresh
}
this.setData({
url: decodeUrl,
})
wx.hideLoading()
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function() {
if (this.data.refresh) {
this.setData({
flag: true
}, () => {
this.setData({
url: this.data.url
})
})
}
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function() {
if (this.data.refresh) {
this.setData({
flag: false
})
}
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function() {
if (this.data.refresh) {
this.setData({
flag: false
})
}
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {
}
})
\ No newline at end of file \ No newline at end of file
{
"usingComponents": {}
}
\ No newline at end of file \ No newline at end of file
<!-- <web-view src="{{url}}"></web-view> -->
<block wx:if="{{flag}}">
<web-view src="{{url}}"></web-view>
</block>
\ No newline at end of file \ No newline at end of file
/* pages/webView/webView.wxss */
\ No newline at end of file \ No newline at end of file
{
"description": "项目配置文件,详见文档:https://developers.weixin.qq.com/miniprogram/dev/devtools/projectconfig.html",
"packOptions": {
"ignore": [],
"include": []
},
"setting": {
"urlCheck": false,
"es6": true,
"enhance": true,
"postcss": true,
"preloadBackgroundData": false,
"minified": false,
"newFeature": false,
"coverView": true,
"nodeModules": false,
"autoAudits": false,
"showShadowRootInWxmlPanel": true,
"scopeDataCheck": false,
"uglifyFileName": false,
"checkInvalidKey": true,
"checkSiteMap": true,
"uploadWithSourceMap": true,
"compileHotReLoad": false,
"useMultiFrameRuntime": true,
"useApiHook": true,
"babelSetting": {
"ignore": [],
"disablePlugins": [],
"outputPath": ""
},
"bundle": false,
"useIsolateContext": true,
"useCompilerModule": false,
"userConfirmedUseCompilerModuleSwitch": false,
"userConfirmedBundleSwitch": false,
"packNpmManually": false,
"packNpmRelationList": [],
"minifyWXSS": true,
"useApiHostProcess": false,
"lazyloadPlaceholderEnable": false,
"useStaticServer": true,
"showES6CompileOption": false,
"disableUseStrict": false,
"useCompilerPlugins": false
},
"compileType": "miniprogram",
"libVersion": "2.15.0",
"appid": "wx0b962934a20ad371",
"projectname": "%E5%B9%BF%E8%81%94%E5%B0%8F%E7%A8%8B%E5%BA%8F%E6%A8%A1%E7%89%88",
"simulatorType": "wechat",
"simulatorPluginLibVersion": {},
"condition": {
"miniprogram": {
"list": [
{
"name": "分享组件",
"pathName": "tabComponents/pages/share/share",
"query": "",
"scene": null
},
{
"name": "授权组件",
"pathName": "tabComponents/pages/authorize/authorize",
"query": "",
"scene": null
},
{
"name": "时间范围选择器",
"pathName": "tabComponents/pages/time-horizon/time-horizon",
"query": "",
"scene": null
},
{
"name": "cell",
"pathName": "tabComponents/pages/gl-cell/gl-cell",
"query": "",
"scene": null
},
{
"name": "日历",
"pathName": "tabComponents/pages/calendar/calendar",
"query": "",
"scene": null
}
]
}
},
"editorSetting": {
"tabIndent": "insertSpaces",
"tabSize": 2
}
}
\ No newline at end of file \ No newline at end of file
{
"description": "项目私有配置文件。此文件中的内容将覆盖 project.config.json 中的相同字段。项目的改动优先同步到此文件中。详见文档:https://developers.weixin.qq.com/miniprogram/dev/devtools/projectconfig.html",
"projectname": "%E5%B9%BF%E8%81%94%E5%B0%8F%E7%A8%8B%E5%BA%8F%E6%A8%A1%E7%89%88",
"setting": {
"compileHotReLoad": false
}
}
\ No newline at end of file \ No newline at end of file
import Router from './router.js'
import routes from './routers.js'
export default new Router(routes)
\ No newline at end of file \ No newline at end of file
const _routeHooks = Symbol('_routeHooks')
const _query = Symbol('_query')
const _routerList = Symbol('_routerList')
import util from '../utils/util.js'
const generateRoutList = routerList => {
let _routerList = routerList
try {
__wxConfig &&
__wxConfig.tabBar &&
__wxConfig.tabBar.list &&
(_routerList = routerList.map(item => {
let obj = {}
if (item.parent != '__plugin__') {
obj = {
...item,
isTab: __wxConfig.tabBar.list.some(({
pagePath
}) =>
item.url.includes(pagePath.replace('.html', ''))
),
}
if (item.parent !== 'pages') {
let parentList = item.url.split(`/`)
if (parentList.length > 5) {
item.url = item.url.replace(/\/__plugin__\/[a-z0-9A-Z]+/, '')
obj.subPages = item.url.split(`/${item.parent}/pages/`)[1].split('/')[0]
}
}
}
return obj
}))
} catch (err) {}
return _routerList
}
class Router {
[_query] = {};
[_routeHooks] = [];
[_routerList] = [];
constructor(router) {
this[_routerList] = generateRoutList(router)
wx.onAppRoute &&
wx.onAppRoute(e => {
let thisPage = this.getPageInstance()
if (thisPage) {
this.setNavigationBarTitleText(thisPage)
let onRoute = thisPage.onRoute
thisPage.$query = this[_query]
typeof onRoute === 'function' && onRoute(this[_query])
let userInfo = util.getUserInfo()
if (userInfo && userInfo.phone) {
if (wx.$authStatus) {
thisPage.setData({
userInfo: null
})
} else {
thisPage.setData({
userInfo
})
if (thisPage.init) thisPage.init(userInfo)
}
}
}
this[_routeHooks].forEach(fn => {
try {
typeof fn === 'function' && fn(e, this[_query], this[_routerList])
} catch (err) {
console.log(err)
}
})
this[_query] = {}
})
}
/**设置标题栏 */
setNavigationBarTitleText(thisPage) {
let title = wx.$util.getNavigationBarTitleText()
if (wx.$util.getUserInfo()) title = wx.$util.getUserInfo().merchantName
const router = `${thisPage.__route__}.html`
if (__wxConfig && __wxConfig.page && __wxConfig.page[router]) {
let {
navigationBarTitleText,
navigationStyle
} = __wxConfig.page[router].window
if (!title) title = ''
if (!navigationBarTitleText && !navigationStyle) wx.setNavigationBarTitle({
title
})
}
}
/**获取页面对象实例 */
getPageInstance = (size = 1) => {
const pages = getCurrentPages()
return pages[pages.length - size]
}
checkRouter(route, events) {
this[_query] = events || {}
const [_parent, _name, last_name] = route.split('.')
let name = route
let [parent] = this.getPageInstance().__route__.split('/')
let query = ''
if (route.includes('?')) {
let [_name_, _query_] = route.split('?')
query = `?${_query_}`
name = _name_
}
if (_parent && _name) {
name = _name.split('?')[0]
parent = _parent
}
/**只传页面名 默认跳转当前包下的页面,相同名称默认第一个 */
if (!_name && !last_name) {
name = _parent
parent = parent
}
const routerMapItem = this[_routerList].find(item => {
if (last_name) {
return item.parent === parent && item.name === last_name && item.subPages === name
} else {
return item.parent === parent && item.name === name
}
})
if (!routerMapItem) {
console.error('找不到路由')
return
}
return {
routerMapItem,
query
}
}
/**跳转至H5 */
jumpH5(url) {
this.intercept().then(response => {
if (response) return
wx.navigateTo({
url: `/pages/webView/webView?url=${encodeURIComponent(url)}`,
})
})
}
/**页面跳转
*
*/
jump(e) {
const item = e.currentTarget.dataset
this.go(item.url, item)
}
/**
* 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面 ||
* 保留当前页面,跳转到应用内的某个页面。但是不能跳到 tabbar 页面。使用 $router.back() 可以返回到原页面。小程序中页面栈最多十层
*/
go(route, events) {
let {
routerMapItem,
query
} = this.checkRouter(route, events)
if (routerMapItem.isTab) {
wx.switchTab({
url: routerMapItem.url
})
} else {
if (events && events.notIntercept) {
wx.navigateTo({
url: `${routerMapItem.url}${query}`,
success: res => events && res.eventChannel.emit('getData', events)
})
} else {
this.intercept().then(response => {
if (response) return
wx.navigateTo({
url: `${routerMapItem.url}${query}`,
success: res => events && res.eventChannel.emit('getData', events)
})
})
}
}
}
/**关闭所有页面,打开到应用内的某个页面 */
reLaunch(route, events) {
let {
routerMapItem,
query
} = this.checkRouter(route, events)
this.intercept().then(response => {
if (response) return
wx.reLaunch({
url: `${routerMapItem.url}${query}`
})
})
}
/**关闭当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面。 */
redirectTo(route, events) {
let {
routerMapItem,
query
} = this.checkRouter(route, events)
this.intercept().then(response => {
if (response) return
wx.redirectTo({
url: `${routerMapItem.url}${query}`,
})
})
}
/**prevPageSize = 1
* 返回上prevPageSize页
* callBack返回上prevPageSize页对象 */
back(callBack, prevPageSize = 1) {
let prevPage = this.getPageInstance(Number(prevPageSize) + 1)
if (callBack && 'function' === typeof callBack) callBack(prevPage)
wx.navigateBack({
delta: prevPageSize
}).catch(err => {
this.goHome()
})
}
goHome() {
let [index] = this[_routerList]
wx.switchTab({
url: index.url
})
}
/**获取上一个页面传的数据 */
getData(callBack) {
const data = this.getPageInstance().getOpenerEventChannel()
if (Object.keys(data).length !== 0) data.on('getData', res => callBack(res))
}
onRoute(fn) {
this[_routeHooks].push(fn)
return () => {
const i = list.indexOf(fn)
if (i > -1) list.splice(i, 1)
};
}
async intercept() {
const authStatus = wx.$authStatus
if (authStatus) {
const thisPage = this.getPageInstance()
thisPage.setData({
showLogin: true
})
return await true
} else {
return await false
}
}
}
export default Router
\ No newline at end of file \ No newline at end of file
export default __wxConfig.pages.map(item => ({
url: `/${item}`,
name: item.split('/').pop(),
parent: item.split('/')[0]
}))
\ No newline at end of file \ No newline at end of file
{
"desc": "关于本文件的更多信息,请参考文档 https://developers.weixin.qq.com/miniprogram/dev/framework/sitemap.html",
"rules": [{
"action": "allow",
"page": "*"
}]
}
\ No newline at end of file \ No newline at end of file
/**
* 设置监听器
*/
const watch = page => {
let {
watch
} = page
if(watch){
Object.keys(watch).forEach(val => {
let key = val.split('.')
let nowData = page
for (let i = 0; i < key.length - 1; i++) {
nowData = nowData[key[i]]
}
let lastKey = key[key.length - 1]
let watchFun = watch[val].handler || watch[val]
let deep = watch[val].deep
observe(nowData, lastKey, watchFun, deep, page)
})
}
}
/**
* 监听属性 并执行监听函数
*/
const observe = (obj, key, watchFun, deep, page) => {
let val = obj[key]
if (deep && val != null && typeof val === 'object') {
Object.keys(val).forEach(childKey => {
observe(val, childKey, watchFun, deep, page)
})
}
Object.defineProperty(obj, key, {
configurable: true,
enumerable: true,
set(value) {
watchFun.call(page, value, val)
val = value
if (deep) {
observe(obj, key, watchFun, deep, page)
}
},
get() {
return val
}
})
}
export default watch
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!