基于wu-calendar 制作日期选择组件,可推广全站使用。

This commit is contained in:
廖德云 2025-03-09 02:06:02 +08:00 committed by ldeyun
parent 680b26c6c1
commit 5cda878389
115 changed files with 15653 additions and 1245 deletions

View File

@ -1,4 +1,4 @@
# 开发环境
# 请求接口地址
VITE_REQUEST_BASE_URL = https://36.112.48.190
#VITE_REQUEST_BASE_URL = http://10.75.15.249:8080
#VITE_REQUEST_BASE_URL = https://36.112.48.190
VITE_REQUEST_BASE_URL = http://10.75.166.6:8080

View File

@ -10,6 +10,16 @@ export function queryJinriShengchansj(params) { // 获取今日天然气生产
})
}
export function queryJinriTrqShengchansj(params) { // 获取当前日期、今年以来天然气的生产数据 day gas unit
return https({
url: '/scdt.CxcScdtChart/cxcScdtChart/getStatisticsData',
method: 'get',
data: params
})
}
export function queryYearShengchansj(params) { // 获取今年以来天然气的生产数据
return https({
url: '/scdt.CxcScdtChart/cxcScdtChart/getYearStatis',

View File

@ -176,6 +176,15 @@
// "navigationBarTextStyle": "white"
}
},
{
"path": "pages/views/shengchan/ribaoshuju/rbsjLsxq",
"style": {
// "navigationStyle": "custom"
"navigationBarTitleText": "历史详情",
"enablePullDownRefresh": false,
"navigationBarTextStyle": "white"
}
},
{
"path": "pages/userlist/index",
"style": {

View File

@ -1,444 +0,0 @@
<template>
<view :class="{ gray: store.isgray == 1 }">
<view class="wrapper f-col aic">
<view class="onduty">
<view class="title f-row aic jcb"><uni-title :title="strDate + ':生产数据'" type="h3" color="red" /></view>
<view class="info">
<!-- <uni-title :title="'天然气'" type="h3" color="blue" /> -->
<view v-for="(row, rowIndex) in groupedData" :key="rowIndex" class="data-row">
<uni-row>
<uni-col v-for="(item, colIndex) in row" :key="colIndex" :span="7">
<text style="color: black; font-size: 32; font-weight: bold">{{ item.gas }}</text>
<view class="value-group">
<text style="color: gray; font-size: 24">当日量:</text>
<text style="color: blue; font-size: 28; font-weight: bold">{{ item.dailyVolume }}</text>
<text style="color: gray; font-size: 24">年累计:</text>
<text style="color: blue; font-size: 28; font-weight: bold">{{ item.yearVolume }}</text>
</view>
</uni-col>
</uni-row>
</view>
</view>
</view>
</view>
</view>
</template>
<script setup>
import { ref, onMounted, computed, nextTick } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { queryJinriShengchansj, queryYearShengchansj } from '@/api/shengchan.js';
import { formatDate, getDateAfterDays } from '@/utils/dateTime.js';
import { beforeJump } from '@/utils/index.js';
import { useStore } from '@/store';
const store = useStore();
import dataCom from '@/bpm/dataCom.vue';
const shishiArr = ref([
{
gas: '气井气',
dailyVolume: '',
yearVolume: ''
},
{
gas: '伴生气',
dailyVolume: '',
yearVolume: ''
},
{
gas: '外部气',
dailyVolume: '',
yearVolume: ''
},
{
gas: '站输差',
dailyVolume: '',
yearVolume: ''
},
{
gas: '线输差',
dailyVolume: '',
yearVolume: ''
},
{
gas: '综合输差',
dailyVolume: '',
yearVolume: ''
}
]);
onMounted(() => {
getJinriShengchansj();
getYearShengchansj();
});
const strDate = ref('');
const dataJinri = ref([]);
const dataJinriSum = ref([]);
const dataJinriSumUnit = ref([]);
//
const groupedData = computed(() => {
const groups = [];
for (let i = 0; i < shishiArr.value.length; i += 3) {
groups.push(shishiArr.value.slice(i, i + 3));
}
return groups;
});
const getJinriShengchansj = () => {
const now = new Date();
if (now.getHours() < 11) {
strDate.value = formatDate(getDateAfterDays(now, -1)).toString(); //11
} else {
strDate.value = formatDate(now).toString();
}
let queryParms = {};
dataJinri.value = [];
dataJinriSum.value = [];
dataJinriSumUnit.value = [];
queryParms.rqDate = strDate.value;
queryParms.pageSize = 100;
console.log(queryParms);
queryJinriShengchansj(queryParms).then((res) => {
if (res.success) {
console.log(res);
dataJinri.value = res.result.records;
dataJinriSumUnit.value = sumByUnit(dataJinri.value); //gas unit rq cq totalGas
console.log(dataJinriSumUnit.value);
// 使 nextTick DOM
nextTick();
getYearShengchansj(); //
}
});
};
const getYearShengchansj = () => {
const now = new Date();
let year = formatDate(now).split('-')[0];
let queryParms = {};
queryParms.yearStart = year;
queryParms.yearEnd = year;
// console.log(2, queryParms.value);
queryYearShengchansj(queryParms).then((res) => {
if (res.success) {
try {
// console.log(res.result);
let yearData = res.result[year];
console.log(dataJinriSumUnit.value.length, dataJinriSumUnit.value, yearData.length, yearData);
dataJinriSumUnit.value.forEach((item) => {
yearData.forEach((itemYear) => {
// console.log(item, itemYear);
if (item.unit === itemYear.unit) {
item.yearVolume = itemYear.yearSum || 0;
}
});
});
dataJinriSum.value = sumByGas(dataJinriSumUnit.value);
console.log(dataJinriSum.value);
shishiArr.value.forEach((item) => {
dataJinriSum.value.forEach((itemjinri) => {
if (item.gas === itemjinri.gas) {
// if (item.gas.includes('线')) {
// item.dailyVolume = itemjinri.totalGas.toFixed(4);
// } else {
item.dailyVolume = itemjinri.rq.toFixed(4);
item.yearVolume = itemjinri.yearVolume.toFixed(4);
// }
}
});
});
} catch (error) {
console.log(error);
}
}
});
};
function sumByGas(records) {
console.log(records);
const summaryMap = {};
try {
records.forEach((record) => {
const gas = record.gas;
if (!summaryMap[gas]) {
// gas
summaryMap[gas] = {
gas: gas,
rq: 0,
sq: 0,
totalGas: 0,
yearVolume: 0
};
}
// gas
summaryMap[gas].rq += record.rq || 0;
summaryMap[gas].sq += record.sq || 0;
summaryMap[gas].totalGas += record.totalGas || 0;
summaryMap[gas].yearVolume += record.yearVolume || 0;
});
return Object.values(summaryMap);
} catch (error) {
//TODO handle the exception
console.log(error);
}
}
function sumByUnit(records) {
console.log(records);
const summaryMap = {};
try {
records.forEach((record) => {
const unit = record.unit;
if (!summaryMap[unit]) {
// gas
summaryMap[unit] = {
unit: unit,
gas: record.gas,
rq: 0,
sq: 0,
totalGas: 0,
yearVolume: 0
};
}
// unit
summaryMap[unit].rq += record.rq || 0;
summaryMap[unit].sq += record.sq || 0;
summaryMap[unit].totalGas += record.totalGas || 0;
summaryMap[unit].yearVolume += record.yearVolume || 0;
});
return Object.values(summaryMap);
} catch (error) {
//TODO handle the exception
console.log(error);
}
}
</script>
<style lang="scss" scoped>
// .container {
// padding: 20rpx;
// background-color: #f8f8f8;
// min-height: 100vh;
// }
.content {
padding: 0 30rpx 20rpx 30rpx;
}
.card-content {
padding-right: 5px;
}
.data-row {
margin-bottom: 10rpx;
}
.value-group {
background-color: aliceblue;
display: flex;
flex-direction: column;
border-color: #ff00ff;
gap: 5px;
}
.uni-col {
margin-right: 10px;
background-color: #f8f8f8;
border-radius: 15rpx;
}
.wrapper {
padding: 0 30rpx;
// transform: translateY(-50rpx);
.onduty {
background: #ffffff;
box-shadow: 0rpx 2rpx 4rpx 0rpx rgba(0, 0, 0, 0.5);
border-radius: 16rpx;
padding: 20rpx 24rpx 24rpx 24rpx;
.title {
font-size: 32rpx;
color: #333333;
background-size: 44rpx 12rpx;
background-repeat: no-repeat;
background-position: left bottom;
}
.info {
background: #f8f8f8;
border-radius: 8rpx;
text-align: left;
width: 642rpx;
margin-top: 23rpx;
.info_title {
font-size: 24rpx;
color: #333333;
padding: 24rpx 0;
border-bottom: 1px solid #efefef;
view {
flex: 1;
}
}
.data_box {
font-size: 24rpx;
padding-bottom: 24rpx;
color: #888888;
.first {
font-weight: bold;
color: #333333;
}
.data {
margin-top: 23rpx;
view {
flex: 1;
}
}
}
}
}
.more {
font-size: 24rpx;
color: #999999;
text-align: right;
image {
width: 10rpx;
height: 18rpx;
}
}
.list_wrapper {
background: #ffffff;
box-shadow: 0rpx 2rpx 4rpx 0rpx rgba(0, 0, 0, 0.5);
border-radius: 16rpx;
padding: 26rpx 24rpx 24rpx 24rpx;
position: relative;
margin-top: 30rpx;
width: 642rpx;
&::after {
position: absolute;
top: 100rpx;
left: 0;
content: ' ';
width: 100%;
height: 1px;
background-color: #efefef;
}
.zhidu {
font-size: 24rpx;
color: #666666;
justify-content: flex-end;
padding-top: 40rpx;
view {
width: 120rpx;
height: 60rpx;
line-height: 60rpx;
text-align: center;
&:first-child {
margin-right: 40rpx;
}
}
.active {
position: relative;
color: #3179d6;
&::after {
content: ' ';
width: 120rpx;
height: 60rpx;
border-radius: 60rpx;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
position: absolute;
background-color: rgba(49, 121, 214, 0.1);
}
}
}
.list_title {
text-align: center;
padding-bottom: 29rpx;
font-size: 32rpx;
color: #666666;
.active {
position: relative;
color: #3179d6;
&::after {
content: ' ';
width: 120rpx;
height: 70rpx;
border-radius: 70rpx;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
position: absolute;
background-color: rgba(49, 121, 214, 0.1);
}
}
}
.list_box {
margin-top: 24rpx;
.list {
margin-bottom: 24rpx;
padding: 30rpx 30rpx 35rpx 30rpx;
// width: 570rpx;
background: #f8f8f8;
border-radius: 8rpx;
.topic {
font-size: 28rpx;
color: #333333;
}
.time_Box {
font-size: 24rpx;
color: #888888;
margin-top: 20rpx;
.time {
margin-right: 62rpx;
}
.look {
position: relative;
&::before {
position: absolute;
left: -30rpx;
top: 50%;
transform: translateY(-50%);
content: ' ';
width: 2rpx;
height: 20rpx;
background: #999999;
}
}
image {
width: 28rpx;
height: 22rpx;
margin-right: 8rpx;
}
}
}
}
}
}
</style>

View File

@ -1,35 +0,0 @@
<template>
<view>
<view class="nav">生产经营数据</view>
<view class="placeholder"></view>
<ng-data></ng-data>
</view>
</template>
<script setup>
const res = wx.getSystemInfoSync();
const statusHeight = res.statusBarHeight; //
const cusnavbarheight = statusHeight + 44 + 'px';
import ngData from './NatrueGas/index.vue';
</script>
<style lang="scss" scoped>
.nav {
width: calc(100% - 60rpx);
padding: 0 30rpx;
height: v-bind(cusnavbarheight);
font-size: 24rpx;
color: #ffffff;
position: fixed;
top: 0;
left: 0;
z-index: 99;
background-image: url('../../static/my/navbg.png');
background-repeat: no-repeat;
background-size: 750rpx 458rpx;
}
.placeholder {
height: v-bind(cusnavbarheight);
}
</style>

View File

@ -6,8 +6,7 @@
</uni-row>
<uni-row style="margin-bottom: 20rpx; margin-left: 30rpx; margin-right: 30rpx">
<uni-col :span="24">
<trq-depart-select v-model="orgCode" returnCodeOrID="orgCode"
@change="departChange"></trq-depart-select>
<trq-depart-select v-model="orgCode" returnCodeOrID="orgCode" @change="departChange"></trq-depart-select>
</uni-col>
</uni-row>
<!-- 概览统计 -->
@ -72,7 +71,7 @@
</uni-col>
<uni-col :span="6">
<view class="dataStyle">
<span @click="detail(item)" style="color: red;">详情</span>
<span @click="detail(item)" style="color: red">详情</span>
<!-- <button size="mini" type="primary" @click="detail(item)">详情</button> -->
</view>
</uni-col>
@ -83,295 +82,290 @@
</template>
<script setup>
import {
ref,
reactive,
onMounted
} from 'vue';
import * as echarts from 'echarts';
import { ref, reactive, onMounted } from 'vue';
import * as echarts from 'echarts';
import {
queryRenyuanByDepartID
} from '@/api/renyuan.js';
import { queryRenyuanByDepartID } from '@/api/renyuan.js';
//
const bottomHeight = ref(0);
//
const isLoading = ref(false);
const orgCode = ref('');
const rawData = ref([]);
const tableData = ref([]);
const summary = reactive({
total: 0,
avgAge: 0
//
const bottomHeight = ref(0);
//
const isLoading = ref(false);
const orgCode = ref('');
const rawData = ref([]);
const tableData = ref([]);
const summary = reactive({
total: 0,
avgAge: 0
});
const chart = ref(null);
const chartOption = ref({});
const drillPopup = ref(null);
const drillList = ref([]);
const drillTitle = ref('');
function detail(record) {
// console.log(record)
uni.navigateTo({
url: '/pages/views/renliziyuan/renyuanxinxi/detail?data=' + encodeURIComponent(JSON.stringify(record))
});
const chart = ref(null);
const chartOption = ref({});
const drillPopup = ref(null);
const drillList = ref([]);
const drillTitle = ref('');
function detail(record) {
// console.log(record)
uni.navigateTo({
url: '/pages/views/renliziyuan/renyuanxinxi/detail?data=' + encodeURIComponent(JSON.stringify(record))
});
}
//
const calculateAge = (birthDate) => {
const today = new Date();
const birth = new Date(birthDate);
let age = today.getFullYear() - birth.getFullYear();
const monthDiff = today.getMonth() - birth.getMonth();
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
age--;
}
// initChart
const calculateAge = (birthDate) => {
const today = new Date();
const birth = new Date(birthDate);
let age = today.getFullYear() - birth.getFullYear();
const monthDiff = today.getMonth() - birth.getMonth();
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
age--;
}
return age;
};
//
const departChange = async (e, data) => {
tableData.value = [];
console.log(e);
orgCode.value = e;
try {
//
return age;
};
//
const departChange = async (e, data) => {
tableData.value = [];
console.log(e);
orgCode.value = e;
try {
//
isLoading.value = true;
if (orgCode.value.length <= 6) {
console.log(123242353);
uni.showToast({
title: '全厂数据较多,请选 下一层级...',
icon: 'none',
duration: 1000
});
isLoading.value = false;
return;
} else {
uni.showLoading({
title: '数据加载中...',
mask: true
});
}
let params = {
pageSize: 3000,
fields: ['xm', 'nl', 'xb', 'xb_dictText', 'orgCode', 'jcdw', 'jcxd', 'jcxdCode']
};
if (orgCode.value.length <= 9) {
params.orgCode = orgCode.value;
} else {
params.jcxd_code = orgCode.value;
}
queryRenyuanByDepartID(params)
.then((res) => {
if (res.success) {
processData(res.result.records);
//
isLoading.value = false;
uni.hideLoading();
}
})
.catch((err) => {
console.log(err);
uni.showToast({
title: '数据加载失败',
icon: 'none',
duration: 1000
});
});
} catch (error) {
console.log(error);
isLoading.value = true;
if (orgCode.value.length <= 6) {
console.log(123242353);
uni.showToast({
title: '数据加载失败',
title: '全厂数据较多,请选 下一层级...',
icon: 'none',
duration: 1000
});
} finally {
//
isLoading.value = false;
uni.hideLoading();
return;
} else {
uni.showLoading({
title: '数据加载中...',
mask: true
});
}
};
//
const processData = (data) => {
//
const validData = data
.map((item) => ({
...item,
nl: calculateAge(item.cssj)
}))
.filter((item) => item.nl >= 21 && item.nl <= 64);
//
summary.total = validData.length;
summary.avgAge = validData.reduce((sum, cur) => sum + cur.nl, 0) / summary.total || 0;
//
// tableData.value = validData;
let params = {
pageSize: 3000,
fields: ['xm', 'nl', 'xb', 'xb_dictText', 'orgCode', 'jcdw', 'jcxd', 'jcxdCode']
};
if (orgCode.value.length <= 9) {
params.orgCode = orgCode.value;
} else {
params.jcxd_code = orgCode.value;
}
queryRenyuanByDepartID(params)
.then((res) => {
if (res.success) {
processData(res.result.records);
groupsData(validData);
//
generateChartData(validData);
};
// ...
const subOrgStaffs = ref({}); //
const ageGroupStaffs = ref({}); //
const groupsData = (data) => {
//
subOrgStaffs.value = {};
ageGroupStaffs.value = {};
data.reduce((acc, cur) => {
// console.log(cur)
let subOrg = '';
let ageRange = getAgeRange(cur.nl);
// console.log(cur.orgCode, cur.jcxdCode)
if (cur.orgCode <= 6) {
subOrg = cur.orgCode;
} else {
subOrg = cur.jcxdCode;
}
// subOrgStaffs
if (!subOrgStaffs.value[subOrg]) {
subOrgStaffs.value[subOrg] = [];
}
subOrgStaffs.value[subOrg].push(cur);
// ageGroupStaffs
if (!ageGroupStaffs.value[ageRange]) {
ageGroupStaffs.value[ageRange] = [];
}
ageGroupStaffs.value[ageRange].push(cur);
//
isLoading.value = false;
uni.hideLoading();
}
})
.catch((err) => {
console.log(err);
uni.showToast({
title: '数据加载失败',
icon: 'none',
duration: 1000
});
});
} catch (error) {
console.log(error);
uni.showToast({
title: '数据加载失败',
icon: 'none',
duration: 1000
});
};
} finally {
//
isLoading.value = false;
uni.hideLoading();
}
};
//
const getAgeRange = (age) => {
const ranges = ['21-30岁', '31-40岁', '41-50岁', '51-60岁', '61-64岁'];
const index = Math.floor((age - 21) / 10);
return ranges[index] || '其他';
};
//
const processData = (data) => {
//
const validData = data
.map((item) => ({
...item,
nl: calculateAge(item.cssj)
}))
.filter((item) => item.nl >= 21 && item.nl <= 64);
//
summary.total = validData.length;
summary.avgAge = validData.reduce((sum, cur) => sum + cur.nl, 0) / summary.total || 0;
//
// tableData.value = validData;
//
const showStaffList = (subOrg, ageRange) => {
//
const targetStaffs = subOrgStaffs.value[subOrg].filter((staff) => getAgeRange(staff.nl) === ageRange);
groupsData(validData);
//
generateChartData(validData);
};
staffList.value = targetStaffs;
popupTitle.value = `${subOrg} ${ageRange}人员列表(共${targetStaffs.length}人)`;
popup.value.open();
};
// ...
const subOrgStaffs = ref({}); //
const ageGroupStaffs = ref({}); //
//
const getSubOrgStaffs = (subOrgCode) => {
return subOrgStaffs.value[subOrgCode] || [];
};
const groupsData = (data) => {
//
subOrgStaffs.value = {};
ageGroupStaffs.value = {};
data.reduce((acc, cur) => {
// console.log(cur)
let subOrg = '';
let ageRange = getAgeRange(cur.nl);
// console.log(cur.orgCode, cur.jcxdCode)
if (cur.orgCode <= 6) {
subOrg = cur.orgCode;
} else {
subOrg = cur.jcxdCode;
}
//
const getAgeGroupStaffs = (ageRange) => {
return ageGroupStaffs.value[ageRange] || [];
};
// subOrgStaffs
if (!subOrgStaffs.value[subOrg]) {
subOrgStaffs.value[subOrg] = [];
}
subOrgStaffs.value[subOrg].push(cur);
//
const generateChartData = (data) => {
//
const ageRanges = ['21-30岁', '31-40岁', '41-50岁', '51-60岁', '61-64岁'];
const jcdwGroups = data.reduce((acc, cur) => {
if (!acc[cur.jcdw]) {
acc[cur.jcdw] = {
ageGroups: [0, 0, 0, 0, 0] // 21-30,31-40,41-50,51-60,61-64
};
}
const ageGroup = Math.floor((cur.nl - 21) / 10);
// console.log(ageGroup, cur.jcdw)
if (ageGroup >= 0 && ageGroup <= 4) {
acc[cur.jcdw].ageGroups[ageGroup]++;
}
return acc;
}, {});
// ageGroupStaffs
if (!ageGroupStaffs.value[ageRange]) {
ageGroupStaffs.value[ageRange] = [];
}
ageGroupStaffs.value[ageRange].push(cur);
});
};
//
const xData = Object.keys(jcdwGroups);
//
const getAgeRange = (age) => {
const ranges = ['21-30岁', '31-40岁', '41-50岁', '51-60岁', '61-64岁'];
const index = Math.floor((age - 21) / 10);
return ranges[index] || '其他';
};
const seriesData = ageRanges.map((range, index) => ({
name: range,
type: 'bar',
data: xData.map((jcdw) => jcdwGroups[jcdw].ageGroups[index] || 0),
itemStyle: {
color: ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE'][index]
},
//
label: {
show: true,
position: 'top'
}
// 20
// barWidth: 20
}));
chartOption.value = {
title: {
text: '人员年龄分组统计',
padding: [0, 0, 0, 30]
},
toolbox: {
padding: [0, 30, 0, 0],
show: true,
feature: {
//
//
const showStaffList = (subOrg, ageRange) => {
//
const targetStaffs = subOrgStaffs.value[subOrg].filter((staff) => getAgeRange(staff.nl) === ageRange);
restore: {
show: true //
},
saveAsImage: {
show: true //
}
}
},
// tooltip: {
// trigger: 'axis',
// axisPointer: {
// type: 'shadow',
// label: {
// show: false
// }
// }
// },
grid: {
top: '15%',
left: '4%',
right: '4%',
bottom: '10%',
containLabel: true
},
legend: {
data: ageRanges,
itemGap: 5,
padding: [0, 15, 0, 15],
y: 'bottom',
itemHeight: 8, //
itemWidth: 8, //
type: 'scroll'
},
xAxis: {
type: 'category',
data: xData,
axisLabel: {
color: '#7F84B5',
fontWeight: 300,
interval: 0,
rotate: 0
staffList.value = targetStaffs;
popupTitle.value = `${subOrg} ${ageRange}人员列表(共${targetStaffs.length}人)`;
popup.value.open();
};
//
const getSubOrgStaffs = (subOrgCode) => {
return subOrgStaffs.value[subOrgCode] || [];
};
//
const getAgeGroupStaffs = (ageRange) => {
return ageGroupStaffs.value[ageRange] || [];
};
//
const generateChartData = (data) => {
//
const ageRanges = ['21-30岁', '31-40岁', '41-50岁', '51-60岁', '61-64岁'];
const jcdwGroups = data.reduce((acc, cur) => {
if (!acc[cur.jcdw]) {
acc[cur.jcdw] = {
ageGroups: [0, 0, 0, 0, 0] // 21-30,31-40,41-50,51-60,61-64
};
}
const ageGroup = Math.floor((cur.nl - 21) / 10);
// console.log(ageGroup, cur.jcdw)
if (ageGroup >= 0 && ageGroup <= 4) {
acc[cur.jcdw].ageGroups[ageGroup]++;
}
return acc;
}, {});
//
const xData = Object.keys(jcdwGroups);
const seriesData = ageRanges.map((range, index) => ({
name: range,
type: 'bar',
data: xData.map((jcdw) => jcdwGroups[jcdw].ageGroups[index] || 0),
itemStyle: {
color: ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE'][index]
},
//
label: {
show: true,
position: 'top'
}
// 20
// barWidth: 20
}));
chartOption.value = {
title: {
text: '人员年龄分组统计',
padding: [0, 0, 0, 30]
},
toolbox: {
padding: [0, 30, 0, 0],
show: true,
feature: {
//
restore: {
show: true //
},
padding: [0, 10, 0, 10],
axisTick: {
show: false //线
},
axisLine: {
show: false //线
saveAsImage: {
show: true //
}
}
},
// tooltip: {
// trigger: 'axis',
// axisPointer: {
// type: 'shadow',
// label: {
// show: false
// }
// }
// },
grid: {
top: '15%',
left: '4%',
right: '4%',
bottom: '10%',
containLabel: true
},
legend: {
data: ageRanges,
itemGap: 5,
padding: [0, 15, 0, 15],
y: 'bottom',
itemHeight: 8, //
itemWidth: 8, //
type: 'scroll'
},
xAxis: {
type: 'category',
data: xData,
axisLabel: {
color: '#7F84B5',
fontWeight: 300,
interval: 0,
rotate: 0
},
yAxis: [{
padding: [0, 10, 0, 10],
axisTick: {
show: false //线
},
axisLine: {
show: false //线
}
},
yAxis: [
{
show: true,
boundaryGap: false, //线
type: 'value',
@ -395,146 +389,147 @@
axisLine: {
show: false //线
}
}],
}
],
series: seriesData
};
//
setTimeout(async () => {
if (!chart.value) return;
const myChart = await chart.value.init(echarts);
myChart.setOption(chartOption.value);
myChart.on('click', (params) => {
console.log(params.seriesName);
tableData.value = getAgeGroupStaffs(params.seriesName);
});
}, 300);
// #ifdef APP
getHeight();
// #endif
series: seriesData
};
onMounted(() => {
// #ifdef APP
getHeight();
// #endif
});
// #ifdef APP
const getHeight = () => {
//
const systemInfo = uni.getSystemInfoSync();
const screenHeight = systemInfo.screenHeight;
//
const query = uni.createSelectorQuery();
//
query
.select('#top1')
.boundingClientRect((rect1) => {
//
const topComponentsHeight = rect1.height;
//
bottomHeight.value = screenHeight - topComponentsHeight - 415;
})
.exec();
};
// #endif
//
const initChart = () => {
setTimeout(async () => {
if (!chart.value) return;
const myChart = await chart.value.init(echarts);
myChart.setOption(chartOption.value);
}, 300);
};
setTimeout(async () => {
if (!chart.value) return;
const myChart = await chart.value.init(echarts);
myChart.setOption(chartOption.value);
myChart.on('click', (params) => {
console.log(params.seriesName);
tableData.value = getAgeGroupStaffs(params.seriesName);
});
}, 300);
// #ifdef APP
getHeight();
// #endif
};
onMounted(() => {
// #ifdef APP
getHeight();
// #endif
});
// #ifdef APP
const getHeight = () => {
//
const systemInfo = uni.getSystemInfoSync();
const screenHeight = systemInfo.screenHeight;
//
const query = uni.createSelectorQuery();
//
query
.select('#top1')
.boundingClientRect((rect1) => {
//
const topComponentsHeight = rect1.height;
//
bottomHeight.value = screenHeight - topComponentsHeight - 415;
})
.exec();
};
// #endif
//
const initChart = () => {
setTimeout(async () => {
if (!chart.value) return;
const myChart = await chart.value.init(echarts);
myChart.setOption(chartOption.value);
}, 300);
};
</script>
<style scoped>
.container {
margin: 20, 20, 20, 20rpx;
}
.container {
margin: 20, 20, 20, 20rpx;
}
.input-group {
display: flex;
gap: 20rpx;
margin-bottom: 30rpx;
}
.input-group {
display: flex;
gap: 20rpx;
margin-bottom: 30rpx;
}
.input {
flex: 1;
border: 1rpx solid #ddd;
padding: 15rpx;
border-radius: 8rpx;
}
.input {
flex: 1;
border: 1rpx solid #ddd;
padding: 15rpx;
border-radius: 8rpx;
}
.query-btn {
background: #007aff;
color: white;
padding: 0 40rpx;
border-radius: 8rpx;
}
.query-btn {
background: #007aff;
color: white;
padding: 0 40rpx;
border-radius: 8rpx;
}
.stats-box {
display: flex;
justify-content: space-around;
margin: 30rpx 0;
padding: 20rpx;
background: #f8f8f8;
border-radius: 12rpx;
}
.stats-box {
display: flex;
justify-content: space-around;
margin: 30rpx 0;
padding: 20rpx;
background: #f8f8f8;
border-radius: 12rpx;
}
.stat-item {
display: flex;
flex-direction: column;
align-items: center;
}
.stat-item {
display: flex;
flex-direction: column;
align-items: center;
}
.label {
font-size: 24rpx;
color: #666;
}
.label {
font-size: 24rpx;
color: #666;
}
.value {
font-size: 36rpx;
font-weight: bold;
color: #0000ff;
}
.value {
font-size: 36rpx;
font-weight: bold;
color: #0000ff;
}
.chart-container {
height: 400rpx;
margin-top: 20rpx;
}
.chart-container {
height: 400rpx;
margin-top: 20rpx;
}
.titleStyle {
font-size: 12px;
color: #747474;
line-height: 30px;
height: 30px;
background: #f2f9fc;
text-align: center;
vertical-align: middle;
border-left: 1px solid #919191;
border-bottom: 1px solid #919191;
}
.titleStyle {
font-size: 12px;
color: #747474;
line-height: 30px;
height: 30px;
background: #f2f9fc;
text-align: center;
vertical-align: middle;
border-left: 1px solid #919191;
border-bottom: 1px solid #919191;
}
/* 内容样式 */
.dataStyle {
max-font-size: 14px;
/* 最大字体限制 */
min-font-size: 10px;
/* 最小字体限制 */
font-size: 12px;
color: #00007f;
line-height: 30px;
height: 30px;
font-weight: 500;
text-align: center;
vertical-align: middle;
border-bottom: 1px solid #919191;
border-left: 1px solid #919191;
text-overflow: ellipsis;
}
</style>
/* 内容样式 */
.dataStyle {
max-font-size: 14px;
/* 最大字体限制 */
min-font-size: 10px;
/* 最小字体限制 */
font-size: 12px;
color: #00007f;
line-height: 30px;
height: 30px;
font-weight: 500;
text-align: center;
vertical-align: middle;
border-bottom: 1px solid #919191;
border-left: 1px solid #919191;
text-overflow: ellipsis;
}
</style>

View File

@ -1,52 +1,61 @@
<template>
<view>
<!-- <view class="nav">生产经营数据</view> -->
<view class="placeholder">生产经营数据</view>
<view class="nav"></view>
<view class="placeholder"></view>
<view style="width: 100%; display: grid; place-items: center">
<uni-title :title="dateDate + ':生产经营情况'" type="h1" color="blue" />
</view>
<trq-data></trq-data>
<yy-data></yy-data>
</view>
</template>
<script setup>
import {
formatDate,
getDateAfterDays
} from '@/utils/dateTime.js';
const res = wx.getSystemInfoSync();
const statusHeight = res.statusBarHeight; //
const cusnavbarheight = statusHeight + 44 + 'px';
import { formatDate, getDateAfterDays } from '@/utils/dateTime.js';
import trqData from './ribaoshuju/trqRbsj.vue';
import yyData from './ribaoshuju/yyRbsj.vue';
import { ref, onMounted, computed, nextTick, watchEffect } from 'vue';
const strDate = (() => {
const now = new Date();
if (now.getHours() < 11) {
return formatDate(getDateAfterDays(now, -1)).toString(); //11
} else {
return formatDate(now).toString();
}
})
const res = wx.getSystemInfoSync();
const statusHeight = res.statusBarHeight; //
const cusnavbarheight = statusHeight + 44 + 'px';
const dateDate = ref('');
import trqData from './ribaoshuju/trqRbsj.vue';
import yyData from './ribaoshuju/yyRbsj.vue';
const strDate = () => {
const now = new Date();
if (now.getHours() < 11) {
return formatDate(getDateAfterDays(now, -1)); //11
} else {
return formatDate(now);
}
};
onMounted(() => {
dateDate.value = strDate();
});
</script>
<style lang="scss" scoped>
.nav {
width: calc(100% - 60rpx);
padding: 0 30rpx;
height: v-bind(cusnavbarheight);
.nav {
width: calc(100% - 60rpx);
padding: 0 30rpx;
height: v-bind(cusnavbarheight);
font-size: 24rpx;
color: #ffffff;
position: fixed;
top: 0;
left: 0;
z-index: 99;
background-image: url('../../static/my/navbg.png');
background-repeat: no-repeat;
background-size: 750rpx 458rpx;
}
font-size: 24rpx;
color: #ffffff;
position: fixed;
top: 0;
left: 0;
z-index: 99;
background-image: url('../../static/my/navbg.png');
background-repeat: no-repeat;
background-size: 750rpx 458rpx;
}
.placeholder {
height: v-bind(cusnavbarheight);
}
</style>
.placeholder {
height: v-bind(cusnavbarheight);
}
</style>

View File

@ -0,0 +1,342 @@
<template>
<view>
<view class="stats-container">
<uni-title :title="name.unit + '历史数据---单位(万方)'" color="blue" type="h2"></uni-title>
</view>
<view class="dateSelect">
<cxc-szcx-dateRangeSelect :mode="'range'" v-model="dateRange"></cxc-szcx-dateRangeSelect>
</view>
<cxc-szcx-lineChart :dataList="dataList" x-field="rqDate" y-field="rq" legend-field="unit"
:reference-value="0"></cxc-szcx-lineChart>
<view style="margin: 0 15px">
<view class="stats-container">
<view class="stats-item">最大值: {{ dataStats.max }}</view>
<view class="stats-item">最小值: {{ dataStats.min }}</view>
<view class="stats-item">平均值: {{ dataStats.average }}</view>
</view>
<view class="table-container">
<!-- 表头 -->
<view class="tr header">
<view class="th1">序号</view>
<view class="th">名称</view>
<view class="th">日期</view>
<view class="th">日气量</view>
</view>
<scroll-view scroll-Y="true" class="scroll-wrapper">
<!-- 表格内容 -->
<view class="tr" v-for="(item, index) in dataList" :key="index" :class="{ even: index % 2 === 0 }">
<view class="td1">{{ index + 1 }}</view>
<view class="td">{{ item.unit }}</view>
<view class="td">{{ item.rqDate }}</view>
<view class="td" :class="{ negative: item.rq < 0 }">
{{ item.rq }}
</view>
</view>
<!-- 空数据提示 -->
<view v-if="!dataList.length" class="empty">暂无相关数据</view>
</scroll-view>
</view>
</view>
</view>
</template>
<script setup>
import {
ref,
onMounted,
computed,
nextTick,
watchEffect,
warn,
watch
} from 'vue';
import {
onLoad
} from '@dcloudio/uni-app';
import {
queryJinriShengchansj,
queryJinriYuanyouShengchansj
} from '@/api/shengchan.js';
import {
formatDate,
getDateAfterDays,
getDateAfterMonths
} from '@/utils/dateTime.js';
const name = ref({});
const type = ref('');
const dateRange = ref([]);
const dataList = ref([]);
const endDate = ref('');
const startDate = ref('');
const dataStats = ref({
min: 0,
max: 0,
avg: 0
});
const getJinriShengchansj = (tempDateRange) => {
// console.log(tempDateRange);
//
if (!tempDateRange || tempDateRange.some((date) => !convertToDate(date))) {
console.error('收到无效日期范围:', tempDateRange);
return;
}
let queryParms = {};
dataList.value = [];
queryParms.gas = name.value.gas;
queryParms.unit = name.value.unit;
queryParms.rqDate_begin = formatDate(tempDateRange[0]);
queryParms.rqDate_end = formatDate(tempDateRange[1]);
queryParms.pageSize = 500;
//
if (!queryParms.rqDate_begin || !queryParms.rqDate_end) {
console.error('参数格式化失败:', queryParms);
return;
}
// console.log(queryParms);
queryJinriShengchansj(queryParms).then((res) => {
if (res.success) {
// console.log(res);
dataList.value = res.result.records;
dataStats.value = calculateStats(dataList.value, 'rq');
}
});
};
const getJinriYuanyouShengchansj = (tempDateRange) => {
console.log(tempDateRange);
//
if (!tempDateRange || tempDateRange.some((date) => !convertToDate(date))) {
console.error('收到无效日期范围:', tempDateRange);
return;
}
let queryParms = {};
dataList.value = [];
queryParms.dw = name.value.dw;
queryParms.scrq_begin = formatDate(tempDateRange[0]);
queryParms.scrq_end = formatDate(tempDateRange[1]);
queryParms.pageSize = 500;
//
if (!queryParms.rqDate_begin || !queryParms.rqDate_end) {
console.error('参数格式化失败:', queryParms);
return;
}
console.log(queryParms);
queryJinriYuanyouShengchansj(queryParms).then((res) => {
if (res.success) {
console.log(res);
dataList.value = res.result.records;
dataStats.value = calculateStats(dataList.value, 'rcwy');
}
});
};
function calculateStats(data, field) {
// field null undefined
const validData = data.filter((item) => item[field] !== null && item[field] !== undefined);
if (validData.length === 0) {
return {
max: null,
min: null,
average: null
};
}
//
let max = validData[0][field];
let min = validData[0][field];
let sum = 0;
//
for (let i = 0; i < validData.length; i++) {
const value = validData[i][field];
//
if (value > max) {
max = value;
}
//
if (value < min) {
min = value;
}
//
sum += value;
}
//
const average = (sum / validData.length).toFixed(4);
return {
max: max,
min: min,
average: average
};
}
function convertToDate(str) {
try {
const date = new Date(str);
//
if (isNaN(date.getTime())) {
return false;
}
return true;
} catch (error) {
return false;
//TODO handle the exception
}
}
//
watch(
[() => type.value, dateRange], // type dateRange
([newType, newDateRange]) => {
if (!newDateRange || !convertToDate(newDateRange[0]) || !convertToDate(newDateRange[1])) {
// console.error(':', newDateRange);
return;
}
// console.log(newType, newDateRange);
switch (
newType // 使 newType
) {
case 'trq':
getJinriShengchansj(newDateRange);
break;
case 'yy':
getJinriYuanyouShengchansj(newDateRange);
break;
default:
console.warn('未知类型:', newType);
}
}, {
immediate: true,
deep: true
}
);
onMounted(() => {
// nextTick();
// getJinriShengchansj(dateRange.value);
});
onLoad((options) => {
name.value = JSON.parse(options.data);
type.value = options.type;
// console.log(name.value, type.value);
const now = new Date();
if (now.getHours() < 11) {
endDate.value = getDateAfterDays(now, -1); //11
startDate.value = getDateAfterMonths(endDate.value, -1); //11
} else {
endDate.value = now;
startDate.value = getDateAfterMonths(endDate.value, -1); //11
}
dateRange.value = [startDate.value, endDate.value];
// console.log(1111, dateRange.value);
});
</script>
<style scoped>
.table-container {
width: 100%;
height: 40vh;
overflow: hidden;
}
.scroll-wrapper {
width: 100%;
height: 35vh;
}
.tr {
display: flex;
min-height: 18px;
font-size: 12px;
border-bottom: 1px solid #e8e8e8;
}
.th,
.td {
flex: 1;
min-width: 80px;
padding: 10px;
font-size: 14px;
font-weight: bold;
color: #333;
text-align: center;
white-space: nowrap;
height: 18px;
vertical-align: middle;
overflow: hidden;
text-overflow: ellipsis;
}
.th1,
.td1 {
flex: 1;
max-width: 40px;
padding: 10px;
font-size: 14px;
font-weight: bold;
color: #333;
text-align: center;
white-space: nowrap;
height: 18px;
vertical-align: middle;
}
.th {
background-color: #f0f0f0;
}
.td.negative {
color: #ff4444;
font-weight: 500;
}
.empty {
padding: 40px;
text-align: center;
color: #888;
font-size: 16px;
}
.stats-container {
display: flex;
justify-content: space-around;
align-items: center;
text-align: center;
background-color: #f5f5f5;
border-radius: 4px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
padding: 10px;
margin: 15 15px;
}
.dateSelect {
display: flex;
justify-content: space-around;
align-items: center;
text-align: center;
background-color: #f5f5f5;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
padding: 5px;
margin: 10px;
}
.stats-item {
font-size: 12px;
color: #00aa00;
font-weight: bold;
}
.stats-item+.stats-item {
border-left: 1px solid #ccc;
padding-left: 16px;
}
</style>

View File

@ -1,18 +1,31 @@
<template>
<view :class="{ gray: store.isgray == 1 }">
<view style="margin-left: 20rpx;"> <uni-title :title="strDate + ':生产数据'" type="h1" color="red" />
<view class="progress-bar">
<!-- 动态设置宽度和颜色 -->
<view class="progressTime" :style="{ width: `${timePercent}%`, 'background-color': '#00aaff' }"></view>
<!-- 显示带符号的百分比 -->
<text class="progress-text">全年时间进度:{{ timePercent }}%</text>
</view>
<view class="container">
<view v-for="(item, index) in shishiArr" :key="index" class="card-item" @click="handleCardClick(item.gas)">
<view class="card">
<text class="title">{{ item.gas }}</text>
<view class="content">
<text class="label">气量</text>
<text class="value">{{ item.dailyVolume || '-' }}</text>
<text class="label">气量</text>
<text class="value">{{ formatNumber(item.dailyVolume) || '-' }}</text>
</view>
<view class="content">
<text class="label">年累计</text>
<text class="value">{{ item.yearVolume || '-' }}</text>
<text class="value">{{ formatNumber(item.yearVolume) || '-' }}</text>
</view>
<view class="progress-bar">
<!-- 动态设置宽度和颜色 -->
<view class="progress"
:style="{ width: `${Math.abs(item.yearPerCent)}%`, 'background-color': item.yearPerCent < 0 ? '#ff4444' : '#007aff' }">
</view>
<!-- 显示带符号的百分比 -->
<text v-if="!(item.yearPlan === '' || item.yearPlan === '0')"
class="progress-text">{{ item.yearPerCent }}%</text>
</view>
</view>
</view>
@ -25,41 +38,36 @@
<uni-icons type="closeempty" size="24" color="#666" @click="closePopup"></uni-icons>
</view>
<scroll-view scroll-X="true" scroll-Y="true" class="table-container">
<view class="table">
<!-- 表头 -->
<view class="tr header">
<view class="th1">序号</view>
<view class="th">名称</view>
<view class="th">日气量</view>
<view class="th">总气量 </view>
<view class="th">年累计 </view>
</view>
<view class="table">
<!-- 表头 -->
<view class="tr header">
<view class="th1">序号</view>
<view class="th">名称</view>
<view class="th">日气量</view>
<view class="th">年累计</view>
<view class="th1">操作</view>
</view>
<scroll-view scroll-X="true" scroll-Y="true" class="table-container">
<!-- 表格内容 -->
<view class="tr" v-for="(item, index) in filteredData" :key="index"
:class="{ even: index % 2 === 0 }">
<view class="td1">{{ index }}</view>
<view class="td1">{{ index + 1 }}</view>
<view class="td">{{ item.unit }}</view>
<view class="td" :class="{ negative: item.rq < 0 }">
{{ formatNumber(item.rq) }}
</view>
<view class="td">{{ formatNumber(item.totalGas) }}</view>
<view class="td" :class="{ negative: item.yearVolume < 0 }">
{{ formatNumber(item.yearVolume) }}
</view>
<view class="td1" style="color: red" @click="goHistory(item)">历史</view>
</view>
<!-- 空数据提示 -->
<view v-if="!filteredData.length" class="empty">
暂无相关数据
</view>
</view>
</scroll-view>
<view v-if="!filteredData.length" class="empty">暂无相关数据</view>
</scroll-view>
</view>
</view>
</uni-popup>
</view>
</template>
@ -76,7 +84,8 @@
} from '@dcloudio/uni-app';
import {
queryJinriShengchansj,
queryYearShengchansj
queryYearShengchansj,
queryJinriTrqShengchansj
} from '@/api/shengchan.js';
import {
formatDate,
@ -88,48 +97,44 @@
import {
useStore
} from '@/store';
import {
getYearProgress
} from '@/utils/dateTime.js';
const store = useStore();
const shishiArr = ref([{
gas: '气井气',
dailyVolume: '',
yearVolume: ''
},
{
gas: '伴生气',
dailyVolume: '',
yearVolume: ''
},
{
gas: '外部气',
dailyVolume: '',
yearVolume: ''
},
{
gas: '站输差',
dailyVolume: '',
yearVolume: ''
},
{
gas: '线输差',
dailyVolume: '',
yearVolume: ''
},
{
gas: '综合输差',
dailyVolume: '',
yearVolume: ''
}
]);
const shishiArr = ref([]);
const dataJinriUnit = ref([]);
const selectedGas = ref('');
const filteredData = ref([]);
const popup = ref(null);
const strDate = ref('');
const timePercent = ref(0);
const dataJinri = ref([]);
const dataJinriSum = ref([]);
const dataJinriSumUnit = ref([]);
const selectedGas = ref('');
const filteredData = ref([]);
const popup = ref(null);
//
// const handleCardClick = (gas) => {
// selectedGas.value = gas;
// let queryParms = {};
// filteredData.value = [];
// queryParms.day = strDate.value;
// queryParms.gas = gas;
// queryParms.unit = '23,';
// console.log(queryParms);
// queryJinriTrqShengchansj(queryParms).then((res) => {
// if (res.success) {
// console.log(res);
// filteredData.value = res.result;
// }
// });
// popup.value.open();
// };
const handleCardClick = (gas) => {
selectedGas.value = gas;
filteredData.value = dataJinriSumUnit.value.filter(item => item.gas === gas);
@ -141,42 +146,135 @@
popup.value.close();
};
onMounted(() => {
getJinriShengchansj();
getYearShengchansj();
getJinriTrqShengchansj();
timePercent.value = getYearProgress();
getJinriShengchansj()
});
const strDate = ref('');
//
const formatNumber = (num) => {
if (typeof num !== 'number') return '-';
return num.toFixed(4).replace(/\.?0+$/, '');
let temp = 0;
try {
temp = parseFloat(num);
} catch (error) {
//TODO handle the exception
}
return temp.toFixed(4).replace(/\.?0+$/, '');
};
//
const groupedData = computed(() => {
const groups = [];
for (let i = 0; i < shishiArr.value.length; i += 3) {
groups.push(shishiArr.value.slice(i, i + 3));
}
return groups;
});
//
watchEffect(() => {
const station = shishiArr.value[3] //
const line = shishiArr.value[4] // 线
const composite = shishiArr.value[5] //
function calcZhsc(tempArray) {
let totalJinqi = {
gas: '总进气',
dailyVolume: 0,
yearVolume: 0,
yearPlan: '100',
yearPerCent: 0
};
let totalChuqi = {
gas: '总出气',
dailyVolume: 0,
yearVolume: 0,
yearPlan: '100',
yearPerCent: 0
};
const compositeZx = {
gas: '站线综合输差',
dailyVolume: 0,
yearVolume: 0,
yearPlan: '100',
yearPerCent: 0
}; //
const compositeJc = {
gas: '进出综合输差',
dailyVolume: 0,
yearVolume: 0,
yearPlan: '100',
yearPerCent: 0
}; //
tempArray.forEach((item) => {
if (item.gas === '站输差' || item.gas === '线输差') {
compositeZx.dailyVolume += parseFloat(item.dailyVolume) || 0;
compositeZx.yearVolume += parseFloat(item.yearVolume) || 0;
}
if (item.gas === '气井气' || item.gas === '外部气' || item.gas === '返回气') {
totalJinqi.dailyVolume += parseFloat(item.dailyVolume) || 0;
totalJinqi.yearVolume += parseFloat(item.yearVolume) || 0;
}
if (item.gas === '自耗气' || item.gas === '用户气' || item.gas === '返采油厂干气') {
totalChuqi.dailyVolume += parseFloat(item.dailyVolume) || 0;
totalChuqi.yearVolume += parseFloat(item.yearVolume) || 0;
}
});
compositeZx.yearPerCent = calcPercent(compositeZx.yearPlan, compositeZx.yearVolume);
compositeJc.dailyVolume = (-totalJinqi.dailyVolume + totalChuqi.dailyVolume).toFixed(4);
compositeJc.yearVolume = (-totalJinqi.yearVolume + totalChuqi.yearVolume).toFixed(4);
compositeJc.yearPerCent = calcPercent(compositeJc.yearPlan, compositeJc.yearVolume);
tempArray.push(compositeZx);
// tempArray.push(compositeJc);
return tempArray
// console.log(composite);
};
const getJinriTrqShengchansj = () => {
const now = new Date();
if (now.getHours() < 11) {
strDate.value = formatDate(getDateAfterDays(now, -1)).toString(); //11
} else {
strDate.value = formatDate(now).toString();
}
let queryParms = {};
shishiArr.value = [];
queryParms.day = strDate.value;
// // console.log(queryParms);
queryJinriTrqShengchansj(queryParms).then((res) => {
if (res.success) {
console.log(1, res);
let temp = res.result;
temp.forEach((item) => {
if (item.gas === '气井气') {
item.yearPlan = 7500;
item.yearPerCent = calcPercent(item.yearPlan, item.yearVolume);
}
});
console.log(2, temp)
shishiArr.value = calcZhsc(temp);
console.log(3, shishiArr.value)
}
});
};
function goHistory(val) {
uni.navigateTo({
url: '/pages/views/shengchan/ribaoshuju/rbsjLsxq?data=' + JSON.stringify(val) + '&type=trq'
});
}
function calcPercent(yearJihua, yearShiji) {
// 0
// 100
let plan = parseFloat(yearJihua === '' ? 0 : yearJihua);
let shiji = parseFloat(yearShiji);
let percent = 0;
//
if (plan > 0) {
percent = (shiji / plan) * 100;
percent = Math.min(percent, 100); // 100%
}
return parseFloat(percent.toFixed(2)); //
}
//
const dailyStation = parseFloat(station.dailyVolume) || 0
const dailyLine = parseFloat(line.dailyVolume) || 0
composite.dailyVolume = (dailyStation + dailyLine).toFixed(4)
//
const yearStation = parseFloat(station.yearVolume) || 0
const yearLine = parseFloat(line.yearVolume) || 0
composite.yearVolume = (yearStation + yearLine).toFixed(4)
})
const getJinriShengchansj = () => {
@ -318,7 +416,7 @@
.popup-content {
padding: 30rpx;
max-height: 70vh;
max-height: 40vh;
}
.popup-header {
@ -365,10 +463,13 @@
flex: 1;
min-width: 80rpx;
padding: 10rpx;
font-size: 20rpx;
font-size: 22rpx;
font-weight: bold;
color: #333;
text-align: center;
white-space: nowrap;
height: 30rpx;
vertical-align: middle;
}
.th1,
@ -376,10 +477,13 @@
flex: 1;
max-width: 40rpx;
padding: 10rpx;
font-size: 20rpx;
font-size: 22rpx;
font-weight: bold;
color: #333;
text-align: center;
white-space: nowrap;
height: 30rpx;
vertical-align: middle;
}
.th {
@ -445,4 +549,39 @@
}
}
}
.progress-item {
margin-bottom: 20px;
}
.progress-bar {
position: relative;
height: 20px;
background: #f0f0f0;
border-radius: 10px;
overflow: hidden;
}
.progress {
height: 100%;
transition: all 0.3s;
}
.progressTime {
height: 100%;
transition: all 0.3s;
}
.progress-text {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
color: red;
/* 保持红色 */
font-size: 12px;
font-weight: bold;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
/* 提升可读性 */
}
</style>

View File

@ -18,6 +18,19 @@
<text class="label">年累计</text>
<text class="value">{{ item.nl || '-' }}</text>
</view>
<view class="progress-bar">
<!-- 动态设置宽度和颜色 -->
<view
class="progress"
:style="{
width: `${Math.abs(item.yearPerCent)}%`,
'background-color': item.yearPerCent < 0 ? '#ff4444' : '#007aff'
}"
></view>
<!-- 显示带符号的百分比 -->
<text v-if="!(item.yearPlan === '' || item.yearPlan === '0')" class="progress-text">{{ item.yearPerCent }}%</text>
</view>
</view>
</view>
</view>
@ -33,17 +46,17 @@
<view class="table">
<!-- 表头 -->
<view class="tr header">
<view class="th">序号</view>
<view class="th1">序号</view>
<view class="th">名称</view>
<view class="th">日油量</view>
<view class="th">月累计 </view>
<view class="th">年累计 </view>
<view class="th">月累计</view>
<view class="th">年累计</view>
<view class="th1">操作</view>
</view>
<!-- 表格内容 -->
<view class="tr" v-for="(item, index) in dataJinri" :key="index"
:class="{ even: index % 2 === 0 }">
<view class="td">{{ index }}</view>
<view class="tr" v-for="(item, index) in dataJinri" :key="index" :class="{ even: index % 2 === 0 }">
<view class="td1">{{ index }}</view>
<view class="td">{{ item.dw }}</view>
<view class="td">
{{ formatNumber(item.rcwy) }}
@ -52,275 +65,305 @@
<view class="td">
{{ formatNumber(item.nl) }}
</view>
<view class="td1" style="color: red" @click="goHistory(item)">历史</view>
</view>
<!-- 空数据提示 -->
<view v-if="!dataJinri.length" class="empty">
暂无相关数据
</view>
<view v-if="!dataJinri.length" class="empty">暂无相关数据</view>
</view>
</scroll-view>
</view>
</uni-popup>
</view>
</template>
<script setup>
import {
ref,
onMounted,
computed,
nextTick,
watchEffect
} from 'vue';
import {
onLoad
} from '@dcloudio/uni-app';
import {
queryJinriYuanyouShengchansj
} from '@/api/shengchan.js';
import {
formatDate,
getDateAfterDays
} from '@/utils/dateTime.js';
import {
beforeJump
} from '@/utils/index.js';
import {
useStore
} from '@/store';
import { ref, onMounted, computed, nextTick, watchEffect } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { queryJinriYuanyouShengchansj } from '@/api/shengchan.js';
import { formatDate, getDateAfterDays } from '@/utils/dateTime.js';
import { beforeJump } from '@/utils/index.js';
import { useStore } from '@/store';
const store = useStore();
import dataCom from '@/bpm/dataCom.vue';
const store = useStore();
import dataCom from '@/bpm/dataCom.vue';
const shishiArr = ref([{
gas: '原油产量',
rcwy: '',
yl: '',
nl: ''
},
]);
const dataJinri = ref([]);
const dataJinriSum = ref([]);
const popup = ref(null);
//
const handleCardClick = () => {
popup.value.open();
};
//
const closePopup = () => {
popup.value.close();
};
onMounted(() => {
getJinriYuanyouShengchansj();
// getYearShengchansj();
});
const strDate = ref('');
//
const formatNumber = (num) => {
if (typeof num !== 'number') return '-';
return num.toFixed(4).replace(/\.?0+$/, '');
};
const getJinriYuanyouShengchansj = () => {
const now = new Date();
if (now.getHours() < 11) {
strDate.value = formatDate(getDateAfterDays(now, -1)).toString(); //11
} else {
strDate.value = formatDate(now).toString();
}
let queryParms = {};
dataJinri.value = [];
dataJinriSum.value = [];
queryParms.scrq = strDate.value;
queryParms.pageSize = 100;
console.log(queryParms);
queryJinriYuanyouShengchansj(queryParms).then((res) => {
if (res.success) {
console.log(res);
dataJinri.value = res.result.records;
dataJinriSum.value = sumByOil(dataJinri.value); //gas unit rq cq totalGas
console.log(dataJinriSum.value);
nextTick();
shishiArr.value.forEach((item) => {
dataJinriSum.value.forEach((itemjinri) => {
item.rcwy = itemjinri.rcwy.toFixed(4);
item.nl = itemjinri.nl.toFixed(4);
item.yl = itemjinri.yl.toFixed(4);
});
});
// getYearShengchansj(); //
}
});
};
function sumByOil(records) {
console.log(records);
const summaryMap = {};
try {
records.forEach((record) => {
const gas = record.gas;
if (!summaryMap[gas]) {
// gas
summaryMap[gas] = {
rcwy: 0,
yl: 0,
nl: 0
};
}
// gas
summaryMap[gas].rcwy += record.rcwy || 0;
summaryMap[gas].yl += record.yl || 0;
summaryMap[gas].nl += record.nl || 0
});
return Object.values(summaryMap);
} catch (error) {
//TODO handle the exception
console.log(error);
}
const shishiArr = ref([
{
gas: '原油产量',
rcwy: '',
yl: '',
nl: '',
yearPlan: '1500',
yearPerCent: ''
}
]);
const dataJinri = ref([]);
const dataJinriSum = ref([]);
const popup = ref(null);
//
const handleCardClick = () => {
popup.value.open();
};
//
const closePopup = () => {
popup.value.close();
};
onMounted(() => {
getJinriYuanyouShengchansj();
// getYearShengchansj();
});
const strDate = ref('');
//
const formatNumber = (num) => {
if (typeof num !== 'number') return '-';
return num.toFixed(4).replace(/\.?0+$/, '');
};
function goHistory(val) {
uni.navigateTo({
url: '/pages/views/shengchan/ribaoshuju/rbsjLsxq?data=' + JSON.stringify(val) + '&type=yy'
});
}
const getJinriYuanyouShengchansj = () => {
const now = new Date();
if (now.getHours() < 11) {
strDate.value = formatDate(getDateAfterDays(now, -1)).toString(); //11
} else {
strDate.value = formatDate(now).toString();
}
let queryParms = {};
dataJinri.value = [];
dataJinriSum.value = [];
queryParms.scrq = strDate.value;
queryParms.pageSize = 100;
// // console.log(queryParms);
queryJinriYuanyouShengchansj(queryParms).then((res) => {
if (res.success) {
// // console.log(res);
dataJinri.value = res.result.records;
dataJinriSum.value = sumByOil(dataJinri.value); //gas unit rq cq totalGas
// // console.log(dataJinriSum.value);
nextTick();
shishiArr.value.forEach((item) => {
dataJinriSum.value.forEach((itemjinri) => {
item.rcwy = itemjinri.rcwy.toFixed(4);
item.nl = itemjinri.nl.toFixed(4);
item.yl = itemjinri.yl.toFixed(4);
item.yearPerCent = calcPercent(item.yearPlan, item.nl);
});
});
// getYearShengchansj(); //
}
});
};
function calcPercent(yearJihua, yearShiji) {
// 0
// 100
let plan = parseFloat(yearJihua === '' ? 0 : yearJihua);
let shiji = parseFloat(yearShiji);
let percent = 0;
//
if (plan > 0) {
percent = (shiji / plan) * 100;
percent = Math.min(percent, 100); // 100%
}
return parseFloat(percent.toFixed(2)); //
}
function sumByOil(records) {
// console.log(records);
const summaryMap = {};
try {
records.forEach((record) => {
const gas = record.gas;
if (!summaryMap[gas]) {
// gas
summaryMap[gas] = {
rcwy: 0,
yl: 0,
nl: 0
};
}
// gas
summaryMap[gas].rcwy += record.rcwy || 0;
summaryMap[gas].yl += record.yl || 0;
summaryMap[gas].nl += record.nl || 0;
});
return Object.values(summaryMap);
} catch (error) {
//TODO handle the exception
// console.log(error);
}
}
</script>
<style lang="scss" scoped>
.container {
.container {
display: flex;
flex-wrap: wrap;
padding: 20rpx;
gap: 20rpx;
}
.popup-content {
padding: 30rpx;
max-height: 70vh;
}
.popup-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30rpx;
padding-bottom: 20rpx;
border-bottom: 2rpx solid #eee;
.title {
font-size: 32rpx;
font-weight: 600;
color: #333;
}
}
.table-container {
width: 100%;
height: 30vh;
overflow: hidden;
}
.table {
min-width: 100%;
border: 2rpx solid #e8e8e8;
.tr {
display: flex;
flex-wrap: wrap;
padding: 20rpx;
gap: 20rpx;
border-bottom: 2rpx solid #e8e8e8;
&.header {
background-color: #fafafa;
font-weight: 600;
}
&.even {
background-color: #f8f8f8;
}
}
.popup-content {
padding: 30rpx;
max-height: 70vh;
.th,
.td {
flex: 1;
min-width: 80rpx;
padding: 10rpx;
font-size: 20rpx;
font-weight: 500;
color: #333;
text-align: center;
white-space: nowrap;
}
.th1,
.td1 {
flex: 1;
max-width: 40rpx;
padding: 10rpx;
font-size: 22rpx;
font-weight: bold;
color: #333;
text-align: center;
white-space: nowrap;
height: 30rpx;
vertical-align: middle;
}
.popup-header {
.th {
background-color: #f0f0f0;
}
.td.negative {
color: #ff4444;
font-weight: 500;
}
}
.empty {
padding: 40rpx;
text-align: center;
color: #888;
font-size: 16rpx;
}
.card-item {
flex: 1 1 200rpx; // 300rpx selectedGas formatNumber
min-width: 200rpx;
max-width: calc(50% - 10rpx); //
@media (min-width: 768px) {
max-width: calc(33.33% - 14rpx); // 3
}
}
.card {
background: #ffffff;
border-radius: 16rpx;
padding: 10rpx;
box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
.title {
display: block;
font-size: 28rpx;
font-weight: 600;
color: #333;
margin-bottom: 16rpx;
}
.content {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30rpx;
padding-bottom: 20rpx;
border-bottom: 2rpx solid #eee;
margin-bottom: 10rpx;
.title {
font-size: 32rpx;
font-weight: 600;
color: #333;
}
}
.table-container {
width: 100%;
height: 30vh;
overflow: hidden;
}
.table {
min-width: 100%;
border: 2rpx solid #e8e8e8;
.tr {
display: flex;
border-bottom: 2rpx solid #e8e8e8;
&.header {
background-color: #fafafa;
font-weight: 600;
}
&.even {
background-color: #f8f8f8;
}
&:last-child {
margin-bottom: 0;
}
.th,
.td {
flex: 1;
min-width: 80rpx;
padding: 10rpx;
font-size: 20rpx;
font-weight: 500;
color: #333;
text-align: center;
white-space: nowrap;
.label {
font-size: 24rpx;
color: #666;
}
.th {
background-color: #f0f0f0;
}
.td.negative {
color: #ff4444;
font-weight: 500;
}
}
.empty {
padding: 40rpx;
text-align: center;
color: #888;
font-size: 16rpx;
}
.card-item {
flex: 1 1 200rpx; // 300rpx selectedGas formatNumber
min-width: 200rpx;
max-width: calc(50% - 10rpx); //
@media (min-width: 768px) {
max-width: calc(33.33% - 14rpx); // 3
}
}
.card {
background: #ffffff;
border-radius: 16rpx;
padding: 10rpx;
box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
.title {
display: block;
.value {
font-size: 28rpx;
font-weight: 600;
color: #333;
margin-bottom: 16rpx;
}
.content {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10rpx;
&:last-child {
margin-bottom: 0;
}
.label {
font-size: 24rpx;
color: #666;
}
.value {
font-size: 28rpx;
color: #0000ff;
font-weight: 500;
}
color: #0000ff;
font-weight: 500;
}
}
</style>
}
.progress-item {
margin-bottom: 20px;
}
.progress-bar {
position: relative;
height: 20px;
background: #f0f0f0;
border-radius: 10px;
overflow: hidden;
}
.progress {
height: 100%;
transition: all 0.3s;
}
.progress-text {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
color: red; /* 保持红色 */
font-size: 12px;
font-weight: bold;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); /* 提升可读性 */
}
</style>

View File

@ -0,0 +1,118 @@
<template>
<view class="compact-datetime-picker">
<!-- 输入框区域 -->
<view class="input-container">
<view class="compact-input" @click="openPicker">
{{ dateRange[0] || '开始日期' }}
</view>
<text class="separator"></text>
<view class="compact-input" @click="openPicker">
{{ dateRange[1] || '结束日期' }}
</view>
</view>
<wu-calendar ref="calendar" :mode="mode" :date="dateRange" @confirm="calendarConfirm"
slideSwitchMode="horizontal" type="month" :fold="false" :insert="false" :rangeSameDay="true" :lunar="true"
:monthShowCurrentMonth="false" :range-end-repick="true" :item-height="45"
:rangeEndRepick="true"></wu-calendar>
</view>
</template>
<script>
import {
formatDate,
getDateAfterDays,
getDateAfterMonths
} from '@/utils/dateTime.js';
export default {
props: {
modelValue: {
type: Array,
default: () => [null, null]
},
//
mode: {
type: String,
default: 'single'
},
},
data() {
return {
dateRange: null
};
},
watch: {
modelValue: {
immediate: true,
handler(newVal) {
console.log(44, JSON.stringify(newVal))
let dateType = Object.prototype.toString.call(newVal);
if (this.mode == 'single' && dateType != '[object String]') {
return console.error(`类型错误mode=${this.mode}date=String`);
} else if (this.mode != 'single' && dateType != '[object Array]') {
return console.error(`类型错误mode=${this.mode}date=Array`);
}
if (this.mode == 'single') {
this.dateRange = ''
this.dateRange = newVal;
}
//
if (this.mode == 'multiple') {
this.dateRange = []
this.dateRange = newVal;
} else if (this.mode == 'range') {
this.dateRange = []
this.dateRange.push(formatDate(new Date(newVal[0])));
this.dateRange.push(formatDate(new Date(newVal[1])));
}
}
}
},
methods: {
openPicker() {
this.$refs.calendar.open();
},
calendarConfirm(e) {
this.dateRange = [];
try {
this.dateRange.push(formatDate(new Date(e.range.before)));
this.dateRange.push(formatDate(new Date(e.range.after)));
} catch (error) {
return;
//TODO handle the exception
}
this.$emit('update:modelValue', this.dateRange);
}
}
};
</script>
<style scoped>
.input-container {
display: flex;
align-items: center;
gap: 10px;
}
/* 紧凑型输入框 */
.compact-input {
flex: 1;
padding: 6px 8px;
font-size: 16px;
height: 20px;
line-height: 20px;
border: 1px solid #dcdfe6;
border-radius: 4px;
text-align: center;
width: 120px;
}
.compact-input.active {
border-color: #409eff;
background-color: #f5f7ff;
}
</style>

View File

@ -0,0 +1,83 @@
{
"id": "cxc-szcx-dateRangeSelect",
"displayName": "cxc-szcx-dateRangeSelect",
"version": "1.0.0",
"description": "cxc-szcx-dateRangeSelect",
"keywords": [
"cxc-szcx-dateRangeSelect"
],
"repository": "",
"engines": {
"HBuilderX": "^3.1.0"
},
"dcloudext": {
"type": "component-vue",
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "",
"data": "",
"permissions": ""
},
"npmurl": ""
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "u",
"aliyun": "u",
"alipay": "u"
},
"client": {
"Vue": {
"vue2": "u",
"vue3": "u"
},
"App": {
"app-vue": "u",
"app-nvue": "u",
"app-uvue": "u"
},
"H5-mobile": {
"Safari": "u",
"Android Browser": "u",
"微信浏览器(Android)": "u",
"QQ浏览器(Android)": "u"
},
"H5-pc": {
"Chrome": "u",
"IE": "u",
"Edge": "u",
"Firefox": "u",
"Safari": "u"
},
"小程序": {
"微信": "u",
"阿里": "u",
"百度": "u",
"字节跳动": "u",
"QQ": "u",
"钉钉": "u",
"快手": "u",
"飞书": "u",
"京东": "u"
},
"快应用": {
"华为": "u",
"联盟": "u"
}
}
}
}
}

View File

@ -0,0 +1,139 @@
# cxc-szcx-dateRangeSelect
# # 紧凑型日期时间选择器组件说明书
## 一、组件概述
`compact-datetime-picker` 是一个基于 Vue 开发的紧凑型日期时间选择器组件,用于在页面中选择日期范围。组件提供了自然周期和相对周期两种选择模式,并且支持快捷选择本周、本月、本季、本年、近一周、近一月、近一季、近一年等常见时间范围。
## 二、组件依赖
- **Vue**:组件基于 Vue 框架开发。
- **uni-popup**:来自 `uni-app` 的弹窗组件,用于显示日期选择器的弹出层。
## 三、组件使用方法
### 1. 引入组件
在需要使用该组件的 Vue 文件中,引入 `compact-datetime-picker` 组件。
```vue
<template>
<view>
<compact-datetime-picker v-model="dateRange" />
</view>
</template>
<script>
import CompactDateTimePicker from '@/components/compact-datetime-picker.vue';
export default {
components: {
CompactDateTimePicker
},
data() {
return {
dateRange: [null, null]
};
}
};
</script>
```
### 2. 组件属性
| 属性名 | 类型 | 默认值 | 描述 |
| ---- | ---- | ---- | ---- |
| `modelValue` | `Array` | `[null, null]` | 双向绑定的日期范围数组,第一个元素为开始日期,第二个元素为结束日期。 |
## 四、组件内部实现
### 1. 模板部分
- **输入框区域**:显示开始日期和结束日期的输入框,点击输入框可打开日期选择弹窗。
- **日期选择弹窗**
- **快捷按钮区域**:包含自然周期和相对周期的切换按钮,以及不同模式下的快捷操作按钮。
- **日历选择区域**:显示当前月份的日历,可选择日期。
- **操作按钮**:包含取消和确定按钮,用于关闭弹窗和确认选择的日期范围。
### 2. 脚本部分
#### 2.1 数据属性
```javascript
data() {
return {
isNatural: true, // 是否为自然周期模式
activeType: 'start', // 当前活跃的日期选择类型(开始或结束)
currentMonth: new Date(), // 当前显示的月份
tempStart: null, // 临时开始日期
tempEnd: null, // 临时结束日期
weekDays: ['日', '一', '二', '三', '四', '五', '六'], // 星期几的显示文本
quickButtonszr: [
{ label: '本周', type: 'week' },
{ label: '本月', type: 'month' },
{ label: '本季', type: 'quarter' },
{ label: '本年', type: 'year' }
], // 自然周期模式下的快捷按钮
quickButtonsxd: [
{ label: '近一周', type: 'week' },
{ label: '近一月', type: 'month' },
{ label: '近一季', type: 'quarter' },
{ label: '近一年', type: 'year' }
] // 相对周期模式下的快捷按钮
};
}
```
#### 2.2 计算属性
- `formattedStart`:格式化后的开始日期。
- `formattedEnd`:格式化后的结束日期。
- `calendarDays`:生成当前月份的日历数据。
- `monthText`:当前月份的显示文本。
#### 2.3 监听属性
```javascript
watch: {
modelValue: {
immediate: true,
handler(newVal) {
this.tempStart = newVal[0];
this.tempEnd = newVal[1];
}
}
}
```
监听 `modelValue` 的变化,初始化临时日期。
#### 2.4 方法
- **打开弹窗并初始化临时值**`openPicker(type)`,打开日期选择弹窗,并根据活跃类型初始化临时日期。
- **日期点击处理**`handleDayClick(day)`,处理日期点击事件,更新临时开始或结束日期。
- **确认选择**`confirmSelection()`,确认选择的日期范围,触发 `update:modelValue` 事件并关闭弹窗。
- **关闭弹窗**`closePicker()`,关闭日期选择弹窗,并重置临时日期。
- **重置临时日期**`resetTempDates()`,将临时日期重置为当前的 `modelValue`
- **生成日历数据**`generateCalendar(date)`,根据给定的月份生成日历数据。
- **日期选择处理**`selectDate(date)`,处理日期选择,更新 `modelValue`
- **切换月份**`changeMonth(offset)`,切换当前显示的月份。
- **判断日期状态**
- `isSelected(date)`:判断日期是否被选中。
- `isEnd(date)`:判断日期是否为结束日期。
- `isToday(date)`:判断日期是否为今天。
- `isStart(date)`:判断日期是否为开始日期。
- `isInRange(date)`:判断日期是否在选择的范围内。
- `isSameDay(d1, d2)`:判断两个日期是否为同一天。
- **快捷范围设置**`setQuickRange(type)`,根据快捷按钮的类型设置日期范围,并关闭弹窗。
- **自然周期计算**`calcNaturalRange(type, currentDate)`,计算自然周期模式下的日期范围。
- **相对周期计算**`calcRelativeRange(type, currentDate)`,计算相对周期模式下的日期范围。
- **周计算(周一为起点)**
- `getWeekStart(date)`:获取一周的开始日期。
- `getWeekEnd(startDate)`:获取一周的结束日期。
- **月末处理**`lastDayOfMonth(date)`,获取给定月份的最后一天。
- **月末日调整**`adjustMonthEnd(start, end)`,调整开始日期到合适的月末日期。
- **闰年判断**`isLeapYear(year)`,判断给定年份是否为闰年。
- **模式切换**`toggleMode(isNatural)`,切换自然周期和相对周期模式。
- **日期格式化**`formatDate(date)`,将日期格式化为 `YYYY-MM-DD` 的字符串。
### 3. 样式部分
- **输入框区域**:设置输入框的样式,包括边框、背景色、字体大小等。
- **紧凑弹窗**:设置弹窗的整体样式,包括背景色、边框半径等。
- **紧凑头部**:设置月份标题和导航箭头的样式。
- **紧凑日期网格**:设置星期几和日期的显示样式,以及不同状态下的日期背景色和字体颜色。
- **快捷按钮区域**:设置模式切换按钮和快捷操作按钮的样式。
- **底部操作**:设置取消和确定按钮的样式。
## 五、注意事项
- 组件使用了 `uni-popup` 组件,确保项目中已正确引入和配置。
- 日期范围的选择逻辑较为复杂,特别是在自然周期和相对周期的切换以及快捷范围设置时,需注意日期的计算和显示。
- 组件的样式是基于 `scoped` 作用域的,可根据项目需求进行调整和扩展。

View File

@ -0,0 +1,274 @@
<template>
<view>
<!-- ECharts图表 -->
<view class="chart-container">
<l-echart ref="chart" @finished="initChart" />
</view>
</view>
</template>
<script setup>
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';
import { formatDate, getDateAfterDays, getDateAfterMonths } from '@/utils/dateTime.js';
const props = defineProps({
dataList: {
type: Array,
default: () => [],
required: true
},
xField: {
type: String,
default: 'rqDate'
},
yField: {
type: String,
default: 'rq'
},
legendField: {
type: String,
default: 'unit'
},
referenceValue: {
type: Number,
default: 0
}
});
const chart = ref(null);
const chartOption = ref({});
const chartTitle = ref('');
//
const processSeriesData = () => {
const legendItems = [...new Set(props.dataList.map((item) => item[props.legendField]?.trim() || '未命名'))];
return legendItems.map((legend) => {
const items = props.dataList
.filter((item) => item[props.legendField] === legend)
.sort((a, b) => new Date(a[props.xField]) - new Date(b[props.xField]))
.map((item) => ({
name: item[props.xField],
value: [
formatDate(item[props.xField]), // X
parseFloat(item[props.yField]) || 0 // Y
]
}));
return {
name: legend,
type: 'line',
showSymbol: true,
smooth: true,
data: items
};
});
};
//
watch(
() => props.dataList,
() => {
chartTitle.value = '历史趋势';
updateChart();
},
{ deep: true }
);
//
onMounted(() => {});
onUnmounted(() => {
if (chart.value) {
chart.value.dispose();
chart.value = null;
}
});
// formatDate
const updateChart = () => {
if (!chart.value) return;
chartOption.value = generateOptions();
chart.value.setOption(chartOption.value, true);
};
//
const generateOptions = () => ({
title: {
text: chartTitle.value,
padding: [0, 0, 0, 30]
},
tooltip: {
trigger: 'axis',
backgroundColor: 'rgba(255, 255, 255, 0.96)',
borderColor: '#eee',
borderWidth: 1,
textStyle: {
color: '#333',
fontSize: 14
},
axisPointer: {
type: 'line',
lineStyle: {
color: '#FF6B6B',
width: 1,
type: 'dashed'
}
},
confine: true // tooltip
},
backgroundColor: 'rgba(255, 255, 255, 0.8)',
textStyle: {
color: '#666',
fontSize: 12
},
xAxis: {
type: 'time',
axisLine: {
lineStyle: {
color: '#ddd'
}
},
axisLabel: {
color: '#666',
formatter: '{MM}-{dd}',
rotate: 30
},
splitLine: {
show: true,
lineStyle: {
color: '#f5f5f5'
}
}
},
yAxis: {
type: 'value',
axisLine: {
show: true,
lineStyle: {
color: '#ddd'
}
},
splitLine: {
lineStyle: {
color: '#f5f5f5'
}
},
axisLabel: {
color: '#666',
formatter: (value) => `${value.toFixed(2)}`
}
},
series: [
...processSeriesData().map((series) => ({
...series,
lineStyle: {
width: 2,
shadowColor: 'rgba(0, 0, 0, 0.1)',
shadowBlur: 6,
shadowOffsetY: 3
},
itemStyle: {
color: '#00007f', //
borderColor: '#fff',
borderWidth: 1
}
})),
{
type: 'line',
markLine: {
silent: true,
lineStyle: {
type: 'dashed',
color: '#FF4757',
width: 2
},
data: [{ yAxis: props.referenceValue }],
label: {
show: true,
position: 'end',
formatter: `参考值: ${props.referenceValue}`,
fontSize: 12
}
},
data: [] // 线
}
],
legend: {
type: 'scroll',
bottom: 5,
textStyle: {
color: '#666',
fontSize: 12
},
pageIconColor: '#FF6B6B',
pageTextStyle: {
color: '#999'
}
},
grid: {
top: 30,
right: 30,
bottom: 40,
left: 20,
containLabel: true
},
dataZoom: [
{
type: 'inside',
start: 0,
end: 100,
minValueSpan: 3600 * 24 * 1000 * 7 // 7
}
]
});
//
const initChart = () => {
setTimeout(async () => {
if (!chart.value) return;
const myChart = await chart.value.init(echarts);
myChart.setOption(chartOption.value);
}, 300);
};
</script>
<style scoped>
/* 容器样式 */
.chart-container {
width: 100%;
height: 30vh;
min-height: 200px;
padding: 20rpx;
background: linear-gradient(145deg, #f8f9fa 0%, #ffffff 100%);
border-radius: 16rpx;
box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
position: relative;
overflow: hidden;
}
/* 图表加载占位 */
.chart-container::before {
/* content: '数据加载中...'; */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #666;
font-size: 28rpx;
z-index: 1;
}
/* 图表主体样式 */
.chart-wrapper {
width: 100%;
height: 100%;
transition: opacity 0.3s ease;
}
/* 移动端优化 */
@media screen and (max-width: 768px) {
.chart-container {
height: 30vh;
min-height: 200px;
padding: 10rpx;
border-radius: 12rpx;
}
}
</style>

View File

@ -0,0 +1,83 @@
{
"id": "cxc-szcx-lineChart",
"displayName": "cxc-szcx-lineChart",
"version": "1.0.0",
"description": "cxc-szcx-lineChart",
"keywords": [
"cxc-szcx-lineChart"
],
"repository": "",
"engines": {
"HBuilderX": "^3.1.0"
},
"dcloudext": {
"type": "component-vue",
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "",
"data": "",
"permissions": ""
},
"npmurl": ""
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "u",
"aliyun": "u",
"alipay": "u"
},
"client": {
"Vue": {
"vue2": "u",
"vue3": "u"
},
"App": {
"app-vue": "u",
"app-nvue": "u",
"app-uvue": "u"
},
"H5-mobile": {
"Safari": "u",
"Android Browser": "u",
"微信浏览器(Android)": "u",
"QQ浏览器(Android)": "u"
},
"H5-pc": {
"Chrome": "u",
"IE": "u",
"Edge": "u",
"Firefox": "u",
"Safari": "u"
},
"小程序": {
"微信": "u",
"阿里": "u",
"百度": "u",
"字节跳动": "u",
"QQ": "u",
"钉钉": "u",
"快手": "u",
"飞书": "u",
"京东": "u"
},
"快应用": {
"华为": "u",
"联盟": "u"
}
}
}
}
}

View File

@ -0,0 +1,179 @@
# cxc-szcx-lineChart
# # `line-chart.vue` 组件说明书
## 一、组件概述
`line-chart.vue` 是一个基于 ECharts 实现的折线图组件,用于在 UniApp 项目中展示数据的折线图。该组件接收一系列数据和配置参数,支持动态更新数据,并展示参考线。
## 二、组件依赖
- **Vue 3**:使用 Vue 3 的组合式 API 进行开发。
- **ECharts**:用于绘制折线图。
- **`lime-echart`**UniApp 插件,提供 ECharts 的渲染支持。
## 三、组件使用方法
### 1. 引入组件
在需要使用该组件的页面中引入 `line-chart.vue` 组件。
```vue
<template>
<view>
<line-chart
:dataList="dataList"
:xField="xField"
:yField="yField"
:legendField="legendField"
:referenceValue="referenceValue"
/>
</view>
</template>
<script setup>
import LineChart from '@/components/line-chart.vue';
const dataList = [
{ date: '2023-01-01', value: 10, category: 'A' },
// 更多数据...
];
const xField = 'date';
const yField = 'value';
const legendField = 'category';
const referenceValue = 15;
</script>
```
### 2. 组件属性
| 属性名 | 类型 | 默认值 | 描述 |
| ---- | ---- | ---- | ---- |
| `dataList` | `Object` | `[]` | 包含图表数据的数组,每个元素是一个对象,包含 `xField`、`yField` 和 `legendField` 对应的数据。 |
| `xField` | `String` | `''` | 数据中用于表示 x 轴的字段名。 |
| `yField` | `String` | `''` | 数据中用于表示 y 轴的字段名。 |
| `legendField` | `String` | `''` | 数据中用于表示图例的字段名。 |
| `referenceValue` | `Number` | `10` | 图表中参考线的数值。 |
## 四、组件内部实现
### 1. 模板部分
```vue
<template>
<view class="chart-container">
<l-echart ref="chart" @init="initChart"></l-echart>
</view>
</template>
```
- 使用 `l-echart` 组件渲染图表,通过 `ref` 绑定到 `chart`,并在初始化完成时调用 `initChart` 方法。
### 2. 脚本部分
#### 2.1 引入必要的模块
```javascript
import { ref, watch } from 'vue';
```
引入 Vue 3 的 `ref``watch` 函数。
#### 2.2 定义组件属性
```javascript
const props = defineProps({
dataList: {
type: Object,
default: () => []
},
// 其他属性...
});
```
定义组件接收的属性。
#### 2.3 初始化图表
```javascript
const chart = ref(null);
let echarts = null;
const initChart = async (canvas) => {
await initEcharts(canvas);
updateChart();
};
const initEcharts = async (canvas) => {
echarts = await import('echarts');
const { init } = await import('@/uni_modules/lime-echart/static/echarts.min');
echarts = init(canvas, echarts);
};
```
- `chart` 用于引用 `l-echart` 组件。
- `initChart` 方法在图表初始化时调用,先初始化 ECharts 实例,再更新图表。
- `initEcharts` 方法异步加载 ECharts 并初始化实例。
#### 2.4 处理数据
```javascript
const processData = () => {
const legendData = [...new Set(props.dataList.map((item) => item[props.legendField]))];
return legendData.map((legendItem) => {
const seriesData = props.dataList
.filter((item) => item[props.legendField] === legendItem)
.sort((a, b) => new Date(a[props.xField]) - new Date(b[props.xField]))
.map((item) => ({
name: item[props.xField],
value: [item[props.xField], item[props.yField]]
}));
return {
name: legendItem,
type: 'line',
showSymbol: true,
data: seriesData
};
});
};
```
处理传入的数据,根据 `legendField` 分组,对每组数据按 `xField` 排序,并转换为 ECharts 所需的格式。
#### 2.5 获取图表配置
```javascript
const getOption = () => ({
tooltip: {
trigger: 'axis',
formatter: (params) => {
return `${params[0].axisValue}<br/>` + params.map((item) => `${item.marker} ${item.seriesName}: ${item.value[1]}`).join('<br/>');
}
},
// 其他配置...
});
```
返回 ECharts 的配置对象,包括 tooltip、x 轴、y 轴、系列数据、图例和网格等配置。
#### 2.6 更新图表
```javascript
const updateChart = () => {
if (!chart.value) return;
const option = getOption();
chart.value.setOption(option);
};
```
如果 `chart` 实例存在,获取最新的图表配置并更新图表。
#### 2.7 监听数据变化
```javascript
watch(
() => props.dataList,
() => {
updateChart();
},
{ deep: true }
);
```
`props.dataList` 发生变化时,调用 `updateChart` 方法更新图表。
### 3. 样式部分
```css
.chart-container {
width: 100%;
height: 30vh;
}
```
设置图表容器的宽度为 100%,高度为 30vh。
## 五、注意事项
- 确保项目中已经正确安装并配置了 `lime-echart` 插件。
- 传入的 `dataList` 数据格式要符合要求,包含 `xField`、`yField` 和 `legendField` 对应的数据。
- 由于使用了异步加载 ECharts可能会有一定的延迟需要确保在合适的时机初始化图表。

View File

@ -0,0 +1,145 @@
## 1.5.62024-11-25
1. 修复上版本日历高度错误的bug
2. 新增clearSelect方法用于清除日历选择
3. 新增todayDefaultStyle属性用于控制是否显示今日默认样式
## 1.5.52024-11-14
1. 通过减少view数量优化日历性能
2. 修复nvue错误日历样式以及滑动时无法切换日历的bug
3. 修复nvue警告
## 1.5.42024-10-12
修复忘记删除方法,导致运行错误
## 1.5.32024-10-12
更新nvue下可能会造成日历重叠的bug
## 1.5.22024-06-14
修复错误style语法
## 1.5.12024-06-11
修复弹窗确认与取消设置颜色不生效
## 1.5.02024-06-03
1. 修复monthSwitch事件初始化时被触发的问题
2. monthSwitch事件新增fullDate属性(用来方便直接获取字符串形式的完整日期)
3. 日历新增confirmFullDate属性用来指定在弹窗模式下的日期点击确认按钮时是否需要选择完整日期
## 1.4.92024-05-08
更新域名
## 1.4.82024-04-22
修复日历内外高度不一致的问题
## 1.4.72024-04-16
增加 operationPosition 属性 用来控制弹窗日历取消和确认按钮的显示位置
## 1.4.62024-04-16
新增属性 actBadgeColor, 当通过 `selected` 属性设置某个日期 `badgeColor`后,如果该日期被选择且主题色与 `badgeColor` 一致时,徽标会显示本颜色
## 1.4.52024-04-15
1. 新增reset方法来重置日历数据
2. 新增插槽-operation 用来自定义弹窗日历确认和取消按钮
3. selected 属性新增 badgeColor 用来指定 badge 颜色
4. close 事件改为弹窗日历点击mask关闭时触发新增cancel事件弹窗日历点击取消时触发。
## 1.4.42024-01-19
修复vue2初始化时使用同一引用类型造成的bug
## 1.4.32024-01-17
优化切换折叠状态时的记录方式
## 1.4.22024-01-12
优化 monthShowCurrentMonth 属性, 如果仅显示当月直接不展示该元素。
## 1.4.12024-01-12
优化 monthShowCurrentMonth 属性, 如果仅显示当月直接不展示该元素。
## 1.4.02024-01-11
修复type="week"时找不到
## 1.3.92024-01-10
优化: 将日历日期宽度固定改为跟随父级来决定宽度,避免出现父元素宽度变化带来的对不齐
## 1.3.82024-01-04
1. 增加节日
2. 日历增加自定义高度
3. vue页面日历折叠时增加动效
4. 增加头部插槽
5. 仅显示当月时自动扩大间距,不会再出现下面一排空白的尴尬情况了
## 1.3.72023-12-19
修复回到今日时没有正确记录折叠日期
修复selected变化时无法正常更新打点信息
## 1.3.62023-12-13
修复单选模式下选中时展示的错误的weeks
## 1.3.52023-12-13
修复动态修改date以及其他会触发更新init的函数, swiper不对及只会更新一个下一个数据的bug
## 1.3.42023-12-08
修复selectd没有启用深度监听导致直接添加数组带来的异常
## 1.3.32023-11-23
1. 修复weeks错误类型提示
2. 修复calendarChange返回month类型不对
## 1.3.22023-11-22
修复将今日日期打点禁用后造成的bug
## 1.3.12023-11-21
1. 修复wu-icon依赖缺失
2. 新增rangeHaveDisableTruncation属性, 用来指定范围选择遇到打点禁用日期是否进行截断
## 1.3.02023-11-19
1. 日历新增类型(周、月日历)
2. 日历新增折叠功能
3. 日历新增以周几开始的属性(周日、周一)
## 1.2.92023-11-08
1. 修复mode变化时不会正确重置的问题
2. 优化月份大文字显示方式
## 1.2.82023-10-22
新增maskClick用来控制是否点击遮罩层关闭
新增disabledChoice用来控制是否禁止点击日历
## 1.2.72023-09-22
修复传date值情况下不会默认选中的bug
## 1.2.62023-09-22
修改useToday描述
## 1.2.52023-09-22
新增useToday属性用来指定是否使用今天作为默认时间
## 1.2.42023-09-21
修复插入模式下顶部会显示弹窗关闭的内容
## 1.2.32023-09-20
修复恢复默认数据错误的bug
## 1.2.22023-09-19
新增rangeSameDay属性用来指定选日期范围选择时起始日期是否可以为同一天
## 1.2.12023-09-18
1.修复wu-calendar回到今日错误
2.优化wu-calendar picker日期与当前日历日期同步
3.wu-calendar新增mode属性用来控制单日期、多日期、日期选择范围模式
4.优化wu-calendar date属性来更好的指定多日期、范围日期的默认值
## 1.2.02023-09-17
修复date变化时未成功重置
## 1.1.92023-09-17
1. 新增mode属性用来指定日期选择模式
2. 增加多选
3. 增加范围选择模式、多选模式默认值
## 1.1.82023-09-12
修复回到今日错误
新增日历picker日期与日历同步
## 1.1.72023-09-11
自定义事件声明
## 1.1.62023-09-09
增加 `rangeEndRepick` 属性,用来指定选择完成后点击选择范围内的日期是否可以重选结束日期
## 1.1.52023-09-09
修复每月仅显示当月数据时上方星期错乱的问题
## 1.1.42023-09-05
1. 优化动态计算算法
2. 优化弹窗模式打开缓慢的问题
3. 优化Color方法
## 1.1.32023-09-03
新增插件预览图片
## 1.1.22023-09-02
1. 新增monthShowCurrentMonth 用来设置是否每月仅展示当月数据
2. 修复动态加载时下一月数据更新错误问题
3. 修复confirm和change事件选中的列表中有被禁止的日期的问题
## 1.1.12023-08-31
修复在插入模式中无法滑动的bug
## 1.1.02023-08-29
修复回到今日bug(来自群里464与A毛毛大佬的测试)
## 1.0.92023-08-29
修复依赖缺失
## 1.0.82023-08-22
修复v2初始化时使用不存在的属性导致不可使用的bug(来自wu-ui群内攸宁大佬的反馈)
## 1.0.72023-08-21
阻止默认滑动事件执行
## 1.0.62023-08-21
修复支付宝高度消失的问题
## 1.0.52023-08-21
修改说明
## 1.0.42023-08-20
去除误加打印
## 1.0.32023-08-20
1. 修复初始化时下个月份日期计算不对的问题
2. 增加打点禁用、设置打点徽标位置
## 1.0.22023-08-20
更新展示截图
## 1.0.12023-08-20
修改展示截图及说明
## 1.0.02023-08-20
动态滑动计算的日历插件,还可以设置滑动切换模式、自定义主题颜色、自定义文案、农历显示等功能,可以让您纵享丝滑的使用日历。

View File

@ -0,0 +1,14 @@
{
"wu-calender.ok": "ok",
"wu-calender.cancel": "cancel",
"wu-calender.year": "year",
"wu-calender.month": "month",
"wu-calender.today": "today",
"wu-calender.MON": "MON",
"wu-calender.TUE": "TUE",
"wu-calender.WED": "WED",
"wu-calender.THU": "THU",
"wu-calender.FRI": "FRI",
"wu-calender.SAT": "SAT",
"wu-calender.SUN": "SUN"
}

View File

@ -0,0 +1,8 @@
import en from './en.json'
import zhHans from './zh-Hans.json'
import zhHant from './zh-Hant.json'
export default {
en,
'zh-Hans': zhHans,
'zh-Hant': zhHant
}

View File

@ -0,0 +1,14 @@
{
"wu-calender.ok": "确定",
"wu-calender.cancel": "取消",
"wu-calender.year": "年",
"wu-calender.month": "月",
"wu-calender.today": "今日",
"wu-calender.SUN": "日",
"wu-calender.MON": "一",
"wu-calender.TUE": "二",
"wu-calender.WED": "三",
"wu-calender.THU": "四",
"wu-calender.FRI": "五",
"wu-calender.SAT": "六"
}

View File

@ -0,0 +1,14 @@
{
"wu-calender.ok": "確定",
"wu-calender.cancel": "取消",
"wu-calender.year": "年",
"wu-calender.month": "月",
"wu-calender.today": "今日",
"wu-calender.SUN": "日",
"wu-calender.MON": "一",
"wu-calender.TUE": "二",
"wu-calender.WED": "三",
"wu-calender.THU": "四",
"wu-calender.FRI": "五",
"wu-calender.SAT": "六"
}

View File

@ -0,0 +1,73 @@
export default {
props: {
showMonth: {
type: Boolean,
default: false
},
// 折叠状态
FoldStatus: {
type: String,
default: null
},
month: {
type: [Number, String],
default: null
},
color: {
type: String,
default: '#3c9cff'
},
startText: {
type: String,
default: '开始'
},
endText: {
type: String,
default: '结束'
},
weeks: {
type: [Object, Array],
default: () => {
return []
}
},
calendar: {
type: Object,
default: () => {
return {}
}
},
selected: {
type: Array,
default: () => {
return []
}
},
lunar: {
type: Boolean,
default: false
},
itemHeight: {
type: Number,
default: 64
},
monthShowCurrentMonth: {
type: Boolean,
default: false
},
actBadgeColor: {
type: String,
default: '#fff'
},
// 默认边距 theme.scss
defaultMargin: {
type: Number,
default: 8
},
// 是否显示今日默认样式(默认为true)
todayDefaultStyle: {
type: Boolean,
default: true
},
}
}

View File

@ -0,0 +1,121 @@
<template>
<view class="wu-calendar-block">
<view v-if="showMonth && FoldShowMonth" class="wu-calendar__box-bg">
<text class="wu-calendar__box-bg-text">{{ month }}</text>
</view>
<!-- 月或周日历 -->
<view class="wu-calendar__weeks" v-for="(item, index) in weeks" :key="index">
<template v-for="(weeks, weeksIndex) in item">
<wu-calendar-item
:key="weeksIndex"
v-if="!monthShowCurrentMonth || !weeks.empty"
class="wu-calendar-item--hook"
:weekItemStyle="weekItemStyle"
:weeks="weeks"
:calendar="calendar"
:selected="selected"
:lunar="lunar"
@change="choiceDate"
:color="color"
:actBadgeColor="actBadgeColor"
:startText="startText"
:endText="endText"
:itemHeight="itemHeight - defaultMargin"
:todayDefaultStyle="todayDefaultStyle"
></wu-calendar-item>
<view v-else class="wu-calendar__weeks-item" :style="[weekItemStyle]"></view>
</template>
</view>
</view>
</template>
<script>
import mpMixin from '@/uni_modules/wu-ui-tools/libs/mixin/mpMixin.js';
import mixin from '@/uni_modules/wu-ui-tools/libs/mixin/mixin.js';
import props from './props.js';
import { initVueI18n } from '@dcloudio/uni-i18n';
import i18nMessages from '../i18n/index.js';
const { t } = initVueI18n(i18nMessages);
export default {
emits: ['change'],
mixins: [mpMixin, mixin, props],
data() {
return {
FoldShowMonth: false
};
},
mounted() {
this.FoldShowMonth = this.FoldStatus == 'open';
},
computed: {
weekItemStyle() {
let weeksLength = Object.keys(this.weeks).length;
let calendarHeight = this.FoldStatus === 'open' ? this.itemHeight * 6 : this.itemHeight;
let margin = weeksLength && this.weeks[weeksLength - 1][0].empty ? this.itemHeight / (weeksLength - 1) + this.defaultMargin : this.defaultMargin;
return {
marginTop: margin / 2 + 'px',
marginBottom: margin / 2 + 'px',
height: this.itemHeight - this.defaultMargin + 'px'
};
}
},
watch: {
FoldStatus(newVal) {
this.$nextTick(() => {
this.FoldShowMonth = this.FoldStatus == 'open';
});
}
},
methods: {
choiceDate(weeks) {
this.$emit('change', weeks);
}
}
};
</script>
<style lang="scss" scoped>
$wu-text-color-grey: #999;
.wu-calendar-block {
.wu-calendar__weeks {
position: relative;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
padding: 0 8rpx;
}
.wu-calendar__weeks-item {
flex: 1;
}
.wu-calendar__box-bg {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
justify-content: center;
align-items: center;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.wu-calendar__box-bg-text {
font-size: 100rpx;
transform: scale(4);
font-weight: bold;
color: $wu-text-color-grey;
opacity: 0.1;
text-align: center;
/* #ifndef APP-NVUE */
line-height: 1;
/* #endif */
}
}
</style>

View File

@ -0,0 +1,55 @@
export default {
props: {
color: {
type: String,
default: '#3c9cff'
},
startText: {
type: String,
default: '开始'
},
endText: {
type: String,
default: '结束'
},
weeks: {
type: Object,
default () {
return {}
}
},
calendar: {
type: Object,
default: () => {
return {}
}
},
selected: {
type: Array,
default: () => {
return []
}
},
lunar: {
type: Boolean,
default: false
},
itemHeight: {
type: Number,
default: 64
},
actBadgeColor: {
type: String,
default: '#fff',
},
weekItemStyle: {
type: Object,
default: {}
},
// 是否显示今日默认样式(默认为true)
todayDefaultStyle: {
type: Boolean,
default: true
},
}
}

View File

@ -0,0 +1,291 @@
<template>
<view
ref="$weeksBox"
class="wu-calendar-item__weeks-box"
:style="[
calendarItemStyle,
weekItemStyle,
{
borderTopLeftRadius: weeks.beforeRange ? '12rpx' : '',
borderBottomLeftRadius: weeks.beforeRange ? '12rpx' : '',
borderTopRightRadius: weeks.afterRange ? '12rpx' : '',
borderBottomRightRadius: weeks.afterRange ? '12rpx' : ''
}
]"
@click="choiceDate(weeks)"
>
<view class="wu-calendar-item__weeks-box-item" :style="[actMultipleStyle, { width: itemWidth, height: itemHeight + 'px' }]">
<!-- 自定义打点上方信息 -->
<text
v-if="weeks.extraInfo && weeks.extraInfo.topInfo"
class="wu-calendar-item__weeks-lunar-text"
:style="[{ color: weeks.extraInfo.topInfoColor || '#e43d33' }, calendarItemStyle, actMultipleStyle]"
>
{{ weeks.extraInfo.topInfo }}
</text>
<!-- 徽标 -->
<text v-if="selected && weeks.extraInfo && weeks.extraInfo.badge" class="wu-calendar-item__weeks-box-circle" :style="[badgeStyle]"></text>
<!-- 日期文字 -->
<text class="wu-calendar-item__weeks-box-text" :style="[calendarItemStyle, actMultipleStyle]">{{ weeks.date }}</text>
<!-- 今日的文字 -->
<text
v-if="!lunar && !weeks.extraInfo && weeks.isDay && !weeks.beforeRange && !weeks.afterRange"
class="wu-calendar-item__weeks-lunar-text"
:style="[calendarItemStyle, actMultipleStyle]"
>
{{ todayText }}
</text>
<!-- 农历文字 -->
<text
v-if="lunar && !weeks.extraInfo && !weeks.beforeRange && !weeks.afterRange"
class="wu-calendar-item__weeks-lunar-text"
:style="[calendarItemStyle, actMultipleStyle]"
>
{{ dayText }}
</text>
<!-- 选中的文字展示 -->
<text v-if="!weeks.extraInfo && (weeks.beforeRange || weeks.afterRange)" class="wu-calendar-item__weeks-lunar-text" :style="[calendarItemStyle, actMultipleStyle]">
{{ multipleText }}
</text>
<!-- 自定义打点下方信息 -->
<text
v-if="weeks.extraInfo && weeks.extraInfo.info"
class="wu-calendar-item__weeks-lunar-text"
:style="[{ color: weeks.extraInfo.infoColor || '#e43d33' }, calendarItemStyle, actMultipleStyle]"
>
{{ weeks.extraInfo.info }}
</text>
</view>
</view>
</template>
<script>
import mpMixin from '@/uni_modules/wu-ui-tools/libs/mixin/mpMixin.js';
import mixin from '@/uni_modules/wu-ui-tools/libs/mixin/mixin.js';
import props from './props.js';
import { initVueI18n } from '@dcloudio/uni-i18n';
import i18nMessages from '../i18n/index.js';
import { nextTick } from 'vue';
const { t } = initVueI18n(i18nMessages);
export default {
emits: ['change'],
mixins: [mpMixin, mixin, props],
computed: {
todayText() {
return t('wu-calender.today');
},
//
calendarItemStyle() {
let style = {};
let color = this.$w.Color.gradient(this.color, this.$w.Color.isLight(this.color) ? '#000' : '#fff', 100)[6];
//
//
if (this.weeks.rangeMultiple) {
style = {
backgroundColor: this.$w.Color.gradient(this.color, '#fff', 100)[80],
color
};
}
//
if (this.weeks.isDay && this.todayDefaultStyle) {
style.color = color;
}
//
if (this.weeks.disable) {
style = {
backgroundColor: 'rgba(249, 249, 249, 0.3)',
color: '#c0c0c0'
};
}
return style;
},
//
actMultipleStyle() {
if (
(this.weeks.beforeRange || this.weeks.afterRange || this.weeks.multiples || (this.calendar.fullDate === this.weeks.fullDate && this.weeks.mode === 'single')) &&
!this.weeks.disable
) {
// #ifdef APP-NVUE
if (this.itemWidth == '100%') return {};
return {
backgroundColor: this.color,
color: '#fff',
borderRadius: '12rpx'
};
// #endif
// #ifndef APP-NVUE
return {
backgroundColor: this.color,
color: '#fff',
borderRadius: '12rpx'
};
// #endif
}
},
//
badgeStyle() {
let style = {
backgroundColor: this.weeks.disable ? '#c0c0c0' : '#e43d33',
width: '16rpx',
height: '16rpx'
};
if (this.weeks.extraInfo) {
if (this.weeks.extraInfo.badgeColor) {
// #fff
if (
(this.weeks.beforeRange ||
this.weeks.afterRange ||
this.weeks.multiples ||
(this.calendar.fullDate === this.weeks.fullDate && this.weeks.mode === 'single')) &&
!this.weeks.disable &&
this.$w.Color.convertFormat(this.weeks.extraInfo.badgeColor) == this.$w.Color.convertFormat(this.color)
) {
style.backgroundColor = this.actBadgeColor;
} else {
style.backgroundColor = this.weeks.extraInfo.badgeColor;
}
}
if (this.weeks.extraInfo.badgeSize) {
style.width = this.weeks.extraInfo.badgeSize;
style.height = this.weeks.extraInfo.badgeSize;
}
if (!this.weeks.extraInfo.badgePosition) {
style.right = '10rpx';
style.top = '10rpx';
} else if (this.weeks.extraInfo.badgePosition == 'top-left') {
style.top = '10rpx';
style.left = '10rpx';
} else if (this.weeks.extraInfo.badgePosition == 'top-center') {
style.top = '10rpx';
style.left = 'center';
} else if (this.weeks.extraInfo.badgePosition == 'top-right') {
style.top = '10rpx';
style.right = '10rpx';
} else if (this.weeks.extraInfo.badgePosition == 'bottom-left') {
style.bottom = '10rpx';
style.left = '10rpx';
} else if (this.weeks.extraInfo.badgePosition == 'bottom-center') {
style.bottom = '10rpx';
style.left = 'center';
} else if (this.weeks.extraInfo.badgePosition == 'bottom-right') {
style.bottom = '10rpx';
style.right = '10rpx';
}
}
return style;
},
//
dayText() {
let text = '';
if (this.weeks.isDay) {
text = this.todayText;
} else if (this.weeks.lunar.festival) {
text = this.weeks.lunar.festival;
} else if (this.weeks.lunar.isTerm) {
text = this.weeks.lunar.Term;
} else if (this.weeks.lunar.IDayCn === '初一') {
text = this.weeks.lunar.IMonthCn;
} else {
text = this.weeks.lunar.IDayCn;
}
return text;
},
//
multipleText() {
let text = '';
if (this.weeks.afterRange) {
text = this.endText;
} else if (this.weeks.beforeRange) {
text = this.startText;
}
return text;
}
},
data() {
return {
itemWidth: '100%'
};
},
methods: {
choiceDate(weeks) {
this.$emit('change', weeks);
}
},
mounted() {
// #ifdef APP-NVUE
setTimeout(() => {
const dom = uni.requireNativePlugin('dom');
dom.getComponentRect(this.$refs.$weeksBox, (res) => {
this.itemWidth = res.size.width + 'px';
});
}, 10);
// #endif
}
};
</script>
<style lang="scss" scoped>
@import '@/uni_modules/wu-ui-tools/theme.scss';
$wu-font-size-base: 28rpx;
$wu-text-color: #333;
$wu-font-size-sm: 24rpx;
$wu-color-error: #e43d33;
$wu-opacity-disabled: 0.3;
$wu-text-color-disable: #c0c0c0;
.wu-calendar-item__weeks-box {
flex: 1;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
justify-content: center;
align-items: center;
padding: 0 0.5px;
}
.wu-calendar-item__weeks-box-text {
font-size: $wu-font-size-base;
color: $wu-text-color;
}
.wu-calendar-item__weeks-lunar-text {
font-size: $wu-font-size-sm;
color: $wu-text-color;
}
.wu-calendar-item__weeks-box-item {
flex: 1;
position: relative;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
justify-content: center;
align-items: center;
}
.wu-calendar-item__weeks-box-circle {
position: absolute;
border-radius: 16rpx;
background-color: $wu-color-error;
}
.wu-calendar-item--disable {
background-color: rgba(249, 249, 249, $wu-opacity-disabled);
color: $wu-text-color-disable;
}
.wu-calendar-item--extra {
color: $wu-color-error;
opacity: 0.8;
}
.wu-calendar-item--checked {
color: #fff;
}
</style>

View File

@ -0,0 +1,664 @@
/**
* @1900-2100区间内的公历农历互转
* @charset UTF-8
* @github https://github.com/jjonline/calendar.js
* @Author Jea杨(JJonline@JJonline.Cn)
* @Time 2014-7-21
* @Time 2016-8-13 Fixed 2033hexAttribution Annals
* @Time 2016-9-25 Fixed lunar LeapMonth Param Bug
* @Time 2017-7-24 Fixed use getTerm Func Param Error.use solar year,NOT lunar year
* @Version 1.0.3
* @公历转农历calendar.solar2lunar(1987,11,01); //[you can ignore params of prefix 0]
* @农历转公历calendar.lunar2solar(1987,09,10); //[you can ignore params of prefix 0]
*/
/* eslint-disable */
var calendar = {
/**
* 农历1900-2100的润大小信息表
* @Array Of Property
* @return Hex
*/
lunarInfo: [0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0,
0x055d2, // 1900-1909
0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0, 0x0ada2, 0x095b0, 0x14977, // 1910-1919
0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970, // 1920-1929
0x06566, 0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950, // 1930-1939
0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557, // 1940-1949
0x06ca0, 0x0b550, 0x15355, 0x04da0, 0x0a5b0, 0x14573, 0x052b0, 0x0a9a8, 0x0e950, 0x06aa0, // 1950-1959
0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260, 0x0f263, 0x0d950, 0x05b57, 0x056a0, // 1960-1969
0x096d0, 0x04dd5, 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b6a0, 0x195a6, // 1970-1979
0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40, 0x0af46, 0x0ab60, 0x09570, // 1980-1989
0x04af5, 0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, 0x05ac0, 0x0ab60, 0x096d5, 0x092e0, // 1990-1999
0x0c960, 0x0d954, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5, // 2000-2009
0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9, 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930, // 2010-2019
0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65, 0x0d530, // 2020-2029
0x05aa0, 0x076a3, 0x096d0, 0x04afb, 0x04ad0, 0x0a4d0, 0x1d0b6, 0x0d250, 0x0d520, 0x0dd45, // 2030-2039
0x0b5a0, 0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0, // 2040-2049
/** Add By JJonline@JJonline.Cn**/
0x14b63, 0x09370, 0x049f8, 0x04970, 0x064b0, 0x168a6, 0x0ea50, 0x06b20, 0x1a6c4, 0x0aae0, // 2050-2059
0x0a2e0, 0x0d2e3, 0x0c960, 0x0d557, 0x0d4a0, 0x0da50, 0x05d55, 0x056a0, 0x0a6d0, 0x055d4, // 2060-2069
0x052d0, 0x0a9b8, 0x0a950, 0x0b4a0, 0x0b6a6, 0x0ad50, 0x055a0, 0x0aba4, 0x0a5b0, 0x052b0, // 2070-2079
0x0b273, 0x06930, 0x07337, 0x06aa0, 0x0ad50, 0x14b55, 0x04b60, 0x0a570, 0x054e4, 0x0d160, // 2080-2089
0x0e968, 0x0d520, 0x0daa0, 0x16aa6, 0x056d0, 0x04ae0, 0x0a9d4, 0x0a2d0, 0x0d150, 0x0f252, // 2090-2099
0x0d520
], // 2100
/**
* 公历每个月份的天数普通表
* @Array Of Property
* @return Number
*/
solarMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
/**
* 天干地支之天干速查表
* @Array Of Property trans["甲","乙","丙","丁","戊","己","庚","辛","壬","癸"]
* @return Cn string
*/
Gan: ['\u7532', '\u4e59', '\u4e19', '\u4e01', '\u620a', '\u5df1', '\u5e9a', '\u8f9b', '\u58ec', '\u7678'],
/**
* 天干地支之地支速查表
* @Array Of Property
* @trans["子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"]
* @return Cn string
*/
Zhi: ['\u5b50', '\u4e11', '\u5bc5', '\u536f', '\u8fb0', '\u5df3', '\u5348', '\u672a', '\u7533', '\u9149',
'\u620c', '\u4ea5'
],
/**
* 天干地支之地支速查表<=>生肖
* @Array Of Property
* @trans["鼠","牛","虎","兔","龙","蛇","马","羊","猴","鸡","狗","猪"]
* @return Cn string
*/
Animals: ['\u9f20', '\u725b', '\u864e', '\u5154', '\u9f99', '\u86c7', '\u9a6c', '\u7f8a', '\u7334', '\u9e21',
'\u72d7', '\u732a'
],
/**
* 24节气速查表
* @Array Of Property
* @trans["小寒","大寒","立春","雨水","惊蛰","春分","清明","谷雨","立夏","小满","芒种","夏至","小暑","大暑","立秋","处暑","白露","秋分","寒露","霜降","立冬","小雪","大雪","冬至"]
* @return Cn string
*/
solarTerm: ['\u5c0f\u5bd2', '\u5927\u5bd2', '\u7acb\u6625', '\u96e8\u6c34', '\u60ca\u86f0', '\u6625\u5206',
'\u6e05\u660e', '\u8c37\u96e8', '\u7acb\u590f', '\u5c0f\u6ee1', '\u8292\u79cd', '\u590f\u81f3',
'\u5c0f\u6691', '\u5927\u6691', '\u7acb\u79cb', '\u5904\u6691', '\u767d\u9732', '\u79cb\u5206',
'\u5bd2\u9732', '\u971c\u964d', '\u7acb\u51ac', '\u5c0f\u96ea', '\u5927\u96ea', '\u51ac\u81f3'
],
/**
* 1900-2100各年的24节气日期速查表
* @Array Of Property
* @return 0x string For splice
*/
sTermInfo: [
'9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf97c3598082c95f8c965cc920f',
'97bd0b06bdb0722c965ce1cfcc920f', 'b027097bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e',
'97bcf97c359801ec95f8c965cc920f', '97bd0b06bdb0722c965ce1cfcc920f', 'b027097bd097c36b0b6fc9274c91aa',
'97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f', '97bd0b06bdb0722c965ce1cfcc920f',
'b027097bd097c36b0b6fc9274c91aa', '9778397bd19801ec9210c965cc920e', '97b6b97bd19801ec95f8c965cc920f',
'97bd09801d98082c95f8e1cfcc920f', '97bd097bd097c36b0b6fc9210c8dc2', '9778397bd197c36c9210c9274c91aa',
'97b6b97bd19801ec95f8c965cc920e', '97bd09801d98082c95f8e1cfcc920f', '97bd097bd097c36b0b6fc9210c8dc2',
'9778397bd097c36c9210c9274c91aa', '97b6b97bd19801ec95f8c965cc920e', '97bcf97c3598082c95f8e1cfcc920f',
'97bd097bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c91aa', '97b6b97bd19801ec9210c965cc920e',
'97bcf97c3598082c95f8c965cc920f', '97bd097bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa',
'97b6b97bd19801ec9210c965cc920e', '97bcf97c3598082c95f8c965cc920f', '97bd097bd097c35b0b6fc920fb0722',
'9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f',
'97bd097bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e',
'97bcf97c359801ec95f8c965cc920f', '97bd097bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa',
'97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f', '97bd097bd07f595b0b6fc920fb0722',
'9778397bd097c36b0b6fc9210c8dc2', '9778397bd19801ec9210c9274c920e', '97b6b97bd19801ec95f8c965cc920f',
'97bd07f5307f595b0b0bc920fb0722', '7f0e397bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c920e',
'97b6b97bd19801ec95f8c965cc920f', '97bd07f5307f595b0b0bc920fb0722', '7f0e397bd097c36b0b6fc9210c8dc2',
'9778397bd097c36c9210c9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bd07f1487f595b0b0bc920fb0722',
'7f0e397bd097c36b0b6fc9210c8dc2', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e',
'97bcf7f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa',
'97b6b97bd19801ec9210c965cc920e', '97bcf7f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722',
'9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf7f1487f531b0b0bb0b6fb0722',
'7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e',
'97bcf7f1487f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa',
'97b6b97bd19801ec9210c9274c920e', '97bcf7f0e47f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722',
'9778397bd097c36b0b6fc9210c91aa', '97b6b97bd197c36c9210c9274c920e', '97bcf7f0e47f531b0b0bb0b6fb0722',
'7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c920e',
'97b6b7f0e47f531b0723b0b6fb0722', '7f0e37f5307f595b0b0bc920fb0722', '7f0e397bd097c36b0b6fc9210c8dc2',
'9778397bd097c36b0b70c9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721', '7f0e37f1487f595b0b0bb0b6fb0722',
'7f0e397bd097c35b0b6fc9210c8dc2', '9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721',
'7f0e27f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa',
'97b6b7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722',
'9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722',
'7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721',
'7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9274c91aa',
'97b6b7f0e47f531b0723b0787b0721', '7f0e27f0e47f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722',
'9778397bd097c36b0b6fc9210c91aa', '97b6b7f0e47f149b0723b0787b0721', '7f0e27f0e47f531b0723b0b6fb0722',
'7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9210c8dc2', '977837f0e37f149b0723b0787b0721',
'7f07e7f0e47f531b0723b0b6fb0722', '7f0e37f5307f595b0b0bc920fb0722', '7f0e397bd097c35b0b6fc9210c8dc2',
'977837f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e37f1487f595b0b0bb0b6fb0722',
'7f0e397bd097c35b0b6fc9210c8dc2', '977837f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721',
'7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', '977837f0e37f14998082b0787b06bd',
'7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722',
'977837f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722',
'7f0e397bd07f595b0b0bc920fb0722', '977837f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721',
'7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722', '977837f0e37f14998082b0787b06bd',
'7f07e7f0e47f149b0723b0787b0721', '7f0e27f0e47f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722',
'977837f0e37f14998082b0723b06bd', '7f07e7f0e37f149b0723b0787b0721', '7f0e27f0e47f531b0723b0b6fb0722',
'7f0e397bd07f595b0b0bc920fb0722', '977837f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b0721',
'7f07e7f0e47f531b0723b0b6fb0722', '7f0e37f1487f595b0b0bb0b6fb0722', '7f0e37f0e37f14898082b0723b02d5',
'7ec967f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0722', '7f0e37f1487f531b0b0bb0b6fb0722',
'7f0e37f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721',
'7f0e37f1487f531b0b0bb0b6fb0722', '7f0e37f0e37f14898082b072297c35', '7ec967f0e37f14998082b0787b06bd',
'7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e37f0e37f14898082b072297c35',
'7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722',
'7f0e37f0e366aa89801eb072297c35', '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f149b0723b0787b0721',
'7f0e27f1487f531b0b0bb0b6fb0722', '7f0e37f0e366aa89801eb072297c35', '7ec967f0e37f14998082b0723b06bd',
'7f07e7f0e47f149b0723b0787b0721', '7f0e27f0e47f531b0723b0b6fb0722', '7f0e37f0e366aa89801eb072297c35',
'7ec967f0e37f14998082b0723b06bd', '7f07e7f0e37f14998083b0787b0721', '7f0e27f0e47f531b0723b0b6fb0722',
'7f0e37f0e366aa89801eb072297c35', '7ec967f0e37f14898082b0723b02d5', '7f07e7f0e37f14998082b0787b0721',
'7f07e7f0e47f531b0723b0b6fb0722', '7f0e36665b66aa89801e9808297c35', '665f67f0e37f14898082b0723b02d5',
'7ec967f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0722', '7f0e36665b66a449801e9808297c35',
'665f67f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721',
'7f0e36665b66a449801e9808297c35', '665f67f0e37f14898082b072297c35', '7ec967f0e37f14998082b0787b06bd',
'7f07e7f0e47f531b0723b0b6fb0721', '7f0e26665b66a449801e9808297c35', '665f67f0e37f1489801eb072297c35',
'7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722'
],
festivals: {
'1-1': '元旦',
'2-14': '情人节',
'3-8': '妇女节',
'3-12': '植树节',
'4-1': '愚人节',
'5-1': '劳动节',
'5-4': '青年节',
'5-12': '护士节',
'6-1': '儿童节',
'8-1': '建军节',
'9-10': '教师节',
'10-1': '国庆',
'11-1': '万圣节',
'12-24': '圣诞节',
'正月初一': '春节',
'二月初二': '龙抬头',
'五月初五': '端午节',
'七月初七': '七夕节',
'七月十五': '中元节',
'八月十五': '中秋节',
'九月初九': '重阳节',
'腊月初八': '腊八节',
'腊月廿三': '小年',
'腊月三十': '除夕',
},
/**
* 数字转中文速查表
* @Array Of Property
* @trans ['日','一','二','三','四','五','六','七','八','九','十']
* @return Cn string
*/
nStr1: ['\u65e5', '\u4e00', '\u4e8c', '\u4e09', '\u56db', '\u4e94', '\u516d', '\u4e03', '\u516b', '\u4e5d',
'\u5341'
],
/**
* 日期转农历称呼速查表
* @Array Of Property
* @trans ['初','十','廿','卅']
* @return Cn string
*/
nStr2: ['\u521d', '\u5341', '\u5eff', '\u5345'],
/**
* 月份转农历称呼速查表
* @Array Of Property
* @trans ['正','一','二','三','四','五','六','七','八','九','十','冬','腊']
* @return Cn string
*/
nStr3: ['\u6b63', '\u4e8c', '\u4e09', '\u56db', '\u4e94', '\u516d', '\u4e03', '\u516b', '\u4e5d', '\u5341',
'\u51ac', '\u814a'
],
/**
* 返回农历y年一整年的总天数
* @param lunar Year
* @return Number
* @eg:var count = calendar.lYearDays(1987) ;//count=387
*/
lYearDays: function(y) {
var i;
var sum = 348
for (i = 0x8000; i > 0x8; i >>= 1) {
sum += (this.lunarInfo[y - 1900] & i) ? 1 : 0
}
return (sum + this.leapDays(y))
},
/**
* 返回农历y年闰月是哪个月若y年没有闰月 则返回0
* @param lunar Year
* @return Number (0-12)
* @eg:var leapMonth = calendar.leapMonth(1987) ;//leapMonth=6
*/
leapMonth: function(y) { // 闰字编码 \u95f0
return (this.lunarInfo[y - 1900] & 0xf)
},
/**
* 返回农历y年闰月的天数 若该年没有闰月则返回0
* @param lunar Year
* @return Number (02930)
* @eg:var leapMonthDay = calendar.leapDays(1987) ;//leapMonthDay=29
*/
leapDays: function(y) {
if (this.leapMonth(y)) {
return ((this.lunarInfo[y - 1900] & 0x10000) ? 30 : 29)
}
return (0)
},
/**
* 返回农历y年m月非闰月的总天数计算m为闰月时的天数请使用leapDays方法
* @param lunar Year
* @return Number (-12930)
* @eg:var MonthDay = calendar.monthDays(1987,9) ;//MonthDay=29
*/
monthDays: function(y, m) {
if (m > 12 || m < 1) {
return -1
} // 月份参数从1至12参数错误返回-1
return ((this.lunarInfo[y - 1900] & (0x10000 >> m)) ? 30 : 29)
},
/**
* 返回公历(!)y年m月的天数
* @param solar Year
* @return Number (-128293031)
* @eg:var solarMonthDay = calendar.leapDays(1987) ;//solarMonthDay=30
*/
solarDays: function(y, m) {
if (m > 12 || m < 1) {
return -1
} // 若参数错误 返回-1
var ms = m - 1
if (ms == 1) { // 2月份的闰平规律测算后确认返回28或29
return (((y % 4 == 0) && (y % 100 != 0) || (y % 400 == 0)) ? 29 : 28)
} else {
return (this.solarMonth[ms])
}
},
/**
* 农历年份转换为干支纪年
* @param lYear 农历年的年份数
* @return Cn string
*/
toGanZhiYear: function(lYear) {
var ganKey = (lYear - 3) % 10
var zhiKey = (lYear - 3) % 12
if (ganKey == 0) ganKey = 10 // 如果余数为0则为最后一个天干
if (zhiKey == 0) zhiKey = 12 // 如果余数为0则为最后一个地支
return this.Gan[ganKey - 1] + this.Zhi[zhiKey - 1]
},
/**
* 公历月日判断所属星座
* @param cMonth [description]
* @param cDay [description]
* @return Cn string
*/
toAstro: function(cMonth, cDay) {
var s =
'\u9b54\u7faf\u6c34\u74f6\u53cc\u9c7c\u767d\u7f8a\u91d1\u725b\u53cc\u5b50\u5de8\u87f9\u72ee\u5b50\u5904\u5973\u5929\u79e4\u5929\u874e\u5c04\u624b\u9b54\u7faf'
var arr = [20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22]
return s.substr(cMonth * 2 - (cDay < arr[cMonth - 1] ? 2 : 0), 2) + '\u5ea7' // 座
},
/**
* 传入offset偏移量返回干支
* @param offset 相对甲子的偏移量
* @return Cn string
*/
toGanZhi: function(offset) {
return this.Gan[offset % 10] + this.Zhi[offset % 12]
},
/**
* 传入公历(!)y年获得该年第n个节气的公历日期
* @param y公历年(1900-2100)n二十四节气中的第几个节气(1~24)从n=1(小寒)算起
* @return day Number
* @eg:var _24 = calendar.getTerm(1987,3) ;//_24=4;意即1987年2月4日立春
*/
getTerm: function(y, n) {
if (y < 1900 || y > 2100) {
return -1
}
if (n < 1 || n > 24) {
return -1
}
var _table = this.sTermInfo[y - 1900]
var _info = [
parseInt('0x' + _table.substr(0, 5)).toString(),
parseInt('0x' + _table.substr(5, 5)).toString(),
parseInt('0x' + _table.substr(10, 5)).toString(),
parseInt('0x' + _table.substr(15, 5)).toString(),
parseInt('0x' + _table.substr(20, 5)).toString(),
parseInt('0x' + _table.substr(25, 5)).toString()
]
var _calday = [
_info[0].substr(0, 1),
_info[0].substr(1, 2),
_info[0].substr(3, 1),
_info[0].substr(4, 2),
_info[1].substr(0, 1),
_info[1].substr(1, 2),
_info[1].substr(3, 1),
_info[1].substr(4, 2),
_info[2].substr(0, 1),
_info[2].substr(1, 2),
_info[2].substr(3, 1),
_info[2].substr(4, 2),
_info[3].substr(0, 1),
_info[3].substr(1, 2),
_info[3].substr(3, 1),
_info[3].substr(4, 2),
_info[4].substr(0, 1),
_info[4].substr(1, 2),
_info[4].substr(3, 1),
_info[4].substr(4, 2),
_info[5].substr(0, 1),
_info[5].substr(1, 2),
_info[5].substr(3, 1),
_info[5].substr(4, 2)
]
return parseInt(_calday[n - 1])
},
/**
* 传入农历数字月份返回汉语通俗表示法
* @param lunar month
* @return Cn string
* @eg:var cnMonth = calendar.toChinaMonth(12) ;//cnMonth='腊月'
*/
toChinaMonth: function(m) { // 月 => \u6708
if (m > 12 || m < 1) {
return -1
} // 若参数错误 返回-1
var s = this.nStr3[m - 1]
s += '\u6708' // 加上月字
return s
},
/**
* 传入农历日期数字返回汉字表示法
* @param lunar day
* @return Cn string
* @eg:var cnDay = calendar.toChinaDay(21) ;//cnMonth='廿一'
*/
toChinaDay: function(d) { // 日 => \u65e5
var s
switch (d) {
case 10:
s = '\u521d\u5341';
break
case 20:
s = '\u4e8c\u5341';
break
break
case 30:
s = '\u4e09\u5341';
break
break
default:
s = this.nStr2[Math.floor(d / 10)]
s += this.nStr1[d % 10]
}
return (s)
},
/**
* 年份转生肖[!仅能大致转换] => 精确划分生肖分界线是立春
* @param y year
* @return Cn string
* @eg:var animal = calendar.getAnimal(1987) ;//animal='兔'
*/
getAnimal: function(y) {
return this.Animals[(y - 4) % 12]
},
/**
* 传入阳历年月日获得详细的公历农历object信息 <=>JSON
* @param y solar year
* @param m solar month
* @param d solar day
* @return JSON object
* @eg:console.log(calendar.solar2lunar(1987,11,01));
*/
solar2lunar: function(y, m, d) { // 参数区间1900.1.31~2100.12.31
// 年份限定、上限
if (y < 1900 || y > 2100) {
return -1 // undefined转换为数字变为NaN
}
// 公历传参最下限
if (y == 1900 && m == 1 && d < 31) {
return -1
}
// 未传参 获得当天
if (!y) {
var objDate = new Date()
} else {
var objDate = new Date(y, parseInt(m) - 1, d)
}
var i;
var leap = 0;
var temp = 0
// 修正ymd参数
var y = objDate.getFullYear()
var m = objDate.getMonth() + 1
var d = objDate.getDate()
var offset = (Date.UTC(objDate.getFullYear(), objDate.getMonth(), objDate.getDate()) - Date.UTC(1900, 0,
31)) / 86400000
for (i = 1900; i < 2101 && offset > 0; i++) {
temp = this.lYearDays(i)
offset -= temp
}
if (offset < 0) {
offset += temp;
i--
}
// 是否今天
var isTodayObj = new Date()
var isToday = false
if (isTodayObj.getFullYear() == y && isTodayObj.getMonth() + 1 == m && isTodayObj.getDate() == d) {
isToday = true
}
// 星期几
var nWeek = objDate.getDay()
var cWeek = this.nStr1[nWeek]
// 数字表示周几顺应天朝周一开始的惯例
if (nWeek == 0) {
nWeek = 7
}
// 农历年
var year = i
var leap = this.leapMonth(i) // 闰哪个月
var isLeap = false
// 效验闰月
for (i = 1; i < 13 && offset > 0; i++) {
// 闰月
if (leap > 0 && i == (leap + 1) && isLeap == false) {
--i
isLeap = true;
temp = this.leapDays(year) // 计算农历闰月天数
} else {
temp = this.monthDays(year, i) // 计算农历普通月天数
}
// 解除闰月
if (isLeap == true && i == (leap + 1)) {
isLeap = false
}
offset -= temp
}
// 闰月导致数组下标重叠取反
if (offset == 0 && leap > 0 && i == leap + 1) {
if (isLeap) {
isLeap = false
} else {
isLeap = true;
--i
}
}
if (offset < 0) {
offset += temp;
--i
}
// 农历月
var month = i
// 农历日
var day = offset + 1
// 天干地支处理
var sm = m - 1
var gzY = this.toGanZhiYear(year)
// 当月的两个节气
// bugfix-2017-7-24 11:03:38 use lunar Year Param `y` Not `year`
var firstNode = this.getTerm(y, (m * 2 - 1)) // 返回当月「节」为几日开始
var secondNode = this.getTerm(y, (m * 2)) // 返回当月「节」为几日开始
// 依据12节气修正干支月
var gzM = this.toGanZhi((y - 1900) * 12 + m + 11)
if (d >= firstNode) {
gzM = this.toGanZhi((y - 1900) * 12 + m + 12)
}
// 传入的日期的节气与否
var isTerm = false
var Term = null
if (firstNode == d) {
isTerm = true
Term = this.solarTerm[m * 2 - 2]
}
if (secondNode == d) {
isTerm = true
Term = this.solarTerm[m * 2 - 1]
}
// 计算农历日期
const IMonthCn = (isLeap ? '\u95f0' : '') + this.toChinaMonth(month)
// 农历日期的汉字表述法
let IDayCn = this.toChinaDay(day)
// 节日
let festival = '';
// 农历的月日汉字表述
let lMDcn = IMonthCn + IDayCn;
// 月份日期
let MD = m + '-' + d;
if (this.festivals.hasOwnProperty(lMDcn)) {
festival = this.festivals[lMDcn]
} else if(this.festivals.hasOwnProperty(MD)) {
festival = this.festivals[MD]
}
// 日柱 当月一日与 1900/1/1 相差天数
var dayCyclical = Date.UTC(y, sm, 1, 0, 0, 0, 0) / 86400000 + 25567 + 10
var gzD = this.toGanZhi(dayCyclical + d - 1)
// 该日期所属的星座
var astro = this.toAstro(m, d)
return {
'lYear': year,
'lMonth': month,
'lDay': day,
'Animal': this.getAnimal(year),
'IMonthCn': IMonthCn,
'IDayCn': IDayCn,
'cYear': y,
'cMonth': m,
'cDay': d,
'gzYear': gzY,
'gzMonth': gzM,
'gzDay': gzD,
'isToday': isToday,
'isLeap': isLeap,
'nWeek': nWeek,
'ncWeek': '\u661f\u671f' + cWeek,
'isTerm': isTerm,
'Term': Term,
'astro': astro,
'festival': festival
}
},
/**
* 传入农历年月日以及传入的月份是否闰月获得详细的公历农历object信息 <=>JSON
* @param y lunar year
* @param m lunar month
* @param d lunar day
* @param isLeapMonth lunar month is leap or not.[如果是农历闰月第四个参数赋值true即可]
* @return JSON object
* @eg:console.log(calendar.lunar2solar(1987,9,10));
*/
lunar2solar: function(y, m, d, isLeapMonth) { // 参数区间1900.1.31~2100.12.1
var isLeapMonth = !!isLeapMonth
var leapOffset = 0
var leapMonth = this.leapMonth(y)
var leapDay = this.leapDays(y)
if (isLeapMonth && (leapMonth != m)) {
return -1
} // 传参要求计算该闰月公历 但该年得出的闰月与传参的月份并不同
if (y == 2100 && m == 12 && d > 1 || y == 1900 && m == 1 && d < 31) {
return -1
} // 超出了最大极限值
var day = this.monthDays(y, m)
var _day = day
// bugFix 2016-9-25
// if month is leap, _day use leapDays method
if (isLeapMonth) {
_day = this.leapDays(y, m)
}
if (y < 1900 || y > 2100 || d > _day) {
return -1
} // 参数合法性效验
// 计算农历的时间差
var offset = 0
for (var i = 1900; i < y; i++) {
offset += this.lYearDays(i)
}
var leap = 0;
var isAdd = false
for (var i = 1; i < m; i++) {
leap = this.leapMonth(y)
if (!isAdd) { // 处理闰月
if (leap <= i && leap > 0) {
offset += this.leapDays(y);
isAdd = true
}
}
offset += this.monthDays(y, i)
}
// 转换闰月农历 需补充该年闰月的前一个月的时差
if (isLeapMonth) {
offset += day
}
// 1900年农历正月一日的公历时间为1900年1月30日0时0分0秒(该时间也是本农历的最开始起始点)
var stmap = Date.UTC(1900, 1, 30, 0, 0, 0)
var calObj = new Date((offset + d - 31) * 86400000 + stmap)
var cY = calObj.getUTCFullYear()
var cM = calObj.getUTCMonth() + 1
var cD = calObj.getUTCDate()
return this.solar2lunar(cY, cM, cD)
}
}
export default calendar

View File

@ -0,0 +1,166 @@
export default {
props: {
// 自定义当前时间
date: {
type: [String, Array],
default: ''
},
// 日历类型(默认为month)
type: {
type: String,
default: 'month',
validator(value) {
return ['month', 'week'].includes(value)
}
},
// 日期选择模式
mode: {
type: String,
default: 'single'
},
// 是否使用默认日期(今天默认为true)
useToday: {
type: Boolean,
default: true
},
// 是否显示今日默认样式(默认为true)
todayDefaultStyle: {
type: Boolean,
default: true
},
// 是否使用折叠功能
fold: {
type: Boolean,
default: null
},
// 主题色
color: {
type: String,
default: '#3c9cff'
},
// 日历中每一项日期的高度(默认70),单位px
itemHeight: {
type: Number,
default: 70
},
// 取消文字的颜色
cancelColor: {
type: String,
default: '#333'
},
// 确定文字的颜色
confirmColor: {
type: String,
default: '#333'
},
// mode=range时第一个日期底部的提示文字
startText: {
type: String,
default: '开始'
},
// mode=range时最后一个日期底部的提示文字
endText: {
type: String,
default: '结束'
},
// 日历以周几开始
startWeek: {
type: String,
default: 'sun',
validator(value) {
return ['sun', 'mon'].includes(value)
}
},
// 打点,期待格式[{date: '2019-06-27', info: '签到', data: { custom: '自定义信息', name: '自定义消息头',xxx:xxx... }}]
selected: {
type: Array,
default () {
return []
}
},
// 是否显示农历
lunar: {
type: Boolean,
default: false
},
// 日期选择范围-开始日期
startDate: {
type: String,
default: ''
},
// 日期选择范围-结束日期
endDate: {
type: String,
default: ''
},
// 允许日期选择范围内重选结束日期
rangeEndRepick: {
type: Boolean,
default: false
},
// 允许日期选择范围起始日期为同一天
rangeSameDay: {
type: Boolean,
default: false
},
// 允许日期选择范围内遇到打点禁用日期进行截断
rangeHaveDisableTruncation: {
type: Boolean,
default: false
},
// 每月仅显示当月日期
monthShowCurrentMonth: {
type: Boolean,
default: false
},
// 插入模式,可选值ture插入模式false弹窗模式 默认为插入模式
insert: {
type: Boolean,
default: true
},
// 滑动切换模式,可选值 horizontal: 横向 vertical纵向 none 不使用滑动切换
slideSwitchMode: {
type: String,
default: 'horizontal'
},
// 是否显示月份为背景
showMonth: {
type: Boolean,
default: true
},
// 弹窗模式是否清空上次选择内容
clearDate: {
type: Boolean,
default: true
},
// 是否点击遮罩层关闭
maskClick: {
type: Boolean,
default: false
},
// 是否禁止点击日历
disabledChoice: {
type: Boolean,
default: false
},
// 弹窗日历取消和确认按钮的显示位置
operationPosition: {
type: String,
default: 'top',
validator(value) {
return ['top', 'bottom'].includes(value)
}
},
// 弹窗日历点击确认时是否需要选择完整日期
confirmFullDate: {
type: Boolean,
default: false
},
// 当通过 `selected` 属性设置某个日期 `badgeColor`后,如果该日期被选择且主题色与 `badgeColor` 一致时,徽标会显示本颜色
actBadgeColor: {
type: String,
default: '#fff'
},
...uni.$w?.props?.calendar
}
}

View File

@ -0,0 +1,553 @@
import calendar from './calendar.js';
import CALENDAR from './calendar.js'
class Calendar {
constructor({
date,
selected,
startDate,
endDate,
mode,
monthShowCurrentMonth,
rangeEndRepick,
rangeSameDay,
rangeHaveDisableTruncation,
type,
foldStatus,
startWeek
} = {}) {
// 当前日期
this.date = this.getDate(new Date()) // 当前初入日期
// 打点信息
this.selected = selected || [];
// 范围开始
this.startDate = startDate
// 范围结束
this.endDate = endDate
// 日历以周几开始
this.startWeek = startWeek
// 日期选择类型
this.mode = mode
// 日历类型
this.type = type
// 折叠状态
this.foldStatus = foldStatus
// 允许范围内重选结束日期
this.rangeEndRepick = rangeEndRepick
// 允许日期选择范围起始日期为同一天
this.rangeSameDay = rangeSameDay
// 日期选择范围内遇到打点禁用日期是否截断
this.rangeHaveDisableTruncation = rangeHaveDisableTruncation
// 每月是否仅显示当月的数据
this.monthShowCurrentMonth = monthShowCurrentMonth
// 清理多选状态
this.cleanRange()
// 每周日期
this.weeks = {}
// 多个日期
this.multiple = [];
}
/**
* 设置日期
* @param {Object} date
*/
setDate(date) {
this.selectDate = this.getDate(date)
this._getWeek(this.selectDate.fullDate)
}
/**
* 清除范围
*/
cleanRange() {
this.rangeStatus = {
before: '',
after: '',
data: []
}
}
/**
* 清除多选
*/
cleanMultiple() {
this.multiple = []
}
/**
* 重置开始日期
*/
resetSatrtDate(startDate) {
// 范围开始
this.startDate = startDate
}
/**
* 重置结束日期
*/
resetEndDate(endDate) {
// 范围结束
this.endDate = endDate
}
/**
* 重置是否每月仅显示当月数据
* @param {Boolean} show 是否仅显示当月数据
*/
resetMonthShowCurrentMonth(show) {
this.monthShowCurrentMonth = show
}
// 重置允许范围内重选结束日期
resetRangeEndRepick(val) {
this.rangeEndRepick = val
}
// 重置允许日期范围选择起始日期为同一天
resetRangeSameDay(val) {
this.rangeSameDay = val
}
// 重置范围内遇到打点禁用日期是否截断
resetRangeHaveDisableTruncation(val) {
this.rangeHaveDisableTruncation = val
}
// 重置日期选择模式
resetMode(val) {
this.mode = val
}
// 重置折叠状态
resetFoldStatus(val) {
this.foldStatus = val
}
// 重置日历以周几开始
resetStartWeek(val) {
this.startWeek = val
}
/**
* 创建本月某一天的信息
*/
_createCurrentDay(nowDate, full, date) {
// 是否今天
let isDay = this.date.fullDate === nowDate
// 获取打点信息
let info = this.selected && this.selected.find((item) => {
if (this.dateEqual(nowDate, item.date)) {
return item
}
})
// 日期禁用
let disableBefore = true
let disableAfter = true
if (this.startDate) {
disableBefore = this.dateCompare(this.startDate, nowDate)
}
if (this.endDate) {
disableAfter = this.dateCompare(nowDate, this.endDate)
}
// 范围选择模式
let ranges = this.rangeStatus.data
let checked = false
if (this.mode == 'range') {
checked = ranges.findIndex((item) => this.dateEqual(item, nowDate)) !== -1 ? true : false;
}
// 多日期选择模式
let multiples = this.multiple
let multiplesChecked = false
if (this.mode == 'multiple') {
multiplesChecked = multiples.findIndex(item => this.dateEqual(item, nowDate)) !== -1;
}
let data = {
fullDate: nowDate,
year: full.year,
date,
type: this.type,
mode: this.mode,
multiples: this.mode == 'multiple' ? multiplesChecked : false,
rangeMultiple: this.mode == 'range' ? checked : false,
beforeRange: this.dateEqual(this.rangeStatus.before, nowDate),
afterRange: this.dateEqual(this.rangeStatus.after, nowDate),
month: full.month,
lunar: this.getlunar(full.year, full.month, date),
disable: !(disableBefore && disableAfter),
isDay
}
if (info) {
data.extraInfo = info;
data.disable = info.disable || false;
}
return data
}
/**
* 获取任意时间
*/
getDate(date, AddDayCount = 0, str = 'day') {
if (!date) {
date = new Date()
}
if (typeof date !== 'object') {
date = date.replace(/-/g, '/')
}
const dd = new Date(date)
switch (str) {
case 'day':
dd.setDate(dd.getDate() + AddDayCount) // 获取AddDayCount天后的日期
break
case 'month':
if (dd.getDate() === 31 && AddDayCount > 0) {
dd.setDate(dd.getDate() + AddDayCount)
} else {
const preMonth = dd.getMonth()
dd.setMonth(preMonth + AddDayCount) // 获取AddDayCount天后的日期
const nextMonth = dd.getMonth()
// 处理 pre 切换月份目标月份为2月没有当前日(30 31) 切换错误问题
if (AddDayCount < 0 && preMonth !== 0 && nextMonth - preMonth > AddDayCount) {
dd.setMonth(nextMonth + (nextMonth - preMonth + AddDayCount))
}
// 处理 next 切换月份目标月份为2月没有当前日(30 31) 切换错误问题
if (AddDayCount > 0 && nextMonth - preMonth > AddDayCount) {
dd.setMonth(nextMonth - (nextMonth - preMonth - AddDayCount))
}
}
break
case 'week':
dd.setDate(dd.getDate() + (AddDayCount * 7))
break;
case 'year':
dd.setFullYear(dd.getFullYear() + AddDayCount) // 获取AddDayCount天后的日期
break
}
const y = dd.getFullYear()
const m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1 // 获取当前月份的日期不足10补0
const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate() // 获取当前几号不足10补0
return {
fullDate: y + '-' + m + '-' + d,
year: y,
month: m,
date: d,
day: dd.getDay()
}
}
/**
* 获取上月剩余天数
*/
_getLastMonthDays(firstDay, full) {
let dateArr = []
for (let i = firstDay; i > 0; i--) {
const beforeDate = new Date(full.year, full.month - 1, -i + 1).getDate()
dateArr.push({
date: beforeDate,
month: full.month - 1,
year: full.year,
lunar: this.getlunar(full.year, full.month - 1, beforeDate),
disable: true
})
}
return dateArr
}
/**
* 获取本月天数
*/
_currentMonthDays(dateData, full) {
let dateArr = []
let fullDate = this.date.fullDate
for (let i = 1; i <= dateData; i++) {
let nowDate = full.year + '-' + (full.month < 10 ?
full.month : full.month) + '-' + (i < 10 ?
'0' + i : i)
dateArr.push(this._createCurrentDay(nowDate, full, i))
}
return dateArr
}
/**
* 获取下月天数
*/
_getNextMonthDays(surplus, full) {
let dateArr = []
for (let i = 1; i < surplus + 1; i++) {
dateArr.push({
date: i,
month: Number(full.month) + 1,
lunar: this.getlunar(full.year, Number(full.month) + 1, i),
disable: true
})
}
return dateArr
}
/**
* 获取任意日期的一周
*/
_getWeekDays(dateData) {
let dateArr = [];
let oneDayTime = 1000 * 60 * 60 * 24
let today = new Date(dateData);
// 获取这个日期是星期几
let todayDay;
let startDate;
// 如果日历以周一开始
if (this.startWeek == 'mon') {
todayDay = today.getDay() || 7;
startDate = new Date(today.getTime() - oneDayTime * (todayDay - 1));
} else {
todayDay = today.getDay();
startDate = new Date(today.getTime() - oneDayTime * todayDay);
}
for (let i = 0; i < 7; i++) {
let temp = new Date(startDate.getTime() + i * oneDayTime)
let newDate = this.getDate(`${temp.getFullYear()}-${temp.getMonth() + 1}-${temp.getDate()}`)
dateArr.push(this._createCurrentDay(newDate.fullDate, newDate, Number(newDate.date)))
}
return dateArr;
}
/**
* 获取当前日期详情
* @param {Object} date
*/
getInfo(date) {
if (!date) {
date = new Date()
}
const dateInfo = this.canlender.find(item => item.fullDate === this.getDate(date).fullDate)
return dateInfo
}
/**
* 比较时间大小
*/
dateCompare(startDate, endDate) {
// 计算截止时间
startDate = new Date(startDate.replace('-', '/').replace('-', '/'))
// 计算详细项的截止时间
endDate = new Date(endDate.replace('-', '/').replace('-', '/'))
if (startDate <= endDate) {
return true
} else {
return false
}
}
/**
* 比较时间是否相等
*/
dateEqual(before = '', after = '') {
// 计算截止时间
before = new Date(before.replace('-', '/').replace('-', '/'))
// 计算详细项的截止时间
after = new Date(after.replace('-', '/').replace('-', '/'))
if (before.getTime() - after.getTime() === 0) {
return true
} else {
return false
}
}
/**
* 获取日期范围内所有日期
* @param {Object} begin
* @param {Object} end
*/
getDateAll(begin, end) {
// 找出所有打点中已禁用的部分 不让其被添加在日期选择范围内
let disableList = this.selected.filter(item => item.date && item.disable).map(item => item.date)
var arr = []
var ab = begin.split('-')
var ae = end.split('-')
var db = new Date()
db.setFullYear(ab[0], ab[1] - 1, ab[2])
var de = new Date()
de.setFullYear(ae[0], ae[1] - 1, ae[2])
var wuxDb = db.getTime() - 24 * 60 * 60 * 1000
var wuxDe = de.getTime() - 24 * 60 * 60 * 1000
for (var k = wuxDb; k <= wuxDe;) {
k = k + 24 * 60 * 60 * 1000
let fullDate = this.getDate(new Date(parseInt(k))).fullDate
// 如果要在选择范围内截断日期
if (this.rangeHaveDisableTruncation) {
// 如果不在打点禁止列表中
if (disableList.includes(fullDate)) return arr;
arr.push(fullDate)
} else {
if (!disableList.includes(fullDate)) arr.push(fullDate);
}
}
return arr
}
/**
* 计算阴历日期显示
*/
getlunar(year, month, date) {
return CALENDAR.solar2lunar(year, month, date)
}
/**
* 设置打点
*/
setSelectInfo(data, value) {
this.selected = value
this._getWeek(data)
}
/**
* 设置范围
*/
setRange(fullDate) {
let {
before,
after
} = this.rangeStatus;
// 非范围选择不再执行
if (this.mode != 'range') return
// 判断目前的日期 是否 比before日期小或者等于before日期 如果为true就要重置
let reset = this.dateCompare(fullDate, before);
// 如果日期选择范围允许为同一天 且 目前是需要重置的
if (this.rangeSameDay && before && reset) {
// 判断是否需要相等 如果 不相等 则 重置 如果相等 则不重置
reset = !this.dateEqual(fullDate, before);
}
if ((before && after || reset) && (!this.rangeEndRepick || (this.rangeEndRepick && this.rangeStatus.data
.indexOf(fullDate) == -1))) {
this.rangeStatus.before = fullDate;
this.rangeStatus.after = '';
this.rangeStatus.data = [];
} else {
if (!before) {
this.rangeStatus.before = fullDate
} else {
if (this.dateCompare(this.rangeStatus.before, fullDate)) {
this.rangeStatus.data = this.getDateAll(this.rangeStatus.before, fullDate);
} else {
this.rangeStatus.data = this.getDateAll(fullDate, this.rangeStatus.before);
}
this.rangeStatus.after = this.rangeStatus.data[this.rangeStatus.data.length - 1]
}
}
this._getWeek(fullDate)
}
/**
* 设置多选
*/
setMultiple(fullDate) {
// 非多选不再执行
if (this.mode != 'multiple') return
// 检查是否已经多选
let index = this.multiple.findIndex((item) => {
if (this.dateEqual(fullDate, item)) {
return item
}
});
if (index === -1) {
this.multiple.push(fullDate)
this.setDate(fullDate)
} else {
this.multiple = this.multiple.filter((item, i) => i != index)
}
this._getWeek(fullDate)
}
/**
* 获取每周数据
* @param {Object} dateData
*/
_getWeek(dateData, useWeeks = true) {
const {
year,
month
} = this.getDate(dateData)
let weeks = {}
// 日历数据
let canlender = [];
if (this.foldStatus === 'open') {
// 默认以周末开始
let firstDay = new Date(year, month - 1, 1).getDay();
// 如果以周一开始
if (this.startWeek === 'mon') {
firstDay = firstDay === 0 ? 6 : firstDay - 1;
}
let currentDay = new Date(year, month, 0).getDate()
// 日期数据
let dates = {
lastMonthDays: this._getLastMonthDays(firstDay, this.getDate(dateData)), // 上个月末尾几天
currentMonthDys: this._currentMonthDays(currentDay, this.getDate(dateData)), // 本月天数
weeks: []
}
// 下月开始几天
const surplus = 42 - (dates.lastMonthDays.length + dates.currentMonthDys.length)
dates.nextMonthDays = this._getNextMonthDays(surplus, this.getDate(dateData))
// 如果仅显示当月
if (this.monthShowCurrentMonth) {
// 日历数据
canlender = canlender.concat(
dates.lastMonthDays.map(item => item = {
empty: true,
lunar: {},
}),
dates.currentMonthDys,
dates.nextMonthDays.map(item => item = {
empty: true,
lunar: {},
}),
);
} else {
// 拼接数组 上个月开始几天 + 本月天数+ 下个月开始几天
canlender = canlender.concat(dates.lastMonthDays, dates.currentMonthDys, dates.nextMonthDays)
}
} else {
canlender = this._getWeekDays(dateData)
}
for (let i = 0; i < canlender.length; i++) {
if (i % 7 === 0) {
weeks[parseInt(i / 7)] = new Array(7)
}
weeks[parseInt(i / 7)][i % 7] = canlender[i] || {};
}
if (useWeeks) {
this.canlender = canlender
this.weeks = weeks
}
return weeks
}
//静态方法
// static init(date) {
// if (!this.instance) {
// this.instance = new Calendar(date);
// }
// return this.instance;
// }
}
export default Calendar

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,91 @@
{
"id": "wu-calendar",
"displayName": "wu-calendar 最全日历,动态滑动切换、多滑动模式、多日历类型、多日期选择模式等,全端兼容,无论平台,一致体验。",
"version": "1.5.6",
"description": "唯一支持动态滑动计算的日历插件,多滑动切换模式(纵、横、不滑动)、多日历类型(周、月)、多日期选择模式(单选、多选、范围)、日历周几(周日、周一)、自定义主题、农历显示等,可以让您纵享丝滑的使用日历",
"keywords": [
"wu-calendar",
"日历",
"多日历类型",
"动态滑动计算",
"wu-ui"
],
"repository": "",
"engines": {
"HBuilderX": "^3.5.5"
},
"dcloudext": {
"type": "component-vue",
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "插件不采集任何数据",
"permissions": "无"
},
"npmurl": ""
},
"uni_modules": {
"dependencies": [
"wu-ui-tools",
"wu-icon",
"wu-safe-bottom"
],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y",
"alipay": "n"
},
"client": {
"Vue": {
"vue2": "y",
"vue3": "y"
},
"App": {
"app-vue": "y",
"app-nvue": "y",
"app-uvue": "u"
},
"H5-mobile": {
"Safari": "y",
"Android Browser": "y",
"微信浏览器(Android)": "y",
"QQ浏览器(Android)": "y"
},
"H5-pc": {
"Chrome": "y",
"IE": "y",
"Edge": "y",
"Firefox": "y",
"Safari": "y"
},
"小程序": {
"微信": "y",
"阿里": "y",
"百度": "y",
"字节跳动": "y",
"QQ": "y",
"钉钉": "n",
"快手": "n",
"飞书": "n",
"京东": "n"
},
"快应用": {
"华为": "n",
"联盟": "n"
}
}
}
}
}

View File

@ -0,0 +1,16 @@
## wu-calendar 最全日历
> **组件名wu-calendar**
目前插件市场上唯一可以动态滑动计算的日历插件,多滑动切换模式(纵、横向滑动,不滑动)、多日历类型(周、月日历)、多日历选择模式(日期单选、多选、范围选择)、多日历起始周几设置(周日、周一)、自定义主题颜色(副色自动生成)、自定义文案、农历显示等功能,可以让您纵享丝滑的使用日历。
## [查看文档](https://wuui.cn/zh-CN/components/calendar.html)
## [更多组件, 请查看 `wu-ui` 组件库](https://ext.dcloud.net.cn/plugin?name=wu--ui)
(请勿下载插件zip)
<a href="https://ext.dcloud.net.cn/plugin?name=wu--ui">
<img src="https://wuui.cn/intr.png">
</a>
**如使用过程中有任何问题或者您对wu-ui有一些好的建议。<br>欢迎加入 [wu-ui 交流群](https://wuui.cn/zh-CN/components/qqFeedBack.html)**

View File

@ -0,0 +1,10 @@
## 1.0.42024-05-08
更新域名
## 1.0.32023-08-08
修复链接引入错误
## 1.0.22023-08-07
修复引入错误
## 1.0.12023-08-07
支持自定义(包括nvue)文字与图片图标
## 1.0.02023-08-03
基于字体的图标集,包含了大多数常见场景的图标,支持自定义,支持自定义图片图标等。可自定义颜色、大小。

View File

@ -0,0 +1,159 @@
export default {
'wuicon-level': 'e68f',
'wuicon-download': 'e670',
'wuicon-search': 'e632',
'wuicon-reload': 'e627',
'wuicon-scan': 'e631',
'wuicon-calendar': 'e65c',
'wuicon-bag': 'e647',
'wuicon-checkbox-mark': 'e659',
'wuicon-attach': 'e640',
'wuicon-wifi-off': 'e6cc',
'wuicon-woman': 'e626',
'wuicon-man': 'e675',
'wuicon-chat': 'e656',
'wuicon-chat-fill': 'e63f',
'wuicon-red-packet': 'e6c3',
'wuicon-folder': 'e694',
'wuicon-order': 'e695',
'wuicon-arrow-up-fill': 'e636',
'wuicon-arrow-down-fill': 'e638',
'wuicon-backspace': 'e64d',
'wuicon-photo': 'e60d',
'wuicon-photo-fill': 'e6b4',
'wuicon-lock': 'e69d',
'wuicon-lock-fill': 'e6a6',
'wuicon-lock-open': 'e68d',
'wuicon-lock-opened-fill': 'e6a1',
'wuicon-home': 'e67b',
'wuicon-home-fill': 'e68e',
'wuicon-star': 'e618',
'wuicon-star-fill': 'e61e',
'wuicon-share': 'e629',
'wuicon-share-fill': 'e6bb',
'wuicon-share-square': 'e6c4',
'wuicon-volume': 'e605',
'wuicon-volume-fill': 'e624',
'wuicon-volume-off': 'e6bd',
'wuicon-volume-off-fill': 'e6c8',
'wuicon-trash': 'e623',
'wuicon-trash-fill': 'e6ce',
'wuicon-shopping-cart': 'e6cb',
'wuicon-shopping-cart-fill': 'e630',
'wuicon-question-circle': 'e622',
'wuicon-question-circle-fill': 'e6bc',
'wuicon-plus': 'e625',
'wuicon-plus-circle': 'e603',
'wuicon-plus-circle-fill': 'e611',
'wuicon-tags': 'e621',
'wuicon-tags-fill': 'e613',
'wuicon-pause': 'e61c',
'wuicon-pause-circle': 'e696',
'wuicon-pause-circle-fill': 'e60c',
'wuicon-play-circle': 'e6af',
'wuicon-play-circle-fill': 'e62a',
'wuicon-map': 'e665',
'wuicon-map-fill': 'e6a8',
'wuicon-phone': 'e6ba',
'wuicon-phone-fill': 'e6ac',
'wuicon-list': 'e690',
'wuicon-list-dot': 'e6a9',
'wuicon-info-circle': 'e69f',
'wuicon-info-circle-fill': 'e6a7',
'wuicon-minus': 'e614',
'wuicon-minus-circle': 'e6a5',
'wuicon-mic': 'e66d',
'wuicon-mic-off': 'e691',
'wuicon-grid': 'e68c',
'wuicon-grid-fill': 'e698',
'wuicon-eye': 'e664',
'wuicon-eye-fill': 'e697',
'wuicon-eye-off': 'e69c',
'wuicon-eye-off-outline': 'e688',
'wuicon-file-text': 'e687',
'wuicon-file-text-fill': 'e67f',
'wuicon-edit-pen': 'e65d',
'wuicon-edit-pen-fill': 'e679',
'wuicon-email': 'e673',
'wuicon-email-fill': 'e683',
'wuicon-checkmark': 'e64a',
'wuicon-checkmark-circle': 'e643',
'wuicon-checkmark-circle-fill': 'e668',
'wuicon-clock': 'e66c',
'wuicon-clock-fill': 'e64b',
'wuicon-close': 'e65a',
'wuicon-close-circle': 'e64e',
'wuicon-close-circle-fill': 'e666',
'wuicon-car': 'e64f',
'wuicon-car-fill': 'e648',
'wuicon-bell': 'e651',
'wuicon-bell-fill': 'e604',
'wuicon-play-left': 'e6bf',
'wuicon-play-right': 'e6b3',
'wuicon-play-left-fill': 'e6ae',
'wuicon-play-right-fill': 'e6ad',
'wuicon-skip-back-left': 'e6c5',
'wuicon-skip-forward-right': 'e61f',
'wuicon-setting': 'e602',
'wuicon-setting-fill': 'e6d0',
'wuicon-more-dot-fill': 'e66f',
'wuicon-more-circle': 'e69e',
'wuicon-more-circle-fill': 'e684',
'wuicon-arrow-upward': 'e641',
'wuicon-arrow-downward': 'e634',
'wuicon-arrow-leftward': 'e63b',
'wuicon-arrow-rightward': 'e644',
'wuicon-arrow-up': 'e633',
'wuicon-arrow-down': 'e63e',
'wuicon-arrow-left': 'e646',
'wuicon-arrow-right': 'e63c',
'wuicon-thumb-up': 'e612',
'wuicon-thumb-up-fill': 'e62c',
'wuicon-thumb-down': 'e60a',
'wuicon-thumb-down-fill': 'e628',
'wuicon-coupon': 'e65f',
'wuicon-coupon-fill': 'e64c',
'wuicon-kefu-ermai': 'e660',
'wuicon-server-fill': 'e610',
'wuicon-server-man': 'e601',
'wuicon-warning': 'e6c1',
'wuicon-warning-fill': 'e6c7',
'wuicon-camera': 'e642',
'wuicon-camera-fill': 'e650',
'wuicon-pushpin': 'e6d1',
'wuicon-pushpin-fill': 'e6b6',
'wuicon-heart': 'e6a2',
'wuicon-heart-fill': 'e68b',
'wuicon-account': 'e63a',
'wuicon-account-fill': 'e653',
'wuicon-integral': 'e693',
'wuicon-integral-fill': 'e6b1',
'wuicon-gift': 'e680',
'wuicon-gift-fill': 'e6b0',
'wuicon-empty-data': 'e671',
'wuicon-empty-address': 'e68a',
'wuicon-empty-favor': 'e662',
'wuicon-empty-car': 'e656',
'wuicon-empty-order': 'e66b',
'wuicon-empty-list': 'e671',
'wuicon-empty-search': 'e677',
'wuicon-empty-permission': 'e67c',
'wuicon-empty-news': 'e67d',
'wuicon-empty-history': 'e684',
'wuicon-empty-coupon': 'e69b',
'wuicon-empty-page': 'e60e',
'wuicon-apple-fill': 'e635',
'wuicon-zhifubao-circle-fill': 'e617',
'wuicon-weixin-circle-fill': 'e6cd',
'wuicon-weixin-fill': 'e620',
'wuicon-qq-fill': 'e608',
'wuicon-qq-circle-fill': 'e6b9',
'wuicon-moments': 'e6a0',
'wuicon-moments-circel-fill': 'e6c2',
'wuicon-twitter': 'e607',
'wuicon-twitter-circle-fill': 'e6cf',
}

View File

@ -0,0 +1,90 @@
export default {
props: {
// 图标类名
name: {
type: String,
default: ''
},
// 图标颜色,可接受主题色
color: {
type: String,
default: '#606266'
},
// 字体大小单位px
size: {
type: [String, Number],
default: '16px'
},
// 是否显示粗体
bold: {
type: Boolean,
default: false
},
// 点击图标的时候传递事件出去的index用于区分点击了哪一个
index: {
type: [String, Number],
default: null
},
// 触摸图标时的类名
hoverClass: {
type: String,
default: ''
},
// 自定义扩展前缀,方便用户扩展自己的图标库
customPrefix: {
type: String,
default: 'wuicon'
},
// 图标右边或者下面的文字
label: {
type: [String, Number],
default: ''
},
// label的位置只能右边或者下边
labelPos: {
type: String,
default: 'right'
},
// label的大小
labelSize: {
type: [String, Number],
default: '15px'
},
// label的颜色
labelColor: {
type: String,
default: '#606266'
},
// label与图标的距离
space: {
type: [String, Number],
default: '3px'
},
// 图片的mode
imgMode: {
type: String,
default: ''
},
// 用于显示图片小图标时,图片的宽度
width: {
type: [String, Number],
default: ''
},
// 用于显示图片小图标时,图片的高度
height: {
type: [String, Number],
default: ''
},
// 用于解决某些情况下,让图标垂直居中的用途
top: {
type: [String, Number],
default: 0
},
// 是否阻止事件传播
stop: {
type: Boolean,
default: false
},
...uni.$w?.props?.icon
}
}

View File

@ -0,0 +1,225 @@
<template>
<view class="wu-icon" @tap="clickHandler" :class="['wu-icon--' + labelPos]">
<!-- 这里进行空字符串判断如果仅仅是v-if="label"可能会出现传递0的时候结果也无法显示 -->
<text v-if="label !== '' && (labelPos == 'left' || labelPos == 'top')" class="wu-icon__label" :style="labelStyle">{{ label }}</text>
<image class="wu-icon__img" v-if="isImg" :src="name" :mode="imgMode"
:style="[imgStyle, $w.addStyle(customStyle)]"></image>
<text v-else class="wu-icon__icon" :class="uClasses" :style="[iconStyle, $w.addStyle(customStyle)]"
:hover-class="hoverClass">{{icon}}</text>
<!-- 这里进行空字符串判断如果仅仅是v-if="label"可能会出现传递0的时候结果也无法显示 -->
<text v-if="label !== '' && (labelPos == 'right' || labelPos == 'bottom')" class="wu-icon__label" :style="labelStyle">{{ label }}</text>
</view>
</template>
<script>
import mpMixin from '@/uni_modules/wu-ui-tools/libs/mixin/mpMixin.js'
import mixin from '@/uni_modules/wu-ui-tools/libs/mixin/mixin.js'
// #ifdef APP-NVUE
// nvueweexdom
// https://weex.apache.org/zh/docs/modules/dom.html#addrule
import iconUrl from './wuicons.ttf';
const domModule = weex.requireModule('dom');
domModule.addRule('fontFace', {
'fontFamily': "wuicon-iconfont",
'src': "url('" + iconUrl + "')"
})
// #endif
// unicode
import icons from './icons';
import props from './props.js';
/**
* icon 图标
* @description 基于字体的图标集包含了大多数常见场景的图标
* @tutorial https://wuui.cn/zh-CN/components/icon.html
* @property {String} name 图标名称若带有 `/` 或遵循 `base64` 图片格式会被认为是图片图标则文字图标相关属性会失效
* @property {String} color 图标颜色,可接受主题色 默认 color: #606266
* @property {String | Number} size 图标字体大小单位px/rpx 默认 '16px'
* @property {Boolean} bold 是否显示粗体 默认 false
* @property {String | Number} index 点击图标的时候传递事件出去的index用于区分点击了哪一个
* @property {String} hoverClass 图标按下去的样式类用法同uni的view组件的hoverClass参数详情见官网
* @property {String} customPrefix 自定义扩展前缀方便用户扩展自己的图标库 默认 'wuicon'
* @property {String | Number} label 图标右侧的label文字
* @property {String} labelPos label相对于图标的位置默认 'right'
* @value top 上方
* @value bottom 下方
* @value left 左侧
* @value right 右侧
* @property {String | Number} labelSize label字体大小单位px 默认 '15px'
* @property {String} labelColor 图标右侧的label文字颜色 默认 color['wu-content-color']
* @property {String | Number} space label与图标的距离单位px 默认 '3px'
* @property {String} imgMode image组件的mode详见[image](https://uniapp.dcloud.net.cn/component/image.html#image)
* @property {String | Number} width 显示图片小图标时的宽度
* @property {String | Number} height 显示图片小图标时的高度
* @property {String | Number} top 图标在垂直方向上的定位 用于解决某些情况下让图标垂直居中的用途 默认 0
* @property {Boolean} stop 是否阻止事件传播 默认 false
* @property {Object} customStyle icon的样式对象形式
* @event {Function} click 点击图标时触发
* @event {Function} touchstart 事件触摸时触发
* @example <wu-icon name="photo" color="#2979ff" size="28"></wu-icon>
*/
export default {
name: 'wu-icon',
emits: ['click'],
mixins: [mpMixin, mixin, props],
data() {
return {
colorType: [
'primary',
'success',
'info',
'error',
'warning'
]
}
},
computed: {
uClasses() {
let classes = []
classes.push(this.customPrefix)
classes.push(this.customPrefix + '-' + this.name)
//
if (this.color && this.colorType.includes(this.color)) classes.push('wu-icon__icon--' + this.color)
// 使[a, b, c]
//
//#ifdef MP-ALIPAY || MP-TOUTIAO || MP-BAIDU
classes = classes.join(' ')
//#endif
return classes
},
iconStyle() {
let style = {}
style = {
fontSize: this.$w.addUnit(this.size),
lineHeight: this.$w.addUnit(this.size),
fontWeight: this.bold ? 'bold' : 'normal',
//
top: this.$w.addUnit(this.top)
}
//
if (this.color && !this.colorType.includes(this.color)) style.color = this.color
return style
},
// name"/"
isImg() {
const isBase64 = this.name.indexOf('data:') > -1 && this.name.indexOf('base64') > -1;
return this.name.indexOf('/') !== -1 || isBase64;
},
imgStyle() {
let style = {}
// widthheight使使size
style.width = this.width ? this.$w.addUnit(this.width) : this.$w.addUnit(this.size)
style.height = this.height ? this.$w.addUnit(this.height) : this.$w.addUnit(this.size)
return style
},
//
icon() {
// nameunicode
const code = icons['wuicon-' + this.name];
if (['wuicon'].indexOf(this.customPrefix) > -1) {
return code ? unescape(`%u${code}`) : this.name;
} else {
// #ifndef APP-NVUE
return ''
// #endif
// #ifdef APP-NVUE
return unescape(`%u${this.name}`)
// #endif
}
},
// label
labelStyle() {
let style = {
color: this.labelColor,
fontSize: this.$w.addUnit(this.labelSize),
marginLeft: this.labelPos == 'right' ? this.$w.addUnit(this.space) : 0,
marginTop: this.labelPos == 'bottom' ? this.$w.addUnit(this.space) : 0,
marginRight: this.labelPos == 'left' ? this.$w.addUnit(this.space) : 0,
marginBottom: this.labelPos == 'top' ? this.$w.addUnit(this.space) : 0
};
return style
}
},
methods: {
clickHandler(e) {
this.$emit('click', this.index)
//
this.stop && this.preventEvent(e)
}
}
}
</script>
<style lang="scss" scoped>
@import '@/uni_modules/wu-ui-tools/libs/css/components.scss';
@import '@/uni_modules/wu-ui-tools/libs/css/color.scss';
//
$wu-icon-primary: $wu-primary !default;
$wu-icon-success: $wu-success !default;
$wu-icon-info: $wu-info !default;
$wu-icon-warning: $wu-warning !default;
$wu-icon-error: $wu-error !default;
$wu-icon-label-line-height: 1 !default;
/* #ifndef APP-NVUE */
// nvue
@font-face {
font-family: 'wuicon-iconfont';
src: url('./wuicons.ttf') format('truetype');
}
/* #endif */
.wu-icon {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
align-items: center;
&--left, &--right {
flex-direction: row;
}
&--top, &--bottom {
flex-direction: column;
}
&__icon {
font-family: wuicon-iconfont;
position: relative;
@include flex;
align-items: center;
&--primary {
color: $wu-icon-primary;
}
&--success {
color: $wu-icon-success;
}
&--error {
color: $wu-icon-error;
}
&--warning {
color: $wu-icon-warning;
}
&--info {
color: $wu-icon-info;
}
}
&__img {
/* #ifndef APP-NVUE */
height: auto;
will-change: transform;
/* #endif */
}
&__label {
/* #ifndef APP-NVUE */
line-height: $wu-icon-label-line-height;
/* #endif */
}
}
</style>

Binary file not shown.

View File

@ -0,0 +1,87 @@
{
"id": "wu-icon",
"displayName": "wu-icon 图标 全面兼容小程序、nvue、vue2、vue3等多端",
"version": "1.0.4",
"description": "基于字体的图标集,包含了大多数常见场景的图标,支持自定义,支持自定义图片图标等。可自定义颜色、大小。",
"keywords": [
"wu-ui",
"图标",
"wu-icon",
"文字图标"
],
"repository": "",
"engines": {
"HBuilderX": "^3.4.15"
},
"dcloudext": {
"type": "component-vue",
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "插件不采集任何数据",
"permissions": "无"
},
"npmurl": ""
},
"uni_modules": {
"dependencies": [
"wu-ui-tools"
],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y",
"alipay": "n"
},
"client": {
"Vue": {
"vue2": "y",
"vue3": "y"
},
"App": {
"app-vue": "y",
"app-nvue": "y"
},
"H5-mobile": {
"Safari": "y",
"Android Browser": "y",
"微信浏览器(Android)": "y",
"QQ浏览器(Android)": "y"
},
"H5-pc": {
"Chrome": "y",
"IE": "y",
"Edge": "y",
"Firefox": "y",
"Safari": "y"
},
"小程序": {
"微信": "y",
"阿里": "y",
"百度": "y",
"字节跳动": "y",
"QQ": "y",
"钉钉": "u",
"快手": "u",
"飞书": "u",
"京东": "u"
},
"快应用": {
"华为": "u",
"联盟": "u"
}
}
}
}
}

View File

@ -0,0 +1,10 @@
## wu-icon 图标库
> **组件名wu-icon**
基于字体的图标集,包含了大多数常见场景的图标,支持自定义(包括nvue)文字与图片图标等。
## <a href="https://wuui.cn/zh-CN/components/icon" target="_blank">查看文档</a>
## [更多插件请关注wu-ui组件库](https://ext.dcloud.net.cn/plugin?name=wuui) <small>(请不要 下载插件ZIP</small>
**如使用过程中有任何问题或者您对wu-ui有一些好的建议。<br>欢迎加入 [wu-ui 交流群](https://wuui.cn/zh-CN/components/qqFeedBack.html)**

View File

@ -0,0 +1,6 @@
## 1.0.22024-05-08
更新域名
## 1.0.12023-09-11
优化底部安全距离计算方法
## 1.0.02023-09-01
主要是针对IPhone X等一些底部带指示条的机型指示条的操作区域与页面底部存在重合容易导致用户误操作因此我们需要针对这些机型进行底部安全区适配。

View File

@ -0,0 +1,5 @@
export default {
props: {
...uni.$w?.props?.safeBottom
}
}

View File

@ -0,0 +1,61 @@
<template>
<view
class="wu-safe-bottom"
:style="[style]"
>
</view>
</template>
<script>
import mpMixin from '@/uni_modules/wu-ui-tools/libs/mixin/mpMixin.js';
import mixin from '@/uni_modules/wu-ui-tools/libs/mixin/mixin.js';
import props from './props.js';
/**
* SafeBottom 底部安全区
* @description 这个适配主要是针对IPhone X等一些底部带指示条的机型指示条的操作区域与页面底部存在重合容易导致用户误操作因此我们需要针对这些机型进行底部安全区适配
* @tutorial https://wuui.cn/zh-CN/components/safeAreaInset.html
* @property {type} prop_name
* @property {Object} customStyle 定义需要用到的外部样式
*
* @event {Function()}
* @example <wu-status-bar></wu-status-bar>
*/
export default {
name: "wu-safe-bottom",
mixins: [mpMixin, mixin, props],
data() {
return {
safeAreaBottomHeight: 0,
isNvue: false,
};
},
computed: {
style() {
const {
windowWidth,
windowHeight,
windowTop,
safeArea,
screenHeight,
safeAreaInsets
} = this.$w.sys();
const style = {};
// #ifdef MP-WEIXIN
style.height = this.$w.addUnit(screenHeight - safeArea.bottom, 'px');
// #endif
// #ifndef MP-WEIXIN
style.height = this.$w.addUnit(safeAreaInsets.bottom, 'px');
// #endif
return this.$w.deepMerge(style, this.$w.addStyle(this.customStyle));
},
},
};
</script>
<style lang="scss" scoped>
.wu-safe-bottom {
/* #ifndef APP-NVUE */
width: 100%;
/* #endif */
}
</style>

View File

@ -0,0 +1,88 @@
{
"id": "wu-safe-bottom",
"displayName": "wu-safe-bottom底部安全区 全端兼容 无论平台 一致体验",
"version": "1.0.2",
"description": "针对一些底部带指示条的机型,操作区域与页面底部重合,容易误操作,因此本插件对这些机型进行底部安全区适配",
"keywords": [
"wu-ui",
"wuui",
"wu-safe-bottom",
"safe-bottom",
"底部安全区"
],
"repository": "",
"engines": {
"HBuilderX": "^3.4.15"
},
"dcloudext": {
"type": "component-vue",
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "插件不采集任何数据",
"permissions": "无"
},
"npmurl": ""
},
"uni_modules": {
"dependencies": [
"wu-ui-tools"
],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y",
"alipay": "n"
},
"client": {
"Vue": {
"vue2": "y",
"vue3": "y"
},
"App": {
"app-vue": "y",
"app-nvue": "y"
},
"H5-mobile": {
"Safari": "y",
"Android Browser": "y",
"微信浏览器(Android)": "y",
"QQ浏览器(Android)": "y"
},
"H5-pc": {
"Chrome": "y",
"IE": "y",
"Edge": "y",
"Firefox": "y",
"Safari": "y"
},
"小程序": {
"微信": "y",
"阿里": "y",
"百度": "y",
"字节跳动": "y",
"QQ": "y",
"钉钉": "n",
"快手": "n",
"飞书": "n",
"京东": "n"
},
"快应用": {
"华为": "n",
"联盟": "n"
}
}
}
}
}

View File

@ -0,0 +1,16 @@
## wu-safe-bottom 底部安全区
> **组件名wu-safe-bottom**
这个适配主要是针对IPhone X等一些底部带指示条的机型指示条的操作区域与页面底部存在重合容易导致用户误操作因此我们需要针对这些机型进行底部安全区适配。
## [查看文档](https://wuui.cn/zh-CN/components/safeAreaInset.html)
## [更多组件, 请查看 `wu-ui` 组件库](https://ext.dcloud.net.cn/plugin?name=wu--ui)
(请勿下载插件zip)
<a href="https://ext.dcloud.net.cn/plugin?name=wu--ui">
<img src="https://wuui.cn/intr.png">
</a>
**如使用过程中有任何问题或者您对wu-ui有一些好的建议。<br>欢迎加入 [wu-ui 交流群](https://wuui.cn/zh-CN/components/qqFeedBack.html)**

View File

@ -0,0 +1,22 @@
## 1.1.02023-09-13
更新版本
## 1.0.92023-09-08
修复Color方法引入路径错误
## 1.0.82023-09-05
Color不在使用npm包改为本地方法
## 1.0.72023-09-03
修复引入错误
## 1.0.62023-09-03
发布1.0.6版本
## 1.0.52023-08-30
修复api部分未导入
## 1.0.42023-08-21
修复Color API引入错误
## 1.0.32023-08-18
新增颜色API支持任意颜色格式转换颜色亮度调节、颜色饱和度调节、亮度获取、颜色是否深/亮等
## 1.0.22023-08-16
mixin交互节点信息根边距设置
## 1.0.12023-08-16
mixin更新节点交互信息查询
## 1.0.02023-08-01
wu-ui-tools 工具库 全面兼容小程序、nvue、vue2、vue3等多端

View File

@ -0,0 +1,6 @@
<template>
</template>
<script>
</script>
<style>
</style>

View File

@ -0,0 +1,73 @@
// 全局挂载引入http相关请求拦截插件
import Request from './libs/luch-request'
// 引入全局mixin
import mixin from './libs/mixin/mixin.js'
// 小程序特有的mixin
import mpMixin from './libs/mixin/mpMixin.js'
// #ifdef MP
import mpShare from './libs/mixin/mpShare.js'
// #endif
// 路由封装
import route from './libs/util/route.js'
// 公共工具函数
import * as index from './libs/function/index.js'
// 防抖方法
import debounce from './libs/function/debounce.js'
// 节流方法
import throttle from './libs/function/throttle.js'
// 规则检验
import * as test from './libs/function/test.js'
// 配置信息
import config from './libs/config/config.js'
// 平台
import platform from './libs/function/platform'
import Color from './libs/function/color/index.js'
const $w = {
...index,
route,
config,
test,
throttle,
date: index.timeFormat, // 另名date
Color,
http: new Request(),
debounce,
throttle,
platform,
mixin,
mpMixin
}
uni.$w = $w;
const install = (Vue,options={}) => {
// #ifndef APP-NVUE
Vue.mixin(mixin);
// #ifdef MP
if(options.mpShare){
Vue.mixin(mpShare);
}
// #endif
// #endif
// #ifdef VUE2
// 时间格式化同时两个名称date和timeFormat
Vue.filter('timeFormat', (timestamp, format) => uni.$w.timeFormat(timestamp, format));
Vue.filter('date', (timestamp, format) => uni.$w.timeFormat(timestamp, format));
// 将多久以前的方法,注入到全局过滤器
Vue.filter('timeFrom', (timestamp, format) => uni.$w.timeFrom(timestamp, format));
// 同时挂载到uni和Vue.prototype中
// #ifndef APP-NVUE
// 只有vue挂载到Vue.prototype才有意义因为nvue中全局Vue.prototype和Vue.mixin是无效的
Vue.prototype.$w = $w;
// #endif
// #endif
// #ifdef VUE3
Vue.config.globalProperties.$w = $w;
// #endif
}
export default {
install
}

View File

@ -0,0 +1,7 @@
// 引入公共基础类
@import "./libs/css/common.scss";
// 非nvue的样式
/* #ifndef APP-NVUE */
@import "./libs/css/vue.scss";
/* #endif */

View File

@ -0,0 +1,34 @@
// 此版本发布于2023-09-13
const version = '1.0.9'
// 开发环境才提示,生产环境不会提示
if (process.env.NODE_ENV === 'development') {
console.log(`\n %c wuui V${version} https://wuui.geeks.ink/ \n\n`, 'color: #ffffff; background: #3c9cff; padding:5px 0; border-radius: 5px;');
}
export default {
v: version,
version,
// 主题名称
type: [
'primary',
'success',
'info',
'error',
'warning'
],
// 颜色部分本来可以通过scss的:export导出供js使用但是奈何nvue不支持
color: {
'wu-primary': '#2979ff',
'wu-warning': '#ff9900',
'wu-success': '#19be6b',
'wu-error': '#fa3534',
'wu-info': '#909399',
'wu-main-color': '#303133',
'wu-content-color': '#606266',
'wu-tips-color': '#909399',
'wu-light-color': '#c0c4cc'
},
// 默认单位可以通过配置为rpx那么在用于传入组件大小参数为数值时就默认为rpx
unit: 'px'
}

View File

@ -0,0 +1,32 @@
$wu-main-color: #303133 !default;
$wu-content-color: #606266 !default;
$wu-tips-color: #909193 !default;
$wu-light-color: #c0c4cc !default;
$wu-border-color: #dadbde !default;
$wu-bg-color: #f3f4f6 !default;
$wu-disabled-color: #c8c9cc !default;
$wu-primary: #3c9cff !default;
$wu-primary-dark: #398ade !default;
$wu-primary-disabled: #9acafc !default;
$wu-primary-light: #ecf5ff !default;
$wu-warning: #f9ae3d !default;
$wu-warning-dark: #f1a532 !default;
$wu-warning-disabled: #f9d39b !default;
$wu-warning-light: #fdf6ec !default;
$wu-success: #5ac725 !default;
$wu-success-dark: #53c21d !default;
$wu-success-disabled: #a9e08f !default;
$wu-success-light: #f5fff0;
$wu-error: #f56c6c !default;
$wu-error-dark: #e45656 !default;
$wu-error-disabled: #f7b2b2 !default;
$wu-error-light: #fef0f0 !default;
$wu-info: #909399 !default;
$wu-info-dark: #767a82 !default;
$wu-info-disabled: #c4c6c9 !default;
$wu-info-light: #f4f4f5 !default;

View File

@ -0,0 +1,100 @@
// 超出行数自动显示行尾省略号最多5行
// 来自wuui的温馨提示当您在控制台看到此报错说明需要在App.vue的style标签加上lang="scss"
@for $i from 1 through 5 {
.wu-line-#{$i} {
/* #ifdef APP-NVUE */
// nvue下可以直接使用lines属性这是weex特有样式
lines: $i;
text-overflow: ellipsis;
overflow: hidden;
flex: 1;
/* #endif */
/* #ifndef APP-NVUE */
// vue下单行和多行显示省略号需要单独处理
@if $i == '1' {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
} @else {
display: -webkit-box!important;
overflow: hidden;
text-overflow: ellipsis;
word-break: break-all;
-webkit-line-clamp: $i;
-webkit-box-orient: vertical!important;
}
/* #endif */
}
}
$wu-bordercolor: #dadbde;
@if variable-exists(wu-border-color) {
$wu-bordercolor: $wu-border-color;
}
// 此处加上!important并非随意乱用而是因为目前*.nvue页面编译到H5时
// App.vue的样式会被uni-app的view元素的自带border属性覆盖导致无效
// 综上这是uni-app的缺陷导致我们为了多端兼容而必须要加上!important
// 移动端兼容性较好直接使用0.5px去实现细边框不使用伪元素形式实现
.wu-border {
border-width: 0.5px!important;
border-color: $wu-bordercolor!important;
border-style: solid;
}
.wu-border-top {
border-top-width: 0.5px!important;
border-color: $wu-bordercolor!important;
border-top-style: solid;
}
.wu-border-left {
border-left-width: 0.5px!important;
border-color: $wu-bordercolor!important;
border-left-style: solid;
}
.wu-border-right {
border-right-width: 0.5px!important;
border-color: $wu-bordercolor!important;
border-right-style: solid;
}
.wu-border-bottom {
border-bottom-width: 0.5px!important;
border-color: $wu-bordercolor!important;
border-bottom-style: solid;
}
.wu-border-top-bottom {
border-top-width: 0.5px!important;
border-bottom-width: 0.5px!important;
border-color: $wu-bordercolor!important;
border-top-style: solid;
border-bottom-style: solid;
}
// 去除button的所有默认样式让其表现跟普通的viewtext元素一样
.wu-reset-button {
padding: 0;
background-color: transparent;
/* #ifndef APP-PLUS */
font-size: inherit;
line-height: inherit;
color: inherit;
/* #endif */
/* #ifdef APP-NVUE */
border-width: 0;
/* #endif */
}
/* #ifndef APP-NVUE */
.wu-reset-button::after {
border: none;
}
/* #endif */
.wu-hover-class {
opacity: 0.7;
}

View File

@ -0,0 +1,23 @@
@mixin flex($direction: row) {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: $direction;
}
/* #ifndef APP-NVUE */
// 由于wuui是基于nvue环境进行开发的此环境中普通元素默认为flex-direction: column;
// 所以在非nvue中需要对元素进行重置为flex-direction: column; 否则可能会表现异常
$wuui-nvue-style: true !default;
@if $wuui-nvue-style == true {
view, scroll-view, swiper-item {
display: flex;
flex-direction: column;
flex-shrink: 0;
flex-grow: 0;
flex-basis: auto;
align-items: stretch;
align-content: flex-start;
}
}
/* #endif */

View File

@ -0,0 +1,111 @@
// 超出行数自动显示行尾省略号最多5行
// 来自uvui的温馨提示当您在控制台看到此报错说明需要在App.vue的style标签加上lang="scss"
@if variable-exists(show-lines) {
@for $i from 1 through 5 {
.wu-line-#{$i} {
/* #ifdef APP-NVUE */
// nvue下可以直接使用lines属性这是weex特有样式
lines: $i;
text-overflow: ellipsis;
overflow: hidden;
flex: 1;
/* #endif */
/* #ifndef APP-NVUE */
// vue下单行和多行显示省略号需要单独处理
@if $i == '1' {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
} @else {
display: -webkit-box!important;
overflow: hidden;
text-overflow: ellipsis;
word-break: break-all;
-webkit-line-clamp: $i;
-webkit-box-orient: vertical!important;
}
/* #endif */
}
}
}
@if variable-exists(show-border) {
$wu-bordercolor: #dadbde;
@if variable-exists(wu-border-color) {
$wu-bordercolor: $wu-border-color;
}
// 此处加上!important并非随意乱用而是因为目前*.nvue页面编译到H5时
// App.vue的样式会被uni-app的view元素的自带border属性覆盖导致无效
// 综上这是uni-app的缺陷导致我们为了多端兼容而必须要加上!important
// 移动端兼容性较好直接使用0.5px去实现细边框不使用伪元素形式实现
@if variable-exists(show-border-surround) {
.wu-border {
border-width: 0.5px!important;
border-color: $wu-bordercolor!important;
border-style: solid;
}
}
@if variable-exists(show-border-top) {
.wu-border-top {
border-top-width: 0.5px!important;
border-color: $wu-bordercolor!important;
border-top-style: solid;
}
}
@if variable-exists(show-border-left) {
.wu-border-left {
border-left-width: 0.5px!important;
border-color: $wu-bordercolor!important;
border-left-style: solid;
}
}
@if variable-exists(show-border-right) {
.wu-border-right {
border-right-width: 0.5px!important;
border-color: $wu-bordercolor!important;
border-right-style: solid;
}
}
@if variable-exists(show-border-bottom) {
.wu-border-bottom {
border-bottom-width: 0.5px!important;
border-color: $wu-bordercolor!important;
border-bottom-style: solid;
}
}
@if variable-exists(show-border-top-bottom) {
.wu-border-top-bottom {
border-top-width: 0.5px!important;
border-bottom-width: 0.5px!important;
border-color: $wu-bordercolor!important;
border-top-style: solid;
border-bottom-style: solid;
}
}
}
@if variable-exists(show-reset-button) {
// 去除button的所有默认样式让其表现跟普通的viewtext元素一样
.wu-reset-button {
padding: 0;
background-color: transparent;
/* #ifndef APP-PLUS */
font-size: inherit;
line-height: inherit;
color: inherit;
/* #endif */
/* #ifdef APP-NVUE */
border-width: 0;
/* #endif */
}
/* #ifndef APP-NVUE */
.wu-reset-button::after {
border: none;
}
/* #endif */
}
@if variable-exists(show-hover) {
.wu-hover-class {
opacity: 0.7;
}
}

View File

@ -0,0 +1,40 @@
// 历遍生成4个方向的底部安全区
@each $d in top, right, bottom, left {
.wu-safe-area-inset-#{$d} {
padding-#{$d}: 0;
padding-#{$d}: constant(safe-area-inset-#{$d});
padding-#{$d}: env(safe-area-inset-#{$d});
}
}
//提升H5端uni.toast()的层级避免被wuui的modal等遮盖
/* #ifdef H5 */
uni-toast {
z-index: 10090;
}
uni-toast .uni-toast {
z-index: 10090;
}
/* #endif */
// 隐藏scroll-view的滚动条
::-webkit-scrollbar {
display: none;
width: 0 !important;
height: 0 !important;
-webkit-appearance: none;
background: transparent;
}
$wuui-nvue-style: true !default;
@if $wuui-nvue-style == false {
view, scroll-view, swiper-item {
display: flex;
flex-direction: column;
flex-shrink: 0;
flex-grow: 0;
flex-basis: auto;
align-items: stretch;
align-content: flex-start;
}
}

View File

@ -0,0 +1,54 @@
# 1.0.0 - 2016-01-07
- Removed: unused speed test
- Added: Automatic routing between previously unsupported conversions
([#27](https://github.com/Qix-/color-convert/pull/27))
- Removed: `xxx2xxx()` and `xxx2xxxRaw()` functions
([#27](https://github.com/Qix-/color-convert/pull/27))
- Removed: `convert()` class
([#27](https://github.com/Qix-/color-convert/pull/27))
- Changed: all functions to lookup dictionary
([#27](https://github.com/Qix-/color-convert/pull/27))
- Changed: `ansi` to `ansi256`
([#27](https://github.com/Qix-/color-convert/pull/27))
- Fixed: argument grouping for functions requiring only one argument
([#27](https://github.com/Qix-/color-convert/pull/27))
# 0.6.0 - 2015-07-23
- Added: methods to handle
[ANSI](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) 16/256 colors:
- rgb2ansi16
- rgb2ansi
- hsl2ansi16
- hsl2ansi
- hsv2ansi16
- hsv2ansi
- hwb2ansi16
- hwb2ansi
- cmyk2ansi16
- cmyk2ansi
- keyword2ansi16
- keyword2ansi
- ansi162rgb
- ansi162hsl
- ansi162hsv
- ansi162hwb
- ansi162cmyk
- ansi162keyword
- ansi2rgb
- ansi2hsl
- ansi2hsv
- ansi2hwb
- ansi2cmyk
- ansi2keyword
([#18](https://github.com/harthur/color-convert/pull/18))
# 0.5.3 - 2015-06-02
- Fixed: hsl2hsv does not return `NaN` anymore when using `[0,0,0]`
([#15](https://github.com/harthur/color-convert/issues/15))
---
Check out commit logs for older releases

View File

@ -0,0 +1,21 @@
Copyright (c) 2011-2016 Heather Arthur <fayearthur@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,68 @@
# color-convert
[![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert)
Color-convert is a color conversion library for JavaScript and node.
It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest):
```js
var convert = require('color-convert');
convert.rgb.hsl(140, 200, 100); // [96, 48, 59]
convert.keyword.rgb('blue'); // [0, 0, 255]
var rgbChannels = convert.rgb.channels; // 3
var cmykChannels = convert.cmyk.channels; // 4
var ansiChannels = convert.ansi16.channels; // 1
```
# Install
```console
$ npm install color-convert
```
# API
Simply get the property of the _from_ and _to_ conversion that you're looking for.
All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function.
All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha).
```js
var convert = require('color-convert');
// Hex to LAB
convert.hex.lab('DEADBF'); // [ 76, 21, -2 ]
convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ]
// RGB to CMYK
convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ]
convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ]
```
### Arrays
All functions that accept multiple arguments also support passing an array.
Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.)
```js
var convert = require('color-convert');
convert.rgb.hex(123, 45, 67); // '7B2D43'
convert.rgb.hex([123, 45, 67]); // '7B2D43'
```
## Routing
Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex).
Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js).
# Contribute
If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request.
# License
Copyright &copy; 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE).

View File

@ -0,0 +1,839 @@
/* MIT license */
/* eslint-disable no-mixed-operators */
import cssKeywords from '../color-name';
// NOTE: conversions should only return primitive values (i.e. arrays, or
// values that give correct `typeof` results).
// do not use box values types (i.e. Number(), String(), etc.)
const reverseKeywords = {};
for (const key of Object.keys(cssKeywords)) {
reverseKeywords[cssKeywords[key]] = key;
}
const convert = {
rgb: {channels: 3, labels: 'rgb'},
hsl: {channels: 3, labels: 'hsl'},
hsv: {channels: 3, labels: 'hsv'},
hwb: {channels: 3, labels: 'hwb'},
cmyk: {channels: 4, labels: 'cmyk'},
xyz: {channels: 3, labels: 'xyz'},
lab: {channels: 3, labels: 'lab'},
lch: {channels: 3, labels: 'lch'},
hex: {channels: 1, labels: ['hex']},
keyword: {channels: 1, labels: ['keyword']},
ansi16: {channels: 1, labels: ['ansi16']},
ansi256: {channels: 1, labels: ['ansi256']},
hcg: {channels: 3, labels: ['h', 'c', 'g']},
apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
gray: {channels: 1, labels: ['gray']}
};
export default convert;
// Hide .channels and .labels properties
for (const model of Object.keys(convert)) {
if (!('channels' in convert[model])) {
throw new Error('missing channels property: ' + model);
}
if (!('labels' in convert[model])) {
throw new Error('missing channel labels property: ' + model);
}
if (convert[model].labels.length !== convert[model].channels) {
throw new Error('channel and label counts mismatch: ' + model);
}
const {channels, labels} = convert[model];
delete convert[model].channels;
delete convert[model].labels;
Object.defineProperty(convert[model], 'channels', {value: channels});
Object.defineProperty(convert[model], 'labels', {value: labels});
}
convert.rgb.hsl = function (rgb) {
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const min = Math.min(r, g, b);
const max = Math.max(r, g, b);
const delta = max - min;
let h;
let s;
if (max === min) {
h = 0;
} else if (r === max) {
h = (g - b) / delta;
} else if (g === max) {
h = 2 + (b - r) / delta;
} else if (b === max) {
h = 4 + (r - g) / delta;
}
h = Math.min(h * 60, 360);
if (h < 0) {
h += 360;
}
const l = (min + max) / 2;
if (max === min) {
s = 0;
} else if (l <= 0.5) {
s = delta / (max + min);
} else {
s = delta / (2 - max - min);
}
return [h, s * 100, l * 100];
};
convert.rgb.hsv = function (rgb) {
let rdif;
let gdif;
let bdif;
let h;
let s;
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const v = Math.max(r, g, b);
const diff = v - Math.min(r, g, b);
const diffc = function (c) {
return (v - c) / 6 / diff + 1 / 2;
};
if (diff === 0) {
h = 0;
s = 0;
} else {
s = diff / v;
rdif = diffc(r);
gdif = diffc(g);
bdif = diffc(b);
if (r === v) {
h = bdif - gdif;
} else if (g === v) {
h = (1 / 3) + rdif - bdif;
} else if (b === v) {
h = (2 / 3) + gdif - rdif;
}
if (h < 0) {
h += 1;
} else if (h > 1) {
h -= 1;
}
}
return [
h * 360,
s * 100,
v * 100
];
};
convert.rgb.hwb = function (rgb) {
const r = rgb[0];
const g = rgb[1];
let b = rgb[2];
const h = convert.rgb.hsl(rgb)[0];
const w = 1 / 255 * Math.min(r, Math.min(g, b));
b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
return [h, w * 100, b * 100];
};
convert.rgb.cmyk = function (rgb) {
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const k = Math.min(1 - r, 1 - g, 1 - b);
const c = (1 - r - k) / (1 - k) || 0;
const m = (1 - g - k) / (1 - k) || 0;
const y = (1 - b - k) / (1 - k) || 0;
return [c * 100, m * 100, y * 100, k * 100];
};
function comparativeDistance(x, y) {
/*
See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
*/
return (
((x[0] - y[0]) ** 2) +
((x[1] - y[1]) ** 2) +
((x[2] - y[2]) ** 2)
);
}
convert.rgb.keyword = function (rgb) {
const reversed = reverseKeywords[rgb];
if (reversed) {
return reversed;
}
let currentClosestDistance = Infinity;
let currentClosestKeyword;
for (const keyword of Object.keys(cssKeywords)) {
const value = cssKeywords[keyword];
// Compute comparative distance
const distance = comparativeDistance(rgb, value);
// Check if its less, if so set as closest
if (distance < currentClosestDistance) {
currentClosestDistance = distance;
currentClosestKeyword = keyword;
}
}
return currentClosestKeyword;
};
convert.keyword.rgb = function (keyword) {
return cssKeywords[keyword];
};
convert.rgb.xyz = function (rgb) {
let r = rgb[0] / 255;
let g = rgb[1] / 255;
let b = rgb[2] / 255;
// Assume sRGB
r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92);
g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92);
b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92);
const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
return [x * 100, y * 100, z * 100];
};
convert.rgb.lab = function (rgb) {
const xyz = convert.rgb.xyz(rgb);
let x = xyz[0];
let y = xyz[1];
let z = xyz[2];
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
const l = (116 * y) - 16;
const a = 500 * (x - y);
const b = 200 * (y - z);
return [l, a, b];
};
convert.hsl.rgb = function (hsl) {
const h = hsl[0] / 360;
const s = hsl[1] / 100;
const l = hsl[2] / 100;
let t2;
let t3;
let val;
if (s === 0) {
val = l * 255;
return [val, val, val];
}
if (l < 0.5) {
t2 = l * (1 + s);
} else {
t2 = l + s - l * s;
}
const t1 = 2 * l - t2;
const rgb = [0, 0, 0];
for (let i = 0; i < 3; i++) {
t3 = h + 1 / 3 * -(i - 1);
if (t3 < 0) {
t3++;
}
if (t3 > 1) {
t3--;
}
if (6 * t3 < 1) {
val = t1 + (t2 - t1) * 6 * t3;
} else if (2 * t3 < 1) {
val = t2;
} else if (3 * t3 < 2) {
val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
} else {
val = t1;
}
rgb[i] = val * 255;
}
return rgb;
};
convert.hsl.hsv = function (hsl) {
const h = hsl[0];
let s = hsl[1] / 100;
let l = hsl[2] / 100;
let smin = s;
const lmin = Math.max(l, 0.01);
l *= 2;
s *= (l <= 1) ? l : 2 - l;
smin *= lmin <= 1 ? lmin : 2 - lmin;
const v = (l + s) / 2;
const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
return [h, sv * 100, v * 100];
};
convert.hsv.rgb = function (hsv) {
const h = hsv[0] / 60;
const s = hsv[1] / 100;
let v = hsv[2] / 100;
const hi = Math.floor(h) % 6;
const f = h - Math.floor(h);
const p = 255 * v * (1 - s);
const q = 255 * v * (1 - (s * f));
const t = 255 * v * (1 - (s * (1 - f)));
v *= 255;
switch (hi) {
case 0:
return [v, t, p];
case 1:
return [q, v, p];
case 2:
return [p, v, t];
case 3:
return [p, q, v];
case 4:
return [t, p, v];
case 5:
return [v, p, q];
}
};
convert.hsv.hsl = function (hsv) {
const h = hsv[0];
const s = hsv[1] / 100;
const v = hsv[2] / 100;
const vmin = Math.max(v, 0.01);
let sl;
let l;
l = (2 - s) * v;
const lmin = (2 - s) * vmin;
sl = s * vmin;
sl /= (lmin <= 1) ? lmin : 2 - lmin;
sl = sl || 0;
l /= 2;
return [h, sl * 100, l * 100];
};
// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
convert.hwb.rgb = function (hwb) {
const h = hwb[0] / 360;
let wh = hwb[1] / 100;
let bl = hwb[2] / 100;
const ratio = wh + bl;
let f;
// Wh + bl cant be > 1
if (ratio > 1) {
wh /= ratio;
bl /= ratio;
}
const i = Math.floor(6 * h);
const v = 1 - bl;
f = 6 * h - i;
if ((i & 0x01) !== 0) {
f = 1 - f;
}
const n = wh + f * (v - wh); // Linear interpolation
let r;
let g;
let b;
/* eslint-disable max-statements-per-line,no-multi-spaces */
switch (i) {
default:
case 6:
case 0: r = v; g = n; b = wh; break;
case 1: r = n; g = v; b = wh; break;
case 2: r = wh; g = v; b = n; break;
case 3: r = wh; g = n; b = v; break;
case 4: r = n; g = wh; b = v; break;
case 5: r = v; g = wh; b = n; break;
}
/* eslint-enable max-statements-per-line,no-multi-spaces */
return [r * 255, g * 255, b * 255];
};
convert.cmyk.rgb = function (cmyk) {
const c = cmyk[0] / 100;
const m = cmyk[1] / 100;
const y = cmyk[2] / 100;
const k = cmyk[3] / 100;
const r = 1 - Math.min(1, c * (1 - k) + k);
const g = 1 - Math.min(1, m * (1 - k) + k);
const b = 1 - Math.min(1, y * (1 - k) + k);
return [r * 255, g * 255, b * 255];
};
convert.xyz.rgb = function (xyz) {
const x = xyz[0] / 100;
const y = xyz[1] / 100;
const z = xyz[2] / 100;
let r;
let g;
let b;
r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
// Assume sRGB
r = r > 0.0031308
? ((1.055 * (r ** (1.0 / 2.4))) - 0.055)
: r * 12.92;
g = g > 0.0031308
? ((1.055 * (g ** (1.0 / 2.4))) - 0.055)
: g * 12.92;
b = b > 0.0031308
? ((1.055 * (b ** (1.0 / 2.4))) - 0.055)
: b * 12.92;
r = Math.min(Math.max(0, r), 1);
g = Math.min(Math.max(0, g), 1);
b = Math.min(Math.max(0, b), 1);
return [r * 255, g * 255, b * 255];
};
convert.xyz.lab = function (xyz) {
let x = xyz[0];
let y = xyz[1];
let z = xyz[2];
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
const l = (116 * y) - 16;
const a = 500 * (x - y);
const b = 200 * (y - z);
return [l, a, b];
};
convert.lab.xyz = function (lab) {
const l = lab[0];
const a = lab[1];
const b = lab[2];
let x;
let y;
let z;
y = (l + 16) / 116;
x = a / 500 + y;
z = y - b / 200;
const y2 = y ** 3;
const x2 = x ** 3;
const z2 = z ** 3;
y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
x *= 95.047;
y *= 100;
z *= 108.883;
return [x, y, z];
};
convert.lab.lch = function (lab) {
const l = lab[0];
const a = lab[1];
const b = lab[2];
let h;
const hr = Math.atan2(b, a);
h = hr * 360 / 2 / Math.PI;
if (h < 0) {
h += 360;
}
const c = Math.sqrt(a * a + b * b);
return [l, c, h];
};
convert.lch.lab = function (lch) {
const l = lch[0];
const c = lch[1];
const h = lch[2];
const hr = h / 360 * 2 * Math.PI;
const a = c * Math.cos(hr);
const b = c * Math.sin(hr);
return [l, a, b];
};
convert.rgb.ansi16 = function (args, saturation = null) {
const [r, g, b] = args;
let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
value = Math.round(value / 50);
if (value === 0) {
return 30;
}
let ansi = 30
+ ((Math.round(b / 255) << 2)
| (Math.round(g / 255) << 1)
| Math.round(r / 255));
if (value === 2) {
ansi += 60;
}
return ansi;
};
convert.hsv.ansi16 = function (args) {
// Optimization here; we already know the value and don't need to get
// it converted for us.
return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
};
convert.rgb.ansi256 = function (args) {
const r = args[0];
const g = args[1];
const b = args[2];
// We use the extended greyscale palette here, with the exception of
// black and white. normal palette only has 4 greyscale shades.
if (r === g && g === b) {
if (r < 8) {
return 16;
}
if (r > 248) {
return 231;
}
return Math.round(((r - 8) / 247) * 24) + 232;
}
const ansi = 16
+ (36 * Math.round(r / 255 * 5))
+ (6 * Math.round(g / 255 * 5))
+ Math.round(b / 255 * 5);
return ansi;
};
convert.ansi16.rgb = function (args) {
let color = args % 10;
// Handle greyscale
if (color === 0 || color === 7) {
if (args > 50) {
color += 3.5;
}
color = color / 10.5 * 255;
return [color, color, color];
}
const mult = (~~(args > 50) + 1) * 0.5;
const r = ((color & 1) * mult) * 255;
const g = (((color >> 1) & 1) * mult) * 255;
const b = (((color >> 2) & 1) * mult) * 255;
return [r, g, b];
};
convert.ansi256.rgb = function (args) {
// Handle greyscale
if (args >= 232) {
const c = (args - 232) * 10 + 8;
return [c, c, c];
}
args -= 16;
let rem;
const r = Math.floor(args / 36) / 5 * 255;
const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
const b = (rem % 6) / 5 * 255;
return [r, g, b];
};
convert.rgb.hex = function (args) {
const integer = ((Math.round(args[0]) & 0xFF) << 16)
+ ((Math.round(args[1]) & 0xFF) << 8)
+ (Math.round(args[2]) & 0xFF);
const string = integer.toString(16).toUpperCase();
return '000000'.substring(string.length) + string;
};
convert.hex.rgb = function (args) {
const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
if (!match) {
return [0, 0, 0];
}
let colorString = match[0];
if (match[0].length === 3) {
colorString = colorString.split('').map(char => {
return char + char;
}).join('');
}
const integer = parseInt(colorString, 16);
const r = (integer >> 16) & 0xFF;
const g = (integer >> 8) & 0xFF;
const b = integer & 0xFF;
return [r, g, b];
};
convert.rgb.hcg = function (rgb) {
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const max = Math.max(Math.max(r, g), b);
const min = Math.min(Math.min(r, g), b);
const chroma = (max - min);
let grayscale;
let hue;
if (chroma < 1) {
grayscale = min / (1 - chroma);
} else {
grayscale = 0;
}
if (chroma <= 0) {
hue = 0;
} else
if (max === r) {
hue = ((g - b) / chroma) % 6;
} else
if (max === g) {
hue = 2 + (b - r) / chroma;
} else {
hue = 4 + (r - g) / chroma;
}
hue /= 6;
hue %= 1;
return [hue * 360, chroma * 100, grayscale * 100];
};
convert.hsl.hcg = function (hsl) {
const s = hsl[1] / 100;
const l = hsl[2] / 100;
const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l));
let f = 0;
if (c < 1.0) {
f = (l - 0.5 * c) / (1.0 - c);
}
return [hsl[0], c * 100, f * 100];
};
convert.hsv.hcg = function (hsv) {
const s = hsv[1] / 100;
const v = hsv[2] / 100;
const c = s * v;
let f = 0;
if (c < 1.0) {
f = (v - c) / (1 - c);
}
return [hsv[0], c * 100, f * 100];
};
convert.hcg.rgb = function (hcg) {
const h = hcg[0] / 360;
const c = hcg[1] / 100;
const g = hcg[2] / 100;
if (c === 0.0) {
return [g * 255, g * 255, g * 255];
}
const pure = [0, 0, 0];
const hi = (h % 1) * 6;
const v = hi % 1;
const w = 1 - v;
let mg = 0;
/* eslint-disable max-statements-per-line */
switch (Math.floor(hi)) {
case 0:
pure[0] = 1; pure[1] = v; pure[2] = 0; break;
case 1:
pure[0] = w; pure[1] = 1; pure[2] = 0; break;
case 2:
pure[0] = 0; pure[1] = 1; pure[2] = v; break;
case 3:
pure[0] = 0; pure[1] = w; pure[2] = 1; break;
case 4:
pure[0] = v; pure[1] = 0; pure[2] = 1; break;
default:
pure[0] = 1; pure[1] = 0; pure[2] = w;
}
/* eslint-enable max-statements-per-line */
mg = (1.0 - c) * g;
return [
(c * pure[0] + mg) * 255,
(c * pure[1] + mg) * 255,
(c * pure[2] + mg) * 255
];
};
convert.hcg.hsv = function (hcg) {
const c = hcg[1] / 100;
const g = hcg[2] / 100;
const v = c + g * (1.0 - c);
let f = 0;
if (v > 0.0) {
f = c / v;
}
return [hcg[0], f * 100, v * 100];
};
convert.hcg.hsl = function (hcg) {
const c = hcg[1] / 100;
const g = hcg[2] / 100;
const l = g * (1.0 - c) + 0.5 * c;
let s = 0;
if (l > 0.0 && l < 0.5) {
s = c / (2 * l);
} else
if (l >= 0.5 && l < 1.0) {
s = c / (2 * (1 - l));
}
return [hcg[0], s * 100, l * 100];
};
convert.hcg.hwb = function (hcg) {
const c = hcg[1] / 100;
const g = hcg[2] / 100;
const v = c + g * (1.0 - c);
return [hcg[0], (v - c) * 100, (1 - v) * 100];
};
convert.hwb.hcg = function (hwb) {
const w = hwb[1] / 100;
const b = hwb[2] / 100;
const v = 1 - b;
const c = v - w;
let g = 0;
if (c < 1) {
g = (v - c) / (1 - c);
}
return [hwb[0], c * 100, g * 100];
};
convert.apple.rgb = function (apple) {
return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
};
convert.rgb.apple = function (rgb) {
return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
};
convert.gray.rgb = function (args) {
return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
};
convert.gray.hsl = function (args) {
return [0, 0, args[0]];
};
convert.gray.hsv = convert.gray.hsl;
convert.gray.hwb = function (gray) {
return [0, 100, gray[0]];
};
convert.gray.cmyk = function (gray) {
return [0, 0, 0, gray[0]];
};
convert.gray.lab = function (gray) {
return [gray[0], 0, 0];
};
convert.gray.hex = function (gray) {
const val = Math.round(gray[0] / 100 * 255) & 0xFF;
const integer = (val << 16) + (val << 8) + val;
const string = integer.toString(16).toUpperCase();
return '000000'.substring(string.length) + string;
};
convert.rgb.gray = function (rgb) {
const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
return [val / 255 * 100];
};

View File

@ -0,0 +1,81 @@
import route from './route'
import conversions from './conversions'
const convert = {};
const models = Object.keys(conversions);
function wrapRaw(fn) {
const wrappedFn = function (...args) {
const arg0 = args[0];
if (arg0 === undefined || arg0 === null) {
return arg0;
}
if (arg0.length > 1) {
args = arg0;
}
return fn(args);
};
// Preserve .conversion property if there is one
if ('conversion' in fn) {
wrappedFn.conversion = fn.conversion;
}
return wrappedFn;
}
function wrapRounded(fn) {
const wrappedFn = function (...args) {
const arg0 = args[0];
if (arg0 === undefined || arg0 === null) {
return arg0;
}
if (arg0.length > 1) {
args = arg0;
}
const result = fn(args);
// We're assuming the result is an array here.
// see notice in conversions.js; don't use box types
// in conversion functions.
if (typeof result === 'object') {
for (let len = result.length, i = 0; i < len; i++) {
result[i] = Math.round(result[i]);
}
}
return result;
};
// Preserve .conversion property if there is one
if ('conversion' in fn) {
wrappedFn.conversion = fn.conversion;
}
return wrappedFn;
}
models.forEach(fromModel => {
convert[fromModel] = {};
Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
const routes = route(fromModel);
const routeModels = Object.keys(routes);
routeModels.forEach(toModel => {
const fn = routes[toModel];
convert[fromModel][toModel] = wrapRounded(fn);
convert[fromModel][toModel].raw = wrapRaw(fn);
});
});
export default convert;

View File

@ -0,0 +1,48 @@
{
"name": "color-convert",
"description": "Plain color conversion functions",
"version": "2.0.1",
"author": "Heather Arthur <fayearthur@gmail.com>",
"license": "MIT",
"repository": "Qix-/color-convert",
"scripts": {
"pretest": "xo",
"test": "node test/basic.js"
},
"engines": {
"node": ">=7.0.0"
},
"keywords": [
"color",
"colour",
"convert",
"converter",
"conversion",
"rgb",
"hsl",
"hsv",
"hwb",
"cmyk",
"ansi",
"ansi16"
],
"files": [
"index.js",
"conversions.js",
"route.js"
],
"xo": {
"rules": {
"default-case": 0,
"no-inline-comments": 0,
"operator-linebreak": 0
}
},
"devDependencies": {
"chalk": "^2.4.2",
"xo": "^0.24.0"
},
"dependencies": {
"color-name": "~1.1.4"
}
}

View File

@ -0,0 +1,97 @@
import conversions from './conversions'
/*
This function routes a model to all other models.
all functions that are routed have a property `.conversion` attached
to the returned synthetic function. This property is an array
of strings, each with the steps in between the 'from' and 'to'
color models (inclusive).
conversions that are not possible simply are not included.
*/
function buildGraph() {
const graph = {};
// https://jsperf.com/object-keys-vs-for-in-with-closure/3
const models = Object.keys(conversions);
for (let len = models.length, i = 0; i < len; i++) {
graph[models[i]] = {
// http://jsperf.com/1-vs-infinity
// micro-opt, but this is simple.
distance: -1,
parent: null
};
}
return graph;
}
// https://en.wikipedia.org/wiki/Breadth-first_search
function deriveBFS(fromModel) {
const graph = buildGraph();
const queue = [fromModel]; // Unshift -> queue -> pop
graph[fromModel].distance = 0;
while (queue.length) {
const current = queue.pop();
const adjacents = Object.keys(conversions[current]);
for (let len = adjacents.length, i = 0; i < len; i++) {
const adjacent = adjacents[i];
const node = graph[adjacent];
if (node.distance === -1) {
node.distance = graph[current].distance + 1;
node.parent = current;
queue.unshift(adjacent);
}
}
}
return graph;
}
function link(from, to) {
return function (args) {
return to(from(args));
};
}
function wrapConversion(toModel, graph) {
const path = [graph[toModel].parent, toModel];
let fn = conversions[graph[toModel].parent][toModel];
let cur = graph[toModel].parent;
while (graph[cur].parent) {
path.unshift(graph[cur].parent);
fn = link(conversions[graph[cur].parent][cur], fn);
cur = graph[cur].parent;
}
fn.conversion = path;
return fn;
}
export default function (fromModel) {
const graph = deriveBFS(fromModel);
const conversion = {};
const models = Object.keys(graph);
for (let len = models.length, i = 0; i < len; i++) {
const toModel = models[i];
const node = graph[toModel];
if (node.parent === null) {
// No possible conversion, or this node is the source model.
continue;
}
conversion[toModel] = wrapConversion(toModel, graph);
}
return conversion;
};

View File

@ -0,0 +1,8 @@
The MIT License (MIT)
Copyright (c) 2015 Dmitry Ivanov
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,11 @@
A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors.
[![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/)
```js
var colors = require('color-name');
colors.red //[255,0,0]
```
<a href="LICENSE"><img src="https://upload.wikimedia.org/wikipedia/commons/0/0c/MIT_logo.svg" width="120"/></a>

View File

@ -0,0 +1,152 @@
'use strict'
export default {
"aliceblue": [240, 248, 255],
"antiquewhite": [250, 235, 215],
"aqua": [0, 255, 255],
"aquamarine": [127, 255, 212],
"azure": [240, 255, 255],
"beige": [245, 245, 220],
"bisque": [255, 228, 196],
"black": [0, 0, 0],
"blanchedalmond": [255, 235, 205],
"blue": [0, 0, 255],
"blueviolet": [138, 43, 226],
"brown": [165, 42, 42],
"burlywood": [222, 184, 135],
"cadetblue": [95, 158, 160],
"chartreuse": [127, 255, 0],
"chocolate": [210, 105, 30],
"coral": [255, 127, 80],
"cornflowerblue": [100, 149, 237],
"cornsilk": [255, 248, 220],
"crimson": [220, 20, 60],
"cyan": [0, 255, 255],
"darkblue": [0, 0, 139],
"darkcyan": [0, 139, 139],
"darkgoldenrod": [184, 134, 11],
"darkgray": [169, 169, 169],
"darkgreen": [0, 100, 0],
"darkgrey": [169, 169, 169],
"darkkhaki": [189, 183, 107],
"darkmagenta": [139, 0, 139],
"darkolivegreen": [85, 107, 47],
"darkorange": [255, 140, 0],
"darkorchid": [153, 50, 204],
"darkred": [139, 0, 0],
"darksalmon": [233, 150, 122],
"darkseagreen": [143, 188, 143],
"darkslateblue": [72, 61, 139],
"darkslategray": [47, 79, 79],
"darkslategrey": [47, 79, 79],
"darkturquoise": [0, 206, 209],
"darkviolet": [148, 0, 211],
"deeppink": [255, 20, 147],
"deepskyblue": [0, 191, 255],
"dimgray": [105, 105, 105],
"dimgrey": [105, 105, 105],
"dodgerblue": [30, 144, 255],
"firebrick": [178, 34, 34],
"floralwhite": [255, 250, 240],
"forestgreen": [34, 139, 34],
"fuchsia": [255, 0, 255],
"gainsboro": [220, 220, 220],
"ghostwhite": [248, 248, 255],
"gold": [255, 215, 0],
"goldenrod": [218, 165, 32],
"gray": [128, 128, 128],
"green": [0, 128, 0],
"greenyellow": [173, 255, 47],
"grey": [128, 128, 128],
"honeydew": [240, 255, 240],
"hotpink": [255, 105, 180],
"indianred": [205, 92, 92],
"indigo": [75, 0, 130],
"ivory": [255, 255, 240],
"khaki": [240, 230, 140],
"lavender": [230, 230, 250],
"lavenderblush": [255, 240, 245],
"lawngreen": [124, 252, 0],
"lemonchiffon": [255, 250, 205],
"lightblue": [173, 216, 230],
"lightcoral": [240, 128, 128],
"lightcyan": [224, 255, 255],
"lightgoldenrodyellow": [250, 250, 210],
"lightgray": [211, 211, 211],
"lightgreen": [144, 238, 144],
"lightgrey": [211, 211, 211],
"lightpink": [255, 182, 193],
"lightsalmon": [255, 160, 122],
"lightseagreen": [32, 178, 170],
"lightskyblue": [135, 206, 250],
"lightslategray": [119, 136, 153],
"lightslategrey": [119, 136, 153],
"lightsteelblue": [176, 196, 222],
"lightyellow": [255, 255, 224],
"lime": [0, 255, 0],
"limegreen": [50, 205, 50],
"linen": [250, 240, 230],
"magenta": [255, 0, 255],
"maroon": [128, 0, 0],
"mediumaquamarine": [102, 205, 170],
"mediumblue": [0, 0, 205],
"mediumorchid": [186, 85, 211],
"mediumpurple": [147, 112, 219],
"mediumseagreen": [60, 179, 113],
"mediumslateblue": [123, 104, 238],
"mediumspringgreen": [0, 250, 154],
"mediumturquoise": [72, 209, 204],
"mediumvioletred": [199, 21, 133],
"midnightblue": [25, 25, 112],
"mintcream": [245, 255, 250],
"mistyrose": [255, 228, 225],
"moccasin": [255, 228, 181],
"navajowhite": [255, 222, 173],
"navy": [0, 0, 128],
"oldlace": [253, 245, 230],
"olive": [128, 128, 0],
"olivedrab": [107, 142, 35],
"orange": [255, 165, 0],
"orangered": [255, 69, 0],
"orchid": [218, 112, 214],
"palegoldenrod": [238, 232, 170],
"palegreen": [152, 251, 152],
"paleturquoise": [175, 238, 238],
"palevioletred": [219, 112, 147],
"papayawhip": [255, 239, 213],
"peachpuff": [255, 218, 185],
"peru": [205, 133, 63],
"pink": [255, 192, 203],
"plum": [221, 160, 221],
"powderblue": [176, 224, 230],
"purple": [128, 0, 128],
"rebeccapurple": [102, 51, 153],
"red": [255, 0, 0],
"rosybrown": [188, 143, 143],
"royalblue": [65, 105, 225],
"saddlebrown": [139, 69, 19],
"salmon": [250, 128, 114],
"sandybrown": [244, 164, 96],
"seagreen": [46, 139, 87],
"seashell": [255, 245, 238],
"sienna": [160, 82, 45],
"silver": [192, 192, 192],
"skyblue": [135, 206, 235],
"slateblue": [106, 90, 205],
"slategray": [112, 128, 144],
"slategrey": [112, 128, 144],
"snow": [255, 250, 250],
"springgreen": [0, 255, 127],
"steelblue": [70, 130, 180],
"tan": [210, 180, 140],
"teal": [0, 128, 128],
"thistle": [216, 191, 216],
"tomato": [255, 99, 71],
"turquoise": [64, 224, 208],
"violet": [238, 130, 238],
"wheat": [245, 222, 179],
"white": [255, 255, 255],
"whitesmoke": [245, 245, 245],
"yellow": [255, 255, 0],
"yellowgreen": [154, 205, 50]
};

View File

@ -0,0 +1,28 @@
{
"name": "color-name",
"version": "1.1.4",
"description": "A list of color names and its values",
"main": "index.js",
"files": [
"index.js"
],
"scripts": {
"test": "node test.js"
},
"repository": {
"type": "git",
"url": "git@github.com:colorjs/color-name.git"
},
"keywords": [
"color-name",
"color",
"color-keyword",
"keyword"
],
"author": "DY <dfcreative@gmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/colorjs/color-name/issues"
},
"homepage": "https://github.com/colorjs/color-name"
}

View File

@ -0,0 +1,21 @@
Copyright (c) 2011 Heather Arthur <fayearthur@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,62 @@
# color-string
> library for parsing and generating CSS color strings.
## Install
With [npm](http://npmjs.org/):
```console
$ npm install color-string
```
## Usage
### Parsing
```js
colorString.get('#FFF') // {model: 'rgb', value: [255, 255, 255, 1]}
colorString.get('#FFFA') // {model: 'rgb', value: [255, 255, 255, 0.67]}
colorString.get('#FFFFFFAA') // {model: 'rgb', value: [255, 255, 255, 0.67]}
colorString.get('hsl(360, 100%, 50%)') // {model: 'hsl', value: [0, 100, 50, 1]}
colorString.get('hsl(360 100% 50%)') // {model: 'hsl', value: [0, 100, 50, 1]}
colorString.get('hwb(60, 3%, 60%)') // {model: 'hwb', value: [60, 3, 60, 1]}
colorString.get.rgb('#FFF') // [255, 255, 255, 1]
colorString.get.rgb('blue') // [0, 0, 255, 1]
colorString.get.rgb('rgba(200, 60, 60, 0.3)') // [200, 60, 60, 0.3]
colorString.get.rgb('rgba(200 60 60 / 0.3)') // [200, 60, 60, 0.3]
colorString.get.rgb('rgba(200 60 60 / 30%)') // [200, 60, 60, 0.3]
colorString.get.rgb('rgb(200, 200, 200)') // [200, 200, 200, 1]
colorString.get.rgb('rgb(200 200 200)') // [200, 200, 200, 1]
colorString.get.hsl('hsl(360, 100%, 50%)') // [0, 100, 50, 1]
colorString.get.hsl('hsl(360 100% 50%)') // [0, 100, 50, 1]
colorString.get.hsl('hsla(360, 60%, 50%, 0.4)') // [0, 60, 50, 0.4]
colorString.get.hsl('hsl(360 60% 50% / 0.4)') // [0, 60, 50, 0.4]
colorString.get.hwb('hwb(60, 3%, 60%)') // [60, 3, 60, 1]
colorString.get.hwb('hwb(60, 3%, 60%, 0.6)') // [60, 3, 60, 0.6]
colorString.get.rgb('invalid color string') // null
```
### Generation
```js
colorString.to.hex([255, 255, 255]) // "#FFFFFF"
colorString.to.hex([0, 0, 255, 0.4]) // "#0000FF66"
colorString.to.hex([0, 0, 255], 0.4) // "#0000FF66"
colorString.to.rgb([255, 255, 255]) // "rgb(255, 255, 255)"
colorString.to.rgb([0, 0, 255, 0.4]) // "rgba(0, 0, 255, 0.4)"
colorString.to.rgb([0, 0, 255], 0.4) // "rgba(0, 0, 255, 0.4)"
colorString.to.rgb.percent([0, 0, 255]) // "rgb(0%, 0%, 100%)"
colorString.to.keyword([255, 255, 0]) // "yellow"
colorString.to.hsl([360, 100, 100]) // "hsl(360, 100%, 100%)"
colorString.to.hwb([50, 3, 15]) // "hwb(50, 3%, 15%)"
// all functions also support swizzling
colorString.to.rgb(0, [0, 255], 0.4) // "rgba(0, 0, 255, 0.4)"
colorString.to.rgb([0, 0], [255], 0.4) // "rgba(0, 0, 255, 0.4)"
colorString.to.rgb([0], 0, [255, 0.4]) // "rgba(0, 0, 255, 0.4)"
```

View File

@ -0,0 +1,244 @@
/* MIT license */
import colorNames from '../color-name'
import swizzle from '../simple-swizzle'
var hasOwnProperty = Object.hasOwnProperty;
var reverseNames = Object.create(null);
// create a list of reverse color names
for (var name in colorNames) {
if (hasOwnProperty.call(colorNames, name)) {
reverseNames[colorNames[name]] = name;
}
}
var cs = {
to: {},
get: {}
};
cs.get = function (string) {
var prefix = string.substring(0, 3).toLowerCase();
var val;
var model;
switch (prefix) {
case 'hsl':
val = cs.get.hsl(string);
model = 'hsl';
break;
case 'hwb':
val = cs.get.hwb(string);
model = 'hwb';
break;
default:
val = cs.get.rgb(string);
model = 'rgb';
break;
}
if (!val) {
return null;
}
return {model: model, value: val};
};
cs.get.rgb = function (string) {
if (!string) {
return null;
}
var abbr = /^#([a-f0-9]{3,4})$/i;
var hex = /^#([a-f0-9]{6})([a-f0-9]{2})?$/i;
var rgba = /^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/;
var per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/;
var keyword = /^(\w+)$/;
var rgb = [0, 0, 0, 1];
var match;
var i;
var hexAlpha;
if (match = string.match(hex)) {
hexAlpha = match[2];
match = match[1];
for (i = 0; i < 3; i++) {
// https://jsperf.com/slice-vs-substr-vs-substring-methods-long-string/19
var i2 = i * 2;
rgb[i] = parseInt(match.slice(i2, i2 + 2), 16);
}
if (hexAlpha) {
rgb[3] = parseInt(hexAlpha, 16) / 255;
}
} else if (match = string.match(abbr)) {
match = match[1];
hexAlpha = match[3];
for (i = 0; i < 3; i++) {
rgb[i] = parseInt(match[i] + match[i], 16);
}
if (hexAlpha) {
rgb[3] = parseInt(hexAlpha + hexAlpha, 16) / 255;
}
} else if (match = string.match(rgba)) {
for (i = 0; i < 3; i++) {
rgb[i] = parseInt(match[i + 1], 0);
}
if (match[4]) {
if (match[5]) {
rgb[3] = parseFloat(match[4]) * 0.01;
} else {
rgb[3] = parseFloat(match[4]);
}
}
} else if (match = string.match(per)) {
for (i = 0; i < 3; i++) {
rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
}
if (match[4]) {
if (match[5]) {
rgb[3] = parseFloat(match[4]) * 0.01;
} else {
rgb[3] = parseFloat(match[4]);
}
}
} else if (match = string.match(keyword)) {
if (match[1] === 'transparent') {
return [0, 0, 0, 0];
}
if (!hasOwnProperty.call(colorNames, match[1])) {
return null;
}
rgb = colorNames[match[1]];
rgb[3] = 1;
return rgb;
} else {
return null;
}
for (i = 0; i < 3; i++) {
rgb[i] = clamp(rgb[i], 0, 255);
}
rgb[3] = clamp(rgb[3], 0, 1);
return rgb;
};
cs.get.hsl = function (string) {
if (!string) {
return null;
}
var hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/;
var match = string.match(hsl);
if (match) {
var alpha = parseFloat(match[4]);
var h = ((parseFloat(match[1]) % 360) + 360) % 360;
var s = clamp(parseFloat(match[2]), 0, 100);
var l = clamp(parseFloat(match[3]), 0, 100);
var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1);
return [h, s, l, a];
}
return null;
};
cs.get.hwb = function (string) {
if (!string) {
return null;
}
var hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/;
var match = string.match(hwb);
if (match) {
var alpha = parseFloat(match[4]);
var h = ((parseFloat(match[1]) % 360) + 360) % 360;
var w = clamp(parseFloat(match[2]), 0, 100);
var b = clamp(parseFloat(match[3]), 0, 100);
var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1);
return [h, w, b, a];
}
return null;
};
cs.to.hex = function () {
var rgba = swizzle(arguments);
return (
'#' +
hexDouble(rgba[0]) +
hexDouble(rgba[1]) +
hexDouble(rgba[2]) +
(rgba[3] < 1
? (hexDouble(Math.round(rgba[3] * 255)))
: '')
);
};
cs.to.rgb = function () {
var rgba = swizzle(arguments);
return rgba.length < 4 || rgba[3] === 1
? 'rgb(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ')'
: 'rgba(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ', ' + rgba[3] + ')';
};
cs.to.rgb.percent = function () {
var rgba = swizzle(arguments);
var r = Math.round(rgba[0] / 255 * 100);
var g = Math.round(rgba[1] / 255 * 100);
var b = Math.round(rgba[2] / 255 * 100);
return rgba.length < 4 || rgba[3] === 1
? 'rgb(' + r + '%, ' + g + '%, ' + b + '%)'
: 'rgba(' + r + '%, ' + g + '%, ' + b + '%, ' + rgba[3] + ')';
};
cs.to.hsl = function () {
var hsla = swizzle(arguments);
return hsla.length < 4 || hsla[3] === 1
? 'hsl(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%)'
: 'hsla(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%, ' + hsla[3] + ')';
};
// hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
// (hwb have alpha optional & 1 is default value)
cs.to.hwb = function () {
var hwba = swizzle(arguments);
var a = '';
if (hwba.length >= 4 && hwba[3] !== 1) {
a = ', ' + hwba[3];
}
return 'hwb(' + hwba[0] + ', ' + hwba[1] + '%, ' + hwba[2] + '%' + a + ')';
};
cs.to.keyword = function (rgb) {
return reverseNames[rgb.slice(0, 3)];
};
// helpers
function clamp(num, min, max) {
return Math.min(Math.max(min, num), max);
}
function hexDouble(num) {
var str = Math.round(num).toString(16).toUpperCase();
return (str.length < 2) ? '0' + str : str;
}
export default cs;

View File

@ -0,0 +1,39 @@
{
"name": "color-string",
"description": "Parser and generator for CSS color strings",
"version": "1.9.1",
"author": "Heather Arthur <fayearthur@gmail.com>",
"contributors": [
"Maxime Thirouin",
"Dyma Ywanov <dfcreative@gmail.com>",
"Josh Junon"
],
"repository": "Qix-/color-string",
"scripts": {
"pretest": "xo",
"test": "node test/basic.js"
},
"license": "MIT",
"files": [
"index.js"
],
"xo": {
"rules": {
"no-cond-assign": 0,
"operator-linebreak": 0
}
},
"dependencies": {
"color-name": "^1.0.0",
"simple-swizzle": "^0.2.2"
},
"devDependencies": {
"xo": "^0.12.1"
},
"keywords": [
"color",
"colour",
"rgb",
"css"
]
}

View File

@ -0,0 +1,496 @@
import colorString from './color-string'
import convert from './color-convert'
const skippedModels = [
// To be honest, I don't really feel like keyword belongs in color convert, but eh.
'keyword',
// Gray conflicts with some method names, and has its own method defined.
'gray',
// Shouldn't really be in color-convert either...
'hex',
];
const hashedModelKeys = {};
for (const model of Object.keys(convert)) {
hashedModelKeys[[...convert[model].labels].sort().join('')] = model;
}
const limiters = {};
function Color(object, model) {
if (!(this instanceof Color)) {
return new Color(object, model);
}
if (model && model in skippedModels) {
model = null;
}
if (model && !(model in convert)) {
throw new Error('Unknown model: ' + model);
}
let i;
let channels;
if (object == null) { // eslint-disable-line no-eq-null,eqeqeq
this.model = 'rgb';
this.color = [0, 0, 0];
this.valpha = 1;
} else if (object instanceof Color) {
this.model = object.model;
this.color = [...object.color];
this.valpha = object.valpha;
} else if (typeof object === 'string') {
const result = colorString.get(object);
if (result === null) {
throw new Error('Unable to parse color from string: ' + object);
}
this.model = result.model;
channels = convert[this.model].channels;
this.color = result.value.slice(0, channels);
this.valpha = typeof result.value[channels] === 'number' ? result.value[channels] : 1;
} else if (object.length > 0) {
this.model = model || 'rgb';
channels = convert[this.model].channels;
const newArray = Array.prototype.slice.call(object, 0, channels);
this.color = zeroArray(newArray, channels);
this.valpha = typeof object[channels] === 'number' ? object[channels] : 1;
} else if (typeof object === 'number') {
// This is always RGB - can be converted later on.
this.model = 'rgb';
this.color = [
(object >> 16) & 0xFF,
(object >> 8) & 0xFF,
object & 0xFF,
];
this.valpha = 1;
} else {
this.valpha = 1;
const keys = Object.keys(object);
if ('alpha' in object) {
keys.splice(keys.indexOf('alpha'), 1);
this.valpha = typeof object.alpha === 'number' ? object.alpha : 0;
}
const hashedKeys = keys.sort().join('');
if (!(hashedKeys in hashedModelKeys)) {
throw new Error('Unable to parse color from object: ' + JSON.stringify(object));
}
this.model = hashedModelKeys[hashedKeys];
const {labels} = convert[this.model];
const color = [];
for (i = 0; i < labels.length; i++) {
color.push(object[labels[i]]);
}
this.color = zeroArray(color);
}
// Perform limitations (clamping, etc.)
if (limiters[this.model]) {
channels = convert[this.model].channels;
for (i = 0; i < channels; i++) {
const limit = limiters[this.model][i];
if (limit) {
this.color[i] = limit(this.color[i]);
}
}
}
this.valpha = Math.max(0, Math.min(1, this.valpha));
if (Object.freeze) {
Object.freeze(this);
}
}
Color.prototype = {
toString() {
return this.string();
},
toJSON() {
return this[this.model]();
},
string(places) {
let self = this.model in colorString.to ? this : this.rgb();
self = self.round(typeof places === 'number' ? places : 1);
const args = self.valpha === 1 ? self.color : [...self.color, this.valpha];
return colorString.to[self.model](args);
},
percentString(places) {
const self = this.rgb().round(typeof places === 'number' ? places : 1);
const args = self.valpha === 1 ? self.color : [...self.color, this.valpha];
return colorString.to.rgb.percent(args);
},
array() {
return this.valpha === 1 ? [...this.color] : [...this.color, this.valpha];
},
object() {
const result = {};
const {channels} = convert[this.model];
const {labels} = convert[this.model];
for (let i = 0; i < channels; i++) {
result[labels[i]] = this.color[i];
}
if (this.valpha !== 1) {
result.alpha = this.valpha;
}
return result;
},
unitArray() {
const rgb = this.rgb().color;
rgb[0] /= 255;
rgb[1] /= 255;
rgb[2] /= 255;
if (this.valpha !== 1) {
rgb.push(this.valpha);
}
return rgb;
},
unitObject() {
const rgb = this.rgb().object();
rgb.r /= 255;
rgb.g /= 255;
rgb.b /= 255;
if (this.valpha !== 1) {
rgb.alpha = this.valpha;
}
return rgb;
},
round(places) {
places = Math.max(places || 0, 0);
return new Color([...this.color.map(roundToPlace(places)), this.valpha], this.model);
},
alpha(value) {
if (value !== undefined) {
return new Color([...this.color, Math.max(0, Math.min(1, value))], this.model);
}
return this.valpha;
},
// Rgb
red: getset('rgb', 0, maxfn(255)),
green: getset('rgb', 1, maxfn(255)),
blue: getset('rgb', 2, maxfn(255)),
hue: getset(['hsl', 'hsv', 'hsl', 'hwb', 'hcg'], 0, value => ((value % 360) + 360) % 360),
saturationl: getset('hsl', 1, maxfn(100)),
lightness: getset('hsl', 2, maxfn(100)),
saturationv: getset('hsv', 1, maxfn(100)),
value: getset('hsv', 2, maxfn(100)),
chroma: getset('hcg', 1, maxfn(100)),
gray: getset('hcg', 2, maxfn(100)),
white: getset('hwb', 1, maxfn(100)),
wblack: getset('hwb', 2, maxfn(100)),
cyan: getset('cmyk', 0, maxfn(100)),
magenta: getset('cmyk', 1, maxfn(100)),
yellow: getset('cmyk', 2, maxfn(100)),
black: getset('cmyk', 3, maxfn(100)),
x: getset('xyz', 0, maxfn(95.047)),
y: getset('xyz', 1, maxfn(100)),
z: getset('xyz', 2, maxfn(108.833)),
l: getset('lab', 0, maxfn(100)),
a: getset('lab', 1),
b: getset('lab', 2),
keyword(value) {
if (value !== undefined) {
return new Color(value);
}
return convert[this.model].keyword(this.color);
},
hex(value) {
if (value !== undefined) {
return new Color(value);
}
return colorString.to.hex(this.rgb().round().color);
},
hexa(value) {
if (value !== undefined) {
return new Color(value);
}
const rgbArray = this.rgb().round().color;
let alphaHex = Math.round(this.valpha * 255).toString(16).toUpperCase();
if (alphaHex.length === 1) {
alphaHex = '0' + alphaHex;
}
return colorString.to.hex(rgbArray) + alphaHex;
},
rgbNumber() {
const rgb = this.rgb().color;
return ((rgb[0] & 0xFF) << 16) | ((rgb[1] & 0xFF) << 8) | (rgb[2] & 0xFF);
},
luminosity() {
// http://www.w3.org/TR/WCAG20/#relativeluminancedef
const rgb = this.rgb().color;
const lum = [];
for (const [i, element] of rgb.entries()) {
const chan = element / 255;
lum[i] = (chan <= 0.04045) ? chan / 12.92 : ((chan + 0.055) / 1.055) ** 2.4;
}
return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
},
contrast(color2) {
// http://www.w3.org/TR/WCAG20/#contrast-ratiodef
const lum1 = this.luminosity();
const lum2 = color2.luminosity();
if (lum1 > lum2) {
return (lum1 + 0.05) / (lum2 + 0.05);
}
return (lum2 + 0.05) / (lum1 + 0.05);
},
level(color2) {
// https://www.w3.org/TR/WCAG/#contrast-enhanced
const contrastRatio = this.contrast(color2);
if (contrastRatio >= 7) {
return 'AAA';
}
return (contrastRatio >= 4.5) ? 'AA' : '';
},
isDark() {
// YIQ equation from http://24ways.org/2010/calculating-color-contrast
const rgb = this.rgb().color;
const yiq = (rgb[0] * 2126 + rgb[1] * 7152 + rgb[2] * 722) / 10000;
return yiq < 128;
},
isLight() {
return !this.isDark();
},
negate() {
const rgb = this.rgb();
for (let i = 0; i < 3; i++) {
rgb.color[i] = 255 - rgb.color[i];
}
return rgb;
},
lighten(ratio) {
const hsl = this.hsl();
hsl.color[2] += hsl.color[2] * ratio;
return hsl;
},
darken(ratio) {
const hsl = this.hsl();
hsl.color[2] -= hsl.color[2] * ratio;
return hsl;
},
saturate(ratio) {
const hsl = this.hsl();
hsl.color[1] += hsl.color[1] * ratio;
return hsl;
},
desaturate(ratio) {
const hsl = this.hsl();
hsl.color[1] -= hsl.color[1] * ratio;
return hsl;
},
whiten(ratio) {
const hwb = this.hwb();
hwb.color[1] += hwb.color[1] * ratio;
return hwb;
},
blacken(ratio) {
const hwb = this.hwb();
hwb.color[2] += hwb.color[2] * ratio;
return hwb;
},
grayscale() {
// http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
const rgb = this.rgb().color;
const value = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
return Color.rgb(value, value, value);
},
fade(ratio) {
return this.alpha(this.valpha - (this.valpha * ratio));
},
opaquer(ratio) {
return this.alpha(this.valpha + (this.valpha * ratio));
},
rotate(degrees) {
const hsl = this.hsl();
let hue = hsl.color[0];
hue = (hue + degrees) % 360;
hue = hue < 0 ? 360 + hue : hue;
hsl.color[0] = hue;
return hsl;
},
mix(mixinColor, weight) {
// Ported from sass implementation in C
// https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
if (!mixinColor || !mixinColor.rgb) {
throw new Error('Argument to "mix" was not a Color instance, but rather an instance of ' + typeof mixinColor);
}
const color1 = mixinColor.rgb();
const color2 = this.rgb();
const p = weight === undefined ? 0.5 : weight;
const w = 2 * p - 1;
const a = color1.alpha() - color2.alpha();
const w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2;
const w2 = 1 - w1;
return Color.rgb(
w1 * color1.red() + w2 * color2.red(),
w1 * color1.green() + w2 * color2.green(),
w1 * color1.blue() + w2 * color2.blue(),
color1.alpha() * p + color2.alpha() * (1 - p));
},
};
// Model conversion methods and static constructors
for (const model of Object.keys(convert)) {
if (skippedModels.includes(model)) {
continue;
}
const {channels} = convert[model];
// Conversion methods
Color.prototype[model] = function (...args) {
if (this.model === model) {
return new Color(this);
}
if (args.length > 0) {
return new Color(args, model);
}
return new Color([...assertArray(convert[this.model][model].raw(this.color)), this.valpha], model);
};
// 'static' construction methods
Color[model] = function (...args) {
let color = args[0];
if (typeof color === 'number') {
color = zeroArray(args, channels);
}
return new Color(color, model);
};
}
function roundTo(number, places) {
return Number(number.toFixed(places));
}
function roundToPlace(places) {
return function (number) {
return roundTo(number, places);
};
}
function getset(model, channel, modifier) {
model = Array.isArray(model) ? model : [model];
for (const m of model) {
(limiters[m] || (limiters[m] = []))[channel] = modifier;
}
model = model[0];
return function (value) {
let result;
if (value !== undefined) {
if (modifier) {
value = modifier(value);
}
result = this[model]();
result.color[channel] = value;
return result;
}
result = this[model]().color[channel];
if (modifier) {
result = modifier(result);
}
return result;
};
}
function maxfn(max) {
return function (v) {
return Math.max(0, Math.min(max, v));
};
}
function assertArray(value) {
return Array.isArray(value) ? value : [value];
}
function zeroArray(array, length) {
for (let i = 0; i < length; i++) {
if (typeof array[i] !== 'number') {
array[i] = 0;
}
}
return array;
}
export default Color;

View File

@ -0,0 +1,158 @@
import Color from './color';
/**
* 转换颜色格式
* @param {Object} params - 参数对象
* @param {string} color - 输入的颜色默认为 '#fff'
* @param {string} format - 需要转换的格式支持 'rgb', 'hex', 'hsl', 'hsv', 'hwb'
* @param {string} type - 转换后的类型支持 'string', 'object', 'array', 'round'
* @returns {string|Object|Array} 转换后的颜色表示
*/
function convertFormat(color = '#fff', format = 'rgb', type = 'string') {
let colorObj = Color(color);
// 如果格式存在
if (colorObj[format]) {
// hex 无法直接转换为 除string类型外的任何类型
// 所以转为rgb 后 获取其他类型
if(format == 'hex' && type != 'string') format = 'rgb';
// 类型名称
let typeName = '';
switch (type) {
case 'string':
typeName = 'toString';
break;
case 'object':
typeName = 'object';
break;
case 'array':
typeName = 'array';
break;
case 'round':
typeName = 'round';
break;
default:
throw Error('Unsupported target type:' + type)
}
return colorObj[format]()[typeName]();
} else {
throw Error('Unsupported target format: ' + format);
}
}
/**
* 计算两个颜色之间的渐变值
* @param {string} startColor - 开始的颜色默认为黑色
* @param {string} endColor - 结束的颜色默认为白色
* @param {number} step - 渐变的步数默认为10
* @returns {Array<string>} 两个颜色之间的渐变颜色数组
*/
function gradient(startColor = 'rgb(0, 0, 0)', endColor = 'rgb(255, 255, 255)', step = 10) {
const startRGB = convertFormat(startColor, 'rgb', 'array') // 转换为rgb数组模式
const startR = startRGB[0]
const startG = startRGB[1]
const startB = startRGB[2]
const endRGB = convertFormat(endColor, 'rgb', 'array')
const endR = endRGB[0]
const endG = endRGB[1]
const endB = endRGB[2]
const sR = (endR - startR) / step // 总差值
const sG = (endG - startG) / step
const sB = (endB - startB) / step
const colorArr = []
for (let i = 0; i < step; i++) {
// 计算每一步的hex值
let hex = convertFormat(`rgb(${Math.round((sR * i + startR))},${Math.round((sG * i + startG))},${Math.round((sB
* i + startB))})`, 'hex')
// 确保第一个颜色值为startColor的值
if (i === 0) hex = convertFormat(startColor, 'hex')
// 确保最后一个颜色值为endColor的值
if (i === step - 1) hex = convertFormat(endColor, 'hex')
colorArr.push(hex)
}
return colorArr
}
export default {
/**
* 格式转换
*/
convertFormat,
/**
* 计算两个颜色之间的渐变值
*/
gradient,
/**
* 增加颜色的亮度
* @param {string} color - 输入的颜色
* @param {number} value - 增加的亮度值0-1
* @returns {string} 调整后的颜色
*/
lighten: (color, value, format = 'rgb', type = 'string') => convertFormat(Color(color).lighten(value), format, type),
/**
* 减少颜色的亮度
* @param {string} color - 输入的颜色
* @param {number} value - 减少的亮度值0-1
* @returns {string} 调整后的颜色
*/
darken: (color, value, format = 'rgb', type = 'string') => convertFormat(Color(color).darken(value), format, type),
/**
* 增加颜色的饱和度
* @param {string} color - 输入的颜色
* @param {number} value - 增加的饱和度值0-1
* @returns {string} 调整后的颜色
*/
saturate: (color, value, format = 'rgb', type = 'string') => convertFormat(Color(color).saturate(value), format, type),
/**
* 减少颜色的饱和度
* @param {string} color - 输入的颜色
* @param {number} value - 减少的饱和度值0-1
* @returns {string} 调整后的颜色
*/
desaturate: (color, value, format = 'rgb', type = 'string') => convertFormat(Color(color).desaturate(value), format, type),
/**
* 旋转颜色的色相
* @param {string} color - 输入的颜色
* @param {number} degrees - 旋转的度数
* @returns {string} 调整后的颜色
*/
rotate: (color, degrees, format = 'rgb', type = 'string') => convertFormat(Color(color).rotate(degrees), format, type),
/**
* 调整颜色的透明度
* @param {string} color - 输入的颜色
* @param {number} value - 透明度值0-1其中 1 是不透明
* @returns {string} 调整后的颜色
*/
adjustAlpha: (color, value, format = 'rgb', type = 'string') => convertFormat(Color(color).alpha(value), format, type),
/**
* 获取颜色的亮度
* @param {string} color - 输入的颜色
* @returns {number} 颜色的亮度值0-1
*/
luminosity: (color, format) => Color(color).luminosity(),
/**
* 判断颜色是否为暗色
* @param {string} color - 输入的颜色
* @returns {boolean} 如果是暗色则返回 true否则返回 false
*/
isDark: (color, format) => Color(color).isDark(),
/**
* 判断颜色是否为亮色
* @param {string} color - 输入的颜色
* @returns {boolean} 如果是亮色则返回 true否则返回 false
*/
isLight: (color, format) => Color(color).isLight()
};

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 JD Ballard
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,16 @@
# node-is-arrayish [![Travis-CI.org Build Status](https://img.shields.io/travis/Qix-/node-is-arrayish.svg?style=flat-square)](https://travis-ci.org/Qix-/node-is-arrayish) [![Coveralls.io Coverage Rating](https://img.shields.io/coveralls/Qix-/node-is-arrayish.svg?style=flat-square)](https://coveralls.io/r/Qix-/node-is-arrayish)
> Determines if an object can be used like an Array
## Example
```javascript
var isArrayish = require('is-arrayish');
isArrayish([]); // true
isArrayish({__proto__: []}); // true
isArrayish({}); // false
isArrayish({length:10}); // false
```
## License
Licensed under the [MIT License](http://opensource.org/licenses/MIT).
You can find a copy of it in [LICENSE](LICENSE).

View File

@ -0,0 +1,9 @@
export default function isArrayish(obj) {
if (!obj || typeof obj === 'string') {
return false;
}
return obj instanceof Array || Array.isArray(obj) ||
(obj.length >= 0 && (obj.splice instanceof Function ||
(Object.getOwnPropertyDescriptor(obj, (obj.length - 1)) && obj.constructor.name !== 'String')));
};

View File

@ -0,0 +1,45 @@
{
"name": "is-arrayish",
"description": "Determines if an object can be used as an array",
"version": "0.3.2",
"author": "Qix (http://github.com/qix-)",
"keywords": [
"is",
"array",
"duck",
"type",
"arrayish",
"similar",
"proto",
"prototype",
"type"
],
"license": "MIT",
"scripts": {
"test": "mocha --require coffeescript/register ./test/**/*.coffee",
"lint": "zeit-eslint --ext .jsx,.js .",
"lint-staged": "git diff --diff-filter=ACMRT --cached --name-only '*.js' '*.jsx' | xargs zeit-eslint"
},
"repository": {
"type": "git",
"url": "https://github.com/qix-/node-is-arrayish.git"
},
"devDependencies": {
"@zeit/eslint-config-node": "^0.3.0",
"@zeit/git-hooks": "^0.1.4",
"coffeescript": "^2.3.1",
"coveralls": "^3.0.1",
"eslint": "^4.19.1",
"istanbul": "^0.4.5",
"mocha": "^5.2.0",
"should": "^13.2.1"
},
"eslintConfig": {
"extends": [
"@zeit/eslint-config-node"
]
},
"git": {
"pre-commit": "lint-staged"
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 Josh Junon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,39 @@
# simple-swizzle [![Travis-CI.org Build Status](https://img.shields.io/travis/Qix-/node-simple-swizzle.svg?style=flat-square)](https://travis-ci.org/Qix-/node-simple-swizzle) [![Coveralls.io Coverage Rating](https://img.shields.io/coveralls/Qix-/node-simple-swizzle.svg?style=flat-square)](https://coveralls.io/r/Qix-/node-simple-swizzle)
> [Swizzle](https://en.wikipedia.org/wiki/Swizzling_(computer_graphics)) your function arguments; pass in mixed arrays/values and get a clean array
## Usage
```js
var swizzle = require('simple-swizzle');
function myFunc() {
var args = swizzle(arguments);
// ...
return args;
}
myFunc(1, [2, 3], 4); // [1, 2, 3, 4]
myFunc(1, 2, 3, 4); // [1, 2, 3, 4]
myFunc([1, 2, 3, 4]); // [1, 2, 3, 4]
```
Functions can also be wrapped to automatically swizzle arguments and be passed
the resulting array.
```js
var swizzle = require('simple-swizzle');
var swizzledFn = swizzle.wrap(function (args) {
// ...
return args;
});
swizzledFn(1, [2, 3], 4); // [1, 2, 3, 4]
swizzledFn(1, 2, 3, 4); // [1, 2, 3, 4]
swizzledFn([1, 2, 3, 4]); // [1, 2, 3, 4]
```
## License
Licensed under the [MIT License](http://opensource.org/licenses/MIT).
You can find a copy of it in [LICENSE](LICENSE).

View File

@ -0,0 +1,29 @@
'use strict';
import isArrayish from '../is-arrayish';
var concat = Array.prototype.concat;
var slice = Array.prototype.slice;
export default function swizzle(args) {
var results = [];
for (var i = 0, len = args.length; i < len; i++) {
var arg = args[i];
if (isArrayish(arg)) {
// http://jsperf.com/javascript-array-concat-vs-push/98
results = concat.call(results, slice.call(arg));
} else {
results.push(arg);
}
}
return results;
};
swizzle.wrap = function (fn) {
return function () {
return fn(swizzle(arguments));
};
};

View File

@ -0,0 +1,36 @@
{
"name": "simple-swizzle",
"description": "Simply swizzle your arguments",
"version": "0.2.2",
"author": "Qix (http://github.com/qix-)",
"keywords": [
"argument",
"arguments",
"swizzle",
"swizzling",
"parameter",
"parameters",
"mixed",
"array"
],
"license": "MIT",
"scripts": {
"pretest": "xo",
"test": "mocha --compilers coffee:coffee-script/register"
},
"files": [
"index.js"
],
"repository": "qix-/node-simple-swizzle",
"devDependencies": {
"coffee-script": "^1.9.3",
"coveralls": "^2.11.2",
"istanbul": "^0.3.17",
"mocha": "^2.2.5",
"should": "^7.0.1",
"xo": "^0.7.1"
},
"dependencies": {
"is-arrayish": "^0.3.1"
}
}

View File

@ -0,0 +1,29 @@
let timeout = null
/**
* 防抖原理一定时间内只有最后一次操作再过wait毫秒后才执行函数
*
* @param {Function} func 要执行的回调函数
* @param {Number} wait 延时的时间
* @param {Boolean} immediate 是否立即执行
* @return null
*/
function debounce(func, wait = 500, immediate = false) {
// 清除定时器
if (timeout !== null) clearTimeout(timeout)
// 立即执行,此类情况一般用不到
if (immediate) {
const callNow = !timeout
timeout = setTimeout(() => {
timeout = null
}, wait)
if (callNow) typeof func === 'function' && func()
} else {
// 设置定时器当最后一次操作后timeout不会再被清除所以在延时wait毫秒后执行func回调方法
timeout = setTimeout(() => {
typeof func === 'function' && func()
}, wait)
}
}
export default debounce

View File

@ -0,0 +1,167 @@
let _boundaryCheckingState = true; // 是否进行越界检查的全局开关
/**
* 把错误的数据转正
* @private
* @example strip(0.09999999999999998)=0.1
*/
function strip(num, precision = 15) {
return +parseFloat(Number(num).toPrecision(precision));
}
/**
* Return digits length of a number
* @private
* @param {*number} num Input number
*/
function digitLength(num) {
// Get digit length of e
const eSplit = num.toString().split(/[eE]/);
const len = (eSplit[0].split('.')[1] || '').length - +(eSplit[1] || 0);
return len > 0 ? len : 0;
}
/**
* 把小数转成整数,如果是小数则放大成整数
* @private
* @param {*number} num 输入数
*/
function float2Fixed(num) {
if (num.toString().indexOf('e') === -1) {
return Number(num.toString().replace('.', ''));
}
const dLen = digitLength(num);
return dLen > 0 ? strip(Number(num) * Math.pow(10, dLen)) : Number(num);
}
/**
* 检测数字是否越界如果越界给出提示
* @private
* @param {*number} num 输入数
*/
function checkBoundary(num) {
if (_boundaryCheckingState) {
if (num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER) {
console.warn(`${num} 超出了精度限制,结果可能不正确`);
}
}
}
/**
* 把递归操作扁平迭代化
* @param {number[]} arr 要操作的数字数组
* @param {function} operation 迭代操作
* @private
*/
function iteratorOperation(arr, operation) {
const [num1, num2, ...others] = arr;
let res = operation(num1, num2);
others.forEach((num) => {
res = operation(res, num);
});
return res;
}
/**
* 高精度乘法
* @export
*/
export function times(...nums) {
if (nums.length > 2) {
return iteratorOperation(nums, times);
}
const [num1, num2] = nums;
const num1Changed = float2Fixed(num1);
const num2Changed = float2Fixed(num2);
const baseNum = digitLength(num1) + digitLength(num2);
const leftValue = num1Changed * num2Changed;
checkBoundary(leftValue);
return leftValue / Math.pow(10, baseNum);
}
/**
* 高精度加法
* @export
*/
export function plus(...nums) {
if (nums.length > 2) {
return iteratorOperation(nums, plus);
}
const [num1, num2] = nums;
// 取最大的小数位
const baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2)));
// 把小数都转为整数然后再计算
return (times(num1, baseNum) + times(num2, baseNum)) / baseNum;
}
/**
* 高精度减法
* @export
*/
export function minus(...nums) {
if (nums.length > 2) {
return iteratorOperation(nums, minus);
}
const [num1, num2] = nums;
const baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2)));
return (times(num1, baseNum) - times(num2, baseNum)) / baseNum;
}
/**
* 高精度除法
* @export
*/
export function divide(...nums) {
if (nums.length > 2) {
return iteratorOperation(nums, divide);
}
const [num1, num2] = nums;
const num1Changed = float2Fixed(num1);
const num2Changed = float2Fixed(num2);
checkBoundary(num1Changed);
checkBoundary(num2Changed);
// 重要这里必须用strip进行修正
return times(num1Changed / num2Changed, strip(Math.pow(10, digitLength(num2) - digitLength(num1))));
}
/**
* 四舍五入
* @export
*/
export function round(num, ratio) {
const base = Math.pow(10, ratio);
let result = divide(Math.round(Math.abs(times(num, base))), base);
if (num < 0 && result !== 0) {
result = times(result, -1);
}
// 位数不足则补0
return result;
}
/**
* 是否进行边界检查默认开启
* @param flag 标记开关true 为开启false 为关闭默认为 true
* @export
*/
export function enableBoundaryChecking(flag = true) {
_boundaryCheckingState = flag;
}
export default {
times,
plus,
minus,
divide,
round,
enableBoundaryChecking,
};

View File

@ -0,0 +1,738 @@
import { number, empty } from './test.js'
import { round } from './digit.js'
// 颜色操作方法
import Color from './color'
/**
* @description 如果value小于min取min如果value大于max取max
* @param {number} min
* @param {number} max
* @param {number} value
*/
function range(min = 0, max = 0, value = 0) {
return Math.max(min, Math.min(max, Number(value)))
}
/**
* @description 用于获取用户传递值的px值 如果用户传递了"xxpx"或者"xxrpx"取出其数值部分如果是"xxxrpx"还需要用过uni.upx2px进行转换
* @param {number|string} value 用户传递值的px值
* @param {boolean} unit
* @returns {number|string}
*/
function getPx(value, unit = false) {
if (number(value)) {
return unit ? `${value}px` : Number(value)
}
// 如果带有rpx先取出其数值部分再转为px值
if (/(rpx|upx)$/.test(value)) {
return unit ? `${uni.upx2px(parseInt(value))}px` : Number(uni.upx2px(parseInt(value)))
}
return unit ? `${parseInt(value)}px` : parseInt(value)
}
/**
* @description 进行延时以达到可以简写代码的目的 比如: await uni.$w.sleep(20)将会阻塞20ms
* @param {number} value 堵塞时间 单位ms 毫秒
* @returns {Promise} 返回promise
*/
function sleep(value = 30) {
return new Promise((resolve) => {
setTimeout(() => {
resolve()
}, value)
})
}
/**
* @description 运行期判断平台
* @returns {string} 返回所在平台(小写)
* @link 运行期判断平台 https://uniapp.dcloud.io/frame?id=判断平台
*/
function os() {
return uni.getSystemInfoSync().platform.toLowerCase()
}
/**
* @description 获取系统信息同步接口
* @link 获取系统信息同步接口 https://uniapp.dcloud.io/api/system/info?id=getsysteminfosync
*/
function sys() {
return uni.getSystemInfoSync()
}
/**
* @description 取一个区间数
* @param {Number} min 最小值
* @param {Number} max 最大值
*/
function random(min, max) {
if (min >= 0 && max > 0 && max >= min) {
const gab = max - min + 1
return Math.floor(Math.random() * gab + min)
}
return 0
}
/**
* @param {Number} len uuid的长度
* @param {Boolean} firstU 将返回的首字母置为"u"
* @param {Nubmer} radix 生成uuid的基数(意味着返回的字符串都是这个基数),2-二进制,8-八进制,10-十进制,16-十六进制
*/
function guid(len = 32, firstU = true, radix = null) {
const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
const uuid = []
radix = radix || chars.length
if (len) {
// 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位
for (let i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
} else {
let r
// rfc4122标准要求返回的uuid中,某些位为固定的字符
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
uuid[14] = '4'
for (let i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]
}
}
}
// 移除第一个字符,并用u替代,因为第一个字符为数值时,该guuid不能用作id或者class
if (firstU) {
uuid.shift()
return `u${uuid.join('')}`
}
return uuid.join('')
}
/**
* @description 获取父组件的参数因为支付宝小程序不支持provide/inject的写法
this.$parent在非H5中可以准确获取到父组件但是在H5中需要多次this.$parent.$parent.xxx
这里默认值等于undefined有它的含义因为最顶层元素(组件)的$parent就是undefined意味着不传name
(默认为undefined)就是查找最顶层的$parent
* @param {string|undefined} name 父组件的参数名
*/
function $parent(name = undefined) {
let parent = this.$parent
// 通过while历遍这里主要是为了H5需要多层解析的问题
while (parent) {
// 父组件
if (parent.$options && parent.$options.name !== name) {
// 如果组件的name不相等继续上一级寻找
parent = parent.$parent
} else {
return parent
}
}
return false
}
/**
* @description 样式转换
* 对象转字符串或者字符串转对象
* @param {object | string} customStyle 需要转换的目标
* @param {String} target 转换的目的object-转为对象string-转为字符串
* @returns {object|string}
*/
function addStyle(customStyle, target = 'object') {
// 字符串转字符串,对象转对象情形,直接返回
if (empty(customStyle) || typeof(customStyle) === 'object' && target === 'object' || target === 'string' &&
typeof(customStyle) === 'string') {
return customStyle
}
// 字符串转对象
if (target === 'object') {
// 去除字符串样式中的两端空格(中间的空格不能去掉比如padding: 20px 0如果去掉了就错了),空格是无用的
customStyle = trim(customStyle)
// 根据";"将字符串转为数组形式
const styleArray = customStyle.split(';')
const style = {}
// 历遍数组,拼接成对象
for (let i = 0; i < styleArray.length; i++) {
// 'font-size:20px;color:red;',如此最后字符串有";"的话会导致styleArray最后一个元素为空字符串这里需要过滤
if (styleArray[i]) {
const item = styleArray[i].split(':')
style[trim(item[0])] = trim(item[1])
}
}
return style
}
// 这里为对象转字符串形式
let string = ''
for (const i in customStyle) {
// 驼峰转为中划线的形式否则css内联样式无法识别驼峰样式属性名
const key = i.replace(/([A-Z])/g, '-$1').toLowerCase()
string += `${key}:${customStyle[i]};`
}
// 去除两端空格
return trim(string)
}
/**
* @description 添加单位如果有rpxupx%px等单位结尾或者值为auto直接返回否则加上px单位结尾
* @param {string|number} value 需要添加单位的值
* @param {string} unit 添加的单位名 比如px
*/
function addUnit(value = 'auto', unit = uni?.$w?.config?.unit ? uni?.$w?.config?.unit : 'px') {
value = String(value)
// 用wuui内置验证规则中的number判断是否为数值
return number(value) ? `${value}${unit}` : value
}
/**
* @description 深度克隆
* @param {object} obj 需要深度克隆的对象
* @param cache 缓存
* @returns {*} 克隆后的对象或者原值不是对象
*/
function deepClone(obj, cache = new WeakMap()) {
if (obj === null || typeof obj !== 'object') return obj;
if (cache.has(obj)) return cache.get(obj);
let clone;
if (obj instanceof Date) {
clone = new Date(obj.getTime());
} else if (obj instanceof RegExp) {
clone = new RegExp(obj);
} else if (obj instanceof Map) {
clone = new Map(Array.from(obj, ([key, value]) => [key, deepClone(value, cache)]));
} else if (obj instanceof Set) {
clone = new Set(Array.from(obj, value => deepClone(value, cache)));
} else if (Array.isArray(obj)) {
clone = obj.map(value => deepClone(value, cache));
} else if (Object.prototype.toString.call(obj) === '[object Object]') {
clone = Object.create(Object.getPrototypeOf(obj));
cache.set(obj, clone);
for (const [key, value] of Object.entries(obj)) {
clone[key] = deepClone(value, cache);
}
} else {
clone = Object.assign({}, obj);
}
cache.set(obj, clone);
return clone;
}
/**
* @description JS对象深度合并
* @param {object} target 需要拷贝的对象
* @param {object} source 拷贝的来源对象
* @returns {object|boolean} 深度合并后的对象或者false入参有不是对象
*/
function deepMerge(target = {}, source = {}) {
target = deepClone(target)
if (typeof target !== 'object' || target === null || typeof source !== 'object' || source === null) return target;
const merged = Array.isArray(target) ? target.slice() : Object.assign({}, target);
for (const prop in source) {
if (!source.hasOwnProperty(prop)) continue;
const sourceValue = source[prop];
const targetValue = merged[prop];
if (sourceValue instanceof Date) {
merged[prop] = new Date(sourceValue);
} else if (sourceValue instanceof RegExp) {
merged[prop] = new RegExp(sourceValue);
} else if (sourceValue instanceof Map) {
merged[prop] = new Map(sourceValue);
} else if (sourceValue instanceof Set) {
merged[prop] = new Set(sourceValue);
} else if (typeof sourceValue === 'object' && sourceValue !== null) {
merged[prop] = deepMerge(targetValue, sourceValue);
} else {
merged[prop] = sourceValue;
}
}
return merged;
}
/**
* @description error提示
* @param {*} err 错误内容
*/
function error(err) {
// 开发环境才提示,生产环境不会提示
if (process.env.NODE_ENV === 'development') {
console.error(`wuui提示${err}`)
}
}
/**
* @description 打乱数组
* @param {array} array 需要打乱的数组
* @returns {array} 打乱后的数组
*/
function randomArray(array = []) {
// 原理是sort排序,Math.random()产生0<= x < 1之间的数,会导致x-0.05大于或者小于0
return array.sort(() => Math.random() - 0.5)
}
// padStart 的 polyfill因为某些机型或情况还无法支持es7的padStart比如电脑版的微信小程序
// 所以这里做一个兼容polyfill的兼容处理
if (!String.prototype.padStart) {
// 为了方便表示这里 fillString 用了ES6 的默认参数,不影响理解
String.prototype.padStart = function(maxLength, fillString = ' ') {
if (Object.prototype.toString.call(fillString) !== '[object String]') {
throw new TypeError(
'fillString must be String'
)
}
const str = this
// 返回 String(str) 这里是为了使返回的值是字符串字面量,在控制台中更符合直觉
if (str.length >= maxLength) return String(str)
const fillLength = maxLength - str.length
let times = Math.ceil(fillLength / fillString.length)
while (times >>= 1) {
fillString += fillString
if (times === 1) {
fillString += fillString
}
}
return fillString.slice(0, fillLength) + str
}
}
/**
* @description 格式化时间
* @param {String|Number} dateTime 需要格式化的时间戳
* @param {String} fmt 格式化规则 yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合 默认yyyy-mm-dd
* @returns {string} 返回格式化后的字符串
*/
function timeFormat(dateTime = null, formatStr = 'yyyy-mm-dd') {
let date
// 若传入时间为假值,则取当前时间
if (!dateTime) {
date = new Date()
}
// 若为unix秒时间戳则转为毫秒时间戳逻辑有点奇怪但不敢改以保证历史兼容
else if (/^\d{10}$/.test(dateTime?.toString().trim())) {
date = new Date(dateTime * 1000)
}
// 若用户传入字符串格式时间戳new Date无法解析需做兼容
else if (typeof dateTime === 'string' && /^\d+$/.test(dateTime.trim())) {
date = new Date(Number(dateTime))
}
// 处理平台性差异在Safari/Webkit中new Date仅支持/作为分割符的字符串时间
// 处理 '2022-07-10 01:02:03',跳过 '2022-07-10T01:02:03'
else if (typeof dateTime === 'string' && dateTime.includes('-') && !dateTime.includes('T')) {
date = new Date(dateTime.replace(/-/g, '/'))
}
// 其他都认为符合 RFC 2822 规范
else {
date = new Date(dateTime)
}
const timeSource = {
'y': date.getFullYear().toString(), // 年
'm': (date.getMonth() + 1).toString().padStart(2, '0'), // 月
'd': date.getDate().toString().padStart(2, '0'), // 日
'h': date.getHours().toString().padStart(2, '0'), // 时
'M': date.getMinutes().toString().padStart(2, '0'), // 分
's': date.getSeconds().toString().padStart(2, '0') // 秒
// 有其他格式化字符需求可以继续添加,必须转化成字符串
}
for (const key in timeSource) {
const [ret] = new RegExp(`${key}+`).exec(formatStr) || []
if (ret) {
// 年可能只需展示两位
const beginIndex = key === 'y' && ret.length === 2 ? 2 : 0
formatStr = formatStr.replace(ret, timeSource[key].slice(beginIndex))
}
}
return formatStr
}
/**
* @description 时间戳转为多久之前
* @param {String|Number} timestamp 时间戳
* @param {String|Boolean} format
* 格式化规则如果为时间格式字符串超出一定时间范围返回固定的时间格式
* 如果为布尔值false无论什么时间都返回多久以前的格式
* @returns {string} 转化后的内容
*/
function timeFrom(timestamp = null, format = 'yyyy-mm-dd') {
if (timestamp == null) timestamp = Number(new Date())
timestamp = parseInt(timestamp)
// 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
if (timestamp.toString().length == 10) timestamp *= 1000
let timer = (new Date()).getTime() - timestamp
timer = parseInt(timer / 1000)
// 如果小于5分钟,则返回"刚刚",其他以此类推
let tips = ''
switch (true) {
case timer < 300:
tips = '刚刚'
break
case timer >= 300 && timer < 3600:
tips = `${parseInt(timer / 60)}分钟前`
break
case timer >= 3600 && timer < 86400:
tips = `${parseInt(timer / 3600)}小时前`
break
case timer >= 86400 && timer < 2592000:
tips = `${parseInt(timer / 86400)}天前`
break
default:
// 如果format为false则无论什么时间戳都显示xx之前
if (format === false) {
if (timer >= 2592000 && timer < 365 * 86400) {
tips = `${parseInt(timer / (86400 * 30))}个月前`
} else {
tips = `${parseInt(timer / (86400 * 365))}年前`
}
} else {
tips = timeFormat(timestamp, format)
}
}
return tips
}
/**
* @description 去除空格
* @param String str 需要去除空格的字符串
* @param String pos both(左右)|left|right|all 默认both
*/
function trim(str, pos = 'both') {
str = String(str)
if (pos == 'both') {
return str.replace(/^\s+|\s+$/g, '')
}
if (pos == 'left') {
return str.replace(/^\s*/, '')
}
if (pos == 'right') {
return str.replace(/(\s*$)/g, '')
}
if (pos == 'all') {
return str.replace(/\s+/g, '')
}
return str
}
/**
* @description 对象转url参数
* @param {object} data,对象
* @param {Boolean} isPrefix,是否自动加上"?"
* @param {string} arrayFormat 规则 indices|brackets|repeat|comma
*/
function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets') {
const prefix = isPrefix ? '?' : ''
const _result = []
if (['indices', 'brackets', 'repeat', 'comma'].indexOf(arrayFormat) == -1) arrayFormat = 'brackets'
for (const key in data) {
const value = data[key]
// 去掉为空的参数
if (['', undefined, null].indexOf(value) >= 0) {
continue
}
// 如果值为数组,另行处理
if (value.constructor === Array) {
// e.g. {ids: [1, 2, 3]}
switch (arrayFormat) {
case 'indices':
// 结果: ids[0]=1&ids[1]=2&ids[2]=3
for (let i = 0; i < value.length; i++) {
_result.push(`${key}[${i}]=${value[i]}`)
}
break
case 'brackets':
// 结果: ids[]=1&ids[]=2&ids[]=3
value.forEach((_value) => {
_result.push(`${key}[]=${_value}`)
})
break
case 'repeat':
// 结果: ids=1&ids=2&ids=3
value.forEach((_value) => {
_result.push(`${key}=${_value}`)
})
break
case 'comma':
// 结果: ids=1,2,3
let commaStr = ''
value.forEach((_value) => {
commaStr += (commaStr ? ',' : '') + _value
})
_result.push(`${key}=${commaStr}`)
break
default:
value.forEach((_value) => {
_result.push(`${key}[]=${_value}`)
})
}
} else {
_result.push(`${key}=${value}`)
}
}
return _result.length ? prefix + _result.join('&') : ''
}
/**
* 显示消息提示框
* @param {String} title 提示的内容长度与 icon 取值有关
* @param {Number} duration 提示的延迟时间单位毫秒默认2000
*/
function toast(title, duration = 2000) {
uni.showToast({
title: String(title),
icon: 'none',
duration
})
}
/**
* @description 根据主题type值,获取对应的图标
* @param {String} type 主题名称,primary|info|error|warning|success
* @param {boolean} fill 是否使用fill填充实体的图标
*/
function type2icon(type = 'success', fill = false) {
// 如果非预置值,默认为success
if (['primary', 'info', 'error', 'warning', 'success'].indexOf(type) == -1) type = 'success'
let iconName = ''
// 目前(2019-12-12),info和primary使用同一个图标
switch (type) {
case 'primary':
iconName = 'info-circle'
break
case 'info':
iconName = 'info-circle'
break
case 'error':
iconName = 'close-circle'
break
case 'warning':
iconName = 'error-circle'
break
case 'success':
iconName = 'checkmark-circle'
break
default:
iconName = 'checkmark-circle'
}
// 是否是实体类型,加上-fill,在icon组件库中,实体的类名是后面加-fill的
if (fill) iconName += '-fill'
return iconName
}
/**
* @description 数字格式化
* @param {number|string} number 要格式化的数字
* @param {number} decimals 保留几位小数
* @param {string} decimalPoint 小数点符号
* @param {string} thousandsSeparator 千分位符号
* @returns {string} 格式化后的数字
*/
function priceFormat(number, decimals = 0, decimalPoint = '.', thousandsSeparator = ',') {
number = (`${number}`).replace(/[^0-9+-Ee.]/g, '')
const n = !isFinite(+number) ? 0 : +number
const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
const sep = (typeof thousandsSeparator === 'undefined') ? ',' : thousandsSeparator
const dec = (typeof decimalPoint === 'undefined') ? '.' : decimalPoint
let s = ''
s = (prec ? round(n, prec) + '' : `${Math.round(n)}`).split('.')
const re = /(-?\d+)(\d{3})/
while (re.test(s[0])) {
s[0] = s[0].replace(re, `$1${sep}$2`)
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || ''
s[1] += new Array(prec - s[1].length + 1).join('0')
}
return s.join(dec)
}
/**
* @description 获取duration值
* 如果带有ms或者s直接返回如果大于一定值认为是ms单位小于一定值认为是s单位
* 比如以30位阈值那么300大于30可以理解为用户想要的是300ms而不是想花300s去执行一个动画
* @param {String|number} value 比如: "1s"|"100ms"|1|100
* @param {boolean} unit 提示: 如果是false 默认返回number
* @return {string|number}
*/
function getDuration(value, unit = true) {
const valueNum = parseInt(value)
if (unit) {
if (/s$/.test(value)) return value
return value > 30 ? `${value}ms` : `${value}s`
}
if (/ms$/.test(value)) return valueNum
if (/s$/.test(value)) return valueNum > 30 ? valueNum : valueNum * 1000
return valueNum
}
/**
* @description 日期的月或日补零操作
* @param {String} value 需要补零的值
*/
function padZero(value) {
return `00${value}`.slice(-2)
}
/**
* @description 在wu-form的子组件内容发生变化或者失去焦点时尝试通知wu-form执行校验方法
* @param {*} instance
* @param {*} event
*/
function formValidate(instance, event) {
const formItem = $parent.call(instance, 'wu-form-item')
const form = $parent.call(instance, 'wu-form')
// 如果发生变化的input或者textarea等其父组件中有wu-form-item或者wu-form等就执行form的validate方法
// 同时将form-item的pros传递给form让其进行精确对象验证
if (formItem && form) {
form.validateField(formItem.prop, () => {}, event)
}
}
/**
* @description 获取某个对象下的属性用于通过类似'a.b.c'的形式去获取一个对象的的属性的形式
* @param {object} obj 对象
* @param {string} key 需要获取的属性字段
* @returns {*}
*/
function getProperty(obj, key) {
if (!obj) {
return
}
if (typeof key !== 'string' || key === '') {
return ''
}
if (key.indexOf('.') !== -1) {
const keys = key.split('.')
let firstObj = obj[keys[0]] || {}
for (let i = 1; i < keys.length; i++) {
if (firstObj) {
firstObj = firstObj[keys[i]]
}
}
return firstObj
}
return obj[key]
}
/**
* @description 设置对象的属性值如果'a.b.c'的形式进行设置
* @param {object} obj 对象
* @param {string} key 需要设置的属性
* @param {string} value 设置的值
*/
function setProperty(obj, key, value) {
if (!obj) {
return
}
// 递归赋值
const inFn = function(_obj, keys, v) {
// 最后一个属性key
if (keys.length === 1) {
_obj[keys[0]] = v
return
}
// 0~length-1个key
while (keys.length > 1) {
const k = keys[0]
if (!_obj[k] || (typeof _obj[k] !== 'object')) {
_obj[k] = {}
}
const key = keys.shift()
// 自调用判断是否存在属性,不存在则自动创建对象
inFn(_obj[k], keys, v)
}
}
if (typeof key !== 'string' || key === '') {
} else if (key.indexOf('.') !== -1) { // 支持多层级赋值操作
const keys = key.split('.')
inFn(obj, keys, value)
} else {
obj[key] = value
}
}
/**
* @description 获取当前页面路径
*/
function page() {
const pages = getCurrentPages();
const route = pages[pages.length - 1]?.route;
// 某些特殊情况下(比如页面进行redirectTo时的一些时机)pages可能为空数组
return `/${route ? route : ''}`
}
/**
* @description 获取当前路由栈实例数组
*/
function pages() {
const pages = getCurrentPages()
return pages
}
/**
* 获取页面历史栈指定层实例
* @param back {number} [0] - 0或者负数表示获取历史栈的哪一层0表示获取当前页面实例-1 表示获取上一个页面实例默认0
*/
function getHistoryPage(back = 0) {
const pages = getCurrentPages()
const len = pages.length
return pages[len - 1 + back]
}
/**
* @description 修改wuui内置属性值
* @param {object} props 修改内置props属性
* @param {object} config 修改内置config属性
* @param {object} color 修改内置color属性
* @param {object} zIndex 修改内置zIndex属性
*/
function setConfig({
props = {},
config = {},
color = {},
zIndex = {}
}) {
const {
deepMerge,
} = uni.$w
uni.$w.config = deepMerge(uni.$w.config, config)
uni.$w.props = deepMerge(uni.$w.props, props)
uni.$w.color = deepMerge(uni.$w.color, color)
uni.$w.zIndex = deepMerge(uni.$w.zIndex, zIndex)
}
export {
range,
getPx,
sleep,
os,
sys,
random,
guid,
$parent,
addStyle,
addUnit,
deepClone,
deepMerge,
error,
randomArray,
timeFormat,
timeFrom,
trim,
queryParams,
toast,
type2icon,
priceFormat,
getDuration,
padZero,
formValidate,
getProperty,
setProperty,
page,
pages,
getHistoryPage,
setConfig,
Color
}

View File

@ -0,0 +1,75 @@
/**
* 注意
* 此部分内容在vue-cli模式下需要在vue.config.js加入如下内容才有效
* module.exports = {
* transpileDependencies: ['uview-v2']
* }
*/
let platform = 'none'
// #ifdef VUE3
platform = 'vue3'
// #endif
// #ifdef VUE2
platform = 'vue2'
// #endif
// #ifdef APP-PLUS
platform = 'plus'
// #endif
// #ifdef APP-NVUE
platform = 'nvue'
// #endif
// #ifdef H5
platform = 'h5'
// #endif
// #ifdef MP-WEIXIN
platform = 'weixin'
// #endif
// #ifdef MP-ALIPAY
platform = 'alipay'
// #endif
// #ifdef MP-BAIDU
platform = 'baidu'
// #endif
// #ifdef MP-TOUTIAO
platform = 'toutiao'
// #endif
// #ifdef MP-QQ
platform = 'qq'
// #endif
// #ifdef MP-KUAISHOU
platform = 'kuaishou'
// #endif
// #ifdef MP-360
platform = '360'
// #endif
// #ifdef MP
platform = 'mp'
// #endif
// #ifdef QUICKAPP-WEBVIEW
platform = 'quickapp-webview'
// #endif
// #ifdef QUICKAPP-WEBVIEW-HUAWEI
platform = 'quickapp-webview-huawei'
// #endif
// #ifdef QUICKAPP-WEBVIEW-UNION
platform = 'quckapp-webview-union'
// #endif
export default platform

View File

@ -0,0 +1,287 @@
/**
* 验证电子邮箱格式
*/
function email(value) {
return /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(value)
}
/**
* 验证手机格式
*/
function mobile(value) {
return /^1([3589]\d|4[5-9]|6[1-2,4-7]|7[0-8])\d{8}$/.test(value)
}
/**
* 验证URL格式
*/
function url(value) {
return /^((https|http|ftp|rtsp|mms):\/\/)(([0-9a-zA-Z_!~*'().&=+$%-]+: )?[0-9a-zA-Z_!~*'().&=+$%-]+@)?(([0-9]{1,3}.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z].[a-zA-Z]{2,6})(:[0-9]{1,4})?((\/?)|(\/[0-9a-zA-Z_!~*'().;?:@&=+$,%#-]+)+\/?)$/
.test(value)
}
/**
* 验证日期格式
*/
function date(value) {
if (!value) return false
// 判断是否数值或者字符串数值(意味着为时间戳)转为数值否则new Date无法识别字符串时间戳
if (number(value)) value = +value
return !/Invalid|NaN/.test(new Date(value).toString())
}
/**
* 验证ISO类型的日期格式
*/
function dateISO(value) {
return /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(value)
}
/**
* 验证十进制数字
*/
function number(value) {
return /^[\+-]?(\d+\.?\d*|\.\d+|\d\.\d+e\+\d+)$/.test(value)
}
/**
* 验证字符串
*/
function string(value) {
return typeof value === 'string'
}
/**
* 验证整数
*/
function digits(value) {
return /^\d+$/.test(value)
}
/**
* 验证身份证号码
*/
function idCard(value) {
return /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(
value
)
}
/**
* 是否车牌号
*/
function carNo(value) {
// 新能源车牌
const xreg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/
// 旧车牌
const creg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/
if (value.length === 7) {
return creg.test(value)
} if (value.length === 8) {
return xreg.test(value)
}
return false
}
/**
* 金额,只允许2位小数
*/
function amount(value) {
// 金额,只允许保留两位小数
return /^[1-9]\d*(,\d{3})*(\.\d{1,2})?$|^0\.\d{1,2}$/.test(value)
}
/**
* 中文
*/
function chinese(value) {
const reg = /^[\u4e00-\u9fa5]+$/gi
return reg.test(value)
}
/**
* 只能输入字母
*/
function letter(value) {
return /^[a-zA-Z]*$/.test(value)
}
/**
* 只能是字母或者数字
*/
function enOrNum(value) {
// 英文或者数字
const reg = /^[0-9a-zA-Z]*$/g
return reg.test(value)
}
/**
* 验证是否包含某个值
*/
function contains(value, param) {
return value.indexOf(param) >= 0
}
/**
* 验证一个值范围[min, max]
*/
function range(value, param) {
return value >= param[0] && value <= param[1]
}
/**
* 验证一个长度范围[min, max]
*/
function rangeLength(value, param) {
return value.length >= param[0] && value.length <= param[1]
}
/**
* 是否固定电话
*/
function landline(value) {
const reg = /^\d{3,4}-\d{7,8}(-\d{3,4})?$/
return reg.test(value)
}
/**
* 判断是否为空
*/
function empty(value) {
switch (typeof value) {
case 'undefined':
return true
case 'string':
if (value.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '').length == 0) return true
break
case 'boolean':
if (!value) return true
break
case 'number':
if (value === 0 || isNaN(value)) return true
break
case 'object':
if (value === null || value.length === 0) return true
for (const i in value) {
return false
}
return true
}
return false
}
/**
* 是否json字符串
*/
function jsonString(value) {
if (typeof value === 'string') {
try {
const obj = JSON.parse(value)
if (typeof obj === 'object' && obj) {
return true
}
return false
} catch (e) {
return false
}
}
return false
}
/**
* 是否数组
*/
function array(value) {
if (typeof Array.isArray === 'function') {
return Array.isArray(value)
}
return Object.prototype.toString.call(value) === '[object Array]'
}
/**
* 是否对象
*/
function object(value) {
return Object.prototype.toString.call(value) === '[object Object]'
}
/**
* 是否短信验证码
*/
function code(value, len = 6) {
return new RegExp(`^\\d{${len}}$`).test(value)
}
/**
* 是否函数方法
* @param {Object} value
*/
function func(value) {
return typeof value === 'function'
}
/**
* 是否promise对象
* @param {Object} value
*/
function promise(value) {
return object(value) && func(value.then) && func(value.catch)
}
/**
* @param {Object} value
*/
function image(value) {
const newValue = value.split('?')[0]
const IMAGE_REGEXP = /\.(jpeg|jpg|gif|png|svg|webp|jfif|bmp|dpg)/i
return IMAGE_REGEXP.test(newValue)
}
/**
* 是否视频格式
* @param {Object} value
*/
function video(value) {
const VIDEO_REGEXP = /\.(mp4|mpg|mpeg|dat|asf|avi|rm|rmvb|mov|wmv|flv|mkv|m3u8)/i
return VIDEO_REGEXP.test(value)
}
/**
* 是否为正则对象
* @param {Object}
* @return {Boolean}
*/
function regExp(o) {
return o && Object.prototype.toString.call(o) === '[object RegExp]'
}
export {
email,
mobile,
url,
date,
dateISO,
number,
digits,
idCard,
carNo,
amount,
chinese,
letter,
enOrNum,
contains,
range,
rangeLength,
empty,
jsonString,
landline,
object,
array,
code,
func,
promise,
video,
image,
regExp,
string
}

View File

@ -0,0 +1,30 @@
let timer; let
flag
/**
* 节流原理在一定时间内只能触发一次
*
* @param {Function} func 要执行的回调函数
* @param {Number} wait 延时的时间
* @param {Boolean} immediate 是否立即执行
* @return null
*/
function throttle(func, wait = 500, immediate = true) {
if (immediate) {
if (!flag) {
flag = true
// 如果是立即执行则在wait毫秒内开始时执行
typeof func === 'function' && func()
timer = setTimeout(() => {
flag = false
}, wait)
}
} else if (!flag) {
flag = true
// 如果是非立即执行则在wait毫秒内的结束处执行
timer = setTimeout(() => {
flag = false
typeof func === 'function' && func()
}, wait)
}
}
export default throttle

View File

@ -0,0 +1,97 @@
import buildURL from '../helpers/buildURL'
import buildFullPath from '../core/buildFullPath'
import settle from '../core/settle'
import { isUndefined } from '../utils'
/**
* 返回可选值存在的配置
* @param {Array} keys - 可选值数组
* @param {Object} config2 - 配置
* @return {{}} - 存在的配置项
*/
const mergeKeys = (keys, config2) => {
const config = {}
keys.forEach((prop) => {
if (!isUndefined(config2[prop])) {
config[prop] = config2[prop]
}
})
return config
}
export default (config) => new Promise((resolve, reject) => {
const fullPath = buildURL(buildFullPath(config.baseURL, config.url), config.params)
const _config = {
url: fullPath,
header: config.header,
complete: (response) => {
config.fullPath = fullPath
response.config = config
try {
// 对可能字符串不是json 的情况容错
if (typeof response.data === 'string') {
response.data = JSON.parse(response.data)
}
// eslint-disable-next-line no-empty
} catch (e) {
}
settle(resolve, reject, response)
}
}
let requestTask
if (config.method === 'UPLOAD') {
delete _config.header['content-type']
delete _config.header['Content-Type']
const otherConfig = {
// #ifdef MP-ALIPAY
fileType: config.fileType,
// #endif
filePath: config.filePath,
name: config.name
}
const optionalKeys = [
// #ifdef APP-PLUS || H5
'files',
// #endif
// #ifdef H5
'file',
// #endif
// #ifdef H5 || APP-PLUS
'timeout',
// #endif
'formData'
]
requestTask = uni.uploadFile({ ..._config, ...otherConfig, ...mergeKeys(optionalKeys, config) })
} else if (config.method === 'DOWNLOAD') {
// #ifdef H5 || APP-PLUS
if (!isUndefined(config.timeout)) {
_config.timeout = config.timeout
}
// #endif
requestTask = uni.downloadFile(_config)
} else {
const optionalKeys = [
'data',
'method',
// #ifdef H5 || APP-PLUS || MP-ALIPAY || MP-WEIXIN
'timeout',
// #endif
'dataType',
// #ifndef MP-ALIPAY
'responseType',
// #endif
// #ifdef APP-PLUS
'sslVerify',
// #endif
// #ifdef H5
'withCredentials',
// #endif
// #ifdef APP-PLUS
'firstIpv4'
// #endif
]
requestTask = uni.request({ ..._config, ...mergeKeys(optionalKeys, config) })
}
if (config.getTask) {
config.getTask(requestTask, config)
}
})

View File

@ -0,0 +1,50 @@
'use strict'
function InterceptorManager() {
this.handlers = []
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
InterceptorManager.prototype.use = function use(fulfilled, rejected) {
this.handlers.push({
fulfilled,
rejected
})
return this.handlers.length - 1
}
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*/
InterceptorManager.prototype.eject = function eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null
}
}
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*/
InterceptorManager.prototype.forEach = function forEach(fn) {
this.handlers.forEach((h) => {
if (h !== null) {
fn(h)
}
})
}
export default InterceptorManager

View File

@ -0,0 +1,198 @@
/**
* @Class Request
* @description luch-request http请求插件
* @version 3.0.7
* @Author lu-ch
* @Date 2021-09-04
* @Email webwork.s@qq.com
* 文档: https://www.quanzhan.co/luch-request/
* github: https://github.com/lei-mu/luch-request
* DCloud: http://ext.dcloud.net.cn/plugin?id=392
* HBuilderX: beat-3.0.4 alpha-3.0.4
*/
import dispatchRequest from './dispatchRequest'
import InterceptorManager from './InterceptorManager'
import mergeConfig from './mergeConfig'
import defaults from './defaults'
import { isPlainObject } from '../utils'
import clone from '../utils/clone'
export default class Request {
/**
* @param {Object} arg - 全局配置
* @param {String} arg.baseURL - 全局根路径
* @param {Object} arg.header - 全局header
* @param {String} arg.method = [GET|POST|PUT|DELETE|CONNECT|HEAD|OPTIONS|TRACE] - 全局默认请求方式
* @param {String} arg.dataType = [json] - 全局默认的dataType
* @param {String} arg.responseType = [text|arraybuffer] - 全局默认的responseType支付宝小程序不支持
* @param {Object} arg.custom - 全局默认的自定义参数
* @param {Number} arg.timeout - 全局默认的超时时间单位 ms默认60000H5(HBuilderX 2.9.9+)APP(HBuilderX 2.9.9+)微信小程序2.10.0支付宝小程序
* @param {Boolean} arg.sslVerify - 全局默认的是否验证 ssl 证书默认true.仅App安卓端支持HBuilderX 2.3.3+
* @param {Boolean} arg.withCredentials - 全局默认的跨域请求时是否携带凭证cookies默认false仅H5支持HBuilderX 2.6.15+
* @param {Boolean} arg.firstIpv4 - 全DNS解析时优先使用ipv4默认false App-Android 支持 (HBuilderX 2.8.0+)
* @param {Function(statusCode):Boolean} arg.validateStatus - 全局默认的自定义验证器默认statusCode >= 200 && statusCode < 300
*/
constructor(arg = {}) {
if (!isPlainObject(arg)) {
arg = {}
console.warn('设置全局参数必须接收一个Object')
}
this.config = clone({ ...defaults, ...arg })
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
}
}
/**
* @Function
* @param {Request~setConfigCallback} f - 设置全局默认配置
*/
setConfig(f) {
this.config = f(this.config)
}
middleware(config) {
config = mergeConfig(this.config, config)
const chain = [dispatchRequest, undefined]
let promise = Promise.resolve(config)
this.interceptors.request.forEach((interceptor) => {
chain.unshift(interceptor.fulfilled, interceptor.rejected)
})
this.interceptors.response.forEach((interceptor) => {
chain.push(interceptor.fulfilled, interceptor.rejected)
})
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift())
}
return promise
}
/**
* @Function
* @param {Object} config - 请求配置项
* @prop {String} options.url - 请求路径
* @prop {Object} options.data - 请求参数
* @prop {Object} [options.responseType = config.responseType] [text|arraybuffer] - 响应的数据类型
* @prop {Object} [options.dataType = config.dataType] - 如果设为 json会尝试对返回的数据做一次 JSON.parse
* @prop {Object} [options.header = config.header] - 请求header
* @prop {Object} [options.method = config.method] - 请求方法
* @returns {Promise<unknown>}
*/
request(config = {}) {
return this.middleware(config)
}
get(url, options = {}) {
return this.middleware({
url,
method: 'GET',
...options
})
}
post(url, data, options = {}) {
return this.middleware({
url,
data,
method: 'POST',
...options
})
}
// #ifndef MP-ALIPAY
put(url, data, options = {}) {
return this.middleware({
url,
data,
method: 'PUT',
...options
})
}
// #endif
// #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-BAIDU
delete(url, data, options = {}) {
return this.middleware({
url,
data,
method: 'DELETE',
...options
})
}
// #endif
// #ifdef H5 || MP-WEIXIN
connect(url, data, options = {}) {
return this.middleware({
url,
data,
method: 'CONNECT',
...options
})
}
// #endif
// #ifdef H5 || MP-WEIXIN || MP-BAIDU
head(url, data, options = {}) {
return this.middleware({
url,
data,
method: 'HEAD',
...options
})
}
// #endif
// #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-BAIDU
options(url, data, options = {}) {
return this.middleware({
url,
data,
method: 'OPTIONS',
...options
})
}
// #endif
// #ifdef H5 || MP-WEIXIN
trace(url, data, options = {}) {
return this.middleware({
url,
data,
method: 'TRACE',
...options
})
}
// #endif
upload(url, config = {}) {
config.url = url
config.method = 'UPLOAD'
return this.middleware(config)
}
download(url, config = {}) {
config.url = url
config.method = 'DOWNLOAD'
return this.middleware(config)
}
}
/**
* setConfig回调
* @return {Object} - 返回操作后的config
* @callback Request~setConfigCallback
* @param {Object} config - 全局默认config
*/

View File

@ -0,0 +1,20 @@
'use strict'
import isAbsoluteURL from '../helpers/isAbsoluteURL'
import combineURLs from '../helpers/combineURLs'
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
* @returns {string} The combined full path
*/
export default function buildFullPath(baseURL, requestedURL) {
if (baseURL && !isAbsoluteURL(requestedURL)) {
return combineURLs(baseURL, requestedURL)
}
return requestedURL
}

View File

@ -0,0 +1,29 @@
/**
* 默认的全局配置
*/
export default {
baseURL: '',
header: {},
method: 'GET',
dataType: 'json',
// #ifndef MP-ALIPAY
responseType: 'text',
// #endif
custom: {},
// #ifdef H5 || APP-PLUS || MP-ALIPAY || MP-WEIXIN
timeout: 60000,
// #endif
// #ifdef APP-PLUS
sslVerify: true,
// #endif
// #ifdef H5
withCredentials: false,
// #endif
// #ifdef APP-PLUS
firstIpv4: false,
// #endif
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300
}
}

View File

@ -0,0 +1,3 @@
import adapter from '../adapters/index'
export default (config) => adapter(config)

View File

@ -0,0 +1,103 @@
import { deepMerge, isUndefined } from '../utils'
/**
* 合并局部配置优先的配置如果局部有该配置项则用局部如果全局有该配置项则用全局
* @param {Array} keys - 配置项
* @param {Object} globalsConfig - 当前的全局配置
* @param {Object} config2 - 局部配置
* @return {{}}
*/
const mergeKeys = (keys, globalsConfig, config2) => {
const config = {}
keys.forEach((prop) => {
if (!isUndefined(config2[prop])) {
config[prop] = config2[prop]
} else if (!isUndefined(globalsConfig[prop])) {
config[prop] = globalsConfig[prop]
}
})
return config
}
/**
*
* @param globalsConfig - 当前实例的全局配置
* @param config2 - 当前的局部配置
* @return - 合并后的配置
*/
export default (globalsConfig, config2 = {}) => {
const method = config2.method || globalsConfig.method || 'GET'
let config = {
baseURL: globalsConfig.baseURL || '',
method,
url: config2.url || '',
params: config2.params || {},
custom: { ...(globalsConfig.custom || {}), ...(config2.custom || {}) },
header: deepMerge(globalsConfig.header || {}, config2.header || {})
}
const defaultToConfig2Keys = ['getTask', 'validateStatus']
config = { ...config, ...mergeKeys(defaultToConfig2Keys, globalsConfig, config2) }
// eslint-disable-next-line no-empty
if (method === 'DOWNLOAD') {
// #ifdef H5 || APP-PLUS
if (!isUndefined(config2.timeout)) {
config.timeout = config2.timeout
} else if (!isUndefined(globalsConfig.timeout)) {
config.timeout = globalsConfig.timeout
}
// #endif
} else if (method === 'UPLOAD') {
delete config.header['content-type']
delete config.header['Content-Type']
const uploadKeys = [
// #ifdef APP-PLUS || H5
'files',
// #endif
// #ifdef MP-ALIPAY
'fileType',
// #endif
// #ifdef H5
'file',
// #endif
'filePath',
'name',
// #ifdef H5 || APP-PLUS
'timeout',
// #endif
'formData'
]
uploadKeys.forEach((prop) => {
if (!isUndefined(config2[prop])) {
config[prop] = config2[prop]
}
})
// #ifdef H5 || APP-PLUS
if (isUndefined(config.timeout) && !isUndefined(globalsConfig.timeout)) {
config.timeout = globalsConfig.timeout
}
// #endif
} else {
const defaultsKeys = [
'data',
// #ifdef H5 || APP-PLUS || MP-ALIPAY || MP-WEIXIN
'timeout',
// #endif
'dataType',
// #ifndef MP-ALIPAY
'responseType',
// #endif
// #ifdef APP-PLUS
'sslVerify',
// #endif
// #ifdef H5
'withCredentials',
// #endif
// #ifdef APP-PLUS
'firstIpv4'
// #endif
]
config = { ...config, ...mergeKeys(defaultsKeys, globalsConfig, config2) }
}
return config
}

View File

@ -0,0 +1,16 @@
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*/
export default function settle(resolve, reject, response) {
const { validateStatus } = response.config
const status = response.statusCode
if (status && (!validateStatus || validateStatus(status))) {
resolve(response)
} else {
reject(response)
}
}

View File

@ -0,0 +1,69 @@
'use strict'
import * as utils from '../utils'
function encode(val) {
return encodeURIComponent(val)
.replace(/%40/gi, '@')
.replace(/%3A/gi, ':')
.replace(/%24/g, '$')
.replace(/%2C/gi, ',')
.replace(/%20/g, '+')
.replace(/%5B/gi, '[')
.replace(/%5D/gi, ']')
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @returns {string} The formatted url
*/
export default function buildURL(url, params) {
/* eslint no-param-reassign:0 */
if (!params) {
return url
}
let serializedParams
if (utils.isURLSearchParams(params)) {
serializedParams = params.toString()
} else {
const parts = []
utils.forEach(params, (val, key) => {
if (val === null || typeof val === 'undefined') {
return
}
if (utils.isArray(val)) {
key = `${key}[]`
} else {
val = [val]
}
utils.forEach(val, (v) => {
if (utils.isDate(v)) {
v = v.toISOString()
} else if (utils.isObject(v)) {
v = JSON.stringify(v)
}
parts.push(`${encode(key)}=${encode(v)}`)
})
})
serializedParams = parts.join('&')
}
if (serializedParams) {
const hashmarkIndex = url.indexOf('#')
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex)
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams
}
return url
}

View File

@ -0,0 +1,14 @@
'use strict'
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
* @returns {string} The combined URL
*/
export default function combineURLs(baseURL, relativeURL) {
return relativeURL
? `${baseURL.replace(/\/+$/, '')}/${relativeURL.replace(/^\/+/, '')}`
: baseURL
}

View File

@ -0,0 +1,14 @@
'use strict'
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
export default function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url)
}

View File

@ -0,0 +1,116 @@
type AnyObject = Record<string | number | symbol, any>
type HttpPromise<T> = Promise<HttpResponse<T>>;
type Tasks = UniApp.RequestTask | UniApp.UploadTask | UniApp.DownloadTask
export interface RequestTask {
abort: () => void;
offHeadersReceived: () => void;
onHeadersReceived: () => void;
}
export interface HttpRequestConfig<T = Tasks> {
/** 请求基地址 */
baseURL?: string;
/** 请求服务器接口地址 */
url?: string;
/** 请求查询参数,自动拼接为查询字符串 */
params?: AnyObject;
/** 请求体参数 */
data?: AnyObject;
/** 文件对应的 key */
name?: string;
/** HTTP 请求中其他额外的 form data */
formData?: AnyObject;
/** 要上传文件资源的路径。 */
filePath?: string;
/** 需要上传的文件列表。使用 files 时filePath 和 name 不生效App、H5 2.6.15+ */
files?: Array<{
name?: string;
file?: File;
uri: string;
}>;
/** 要上传的文件对象仅H52.6.15+)支持 */
file?: File;
/** 请求头信息 */
header?: AnyObject;
/** 请求方式 */
method?: "GET" | "POST" | "PUT" | "DELETE" | "CONNECT" | "HEAD" | "OPTIONS" | "TRACE" | "UPLOAD" | "DOWNLOAD";
/** 如果设为 json会尝试对返回的数据做一次 JSON.parse */
dataType?: string;
/** 设置响应的数据类型,支付宝小程序不支持 */
responseType?: "text" | "arraybuffer";
/** 自定义参数 */
custom?: AnyObject;
/** 超时时间仅微信小程序2.10.0)、支付宝小程序支持 */
timeout?: number;
/** DNS解析时优先使用ipv4仅 App-Android 支持 (HBuilderX 2.8.0+) */
firstIpv4?: boolean;
/** 验证 ssl 证书 仅5+App安卓端支持HBuilderX 2.3.3+ */
sslVerify?: boolean;
/** 跨域请求时是否携带凭证cookies仅H5支持HBuilderX 2.6.15+ */
withCredentials?: boolean;
/** 返回当前请求的task, options。请勿在此处修改options。 */
getTask?: (task: T, options: HttpRequestConfig<T>) => void;
/** 全局自定义验证器 */
validateStatus?: (statusCode: number) => boolean | void;
}
export interface HttpResponse<T = any> {
config: HttpRequestConfig;
statusCode: number;
cookies: Array<string>;
data: T;
errMsg: string;
header: AnyObject;
}
export interface HttpUploadResponse<T = any> {
config: HttpRequestConfig;
statusCode: number;
data: T;
errMsg: string;
}
export interface HttpDownloadResponse extends HttpResponse {
tempFilePath: string;
}
export interface HttpError {
config: HttpRequestConfig;
statusCode?: number;
cookies?: Array<string>;
data?: any;
errMsg: string;
header?: AnyObject;
}
export interface HttpInterceptorManager<V, E = V> {
use(
onFulfilled?: (config: V) => Promise<V> | V,
onRejected?: (config: E) => Promise<E> | E
): void;
eject(id: number): void;
}
export abstract class HttpRequestAbstract {
constructor(config?: HttpRequestConfig);
config: HttpRequestConfig;
interceptors: {
request: HttpInterceptorManager<HttpRequestConfig, HttpRequestConfig>;
response: HttpInterceptorManager<HttpResponse, HttpError>;
}
middleware<T = any>(config: HttpRequestConfig): HttpPromise<T>;
request<T = any>(config: HttpRequestConfig<UniApp.RequestTask>): HttpPromise<T>;
get<T = any>(url: string, config?: HttpRequestConfig<UniApp.RequestTask>): HttpPromise<T>;
upload<T = any>(url: string, config?: HttpRequestConfig<UniApp.UploadTask>): HttpPromise<T>;
delete<T = any>(url: string, data?: AnyObject, config?: HttpRequestConfig<UniApp.RequestTask>): HttpPromise<T>;
head<T = any>(url: string, data?: AnyObject, config?: HttpRequestConfig<UniApp.RequestTask>): HttpPromise<T>;
post<T = any>(url: string, data?: AnyObject, config?: HttpRequestConfig<UniApp.RequestTask>): HttpPromise<T>;
put<T = any>(url: string, data?: AnyObject, config?: HttpRequestConfig<UniApp.RequestTask>): HttpPromise<T>;
connect<T = any>(url: string, data?: AnyObject, config?: HttpRequestConfig<UniApp.RequestTask>): HttpPromise<T>;
options<T = any>(url: string, data?: AnyObject, config?: HttpRequestConfig<UniApp.RequestTask>): HttpPromise<T>;
trace<T = any>(url: string, data?: AnyObject, config?: HttpRequestConfig<UniApp.RequestTask>): HttpPromise<T>;
download(url: string, config?: HttpRequestConfig<UniApp.DownloadTask>): Promise<HttpDownloadResponse>;
setConfig(onSend: (config: HttpRequestConfig) => HttpRequestConfig): void;
}
declare class HttpRequest extends HttpRequestAbstract { }
export default HttpRequest;

View File

@ -0,0 +1,3 @@
import Request from './core/Request'
export default Request

Some files were not shown because too many files have changed in this diff Show More