Commit fd7f50f5 by pangchong

Initial commit

parents

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

node_modules/
.project
unpackage/
.DS_Store
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Editor directories and files
.project
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw*
{
// launch.json 配置了启动调试时相关设置,configurations下节点名称可为 app-plus/h5/mp-weixin/mp-baidu/mp-alipay/mp-qq/mp-toutiao/mp-360/
// launchtype项可配置值为local或remote, local代表前端连本地云函数,remote代表前端连云端云函数
"version" : "0.0",
"configurations" : [
{
"app-plus" :
{
"launchtype" : "remote"
},
"default" :
{
"launchtype" : "remote"
},
"h5" :
{
"launchtype" : "remote"
},
"mp-weixin" :
{
"launchtype" : "remote"
},
"type" : "uniCloud"
},
{
"playground" : "standard",
"type" : "uni-app:app-android"
},
{
"playground" : "standard",
"type" : "uni-app:app-ios"
}
]
}
<script lang="ts" setup>
import { onHide, onLaunch, onShow } from "@dcloudio/uni-app";
// import {
// request,
// ipConfig
// } from '@/utils/request.js';
// import apiMapper from '@/apiMapper/index.js';
import { secondGenerationAppUpdate } from "@/common/appUpdate.js";
onLaunch(() => {
console.log("App Launch");
// 自动检测
setTimeout(() => {
// 获取版本号
let clent = uni.getSystemInfoSync();
let version = '';
// #ifdef APP
version = clent.appWgtVersion;
// #endif
// #ifdef H5
version = clent.appVersion;
// #endif
if (clent.platform == 'android') {
secondGenerationAppUpdate(version || 0, 'Android');
} else {
secondGenerationAppUpdate(version || 0, 'IOS');
}
}, 50)
ammsLaunch();
});
onShow(() => {
console.log("App Show");
});
onHide(() => {
console.log("App Hide");
});
function ammsLaunch() {
// 设置域名参数
uni.setStorageSync("_PARAMETERS_", "10076");
// uni.setStorageSync('urlPrefix', window.location.origin)
}
</script>
<style lang="less">
/* #ifndef APP-NVUE */
@import "colorui/main.css";
@import "colorui/icon.css";
/* @import "uni.scss"; */
/*每个页面公共css */
@import "static/style/public.less";
/* #endif */
uni-page-body {
height: 100%;
overflow: auto;
}
.h1 {
height: 70upx;
}
.home {
overflow-y: scroll;
}
.uni-modal__bd {
text-align: left;
}
</style>
<style lang="scss">
/* 注意要写在第一行,同时给style标签加入lang="scss"属性 */
@import "uview-plus/index.scss";
// 加入mocp主题相关样式
@import "mocpStatic/css/theme.scss";
// 加入mocp字体图标
@import "mocpStatic/font/iconfont.css";
</style>
## 运行方式
将项目拖入[HbuilderX](http://www.dcloud.io/hbuilderx.html),直接运行即可
## 开发建议
使用HbuilderX开发工具
## 注意事项
* 页面初始化完毕后马上跳转页面可能会失败,可以尝试延迟执行
import {
iamUrlMapper,
authLoginMapper,
printerMapper,
ecmMapper,
appsrvMapper,
adminMapper,
msgpushMapper,
swConfigurationMapper,
tdmsMapper,
announcementMapper,
lmoMapper,
tmsMapper,
acMapper,
outUrlMapper,
upointMapper,
ddfcMapper,
billMapper,
iotMapper,
staffMapper,
appadminMapper,
oilMapper
} from './opt'
const apiMappers = {
...iamUrlMapper,
...authLoginMapper,
...printerMapper,
...ecmMapper,
...appsrvMapper,
...adminMapper,
...msgpushMapper,
...swConfigurationMapper,
...tdmsMapper,
...announcementMapper,
...lmoMapper,
...tmsMapper,
...acMapper,
...outUrlMapper,
...upointMapper,
...ddfcMapper,
...billMapper,
...iotMapper,
...staffMapper,
...appadminMapper,
...oilMapper
}
export default apiMappers
\ No newline at end of file
import { mesUrlPrefix } from '@/utils/request.js'
const configs = {
dev: {
// url: 'http://mes.hnatechnic.com/papi',
// url: 'http://10.52.21.60:10066/papi',
// url: '/papi',
url: mesUrlPrefix,
appVersion: '6',
appId: 'elb',
appSecret: 'A2FFDDCED795F4EE8F4E7ABC0E17944D'
},
prod: {
// url: 'http://mes.hnatechnic.com/papi',
// url: 'http://10.52.21.60:10066/papi',
// url: '/papi',
url: mesUrlPrefix,
appVersion: '6',
appId: 'elb',
appSecret: 'A2FFDDCED795F4EE8F4E7ABC0E17944D'
}
}
const config = process.env.NODE_ENV == 'development' ? configs.dev : configs.prod;
export default config;
\ No newline at end of file
export function setUser(user) {
uni.setStorageSync('mes_user_info', user)
}
export function getUser() {
return uni.getStorageSync('mes_user_info')
}
export function setSource(data) {
uni.setStorageSync('mes_filter_source', data)
}
export function getSource() {
return uni.getStorageSync('mes_filter_source')
}
export function clearSource() {
return uni.removeStorageSync('mes_filter_source')
}
export function setOtherSource(data) {
uni.setStorageSync('mes_other_filter_source', data)
}
export function getOtherSource() {
return uni.getStorageSync('mes_other_filter_source')
}
export function clearOtherSource() {
return uni.removeStorageSync('mes_other_filter_source')
}
export function setInspectSource(data) {
uni.setStorageSync('mes_inspect_filter_source', data)
}
export function getInspectSource() {
return uni.getStorageSync('mes_inspect_filter_source')
}
export function clearInspectSource() {
return uni.removeStorageSync('mes_inspect_filter_source')
}
export function setCardSource(data) {
uni.setStorageSync('mes_card_filter_source', data)
}
export function getCardSource() {
return uni.getStorageSync('mes_card_filter_source')
}
export function clearCardSource() {
return uni.removeStorageSync('mes_card_filter_source')
}
export function setNrcSource(data) {
uni.setStorageSync('mes_nrc_filter_source', data)
}
export function getNrcSource() {
return uni.getStorageSync('mes_nrc_filter_source')
}
export function clearNrcSource() {
return uni.removeStorageSync('mes_nrc_filter_source')
}
\ No newline at end of file
import { dictData } from './dictData.js'
export function getDictList(dict){
return dictData.filter(r => r.type == dict);
}
// 获取字典编码对应名称
export function getDictName(dict, v) {
if (!v) return '';
const codeList = getDictList(dict);
if (!codeList) return '';
const o = codeList.find((r) => r.key == v);
if (!o) return '';
return o.value || '';
}
export function getPartOffReason() {
return [{ value: '01', text: '实物件序号不详' }, { value: '02', text: '实物件序号系统不存在' }];
}
export function getPartOnReason() {
return [{ value: '01', text: '从库房领出' }, { value: '02', text: '从飞机拆下' }];
}
export function getPartSnMode() {
return [{ value: '1', text: '序控件' }, { value: '2', text: '非序控件' }];
}
export function getPartActivePassive() {
return [{ value: '1', text: '主串' }, { value: '2', text: '被串' }];
}
export function getPartOb() {
return [{ value: 'A', text: '不可用' }, { value: 'B', text: '可用' }, { value: 'C', text: '观察件' }];
}
// 获取字典编码列表对应名称列表,转字符串,逗号分割
// function getDictNames(dict: string, v?: string | string[]): string {
// if (!v) return '';
// const codeList = getDictList(dict);
// if (!codeList) return '';
// const vs = typeof (v) == 'string' ? v.split(',') : v;
// const list = codeList.filter((r: any) => vs.findIndex((_v) => _v == r.code) != -1);
// if (list.length == 0) return '';
// let lang = uni.getLocale();
// if (lang == 'zh-Hans') lang = 'zh';
// const names: string[] = [];
// list.forEach((r: any) => {
// if (r[lang]) names.push(r[lang]);
// })
// return names.join(',');
// }
// 获取字典编码列表对应名称列表
// function getDictNameList(dict: string, v?: string | string[]): string[] {
// if (!v) return [];
// const codeList = getDictList(dict);
// if (!codeList) return [];
// const vs = typeof (v) == 'string' ? v.split(',') : v;
// const list = codeList.filter((r: any) => vs.findIndex((_v) => _v == r.code) != -1);
// if (list.length == 0) return [];
// let lang = uni.getLocale();
// if (lang == 'zh-Hans') lang = 'zh';
// const names: string[] = [];
// list.forEach((r: any) => {
// if (r[lang]) names.push(r[lang]);
// })
// return names;
// }
//获取字典列表
// function getDictOption(dict: string, textField?: string): Option[] {
// const codeList = getDictList(dict);
// if (!codeList) return [];
// let lang = uni.getLocale();
// if (lang == 'zh-Hans') lang = 'zh';
// const arr: any[] = [];
// codeList.forEach((r: any) => {
// const v = { value: r.code, type: r.type };
// if (v[textField || 'text'] = r[lang]) arr.push(v);
// })
// return arr;
// }
//获取字典映射
// function getDictMap(dict: string): any {
// const codeList = getDictList(dict);
// if (!codeList) return [];
// let lang = uni.getLocale();
// if (lang == 'zh-Hans') lang = 'zh';
// const map = {};
// codeList.forEach((r: any) => {
// map[r.code] = r[lang] || '';
// })
// return map;
// }
// 获取字典项
// function getDictItem(dict: string, code: string): Dict | undefined {
// if (!dict || !code) return null;
// const codeList = getDictList(dict);
// if (!codeList) return null;
// return codeList.find((r: Dict) => r.code == code);
// }
import config from './config.js'
import { getUser} from "./ctx.js"
//Post方式提交信息
export function post(url, data, options) {
const userInfo = getUser();
const header = {
"Content-Type": "application/json",
// "appId": config.appId,
// "appSecret": config.appSecret
};
if (userInfo && userInfo.token) header["zy_token"] = userInfo.token;
const {
timeout
} = options || {};
return new Promise((resolve, reject) => {
uni.request({
url: config.url + url,
method: "POST",
header,
data,
sslVerify: false,
timeout,
success(res) {
if (res.statusCode == 200) {
const r = res.data
if (r.code > 0){
r.code == 2 ? resolve(r) :resolve(r.data)
}else if(r.code === -1000){
uni.showModal({
title:'温馨提示',
content:'token失效,即将返回个人中心',
showCancel: false,
success: (res) => {
            uni.reLaunch({
                url: '/pages/home/homeIndex'
            })
}
})
}else{
/* tsk/pack/page为分页接口,没有code传回 */
if(url==='/tsk/pack/page'){
resolve(r)
}else{
reject(r)
}
}
} else reject({
code: -500,
msg: JSON.stringify(res)
})
},
fail(err) {
reject({
code: -500,
msg: JSON.stringify(err)
});
}
})
})
}
// Get方式提交
export function get(url, data) {
const userInfo = getUser();
const header = {
"Content-Type": "application/json",
// "appId": config.appId,
// "appSecret": config.appSecret
};
if (userInfo && userInfo.token) header["zy_token"] = userInfo.token;
return new Promise((resolve, reject) => {
uni.request({
url: config.url + url,
method: "POST",
header,
data,
sslVerify: false,
success(res) {
if (res.statusCode == 200) {
const r = res.data
if (r.code > 0){
resolve(r.data)
}else if(r.code === -1000){
uni.showModal({
title:'温馨提示',
content:'token失效,即将返回个人中心',
showCancel: false,
success: (res) => {
            uni.reLaunch({
                url: '/pages/home/homeIndex'
            })
}
})
}else{
reject(r)
}
} else reject({
code: -500,
msg: JSON.stringify(res)
})
},
fail(err) {
reject({
code: -500,
msg: JSON.stringify(err)
});
}
})
})
}
//Post方式提交信息
export function filePost(url, data, options) {
const userInfo = getUser();
const header = {
"Content-Type": "application/json",
// "appId": config.appId,
// "appSecret": config.appSecret
};
if (userInfo && userInfo.token) header["zy_token"] = userInfo.token;
const {
timeout
} = options || {};
return new Promise((resolve, reject) => {
uni.request({
url: config.url.replace(/\/papi$/,'/file-api') + url,
method: "POST",
header,
data,
sslVerify: false,
timeout,
success(res) {
if (res.statusCode == 200) {
const r = res.data
if (r.code > 0){
r.code == 2 ? resolve(r) :resolve(r.data)
}else if(r.code === -1000){
uni.showModal({
title:'温馨提示',
content:'token失效,即将返回个人中心',
showCancel: false,
success: (res) => {
            uni.reLaunch({
                url: '/pages/home/homeIndex'
            })
}
})
}else{
/* tsk/pack/page为分页接口,没有code传回 */
if(url==='/tsk/pack/page'){
resolve(r)
}else{
reject(r)
}
}
} else reject({
code: -500,
msg: JSON.stringify(res)
})
},
fail(err) {
reject({
code: -500,
msg: JSON.stringify(err)
});
}
})
})
}
// Post方式提交文件
export function uploadFile(url, file, data, options) {
const userInfo = getUser();
const header = {}
if (userInfo && userInfo.token) header["zy_token"] = userInfo.token;
const {
timeout
} = options || {};
//null值不提交
const formData = {};
if (data) {
for (let k in data) {
const v = data[k];
if (v == null || v == '') continue;
formData[k] = v;
}
}
return new Promise((resolve, reject) => {
uni.uploadFile({
url: config.url.replace(/\/papi$/,'/file-api') + url,
header,
filePath: file,
name: 'file',
formData: formData,
timeout,
success(res) {
if (res.statusCode == 200) {
const r = typeof(res.data) == 'string' ? JSON.parse(res.data) : res.data;
if (r.code > 0){
resolve(r.data)
}else if(r.code === -1000){
uni.showModal({
title:'温馨提示',
content:'token失效,即将返回个人中心',
showCancel: false,
success: (res) => {
            uni.reLaunch({
                url: '/pages/home/homeIndex'
            })
}
})
}else{
reject(r)
}
} else reject({
code: -500,
msg: JSON.stringify(res)
})
},
fail(err) {
console.log(err)
reject({
code: -500,
msg: JSON.stringify(err)
});
}
})
})
}
//识别航材
export function recogineseMat(path) {
const userInfo = getUser();
const header = { 'zy_token': userInfo.token };
return new Promise((resolve, reject) => {
uni.uploadFile({
url: config.url + '/tool/recognise/pn',
filePath: path,
name: 'file',
header,
timeout: 120000,
success:(res)=> {
if (res.statusCode == 200) {
const r = typeof res.data == 'string' ? JSON.parse(res.data) : res.data;
if (r.code > 0) {
resolve(r.data);
}else if(r.code === -1000){
uni.showModal({
title:'温馨提示',
content:'token失效,即将返回个人中心',
showCancel: false,
success: (res) => {
            uni.reLaunch({
                url: '/pages/home/homeIndex'
            })
}
})
}else{
reject(r);
}
} else reject({ code: -500, msg: JSON.stringify(res) });
},
fail:(err)=> {
// console.log(err, uri)
reject({ code: -500, msg: JSON.stringify(err) });
}
});
});
}
\ No newline at end of file
import { getDictName } from './dict.js'
// 任务状态
export function getStautsText(type, data) {
let text
data ? text = getDictName(type, data) : text = ''
return text
}
// 接口地址映射
let prefix = 'ac'
const apiObj = {
// 航站查询
'terminal-select': `/mroapi/${prefix}/terminal/select`
}
export default apiObj
const prefix = '/mroapi/admin'
// 接口地址映射
const apiObj = {
// 通过类型获取字典
'dict-byType': `${prefix}/dict/type/{type}`,
'getZsydxDict': `${prefix}/dict/type/zsydx`,
'dept-byId': `${prefix}/dept/{id}`,
'getFactoryDict': `${prefix}/dict/type/factory`,
'getWarehouseDict': `${prefix}/dict/type/warehouse`,
'getMenu': `${prefix}/menu`,
'getUserInfo': `${prefix}/user/info`,
// 修改用户信息
'updateUserInfo': `${prefix}/user/edit`,
// infoCurrentAccount
'appInfo': `${prefix}/user/app/info`,
// 查询应用菜单列表 "name": "日常盘点","parentid":"10076"
'appmenu-selectMenu': `${prefix}/appmenu/selectMenu`,
// 查询五条热门菜单 "parentid":"10076"
'appmenu-selectPopularCollects': `${prefix}/appmenu/selectPopularCollects`,
// 查询个人的五条热门菜单 "parentid":"10076"
'appmenu-selectHotMenuCollects': `${prefix}/appmenu/selectHotMenuCollects`,
// 查询个人的10条热门菜单 "parentid":"10076"
'appmenu-selectHotMenuCollectsWithTen': `${prefix}/appmenu/selectHotMenuCollectsWithTen`,
// 查询用户收藏菜单,(ifdefault标识是否默认菜单,0否1是)
'appmenu-selectMenuCollectPage': `${prefix}/appmenu/selectMenuCollectPage`,
// 添加收藏菜单 "menuId":10078
'appmenu-saveMenuCollect': `${prefix}/appmenu/saveMenuCollect`,
// 更新排序值
'appmenu-menuResort': `${prefix}/appmenu/menuResort`,
// 移除菜单 "menuId":10078
'appmenu-deleteMenuCollect': `${prefix}/appmenu/deleteMenuCollect`,
// 保存菜单点击,每点击菜单进入的时候记录一次 "menuId":10078
'appmenu-saveClick': `${prefix}/appmenu/saveClick`,
// 单位
'review-unit_type': `${prefix}/dict/type/unit_type`,
// 类别
'review-category_type': `${prefix}/dict/type/category_type`,
}
export default apiObj
const prefix = '/mroapi/version'
const apiObj = {
// 版本变更内容
'versioncontent': `${prefix}/versioncontent`, // 新增、修改
'versioncontent-byid': `${prefix}/versioncontent/{id}`, // 查询详情、删除
'versioncontent-page': `${prefix}/versioncontent/page`, // 分页查询
// 版本管理
'version': `${prefix}/version`, // 新增、修改
'version-byid': `${prefix}/version/{id}`, // 查询详情、删除
'version-page': `${prefix}/version/page`, // 分页查询
'version-permission': `${prefix}/version/permission` // 判断人员权限
}
export default apiObj
\ No newline at end of file
// 接口地址映射
const apiObj = {
// 获取行政区划信息
'adcodeAndCityCode-getInfo': `/mroapi/appadmin/adcodeAndCityCode/getInfo`,
// 新闻资讯 分页
'news-selectappnewspage': `/mroapi/appadmin/news/selectAppNewsPage`,
// 详情
'news-selectOneNews': `/mroapi/appadmin/news/selectOneNews`,
// 查询是不是最新版本号
'appUpgradeAll': `/mroapi/appadmin/appUpgradeAll/selectLatestVersion`,
// 消息
// 用户查询自己消息(APP)page:第几页 length:查询数量 title:标题 content:内容 createTime:创建时间
'appMsgNotify-selectUserMsgPage': `/mroapi/appadmin/appMsgNotify/selectUserMsgPage`,
// 标识消息为已读状态(APP)id:消息id
'appMsgNotify-readMsg': `/mroapi/appadmin/appMsgNotify/readMsg`,
// 标识消息为全部已读状态(APP)
'appMsgNotify-readAllMsg': `/mroapi/appadmin/appMsgNotify/readAllMsg`,
// 用户删除单条消息(APP)id:消息id
'appMsgNotify-deleteMsgByUser': `/mroapi/appadmin/appMsgNotify/deleteMsgByUser`,
// 用户删除全部消息(APP)
'appMsgNotify-deleteAllMsgByUser': `/mroapi/appadmin/appMsgNotify/deleteAllMsgByUser`,
// 详情
'appMsgNotify-selectOneMsg': `/mroapi/appadmin/appMsgNotify/selectOneMsg`,
'downloadApkByIdAll': `/mroapi/appadmin/appUpgradeAll/objectStorage/GetDoc/downloadApkById`,
// 安全周报 分页
'news-selectQualitySafetyPage': `/mroapi/appadmin/news/selectQualitySafetyPage`
}
export default apiObj
\ No newline at end of file
// 接口地址映射
const prefix = '/mroapi/auth'
const apiObj = {
// 域账号登录iam
'cas-login': `${prefix}/iam/token`,
// 普通登录
'auth-login': `${prefix}/oauth/token`,
// 退出登录
'logout': `${prefix}/token/logout`,
'checkToken': `${prefix}/oauth/check_token`
}
export default apiObj
\ No newline at end of file
// 接口地址映射
let prefix = 'bil'
const apiObj = {
// 航线模块
'bil-route-getBaseInfo': `/mroapi/${prefix}/route/getBaseInfo`, // 获取基础信息
'bil-route-getUserTodayTask': `/mroapi/${prefix}/route/getUserTodayTask`, // 获取今日签单
'bil-route-routineMaintenance': `/mroapi/${prefix}/route/routineMaintenance`, // 提交例行维护工作单
'bil-route-nonRoutineMaintenance': `/mroapi/${prefix}/route/nonRoutineMaintenance`, // 非例行维护工作单
'bil-route-temporaryTransit': `/mroapi/${prefix}/route/temporaryTransit`, // 临时性过站收费单
'bil-route-yunnan36HourInspection': `/mroapi/${prefix}/route/yunnan36HourInspection`, // 海技云南36小时检工作单
'bil-route-deicing': `/mroapi/${prefix}/route/deicing`, // 海航技术除防冰收费单
'bil-route-personnelAssignment': `/mroapi/${prefix}/route/personnelAssignment`, // 人员委派单
'bil-route-warehouseUse': `/mroapi/${prefix}/route/warehouseUse` // 航线库房使用收费单
}
export default apiObj
// 接口地址映射
let prefix = 'ddfc'
const apiObj = {
// ddfc--分页查询
'ddfc-page': `/mroapi/${prefix}/ddfc/searchfromsap`,
// ddfc--查询详情
'ddfc-zwfidAmi': `/mroapi/${prefix}/ddfc/idfromsap/{zwfidAmi}`,
// ddfc--数据字典
'ddfc-dict': `/mroapi/${prefix}/dict/{id}`
}
export default apiObj
\ No newline at end of file
// 接口地址映射
const prefix = '/mroapi/ecm'
const apiObj = {
'upload': `${prefix}/objectStorage/external/mobile/upload`, // 上传文件(外部APP)
'getDoc': `${prefix}/objectStorage/external/mobile/GetDoc`, // 预览或下载文件(移动端APP调用)
'getDocNew': `${prefix}/objectStorage/GetDoc/external/mobile`, // 下载图片新接口
'diskDownload': `${prefix}/diskStorage/external/download`, // 预览或下载文件
'getDoc-external': `${prefix}/objectStorage/GetDoc/external`,
'diskUpload': (path) => {
return `${prefix}/diskStorage/external/${path}` // 上传文件
}
}
export default apiObj
// 接口地址映射
const apiObj = {
// iam测试
"iam-test": `http://10.127.12.11:8080/casapp/casapp.html`,
// iam-正式
"iam-formal": `https://amms.hnatechnic.com/casapp/casapp.html`,
// iam-h5
"iam-h5": `/mroapp/index.html#/pages/login/iam-h5`,
};
export default apiObj;
export { default as iamUrlMapper } from './iamUrlMapper'
export { default as authLoginMapper } from './authLoginMapper'
export { default as printerMapper } from './printerMapper'
export { default as ecmMapper } from './ecmMapper'
export { default as appsrvMapper } from './appsrvMapper'
export { default as adminMapper } from './adminMapper'
export { default as msgpushMapper } from './msgpushMapper'
export { default as swConfigurationMapper } from './swConfigurationMapper'
export { default as tdmsMapper } from './tdmsMapper'
export { default as announcementMapper } from './announcementMapper'
export { default as lmoMapper } from './lmoMapper'
export { default as tmsMapper } from './tmsMapper'
export { default as acMapper } from './acMapper'
export { default as outUrlMapper } from './outUrlMapper'
export { default as upointMapper } from './upointMapper'
export { default as ddfcMapper } from './ddfcMapper'
export { default as billMapper } from './billMapper'
export { default as iotMapper } from './iotMapper'
export { default as staffMapper } from './staffMapper'
export { default as appadminMapper } from './appadminMapper'
export { default as oilMapper } from './oilMapper'
\ No newline at end of file
// 接口地址映射
let prefix = 'iot'
const apiObj = {
// 工具故障送修管理
'iot-sxfaultreportitem': `/mroapi/${prefix}/sxfaultreportitem`, // 新增、修改
'iot-sxfaultreportitem-byid': `/mroapi/${prefix}/sxfaultreportitem/{id}`, // 通过id查询、删除
'iot-sxfaultreportitem-page': `/mroapi/${prefix}/sxfaultreportitem/page` // 分页
}
export default apiObj
// 接口地址映射
let prefix = 'lmo'
const apiObj = {
// lmo--分页查询
'lmo-page': `/mroapi/${prefix}/lmo/page`,
// lmo--新增、编辑
'lmo': `/mroapi/${prefix}/lmo`,
// lmo--根据id删除、查询
'lmo-byid': `/mroapi/${prefix}/lmo/{lmoId}`,
// lmo--列表查询
'lmo-list': `/mroapi/${prefix}/lmo/list`,
// lmo--通过esb接口查询人员授权信息,再通过机型来过滤权限
'lmo-getUserArchivesInfo-byActype': `/mroapi/${prefix}/lmo/getUserArchivesInfo/{actype}`,
// lmo--通过esb接口查询人员授权信息
'lmo-getUserArchivesInfo-byUserid': `/mroapi/${prefix}/lmo/getUserArchivesInfo/byUser/{userId}`
}
export default apiObj
\ No newline at end of file
// 接口地址映射
const prefix = '/mroapi/msgpush'
const apiObj = {
'info-page': `${prefix}/msg/info/page`, // 我的消息分页查询
'info-history': `${prefix}/msg/info/list/{msgInfoId}`,
'subscribe-page': `${prefix}/msg/subscribe/page`, // 消息通知查询
'subscribe': `${prefix}/msg/subscribe`, // 新增关注
'subscribe-byid': `${prefix}/msg/subscribe/{id}`, // 通过id查询、删除
'topic-list': `${prefix}/msg/topic/list`, // 消息业务主题列表
'subscribe-config-topic': `${prefix}/msg/subscribe-config-topic`, // 消息配置新增、编辑
'subscribe-config-topic-list': `${prefix}/msg/subscribe-config-topic/list`, // 已配置消息列表
'subscribe-config-topic-byid': `${prefix}/msg/subscribe-config-topic/{id}`, // 通过id删除已配置消息
'topic-node-byTopicId': `${prefix}/msg/topic-node/topic/{topicId}`, // 业务主题查询业务主题节点`
'user-device': `${prefix}/msg/user-device`, // 设备终端新增
'msg-info-no': `${prefix}/msg/info/no` // 查询未查看消息数量
}
export default apiObj
// 接口地址映射
let prefix = 'oil'
const apiObj = {
// 油单确认--分页查询
'confirmation-page': `/mroapi/${prefix}/confirmation/page`,
// 油单确认--新增、编辑
'confirmation': `/mroapi/${prefix}/confirmation`,
// 油单确认--根据id删除、查询
'confirmation-fsid': `/mroapi/${prefix}/confirmation/{fsid}`,
// 用油需求--分页查询
'demand-page': `/mroapi/${prefix}/demand/page`,
// 用油需求--新增、编辑
'demand': `/mroapi/${prefix}/demand`,
// 用油需求--暂存需求单
'demand-store': `/mroapi/${prefix}/demand/store`,
// 用油需求--上传需求单
'demand-upload': `/mroapi/${prefix}/demand/upload`,
// 用油需求--通过fnkey撤回需求单
'demand-withdraw': `/mroapi/${prefix}/demand/withdraw/{fnkey}`,
// 用油需求--根据id删除、查询
'demand-fnkey': `/mroapi/${prefix}/demand/{fnkey}`,
// 油单确认测试
'refueling-page': `/mroapi/${prefix}/refueling/page`
}
export default apiObj
\ No newline at end of file
// 接口地址映射
const apiObj = {
// 高德地图天气查询API
'weather-weatherInfo': `https://restapi.amap.com/v3/weather/weatherInfo`,
// 高德地图逆地理编码
'geocode-regeo': `https://restapi.amap.com/v3/geocode/regeo?parameters`
}
export default apiObj
// 接口地址映射
const apiObj = {
'printer': `/mroapi/printer/printer/page`,
'auth_printer': `/mroapi/printer/printerhostauthority/auth_printer`, // 获取授权打印机列表
'setDefaultPrinter': `/mroapi/printer/printer/setDefault` ,// 设置默认打印机
'printjobTest': `/mroapi/printer/printjob/test` ,// 新增测试打印任务
}
export default apiObj
let prefix = '/mroapi/staff';
const apiObj = {
// 分支 中心 vcparentid orgId=0-1-3-847038-12387-12395-
'tecstaff-staff': `${prefix}/tecstaff/staff`,
// 叶子 查询 姓名 key=郑德勇
'tecstaff-staffByKey': `${prefix}/tecstaff/staffByKey`
}
export default apiObj
\ No newline at end of file
// 接口地址映射
let prefix = 'sw'
const apiObj = {
// 软件构型--分页查询
'swaudittask-page': `/mroapi/${prefix}/swaudittask/page`,
// 软件构型--新增、编辑
'swaudittask': `/mroapi/${prefix}/swaudittask`,
// 软件构型--根据id删除、查询
'swaudittask-byid': `/mroapi/${prefix}/swaudittask/{id}`,
// 软件构型--查询机型
'swaudittask-allModel': `/mroapi/${prefix}/swaudittask/allModel`,
// 软件构型--查询基地
'swaudittask-base': `/mroapi/${prefix}/swaudittask/base`,
// 软件构型--查询章节
'swaudittask-allAta': `/mroapi/${prefix}/swaudittask/allAta`,
// 软件构型--根据机型、章节、软件件号查询软件名
'swaudittask-swName': `/mroapi/${prefix}/swaudittask/swName`,
// 软件构型--根据机型查飞机
'swaudittask-acreg': `/mroapi/${prefix}/swaudittask/acreg`,
// 软件构型--复核查询
'swaudittask-select': `/mroapi/${prefix}/swaudittask/select`,
// 软件构型--复核
'swaudittask-audit': `/mroapi/${prefix}/swaudittask/audit`,
// 软件构型--查询台账基地是否与审核人所属基地一致
'swaudittask-auditBase': `/mroapi/${prefix}/swaudittask/auditBase`,
// 软件构型--预设构型查询
'swaudittask-predict': `/mroapi/${prefix}/swaudittask/predict`,
// 软件构型--复核记录
'swaudittask-history': `/mroapi/${prefix}/swaudittask/history`,
// 软件构型--查询787机型位置信息
'swaudittask-787odlf': `/mroapi/${prefix}/swaudittask/787odlf`
}
export default apiObj
\ No newline at end of file
const prefix = 'tdms'
const apiObj = {
// ta查询--查询
'ta-search': `/mroapi/${prefix}/ta`,
// ta查询--根据功能码查询枚举值
'ta-eurm': `/mroapi/${prefix}/ta/eurm`,
// ta查询--查询营运人
'ta-operator': `/mroapi/${prefix}/ta/operator`,
// ta查询--查询ta机型
'ta-model': `/mroapi/${prefix}/ta/model`,
// 飞机管理--根据机型获取飞机
'daAcreg-getByZstort': `/mroapi/${prefix}/daAcreg/getByZstort`,
// 根据机号查飞机信息,包含机型
'daAcreg-getByAcno': `/mroapi/${prefix}/daAcreg/getByAcno/{acno}`,
// 根据机号查飞机信息,包含航班号(仅适用于机务用油)
'daAcreg-oilbyacno': `/mroapi/${prefix}/daAcreg/oil/{acno}`,
// 通讯 - 总树 部门 0-1-3-847038-12387-
'tdmsorg-getDescendantList': `/mroapi/${prefix}/tdmsorg/getDescendantList/0-1-3-847038-12387-`
}
export default apiObj
\ No newline at end of file
// 接口地址映射
let prefix = 'tms'
const apiObj = {
// 机型管理
'tms-daAcreg-getAll': `/mroapi/${prefix}/tms-daAcreg/getAll`, // 获取机型
'tms-daAcreg-getAllByAcno': `/mroapi/${prefix}/tms-daAcreg/getAllByAcno` // 获取飞机
}
export default apiObj
let upoint = '/mroapi/upoint';
let admin = '/mroapi/admin';
const apiObj = {
// -- 制服积分 --
// 校验折现
'discount-checkDiscount': `${upoint}/discount/checkDiscount`,
// 校验复核
'review-checkReview': `${upoint}/review/checkReview`,
// 单位
'review-unit_type': `${admin}/dict/type/unit_type`,
// 类别
'review-category_type': `${admin}/dict/type/category_type`,
// 获取用户信息
'user-selectUserInfo': `${upoint}/user/selectUserInfo`,
// 申请积分
'review-applyIntefralReview': `${upoint}/review/applyIntefralReview`,
// 查询折现时间
'rule-selectExchangeAndDiscountRule': `${upoint}/rule/selectExchangeAndDiscountRule`,
// 申请折现
'discount-applyDiscount': `${upoint}/discount/applyDiscount`,
// 积分规则
'ruleDesc-selectRuleDesc': `${upoint}/ruleDesc/selectRuleDesc`,
// - 物资列表
// 查询用户能够兑换的物资 list
'exchange-selectExchageMaterial': `${upoint}/exchange/selectExchageMaterial`,
// 兑换
'exchange-materials': `${upoint}/exchange/exchangeMaterialDirect`,
// 判断是否积分够 积分校验
'integration-sufficient': `${upoint}/exchange/checkMaterialExchangeForApp`,
// 积分校验(通过购物车兑换)
'integration-checkMaterialExchange': `${upoint}/exchange/checkMaterialExchange`,
// 加入购物车
'shoppingCart-addShoppingCart': `${upoint}/shoppingCart/addShoppingCart`,
// 查询购物车
'shoppingCart-queryShoppingCart': `${upoint}/shoppingCart/queryShoppingCart`,
// 更新购物车
'shoppingCart-updateShoppingCart': `${upoint}/shoppingCart/updateShoppingCart`,
// 删除购物车 单条
'shoppingCart-deleteShoppingCart': `${upoint}/shoppingCart/deleteShoppingCart`,
// 清空购物车
'shoppingCart-deleteAllShoppingCart': `${upoint}/shoppingCart/deleteAllShoppingCart`,
// 提交兑换物资
'exchange-exchangeMaterial': `${upoint}/exchange/exchangeMaterial`,
// - 兑换记录 year:2022
'exchange-selectExchangeForApp': `${upoint}/exchange/selectExchangeForApp`,
// 用户确认收货 {"id":"1256353245"}
'exchange-confirmReceipt': `${upoint}/exchange/confirmReceipt`,
// - 积分明细 year:2022
'user-selectOneMaterialForApp': `${upoint}/user/selectOneMaterialForApp`,
// - 复核记录 year:2022
'review-selectReviewForApp': `${upoint}/review/selectReviewForApp`,
// 撤销复核申请 {"id":"1256353245"}
'review-revokeReviewBusiness': `${upoint}/review/revokeReviewBusiness`
}
export default apiObj
/*
Animation 微动画
基于ColorUI组建库的动画模块 by 文晓港 2019年3月26日19:52:28
*/
/* css 滤镜 控制黑白底色gif的 */
.gif-black{
mix-blend-mode: screen;
}
.gif-white{
mix-blend-mode: multiply;
}
/* Animation css */
[class*=animation-] {
animation-duration: .5s;
animation-timing-function: ease-out;
animation-fill-mode: both
}
.animation-fade {
animation-name: fade;
animation-duration: .8s;
animation-timing-function: linear
}
.animation-scale-up {
animation-name: scale-up
}
.animation-scale-down {
animation-name: scale-down
}
.animation-slide-top {
animation-name: slide-top
}
.animation-slide-bottom {
animation-name: slide-bottom
}
.animation-slide-left {
animation-name: slide-left
}
.animation-slide-right {
animation-name: slide-right
}
.animation-shake {
animation-name: shake
}
.animation-reverse {
animation-direction: reverse
}
@keyframes fade {
0% {
opacity: 0
}
100% {
opacity: 1
}
}
@keyframes scale-up {
0% {
opacity: 0;
transform: scale(.2)
}
100% {
opacity: 1;
transform: scale(1)
}
}
@keyframes scale-down {
0% {
opacity: 0;
transform: scale(1.8)
}
100% {
opacity: 1;
transform: scale(1)
}
}
@keyframes slide-top {
0% {
opacity: 0;
transform: translateY(-100%)
}
100% {
opacity: 1;
transform: translateY(0)
}
}
@keyframes slide-bottom {
0% {
opacity: 0;
transform: translateY(100%)
}
100% {
opacity: 1;
transform: translateY(0)
}
}
@keyframes shake {
0%,
100% {
transform: translateX(0)
}
10% {
transform: translateX(-9px)
}
20% {
transform: translateX(8px)
}
30% {
transform: translateX(-7px)
}
40% {
transform: translateX(6px)
}
50% {
transform: translateX(-5px)
}
60% {
transform: translateX(4px)
}
70% {
transform: translateX(-3px)
}
80% {
transform: translateX(2px)
}
90% {
transform: translateX(-1px)
}
}
@keyframes slide-left {
0% {
opacity: 0;
transform: translateX(-100%)
}
100% {
opacity: 1;
transform: translateX(0)
}
}
@keyframes slide-right {
0% {
opacity: 0;
transform: translateX(100%)
}
100% {
opacity: 1;
transform: translateX(0)
}
}
\ No newline at end of file
<template>
<view>
<view class="amms-nav-container main-font-color" :style="customStyle">
<view class="amms-nav-bar" :style="style">
<view class="amms-action left" @tap="tapBackPage" v-if="isBack">
<image src="../../static/img/ammsHome/navback.png" class="amms-action" mode="aspectFit"></image>
<slot name="backText"></slot>
</view>
<view class="amms-action left" v-if="footIs">
<slot name="backText"></slot>
</view>
<view class="amms-content">
<slot name="content"></slot>
</view>
<view class="amms-action right" style="width: auto;">
<view class="amms-action-item" @tap="tapChangePage" v-if="showChange">
<image src="../../static/img/ammsHome/change.png" class="amms-action" mode="aspectFit"></image>
<slot name="right"></slot>
</view>
<view class="amms-action-item" @tap="tapToPage" v-if="showTextTap">
<text v-if="textPage">{{ textPage.text }}</text>
<slot name="right"></slot>
</view>
<view class="amms-action-item" @tap="footChang" v-if="footIs">
<image src="../../static/img/ammsHome/setting.png" class="amms-action-item" style="width: 44rpx;" mode="aspectFit"></image>
</view>
<view class="amms-content" @tap="confirm" v-if="showSure">
<text style="font-size: 30rpx;">确定</text>
</view>
</view>
</view>
<uni-popup ref="alertDialog" type="center">
<view class="popup-content">
<view class="bg-white border-rad">
<view class="flex align-center justify-center font26 padding border-b-ddd">
跳转至页面
</view>
<view class="flex justify-center padding">
<uni-data-checkbox mode="tag" v-model="jumpUrl"
:localdata="multiplePath"></uni-data-checkbox>
</view>
<view class="flex align-center justify-between padding">
<view class="main-button-kong text-center" style="width: 100%;margin-right:20rpx;"
@tap="dialogClose">
取消
</view>
<view class="main-button text-center" style="width: 100%;" @tap="dialogConfirm">
确定
</view>
</view>
</view>
</view>
</uni-popup>
</view>
</view>
</template>
<script setup lang="ts">
import { ref, computed, getCurrentInstance, inject } from 'vue';
import { request } from '@/utils/request';
// import {
// onReady,
// onShow
// } from '@dcloudio/uni-app';
import uniPopup from '../../uni_modules/uni-popup/uni-popup.vue';
const { proxy } = getCurrentInstance();
const statusBar:any = inject('statusBarHeight');
const customBar:any = inject('CustomBar');
const jumpUrl = ref('');
const style = computed(() => {
// #ifdef APP-PLUS
return `height:${customBar}px;padding-top: ${statusBar}px;`
// #endif
// #ifdef H5
return 'margin-top: 0rpx;'
// #endif
})
const customStyle = computed(() => {
// #ifdef APP-PLUS
return `height: ${customBar}px;`
// #endif
// #ifdef H5
return 'height: 100rpx;'
// #endif
})
console.log(getCurrentInstance())
const props = defineProps({
bgColor: {
type: String,
default: 'bg-white-cu'
},
isBack: {
type: [Boolean, String],
default: true
},
bgImage: {
type: String,
default: ''
},
showUser: {
type: [Boolean, String],
default: true
},
showChange: {
type: [Boolean, String],
default: false
},
showTextTap: {
type: [Boolean, String],
default: false
},
footIs: {
type: [Boolean, String],
default: false
},
showSure: {
type: [Boolean, String],
default: false
},
changePath: {
type: Object,
default: null
},
multiplePath: {
type: Array,
default: () => {
return []
}
},
textPage: {
type: Object,
default: null
}
});
function dialogConfirm() {
// const leftImgs = ref('../../static/image/return.png');
// const rightImgs = ref('../../static/image/set_up.png');
uni.navigateTo({
url: '.' + jumpUrl.value
})
}
function dialogClose() {
proxy.$refs.alertDialog.close();
}
function tapBackPage() {
uni.navigateBack({
delta: 1
});
}
function confirm() {
let arr = uni.getStorageSync('workListData') || [];
let initData: any = [];
arr?.map((item: any) => {
initData.push({
menuId: item.menuId
})
});
uni.showLoading({ mask: true });
request({
method: 'post',
url: 'appmenu-saveMenuCollect',
data: initData,
}).then((res: any) => {
uni.hideLoading();
if (res.code == 0) {
uni.showToast({
title: '成功!',
icon: 'none'
});
uni.removeStorageSync('workListData');
uni.$emit('menuList', null);
uni.navigateBack()
} else {
uni.showToast({
title: res.msg,
icon: 'none'
});
}
}).catch((err: any) => {
uni.showToast({
title: err.msg,
icon: 'none'
});
uni.hideLoading();
});
}
function tapGoPersonalCenterPage() {
// 若存在window对象,则可以判断当前为使用H5的方式打开,记录下跳转前的页面地址
if (typeof (window) != 'undefined') {
let _redirectUrl = location.hash.split('#')[1]
uni.setStorageSync('preUrl', _redirectUrl)
}
uni.navigateTo({
url: '/pages/login/index'
})
}
function tapChangePage() {
if (props.changePath) {
uni.showModal({
title: '提示',
content: `是否切换跳转至${props.changePath.name}`,
success: function (res) {
if (res.confirm) {
uni.navigateTo({
url: '.' + props.changePath.path
})
}
}
});
}
if (props.multiplePath.length > 0) {
proxy.$refs.alertDialog.open();
}
}
function tapToPage() {
uni.navigateTo({
url: '.' + props.textPage.url
})
}
function footChang() {
uni.navigateTo({
url: '/pages/home/components/stagingSettings'
})
}
</script>
<style lang="less" scoped>
/deep/.uni-data-checklist .checklist-group {
justify-content: center;
}
/deep/.uni-popup__wrapper-box {
width: 80%;
}
.action {}
.bg-white-cu {
background-color: #fff;
}
.content {
font-size: 36rpx;
color: #fff;
}
.amms-nav-container {
width: 100%;
background: linear-gradient(-90deg, #168AFF 0%, #0E57FF 100%);
box-sizing: border-box;
position: relative;
.amms-nav-bar{
display: flex;
align-items: center;
justify-content: center;
position: fixed;
top: 0;
left: 0;
right: 0;
width: 100%;
height: 100rpx;
background: linear-gradient(-90deg, #168AFF 0%, #0E57FF 100%);
box-sizing: border-box;
color: #ffffff;
padding: 20rpx;
z-index: 99;
.amms-action{
min-width: 44rpx;
height: 44rpx;
position: absolute;
&.left{
left: 20rpx;
}
&.right{
right: 20rpx;
}
.amms-action-item{
min-width: 44rpx;
height: 44rpx;
flex-shrink: 0;
}
}
.amms-content{
display: inline-block;
font-size: 36rpx;
font-weight: 500;
color: #ffffff;
}
}
}
</style>
\ No newline at end of file
import {
request123
} from '@/utils/request.js'
export function AssessmentPageAPi(planNo, username, dataid) {
return request123({
url: '/QuestionManagement/queryAssessmentPage',
data: {
planNo,
username,
dataid
},
method: 'GET',
})
}
export function submitAssessment(data) {
return request123({
url: '/QuestionManagement/submitAssessment',
data,
method: 'post'
})
}
export function getUserValidate(ticket) {
return request123({
url: '/api/train/sys/checkToken',
data:{
ticket
},
method: 'GET'
})
}
export function getExamUserToken() {
return request123({
url: '/examApp/getExamUserToken',
method: 'get'
})
}
// 登录接口
export const login = data => {
let time = data.time
return request123({
url: '/sys/login',
method: 'POST',
data: data
})
}
// 图片接口 sys/randomImage/1684720796409 1684720884595
export const loginImg = data => {
let time = data.time
return request123({
url: '/sys/randomImage/' + time,
method: 'GET',
data: data
})
}
// 考试中心
export const examinationCenter = data => {
return request123({
url: '/UsersExamination/getExamsCount',
method: 'POST',
data: data,
})
}
// 考试列表
export const getExamList = data => {
return request123({
url: '/UsersExamination/getExamsList',
method: 'POST',
data: data,
})
}
// 考试分析
export const examinationAnalysis = data => {
return request123({
url: '/UsersExamination/getExamsAnalysis',
method: 'POST',
data: data,
})
}
\ No newline at end of file
async function compressImage(src, platform) {
const imageInfo = await getImageInfo(src);
const orientation = imageInfo.orientation;
let rotate = 0;
let quality = 70;
if (platform === 'ios') {
rotate = 0;
quality = 25;
} else {
switch (orientation) {
case 'up': //exif:1 不旋转
rotate = 0;
break;
case 'down': //exif:3 旋转180度
rotate = 180;
break;
case 'right': //exif:6 旋转90度
rotate = 90;
break;
case 'left': //exif:8 旋转270度
rotate = 270;
break;
default:
rotate = 0;
break;
}
}
return new Promise(function(resolve, reject) {
if (typeof(plus) != 'undefined') {
plus.zip.compressImage({
src: src,
dst: "_doc/uniapp_temp" + '/compressed/' + Math.round(new Date()) + '.jpg',
format: 'jpg',
quality: quality,
width: 'auto',
height: 'auto',
rotate: rotate,
},
function(event) {
let tempPath = event.target;
resolve(tempPath)
},
function(error) {
reject(error);
});
} else {
resolve(src)
// let canvasWidth = imageInfo.width //图片原始长宽
// let canvasHeight = imageInfo.height
// let img = new Image()
// img.src = src
// let canvas = document.createElement('canvas');
// canvas.width = canvasWidth / 4
// canvas.height = canvasHeight / 4
// console.log(33)
// let ctx = canvas.getContext('2d')
// ctx.drawImage(img, 0, 0, canvasWidth / 4, canvasHeight / 4)
// console.log(ctx)
// console.log(src)
// setTimeout(() => {
// canvas.toBlob((fileSrc) => {
// let imgSrc = window.URL.createObjectURL(fileSrc)
// console.log('压缩后', window.URL.createObjectURL(fileSrc))
// resolve(imgSrc)
// }, 'image/jpeg')
// }, 600)
}
})
}
function getImageInfo(path) {
return new Promise(function(resolve, reject) {
if (typeof(plus) != 'undefined') {
plus.io.getImageInfo({
src: path,
success: function(image) {
// console.log(image.width);
// console.log(image.height);
// console.log('orientation=' + image.orientation);
// console.log('path=' + image.path);
resolve(image)
},
fail: function(err) {
console.log("getImageInfoErr: " + JSON.stringify(err));
reject(err)
}
});
} else {
uni.getImageInfo({
src: path,
success: function(image) {
// console.log(image.width);
// console.log(image.height);
// console.log('orientation=' + image.orientation);
// console.log('path=' + image.path);
resolve(image)
},
fail: function(err) {
console.log("getImageInfoErr: " + JSON.stringify(err));
reject(err)
}
});
}
});
}
export default compressImage
\ No newline at end of file
This diff is collapsed. Click to expand it.
/// null = 未请求,1 = 已允许,0 = 拒绝|受限, 2 = 系统未开启
var isIOS
function album() {
var result = 0;
var PHPhotoLibrary = plus.ios.import("PHPhotoLibrary");
var authStatus = PHPhotoLibrary.authorizationStatus();
if (authStatus === 0) {
result = null;
} else if (authStatus == 3) {
result = 1;
} else {
result = 0;
}
plus.ios.deleteObject(PHPhotoLibrary);
return result;
}
function camera() {
var result = 0;
var AVCaptureDevice = plus.ios.import("AVCaptureDevice");
var authStatus = AVCaptureDevice.authorizationStatusForMediaType('vide');
if (authStatus === 0) {
result = null;
} else if (authStatus == 3) {
result = 1;
} else {
result = 0;
}
plus.ios.deleteObject(AVCaptureDevice);
return result;
}
function location() {
var result = 0;
var cllocationManger = plus.ios.import("CLLocationManager");
var enable = cllocationManger.locationServicesEnabled();
var status = cllocationManger.authorizationStatus();
if (!enable) {
result = 2;
} else if (status === 0) {
result = null;
} else if (status === 3 || status === 4) {
result = 1;
} else {
result = 0;
}
plus.ios.deleteObject(cllocationManger);
return result;
}
function push() {
var result = 0;
var UIApplication = plus.ios.import("UIApplication");
var app = UIApplication.sharedApplication();
var enabledTypes = 0;
if (app.currentUserNotificationSettings) {
var settings = app.currentUserNotificationSettings();
enabledTypes = settings.plusGetAttribute("types");
if (enabledTypes == 0) {
result = 0;
console.log("推送权限没有开启");
} else {
result = 1;
console.log("已经开启推送功能!")
}
plus.ios.deleteObject(settings);
} else {
enabledTypes = app.enabledRemoteNotificationTypes();
if (enabledTypes == 0) {
result = 3;
console.log("推送权限没有开启!");
} else {
result = 4;
console.log("已经开启推送功能!")
}
}
plus.ios.deleteObject(app);
plus.ios.deleteObject(UIApplication);
return result;
}
function contact() {
var result = 0;
var CNContactStore = plus.ios.import("CNContactStore");
var cnAuthStatus = CNContactStore.authorizationStatusForEntityType(0);
if (cnAuthStatus === 0) {
result = null;
} else if (cnAuthStatus == 3) {
result = 1;
} else {
result = 0;
}
plus.ios.deleteObject(CNContactStore);
return result;
}
function record() {
var result = null;
var avaudiosession = plus.ios.import("AVAudioSession");
var avaudio = avaudiosession.sharedInstance();
var status = avaudio.recordPermission();
console.log("permissionStatus:" + status);
if (status === 1970168948) {
result = null;
} else if (status === 1735552628) {
result = 1;
} else {
result = 0;
}
plus.ios.deleteObject(avaudiosession);
return result;
}
function calendar() {
var result = null;
var EKEventStore = plus.ios.import("EKEventStore");
var ekAuthStatus = EKEventStore.authorizationStatusForEntityType(0);
if (ekAuthStatus == 3) {
result = 1;
console.log("日历权限已经开启");
} else {
console.log("日历权限没有开启");
}
plus.ios.deleteObject(EKEventStore);
return result;
}
function memo() {
var result = null;
var EKEventStore = plus.ios.import("EKEventStore");
var ekAuthStatus = EKEventStore.authorizationStatusForEntityType(1);
if (ekAuthStatus == 3) {
result = 1;
console.log("备忘录权限已经开启");
} else {
console.log("备忘录权限没有开启");
}
plus.ios.deleteObject(EKEventStore);
return result;
}
function requestIOS(permissionID) {
return new Promise((resolve, reject) => {
switch (permissionID) {
case "push":
resolve(push());
break;
case "location":
resolve(location());
break;
case "record":
resolve(record());
break;
case "camera":
resolve(camera());
break;
case "album":
resolve(album());
break;
case "contact":
resolve(contact());
break;
case "calendar":
resolve(calendar());
break;
case "memo":
resolve(memo());
break;
default:
resolve(0);
break;
}
});
}
function requestAndroid(permissionID) {
return new Promise((resolve, reject) => {
plus.android.requestPermissions(
[permissionID],
function(resultObj) {
var result = 0;
for (var i = 0; i < resultObj.granted.length; i++) {
var grantedPermission = resultObj.granted[i];
console.log('已获取的权限:' + grantedPermission);
result = 1
}
for (var i = 0; i < resultObj.deniedPresent.length; i++) {
var deniedPresentPermission = resultObj.deniedPresent[i];
console.log('拒绝本次申请的权限:' + deniedPresentPermission);
result = 0
}
for (var i = 0; i < resultObj.deniedAlways.length; i++) {
var deniedAlwaysPermission = resultObj.deniedAlways[i];
console.log('永久拒绝申请的权限:' + deniedAlwaysPermission);
result = -1
}
resolve(result);
},
function(error) {
console.log('result error: ' + error.message)
resolve({
code: error.code,
message: error.message
});
}
);
});
}
function gotoAppPermissionSetting() {
if (permission.isIOS) {
var UIApplication = plus.ios.import("UIApplication");
var application2 = UIApplication.sharedApplication();
var NSURL2 = plus.ios.import("NSURL");
var setting2 = NSURL2.URLWithString("app-settings:");
application2.openURL(setting2);
plus.ios.deleteObject(setting2);
plus.ios.deleteObject(NSURL2);
plus.ios.deleteObject(application2);
} else {
var Intent = plus.android.importClass("android.content.Intent");
var Settings = plus.android.importClass("android.provider.Settings");
var Uri = plus.android.importClass("android.net.Uri");
var mainActivity = plus.android.runtimeMainActivity();
var intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
intent.setData(uri);
mainActivity.startActivity(intent);
}
}
const permission = {
get isIOS(){
return typeof isIOS === 'boolean' ? isIOS : (isIOS = uni.getSystemInfoSync().platform === 'ios')
},
requestIOS: requestIOS,
requestAndroid: requestAndroid,
gotoAppSetting: gotoAppPermissionSetting
}
export default permission
export default {
dbName: 'amms', // 数据库名称
dbPath: `_downloads/amms.db`, // 数据库地址,推荐以下划线为开头 _doc/xxx.db
// 判断数据库是否打开
isOpen() {
// 数据库打开了就返回 true,否则返回 false
var open = plus.sqlite.isOpenDatabase({
name: this.dbName, // 数据库名称
path: this.dbPath // 数据库地址
})
return open;
},
// 创建数据库 或 有该数据库就打开
openSqlite() {
return new Promise((resolve, reject) => {
// 打开数据库
plus.sqlite.openDatabase({
name: this.dbName,
path: this.dbPath,
success(e) {
resolve(e); // 成功回调
},
fail(e) {
reject(e); // 失败回调
}
})
})
},
// 关闭数据库
closeSqlite() {
return new Promise((resolve, reject) => {
plus.sqlite.closeDatabase({
name: this.dbName,
success(e) {
resolve(e);
},
fail(e) {
reject(e);
}
})
})
},
// 数据库建表 sql:'CREATE TABLE IF NOT EXISTS dbTable("id" varchar(50),"name" TEXT)
// 创建 CREATE TABLE IF NOT EXISTS 、 dbTable 是表名,不能用数字开头、括号里是表格的表头
createTable(dbTable, data) {
return new Promise((resolve, reject) => {
// executeSql: 执行增删改等操作的SQL语句
plus.sqlite.executeSql({
name: this.dbName,
sql: `CREATE TABLE IF NOT EXISTS ${dbTable}(${data})`,
success(e) {
resolve(e);
},
fail(e) {
reject(e);
}
})
})
},
// 数据库删表 sql:'DROP TABLE dbTable'
dropTable(dbTable) {
return new Promise((resolve, reject) => {
plus.sqlite.executeSql({
name: this.dbName,
sql: `DROP TABLE ${dbTable}`,
success(e) {
resolve(e);
},
fail(e) {
reject(e);
}
})
})
},
// 向表格里添加数据 sql:'INSERT INTO dbTable VALUES('x','x','x')' 对应新增
// 或者 sql:'INSERT INTO dbTable ('x','x','x') VALUES('x','x','x')' 具体新增
// 插入 INSERT INTO 、 dbTable 是表名、根据表头列名插入列值
insertTableData(dbTable, data, condition) {
// 判断有没有传参
if (dbTable !== undefined && data !== undefined) {
// 判断传的参是否有值
var bol = (JSON.stringify(data) == "{}");
if (!bol) {
if (condition == undefined) {
var sql = `INSERT INTO ${dbTable} VALUES('${data}')`;
} else {
var sql = `INSERT INTO ${dbTable} (${condition}) VALUES(${data})`;
}
// console.log(sql);
return new Promise((resolve, reject) => {
// 表格添加数据
plus.sqlite.executeSql({
name: this.dbName,
sql: sql,
success(e) {
resolve(e);
},
fail(e) {
reject(e);
}
})
})
} else {
return new Promise((resolve, reject) => {
reject("错误添加")
})
}
} else {
return new Promise((resolve, reject) => {
reject("错误添加")
})
}
},
// 根据条件向表格里添加数据 有数据更新、无数据插入
// (建表时需要设置主键) 例如 --- "roomid" varchar(50) PRIMARY KEY
insertOrReplaceData(dbTable, data, condition) {
// 判断有没有传参
if (dbTable !== undefined && data !== undefined) {
if (condition == undefined) {
var sql = `INSERT OR REPLACE INTO ${dbTable} VALUES('${data}')`;
} else {
var sql = `INSERT OR REPLACE INTO ${dbTable} (${condition}) VALUES(${data})`;
}
// console.log(sql);
return new Promise((resolve, reject) => {
// 表格添加数据
plus.sqlite.executeSql({
name: this.dbName,
sql: sql,
success(e) {
resolve(e);
},
fail(e) {
reject(e);
}
})
})
} else {
return new Promise((resolve, reject) => {
reject("错误添加")
})
}
},
// 查询获取数据库里的数据 sql:'SELECT * FROM dbTable WHERE lname = 'lvalue''
// 查询 SELECT * FROM 、 dbTable 是表名、 WHERE 查找条件 lname,lvalue 是查询条件的列名和列值
selectTableData(dbTable, uname, namevalue, upass, passvalue, urrn, rrnvalue) {
if (dbTable !== undefined) {
// 第一个是表单名称,后两个参数是列表名,用来检索
if (uname !== undefined && upass !== undefined && urrn !== undefined) {
// 三个检索条件
var sql = `SELECT * FROM ${dbTable} WHERE ${uname} = '${namevalue}' AND ${upass} = '${passvalue}' AND ${urrn}='${rrnvalue}'`;
}
if (uname !== undefined && upass !== undefined && urrn == undefined) {
// 两个检索条件
var sql = `SELECT * FROM ${dbTable} WHERE ${uname} = '${namevalue}' AND ${upass} = '${passvalue}'`;
}
if (uname !== undefined && upass == undefined && urrn == undefined) {
// 一个检索条件
var sql = `SELECT * FROM ${dbTable} WHERE ${uname} = '${namevalue}'`;
// console.log(sql);
}
if (uname == undefined) {
var sql = `SELECT * FROM ${dbTable}`;
}
return new Promise((resolve, reject) => {
// 表格查询数据 执行查询的SQL语句
plus.sqlite.selectSql({
name: this.dbName,
sql: sql,
success(e) {
resolve(e);
},
fail(e) {
reject(e);
}
})
})
} else {
return new Promise((resolve, reject) => {
reject("错误查询")
});
}
},
// 删除表里的数据 sql:'DELETE FROM dbTable WHERE lname = 'lvalue''
// 删除 DELETE FROM 、 dbTable 是表名、 WHERE 查找条件 lname,lvalue 是查询条件的列名和列值
deleteTableData(dbTable, lname, lvalue, ww, ee) {
if (dbTable !== undefined) {
if (lname == undefined) {
var sql = `DELETE FROM ${dbTable}`;
} else {
if (ww !== undefined) {
// 两个检索条件
var sql = `DELETE FROM ${dbTable} WHERE ${lname} = '${lvalue}' AND ${ww} = '${ee}'`;
} else {
// 一个检索条件
var sql = `DELETE FROM ${dbTable} WHERE ${lname} = '${lvalue}'`;
}
}
return new Promise((resolve, reject) => {
// 删除表数据
plus.sqlite.executeSql({
name: this.dbName,
sql: sql,
success(e) {
resolve(e);
},
fail(e) {
reject(e);
}
})
})
} else {
return new Promise((resolve, reject) => {
reject("错误删除")
});
}
},
// 修改数据表里的数据 sql:"UPDATE dbTable SET 列名 = '列值',列名 = '列值' WHERE lname = 'lvalue'"
// 修改 UPDATE 、 dbTable 是表名, data: 要修改的列名=修改后列值, lname,lvalue 是查询条件的列名和列值
updateTableData(dbTable, data, lname, lvalue) {
if (lname == undefined) {
var sql = `UPDATE ${dbTable} SET ${data}`;
} else {
var sql = `UPDATE ${dbTable} SET ${data} WHERE ${lname} = '${lvalue}'`;
}
// WHERE 前面是要修改的列名、列值,后面是条件的列名、列值
return new Promise((resolve, reject) => {
// 修改表数据
plus.sqlite.executeSql({
name: this.dbName,
sql: sql,
success(e) {
resolve(e);
},
fail(e) {
reject(e);
}
})
})
},
// 获取指定数据条数 sql:"SELECT * FROM dbTable ORDER BY 'id' DESC LIMIT 15 OFFSET 'num'"
// dbTable 表名, ORDER BY 代表排序默认正序, id 是排序的条件 DESC 代表倒序,从最后一条数据开始拿
// LIMIT 15 OFFSET '${num}',这句的意思是跳过 num 条拿 15 条数据, num 为跳过多少条数据是动态值
// 例 初始num设为0,就从最后的数据开始拿15条,下次不拿刚获取的数据,所以可以让num为15,这样就能一步一步的拿完所有的数据
pullSQL(dbTable, id, num) {
return new Promise((resolve, reject) => {
plus.sqlite.selectSql({
name: this.dbName,
sql: `SELECT * FROM ${dbTable} ORDER BY '${id}' DESC LIMIT 15 OFFSET '${num}'`,
success(e) {
resolve(e);
},
fail(e) {
reject(e);
}
})
})
}
}
<template>
<view class="radio" :class="{'radio-width-default':widthDefault}" :style="checked?activeStyle :itemStyle" @click="handleChange">
{{name}}
</view>
</template>
<script>
/**
* 防抖
* @param {*} fun
* @param {*} delay
* @param {*} immediate
*/
const debounce = function (fun, delay, immediate) {
var timer, lasttime, context, arg
var later = function () {
var now = new Date().getTime(),
l = now - lasttime
if (l < delay && l >= 0) {
clearTimeout(timer)
timer = setTimeout(later, delay - l)
} else {
clearTimeout(timer)
timer = null
if (!immediate) {
fun.apply(context, arg)
if (!timer) context = arg = null
}
}
}
return function () {
context = this
arg = arguments
lasttime = new Date().getTime()
var callNow = immediate && !timer
if (!timer) timer=setTimeout(later, delay)
if (callNow) {
fun.apply(context, arg)
context = arg = null
}
}
}
export default {
props: {
name: {
type: String,
default: ''
},
value: {
default: null,
},
checked: {
type: [Boolean, Number],
default: false
},
},
computed: {
widthDefault() {
return this.name.length <= 3
},
activeStyle() {
return `background: #d5e4fd;color: #3c7ef6;border-color: #3c7ef6;`
},
itemStyle() {
return `background: #f7f7f7;color: #7d7d7d;`
}
},
data() {
return {
};
},
methods: {
handleChange: debounce(handleChange, 200,true)
}
}
function handleChange() {
this.$emit('change', this.value)
}
</script>
<style>
.radio {
display: inline-block;
height: 60rpx;
line-height: 60rpx;
padding: 0 22rpx;
border-radius: 10rpx;
font-size: 26rpx;
box-sizing: border-box;
border: 1px solid #c3c3c3;
}
.radio:not(:last-child) {
margin: 0 20rpx 30rpx 0;
}
.radio-width-default {
width: 120rpx;
text-align: center;
padding: 0;
}
</style>
<template>
<view class="style-flex style-flex-wrap">
<filter-radio-item v-for="(item, idx) in items" :key="idx" :name="item.name" :value="item.value" :checked="item.checked" @change="radioChange"></filter-radio-item>
</view>
</template>
<script>
import filterRadioItem from './axb-checkbox-item.vue'
export default {
props:{
list:{
type:Array,
default: []
},
multi:{
type:Boolean,
default:false
}
},
components:{
filterRadioItem
},
data() {
return {
items: this.list,
resMulti: [],
};
},
created(){
},
computed:{
},
methods:{
handleChange:function(val){
const arr = []
// 是否为全部
if(val==='all'){
let allr = this.items.find((n) => n.value === val)
this.items.forEach(function(item){
let re = {}
re.name = item.name
re.value = item.value
re.checked= !allr.checked
arr.push(re)
})
} else{
for(let i =0; i<this.items.length;i++){
let r = {}
r.name = this.items[i].name
r.value = this.items[i].value
if(this.multi){ // 多选
if(this.items[i].value === val){ // 选中项处理
r.checked = !this.items[i].checked
}
else{
r.checked=this.items[i].checked
}
}else{ // 单选
if(this.items[i].value === val){ // 选中项处理
r.checked = !this.items[i].checked
}else{
r.checked = false
}
}
arr.push(r)
}
}
// 判断是否全选 全选按钮未全选
if(this.multi&&arr[0].value==='all'){
const select = arr.slice(1)
let r = select.every(function(val){
return val.checked
})
arr[0].checked = r
}
this.items = arr
},
radioChange: function (e) {
console.log('radio发生change事件,携带value值为:' + e)
// 改变单击项
this.handleChange(e)
const re = []
if(this.multi){
this.items.forEach(function(val){
if(val.checked){
re.push(val.value)
}
})
}
let r = this.items.find((val)=>{
return val.value === e
})
let result = this.multi?re:r.checked?e:null
// 返回选择项
this.$emit('change',result)
},
reset:function(){
this.items=this.list
},
setItems:function(val){
this.items = val
}
}
}
</script>
<style>
.radio{
display: inline-block;
height: 60rpx;
line-height: 60rpx;
padding: 0 22rpx;
background: #f7f7f7;
border: 1px solid #c3c3c3;
border-radius: 10rpx;
font-size: 26rpx;
color: #7d7d7d;
box-sizing: border-box;
}
.radio:not(:last-child){
margin: 0 20rpx 30rpx 0;
}
.radio-primay{
background: #d5e4fd;
color: #3c7ef6;
border: 1px solid #3c7ef6;
}
.radio-width-default{
width: 120rpx;
text-align: center;
padding: 0;
}
</style>
.cu-progress-main{
position: relative;
display: flex;
flex-direction: row;
align-items: center;
text-align: center;
justify-content: space-between;
margin: 0;
padding: 0;
background-color: inherit;
overflow: hidden;
}
.cu-progress {
position: absolute;
display: flex;
flex-direction: row;
align-items: center;
text-align: center;
justify-content: space-between;
margin: 0;
padding: 0;
background-color: inherit;
/* overflow: hidden; */
}
.cu-progress-bar{
position: absolute;
left: 0;
}
.cu-area {
position: absolute;
display: flex;
flex-direction: row;
align-items: center;
/* left: 0; */
z-index: 2;
}
.cu-handle {
position: absolute;
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
justify-content: space-around;
overflow: hidden;
z-index: 5;
}
.cu-handle text {
align-items: center;
text-align: center;
white-space: nowrap;
}
.cu-showInfo {
position: absolute;
justify-content: space-around;
align-items: center;
overflow: hidden;
white-space: nowrap;
pointer-events: none;
}
<template>
<view>
<slot name="formItem" v-if="$slots.formItem"></slot>
<view v-else class="evan-form-item-container" :class="'evan-form-item-container--'+mLabelPosition" :style="{borderWidth:border?'1rpx':0}">
<view v-if="label" class="evan-form-item-container__label" :class="{showAsteriskRect:hasRequiredAsterisk,isRequired:showRequiredAsterisk}"
:style="mLabelStyle">{{label}}</view>
<view class="evan-form-item-container__main" :style="mContentStyle">
<slot></slot>
</view>
</view>
</view>
</template>
<script>
export default {
name: 'EvanFormItem',
props: {
labelStyle: Object,
label: String,
contentStyle: {
type: Object,
default: () => {
return {}
}
},
prop: String,
border: {
type: Boolean,
default: true
},
labelPosition: {
validator: function(value) {
if (!value) {
return true
}
return ['top', 'left'].indexOf(value) !== -1
},
default: ''
}
},
computed: {
mLabelStyle() {
const parent = this.getParent()
let labelStyle = Object.assign({}, (parent.labelStyle || {}), (this.labelStyle || {}))
let arr = Object.keys(labelStyle).map((key) => `${key}:${labelStyle[key]}`)
return arr.join(';')
},
mContentStyle() {
let contentStyle = Object.assign({}, this.contentStyle || {})
let arr = Object.keys(contentStyle).map((key) => `${key}:${contentStyle[key]}`)
return arr.join(';')
},
mLabelPosition() {
if (this.labelPosition) {
return this.labelPosition
}
const parent = this.getParent()
if (parent) {
return parent.labelPosition
}
return 'left'
},
// 整个表单是否有*号
hasRequiredAsterisk() {
const parent = this.getParent()
if (parent) {
return parent.hasRequiredAsterisk
}
return false
},
// 当前formItem是否显示*号
showRequiredAsterisk() {
const parent = this.getParent()
if (parent && parent.hideRequiredAsterisk) {
return false
}
const rules = this.getRules()
if (rules && rules.length > 0) {
if (rules.find((rule) => rule.required === true)) {
return true
}
}
return false
}
},
methods: {
// 获取EvanForm组件
getParent() {
let parent = this.$parent
let parentName = parent.$options.name
while (parentName !== 'EvanForm') {
parent = parent.$parent
parentName = parent.$options.name
}
return parent
},
getRules() {
let form = this.getParent()
let formRules = form.mRules;
formRules = formRules ? formRules[this.prop] : [];
return [].concat(formRules || []);
}
}
}
</script>
<style lang="scss">
.evan-form-item-container {
border-bottom: 1rpx solid #eee;
&__label {
font-size: 28rpx;
color: #666;
line-height: 40rpx;
padding: 25rpx 0;
display: inline-block;
&.showAsteriskRect::before {
content: '';
color: #F56C6C;
width: 30rpx;
display: inline-block;
}
&.isRequired::before {
content: '*';
}
}
&__main {
flex: 1;
min-height: 90rpx;
display: flex;
align-items: center;
overflow: hidden;
}
&--left {
display: flex;
flex-direction: row;
align-items: flex-start;
}
&--top {
.evan-form-item-container__label {
padding-bottom: 10rpx;
}
}
}
</style>
<template>
<view class="evan-form-container">
<slot></slot>
</view>
</template>
<script>
import utils from './utils.js'
export default {
name: 'EvanForm',
props: {
labelStyle: {
type: Object,
default: () => {
return {}
}
},
model: Object,
hideRequiredAsterisk: {
type: Boolean,
default: false
},
showMessage: {
type: Boolean,
default: true
},
labelPosition: {
validator: function(value) {
return ['top', 'left'].indexOf(value) !== -1
},
default: 'left'
},
rules: {
type: Object,
default: () => {
return {}
}
}
},
computed: {
// 整个form是否有*号,为了保证label对齐,而不是和*号对齐
hasRequiredAsterisk() {
if (this.hideRequiredAsterisk) {
return false
}
if (this.mRules) {
const values = Object.values(this.mRules)
if (values && values.length > 0) {
for (let i = 0; i < values.length; i++) {
const value = values[i]
if (Array.isArray(value) && value.length > 0) {
const requiredItem = value.find((v) => v.required === true)
if (requiredItem) {
return true
}
} else {
if (value && value.required) {
return true
}
}
}
}
}
return false
}
},
watch: {
rules: {
immediate: true,
deep: true,
handler(value) {
this.mRules = value || {}
}
}
},
data() {
return {
mRules: {}
}
},
methods: {
setRules(rules) {
this.mRules = rules || {}
},
async validate(callback) {
if (typeof callback === 'function') {
utils.validate(this.model, this.mRules, callback, {
showMessage: this.showMessage
})
} else {
return await utils.validate(this.model, this.mRules, callback, {
showMessage: this.showMessage
})
}
},
async validateField(props, callback) {
if (typeof callback === 'function') {
utils.validateField(this.model, this.mRules, props, callback, {
showMessage: this.showMessage
})
} else {
return await utils.validateField(this.model, this.mRules, props, callback, {
showMessage: this.showMessage
})
}
}
}
}
</script>
<style lang="scss">
.evan-form-container {}
</style>
import AsyncValidator from 'async-validator'
const utils = {
validate: (model, rules, callback, options) => {
const initOptions = {
showMessage: true
}
options = Object.assign({}, initOptions, options || {})
let promise = null;
if (typeof callback !== 'function') {
promise = new Promise((resolve, reject) => {
callback = function(valid) {
valid ? resolve(valid) : reject(valid)
}
})
}
// 如果需要验证的fields为空,调用验证时立刻返回callback
if ((!rules || rules.length === 0) && callback) {
callback(true, null);
return true
}
let errors = []
const props = Object.keys(rules)
let count = 0
for (let i in props) {
const prop = props[i]
const value = utils.getValueByProp(model, prop)
utils.validateItem(rules, prop, value, (err) => {
if (err && err.length > 0) {
errors = errors.concat(err)
}
// 处理异步校验,等所有校验都结束时再callback
count++
if (count === props.length) {
if (errors.length > 0) {
if (options.showMessage) {
utils.showToast(errors[0].message)
}
callback(false, errors)
} else {
callback(true, null)
}
}
})
}
if (promise) {
return promise
}
},
validateField: (model, rules, props, callback, options) => {
const initOptions = {
showMessage: true
}
options = Object.assign({}, initOptions, options || {})
let promise = null;
if (typeof callback !== 'function') {
promise = new Promise((resolve, reject) => {
callback = function(valid) {
valid ? resolve(valid) : reject(valid)
}
})
}
props = [].concat(props)
if (props.length === 0) {
return
}
let errors = []
let count = 0
for (let i in props) {
const prop = props[i]
const value = utils.getValueByProp(model, prop)
utils.validateItem(rules, prop, value, (err) => {
if (err && err.length > 0) {
errors = errors.concat(err)
}
// 处理异步校验,等所有校验都结束时再callback
count++
if (count === props.length) {
if (errors.length > 0) {
if (options.showMessage) {
utils.showToast(errors[0].message)
}
callback(false, errors)
} else {
callback(true, null)
}
}
})
}
if (promise) {
return promise
}
},
validateItem(rules, prop, value, callback) {
if (!rules || JSON.stringify(rules) === '{}') {
if (callback instanceof Function) {
callback();
}
return true;
}
const propRules = [].concat(rules[prop] || []);
propRules.forEach((rule) => {
if (rule.pattern) {
rule.pattern = new RegExp(rule.pattern)
}
})
const descriptor = {
[prop]: propRules
};
const validator = new AsyncValidator(descriptor);
const model = {
[prop]: value
};
validator.validate(model, {
firstFields: true
}, (errors) => {
callback(errors);
});
},
getValueByProp: (obj, prop) => {
let tempObj = obj;
prop = prop.replace(/\[(\w+)\]/g, '.$1').replace(/^\./, '');
let keyArr = prop.split('.');
let i = 0;
for (let len = keyArr.length; i < len - 1; ++i) {
if (!tempObj) break;
let key = keyArr[i];
if (key in tempObj) {
tempObj = tempObj[key];
} else {
break;
}
}
return tempObj ? (typeof tempObj[keyArr[i]] === 'string' ? tempObj[keyArr[i]].trim() : tempObj[keyArr[i]]) :
null
},
showToast: (message) => {
uni.showToast({
title: message,
icon: 'none'
})
}
}
export default utils
function getLocalFilePath(path) {
if (path.indexOf('_www') === 0 || path.indexOf('_doc') === 0 || path.indexOf('_documents') === 0 || path.indexOf('_downloads') === 0) {
return path
}
if (path.indexOf('file://') === 0) {
return path
}
if (path.indexOf('/storage/emulated/0/') === 0) {
return path
}
if (path.indexOf('/') === 0) {
var localFilePath = plus.io.convertAbsoluteFileSystem(path)
if (localFilePath !== path) {
return localFilePath
} else {
path = path.substr(1)
}
}
return '_www/' + path
}
export function pathToBase64(path) {
return new Promise(function(resolve, reject) {
if (typeof window === 'object' && 'document' in window) {
if (typeof FileReader === 'function') {
var xhr = new XMLHttpRequest()
xhr.open('GET', path, true)
xhr.responseType = 'blob'
xhr.onload = function() {
if (this.status === 200) {
let fileReader = new FileReader()
fileReader.onload = function(e) {
resolve(e.target.result)
}
fileReader.onerror = reject
fileReader.readAsDataURL(this.response)
}
}
xhr.onerror = reject
xhr.send()
return
}
var canvas = document.createElement('canvas')
var c2x = canvas.getContext('2d')
var img = new Image
img.onload = function() {
canvas.width = img.width
canvas.height = img.height
c2x.drawImage(img, 0, 0)
resolve(canvas.toDataURL())
canvas.height = canvas.width = 0
}
img.onerror = reject
img.src = path
return
}
if (typeof plus === 'object') {
plus.io.resolveLocalFileSystemURL(getLocalFilePath(path), function(entry) {
entry.file(function(file) {
var fileReader = new plus.io.FileReader()
fileReader.onload = function(data) {
resolve(data.target.result)
}
fileReader.onerror = function(error) {
reject(error)
}
fileReader.readAsDataURL(file)
}, function(error) {
reject(error)
})
}, function(error) {
reject(error)
})
return
}
if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
wx.getFileSystemManager().readFile({
filePath: path,
encoding: 'base64',
success: function(res) {
resolve('data:image/png;base64,' + res.data)
},
fail: function(error) {
reject(error)
}
})
return
}
reject(new Error('not support'))
})
}
export function base64ToPath(base64) {
return new Promise(function(resolve, reject) {
if (typeof window === 'object' && 'document' in window) {
base64 = base64.split(',')
var type = base64[0].match(/:(.*?);/)[1]
var str = atob(base64[1])
var n = str.length
var array = new Uint8Array(n)
while (n--) {
array[n] = str.charCodeAt(n)
}
return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], { type: type })))
}
var extName = base64.match(/data\:\S+\/(\S+);/)
if (extName) {
extName = extName[1]
} else {
reject(new Error('base64 error'))
}
var fileName = Date.now() + '.' + extName
if (typeof plus === 'object') {
var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
bitmap.loadBase64Data(base64, function() {
var filePath = '_doc/uniapp_temp/' + fileName
bitmap.save(filePath, {}, function() {
bitmap.clear()
resolve(filePath)
}, function(error) {
bitmap.clear()
reject(error)
})
}, function(error) {
bitmap.clear()
reject(error)
})
return
}
if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
var filePath = wx.env.USER_DATA_PATH + '/' + fileName
wx.getFileSystemManager().writeFile({
filePath: filePath,
data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
encoding: 'base64',
success: function() {
resolve(filePath)
},
fail: function(error) {
reject(error)
}
})
return
}
reject(new Error('not support'))
})
}
\ No newline at end of file
<template>
<view class="imageUploadContainer">
<view class="imageUploadList">
<view class="imageItem" v-for="(path, index) in imageListData" :key="index">
<image :src="path" @tap="previewImage" :data-index="index"></image>
<view v-if="isShowDel" class="imageDel" @tap="deleteImage" :data-index="index">X</view>
</view>
<image v-if="isShowAdd" src="../../static/img/hcdb/i-camera.png" class="imageUpload" @tap="selectImage"></image>
<!-- <view v-if="isShowAdd" class="imageUpload" @tap="selectImage">+</view> -->
</view>
</view>
</template>
<script>
import permision from '@/common/permission.js';
import compressImage from '@/common/imageutil.js';
import { requestUploadFile } from '../../utils/request';
const device = uni.getSystemInfoSync();
export default {
name: 'image-upload',
props: {
value: {
type: Array,
default: () => {
return []
}
},
enableDel: {
type: Boolean,
default: true
},
enableAdd: {
type: Boolean,
default: true
},
limit: {
type: Number,
default: 9
},
attfileList: {
type: Array,
default: () => {
return []
}
},
dataIndex: {
type: Number,
default: 0
},
filePath: {
type: String,
default: ''
},
isCurrentUpload: {
type: Boolean,
default: true
}
},
data() {
return {
imageList: [],
isDestroyed: false
};
},
mounted: function() {
this.imageList = this.value;
},
destroyed: function() {
this.isDestroyed = true;
},
watch: {
value: {
handler (val) {
this.imageList = val
},
immediate: true,
deep: true
}
},
computed: {
imageListData: function() {
if (this.value) {
return this.value;
}
},
isShowDel: function() {
if (this.enableDel === false) {
return false;
} else {
return true;
}
},
isShowAdd: function() {
if (this.enableAdd === false) {
return false;
}
// if (this.limit && this.imageList.length >= this.limit) {
// return false;
// }
return true;
}
},
methods: {
selectImage: async function() {
var _self = this;
if (!_self.imageList) {
_self.imageList = [];
}
// #ifdef APP-PLUS
// TODO 选择相机或相册时 需要弹出actionsheet,目前无法获得是相机还是相册,在失败回调中处理
// if (this.sourceTypeIndex !== 2) {
// let status = await this.checkPermission();
// if (status !== 1) {
// return;
// }
// }
// #endif
// if (this.imageList.length == this.limit) {
// let isContinue = await this.isFullImg();
// console.log('是否继续?', isContinue);
// if (!isContinue) {
// return;
// }
// }
// 限制上传图片数量
// if (!!this.limit) {
// if (this.imageList.length == this.limit) {
// let isContinue = await this.isFullImgNew();
// return;
// }
// }
// 选择图片
uni.chooseImage({
sizeType: ['original', 'compressed'],
count: this.limit ? this.limit : 9,
success: async e => {
uni.showLoading({
title: '上传中',
mask: true
});
_self.$emit('uploading', true);
let imagePathArr = e.tempFilePaths;
let headerObj = {};
if (_self.isCurrentUpload) {
if (uni.getStorageSync('access_token')) {
headerObj['Authorization'] = 'Bearer' + uni.getStorageSync('access_token');
}
for (let i = 0; i < imagePathArr.length; i++) {
const src = await this.compressImageHandler(imagePathArr[i]);
let res = await requestUploadFile({
method: 'post',
url: 'diskUpload',
src: src,
path: this.filePath || 'upload'
})
let result = JSON.parse(res);
if (result.code == 0) {
_self.imageList.push(src);
_self.$emit('data', result.data, this.dataIndex);
} else {
uni.showToast({
title: '上传图片出错',
icon: 'none'
});
}
}
uni.hideLoading();
if (_self.imageList.length == imagePathArr.length) {
uni.showToast({
title: '上传图片成功',
icon: 'success'
});
}
_self.$emit('add', {
currentImages: imagePathArr,
allImages: _self.imageList
});
_self.$emit('input', _self.imageList);
_self.$emit('uploading', false);
} else {
uni.hideLoading();
_self.imageList = imagePathArr;
_self.$emit('data', imagePathArr);
_self.$emit('add', {
currentImages: imagePathArr,
allImages: imagePathArr
});
_self.$emit('input', imagePathArr);
_self.$emit('uploading', false);
}
},
fail: err => {
console.log(err);
if (err['code'] && err.code !== 0 && this.sourceTypeIndex === 2) {
this.checkPermission(err.code);
}
// uni.getSetting({
// success: res => {
// let authStatus = false;
// switch (this.sourceTypeIndex) {
// case 0:
// authStatus = res.authSetting['scope.camera'];
// break;
// case 1:
// authStatus = res.authSetting['scope.album'];
// break;
// case 2:
// authStatus = res.authSetting['scope.album'] && res.authSetting['scope.camera'];
// break;
// default:
// break;
// }
// if (!authStatus) {
// uni.showModal({
// title: '授权失败',
// content: 'Hello uni-app需要从您的相机或相册获取图片,请在设置界面打开相关权限',
// success: res => {
// if (res.confirm) {
// uni.openSetting();
// }
// }
// });
// }
// }
// });
}
});
},
deleteImage: function(e) {
var imageIndex = e.currentTarget.dataset.index;
console.log(this.imageList)
var deletedImagePath = this.imageList[imageIndex];
this.imageList.splice(imageIndex, 1);
this.attfileList.splice(imageIndex, 1);
this.$emit('delete', {
currentImage: deletedImagePath,
allImages: this.imageList
}, this.dataIndex);
this.$emit('input', this.imageList);
},
previewImage: function(e) {
var imageIndex = e.currentTarget.dataset.index;
uni.previewImage({
// current: this.imageList[imageIndex],
current: imageIndex,
indicator: 'number',
loop: 'true',
urls: this.imageList
});
},
isFullImg: function() {
return new Promise(res => {
uni.showModal({
content: '已经有' + this.limit + '张图片了,是否清空现有图片?',
success: e => {
if (e.confirm) {
this.imageList = [];
res(true);
} else {
res(false);
}
},
fail: () => {
res(false);
}
});
});
},
// 限制图片上传数量
isFullImgNew: function() {
return new Promise(res => {
uni.showModal({
content: '最多上传6张照片',
success: e => {
if (e.confirm) {
res(true);
} else {
res(false);
}
},
fail: () => {
res(false);
}
});
});
},
async compressImageHandler(src) {
const tempPath = await compressImage(src, device.platform);
return tempPath;
},
async checkPermission(code) {
let type = code ? code - 1 : this.sourceTypeIndex;
let status = permision.isIOS
? await permision.requestIOS(sourceType[type][0])
: await permision.requestAndroid(type === 0 ? 'android.permission.CAMERA' : 'android.permission.READ_EXTERNAL_STORAGE');
if (status === null || status === 1) {
status = 1;
} else {
uni.showModal({
content: '没有开启权限',
confirmText: '设置',
success: function(res) {
if (res.confirm) {
permision.gotoAppSetting();
}
}
});
}
return status;
}
}
};
</script>
<style>
.imageUploadContainer {
/* padding: 10rpx 5rpx; */
margin: 10rpx 5rpx;
}
.imageUploadList {
display: flex;
flex-wrap: wrap;
}
.imageItem,
.imageUpload {
width: 160rpx;
height: 160rpx;
margin: 10rpx;
}
.imageDel {
position: relative;
left: 120rpx;
bottom: 165rpx;
background-color: rgba(0, 0, 0, 0.5);
width: 36rpx;
text-align: center;
line-height: 35rpx;
border-radius: 17rpx;
color: white;
font-size: 30rpx;
padding-bottom: 2rpx;
}
.imageItem image {
width: 160rpx;
height: 160rpx;
border-radius: 8rpx;
}
.imageUpload {
line-height: 130rpx;
text-align: center;
font-size: 150rpx;
color: #d9d9d9;
/* border: 1px solid #d9d9d9; */
/* border-radius: 8rpx; */
}
</style>
This source diff could not be displayed because it is too large. You can view the blob instead.
<template>
<view class="main">
<view class="input" :style="disabled ? 'background-color:#f5f7fa' : ''">
<input @click="showModal" v-model="bValue" :style="disabled ? 'color:#c0c4cc' : ''" :placeholder="placeholder" disabled />
<text v-if="clearable && !disabled" @click="empty" class="selectIcon iconcross"></text>
</view>
<view class="select-modal" :class="isShowModal ? 'show' : ''" @tap="hideModal">
<view class="select-dialog" @tap.stop="" :style="{ backgroundColor: bgColor }">
<view class="select-bar bg-white">
<view class="action text-blue" @tap="cancelClick">{{ cancelText }}</view>
<view class="action text-green" @tap="confirmClick">{{ confirmText }}</view>
</view>
<view class="select-content">
<view
class="select-item"
v-for="(item, index) in list"
:key="index"
:style="valueIndexOf(item) ? 'color:' + selectColor + ';background-color:' + selectBgColor + ';' : 'color:' + color + ';'"
@click="select(item)"
>
<view class="title">{{ getListKeyValue(item) }}</view>
<text class="selectIcon icongou" v-if="valueIndexOf(item)"></text>
</view>
</view>
</view>
</view>
</view>
</template>
<script>
import eval5 from './eval5.min.js';
export default {
data() {
return {
isShowModal: false,
sValue: null,
bValue: ''
};
},
props: {
value: [String, Array],
placeholder: {
// 占位符
default: '',
type: String
},
multiple: {
// 是否多选
default: false,
type: Boolean
},
list: {
default: () => [],
type: Array
},
valueKey: {
// 指定list中valueKey的值作为下拉框绑定内容
default: null,
type: String
},
listKey: {
// 指定list中listKey的值作为下拉框显示内容
default: null,
type: String
},
disabled: {
default: false,
type: Boolean
},
clearable: {
default: false,
type: Boolean
},
cancelText: {
default: '取消',
type: String
},
confirmText: {
default: '确定',
type: String
},
color: {
default: '#000000',
type: String
},
selectColor: {
default: '#0081ff',
type: String
},
bgColor: {
default: '#F1F1F1',
type: String
},
selectBgColor: {
default: '#FFFFFF',
type: String
}
},
watch: {
sValue(val) {
this.bValue = this.getBValye(val);
this.$emit('change', val);
}
},
created() {
if (Array.isArray(this.value)) {
this.sValue = this.value ? this.value : [];
} else {
this.sValue = this.value;
}
},
methods: {
getBValye(val) {
// 将数组值转换为以,隔开的字符串
if (val.length > 0) {
if (Array.isArray(val)) {
let chooseAttr = [];
val.forEach(item => {
let choose = this.list.find(temp => {
let val_val = this.getValueKeyValue(temp);
return item === val_val;
});
chooseAttr.push(choose);
});
let values = chooseAttr.map(temp => this.getListKeyValue(temp)).join(',');
return values;
} else {
let choose = this.list.find(temp => {
let val_val = this.getValueKeyValue(temp);
return val === val_val;
});
return this.getListKeyValue(choose);
}
} else {
return '';
}
},
select(item) {
let val = this.getValueKeyValue(item);
if (this.multiple) {
let index = this.sValue.indexOf(val);
if (index != -1) {
this.sValue.splice(index, 1);
} else {
this.sValue.push(val);
}
} else {
this.sValue = val;
this.hideModal();
}
},
valueIndexOf(item) {
if (this.valueKey) {
return this.value.indexOf(this.evil(item)) != -1;
} else {
return this.value.indexOf(item) != -1;
}
},
getListKeyValue(item) {
if (this.listKey) {
let func = new eval5('item', 'return ' + 'item.' + this.listKey);
return func(item);
} else {
return item;
}
},
getValueKeyValue(item) {
if (this.valueKey) {
return this.evil(item);
} else {
return item;
}
},
evil(item) {
let func = new eval5('item', 'return ' + 'item.' + this.valueKey);
return func(item);
},
empty() {
if (this.multiple) {
this.sValue = [];
} else {
this.sValue = '';
}
},
cancelClick() {
// 点击取消
this.$emit('cancel', this.sValue);
this.hideModal();
},
confirmClick() {
// 点击确定
this.$emit('confirm', this.sValue);
this.hideModal();
},
showModal() {
if (!this.disabled) {
this.isShowModal = true;
}
},
hideModal() {
this.isShowModal = false;
}
}
};
</script>
<style>
@font-face {
font-family: 'selectIcon';
src: url('//at.alicdn.com/t/font_1833441_ycfzdhg2u3.eot?t=1590375117208'); /* IE9 */
src: url('//at.alicdn.com/t/font_1833441_ycfzdhg2u3.eot?t=1590375117208#iefix') format('embedded-opentype'),
/* IE6-IE8 */
url('data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAAAMEAAsAAAAABvQAAAK4AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHEIGVgCDBgqBRIFCATYCJAMMCwgABCAFhQUHNRsfBsg+QCa3uoO0oAJTMwhxVu965keqWBy1hkbwtfzWb2Z279/shRhJisKF6FApKLI7oyBbpAaHo3w24k+ca9EUJbDmjaeznUdZ/FOUlkWdJ33rizZY/Pw6J5Xw0qKYxHTMesePHVT6EFpaC4zV70sKi2bYgNPc1w0WHnDVC/e/UnNTgyP+4Jq6BBpIHoisgypLaIAFEtU0wgeaIG8Yu4nAIZwnUK1QgFfOT6nUUoBpgXjj2lqplTMpiuXtCW3N2iK+aPTS2/Qdnzny8d+5IEiaDMy99exklra//FrKnX48pChmgrq5QcYRQCEe17ruqgqLAKv8WntwqwhpLms/nB5yW/iHRxJEC0QOgT3NnfgF01NBKvOuIzNoZdh5gJuAeGrsozE8vOJ7u5D832oz55039W5G+S52K0H+zNf1TJz07k26kqoQybRfwVFV4rjDS/K8EXUyuF1cXnT3weKS9Rvdm/xe7h8oA1hLwOR18R+Y4n4zwpr4z5SU089Vc+cpfWL+mn5APmT3Z39jeOs/GbWjK+DnmsuL/u6ehMX4j4yedSVkAUUuPh3TY022MtKZUEOtPqCb8Bkvnr5XT6imU0gGrEJW7aAL/gw0OhegVV2F6pC7uTOppirKIA4MFQhTrpCM+AbZlDu64L/QmAkQWlMhQXU75D07O9Gtl0PUYjTBLyAzOLNQYtypIEEjvsXtBLQTooV2nrQrGEau2gKmZlR4L8gwnGtBJbUn1diCOOQUnEkTkRAOeci9KHOQxvFro+tx3ZcGAaeljstCSBNDJuArgIyBYyy6OdZxAhHIELu1IC9AtgShCVtLltEKrSff1XoHJo3RC33hM63o3j6pSNkmqmIWEAtxFHB2OwoRBAfyeqE3r2ogHeF42dBhs7gvf7CukH5MmlUGOCpHihxFfs6TehDyKCqVAA==')
format('woff2'),
url('//at.alicdn.com/t/font_1833441_ycfzdhg2u3.woff?t=1590375117208') format('woff'),
url('//at.alicdn.com/t/font_1833441_ycfzdhg2u3.ttf?t=1590375117208') format('truetype'),
/* chrome, firefox, opera, Safari, Android, iOS 4.2+ */ url('//at.alicdn.com/t/font_1833441_ycfzdhg2u3.svg?t=1590375117208#selectIcon') format('svg'); /* iOS 4.1- */
}
.selectIcon {
font-family: 'selectIcon' !important;
font-size: 16px;
font-style: normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.icongou:before {
content: '\e61c';
}
.iconcross:before {
content: '\e61a';
}
</style>
<style lang="scss" scoped>
.main {
font-size: 28rpx;
flex: 1;
}
.bg-white {
background-color: #ffffff;
}
.text-blue {
color: #0081ff;
}
.text-green {
color: #39b54a;
}
.cu-form-group uni-input {
padding-right: 0;
}
.input {
display: flex;
// align-items: center;
font-size: 28rpx;
height: 60rpx;
padding: 10rpx 20rpx;
text-align: right;
// border-radius: 10rpx;
// border-style: solid;
// border-width: 1rpx;
// border-color: rgba(0, 0, 0, 0.1);
input {
flex: 1;
}
}
.select-modal {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 9999;
opacity: 0;
outline: 0;
text-align: center;
-ms-transform: scale(1.185);
transform: scale(1.185);
backface-visibility: hidden;
perspective: 2000rpx;
background: rgba(0, 0, 0, 0.6);
transition: all 0.3s ease-in-out 0s;
pointer-events: none;
margin-bottom: -1000rpx;
&::before {
content: '\200B';
display: inline-block;
height: 100%;
vertical-align: bottom;
}
.select-dialog {
position: relative;
display: inline-block;
margin-left: auto;
margin-right: auto;
background-color: #f8f8f8;
overflow: hidden;
width: 100%;
border-radius: 0;
.select-content {
// background-color: #F1F1F1;
max-height: 420rpx;
overflow: auto;
.select-item {
padding: 20rpx;
display: flex;
.title {
flex: 1;
}
}
}
}
}
.select-modal.show {
opacity: 1;
transition-duration: 0.3s;
-ms-transform: scale(1);
transform: scale(1);
overflow-x: hidden;
overflow-y: auto;
pointer-events: auto;
margin-bottom: 0;
}
.select-bar {
padding: 0 20rpx;
display: flex;
position: relative;
align-items: center;
min-height: 80rpx;
justify-content: space-between;
.action {
display: flex;
align-items: center;
height: 100%;
justify-content: center;
max-width: 100%;
}
}
</style>
Copyright (c) JS Foundation and other contributors
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.
# [Moment.js](http://momentjs.com/)
[![NPM version][npm-version-image]][npm-url]
[![NPM downloads][npm-downloads-image]][npm-downloads-url]
[![MIT License][license-image]][license-url]
[![Build Status][travis-image]][travis-url]
[![Coverage Status][coveralls-image]][coveralls-url]
[![FOSSA Status][fossa-badge-image]][fossa-badge-url]
[![SemVer compatibility][semver-image]][semver-url]
A JavaScript date library for parsing, validating, manipulating, and formatting dates.
## Project Status
Moment.js is a legacy project, now in maintenance mode. In most cases, you should choose a different library.
For more details and recommendations, please see [Project Status](https://momentjs.com/docs/#/-project-status/) in the docs.
*Thank you.*
## Resources
- [Documentation](https://momentjs.com/docs/)
- [Changelog](CHANGELOG.md)
- [Stack Overflow](https://stackoverflow.com/questions/tagged/momentjs)
## License
Moment.js is freely distributable under the terms of the [MIT license][license-url].
[![FOSSA Status][fossa-large-image]][fossa-large-url]
[license-image]: https://img.shields.io/badge/license-MIT-blue.svg?style=flat
[license-url]: LICENSE
[npm-url]: https://npmjs.org/package/moment
[npm-version-image]: https://img.shields.io/npm/v/moment.svg?style=flat
[npm-downloads-image]: https://img.shields.io/npm/dm/moment.svg?style=flat
[npm-downloads-url]: https://npmcharts.com/compare/moment?minimal=true
[travis-url]: https://travis-ci.org/moment/moment
[travis-image]: https://img.shields.io/travis/moment/moment/develop.svg?style=flat
[coveralls-image]: https://coveralls.io/repos/moment/moment/badge.svg?branch=develop
[coveralls-url]: https://coveralls.io/r/moment/moment?branch=develop
[fossa-badge-image]: https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fmoment%2Fmoment.svg?type=shield
[fossa-badge-url]: https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fmoment%2Fmoment?ref=badge_shield
[fossa-large-image]: https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fmoment%2Fmoment.svg?type=large
[fossa-large-url]: https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fmoment%2Fmoment?ref=badge_large
[semver-image]: https://api.dependabot.com/badges/compatibility_score?dependency-name=moment&package-manager=npm_and_yarn&version-scheme=semver
[semver-url]: https://dependabot.com/compatibility-score.html?dependency-name=moment&package-manager=npm_and_yarn&version-scheme=semver
//! moment.js locale configuration
//! locale : Afrikaans [af]
//! author : Werner Mollentze : https://github.com/wernerm
import moment from '../moment';
export default moment.defineLocale('af', {
months: 'Januarie_Februarie_Maart_April_Mei_Junie_Julie_Augustus_September_Oktober_November_Desember'.split(
'_'
),
monthsShort: 'Jan_Feb_Mrt_Apr_Mei_Jun_Jul_Aug_Sep_Okt_Nov_Des'.split('_'),
weekdays: 'Sondag_Maandag_Dinsdag_Woensdag_Donderdag_Vrydag_Saterdag'.split(
'_'
),
weekdaysShort: 'Son_Maa_Din_Woe_Don_Vry_Sat'.split('_'),
weekdaysMin: 'So_Ma_Di_Wo_Do_Vr_Sa'.split('_'),
meridiemParse: /vm|nm/i,
isPM: function (input) {
return /^nm$/i.test(input);
},
meridiem: function (hours, minutes, isLower) {
if (hours < 12) {
return isLower ? 'vm' : 'VM';
} else {
return isLower ? 'nm' : 'NM';
}
},
longDateFormat: {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L: 'DD/MM/YYYY',
LL: 'D MMMM YYYY',
LLL: 'D MMMM YYYY HH:mm',
LLLL: 'dddd, D MMMM YYYY HH:mm',
},
calendar: {
sameDay: '[Vandag om] LT',
nextDay: '[Môre om] LT',
nextWeek: 'dddd [om] LT',
lastDay: '[Gister om] LT',
lastWeek: '[Laas] dddd [om] LT',
sameElse: 'L',
},
relativeTime: {
future: 'oor %s',
past: '%s gelede',
s: "'n paar sekondes",
ss: '%d sekondes',
m: "'n minuut",
mm: '%d minute',
h: "'n uur",
hh: '%d ure',
d: "'n dag",
dd: '%d dae',
M: "'n maand",
MM: '%d maande',
y: "'n jaar",
yy: '%d jaar',
},
dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/,
ordinal: function (number) {
return (
number +
(number === 1 || number === 8 || number >= 20 ? 'ste' : 'de')
); // Thanks to Joris Röling : https://github.com/jjupiter
},
week: {
dow: 1, // Maandag is die eerste dag van die week.
doy: 4, // Die week wat die 4de Januarie bevat is die eerste week van die jaar.
},
});
//! moment.js locale configuration
//! locale : Arabic (Algeria) [ar-dz]
//! author : Amine Roukh: https://github.com/Amine27
//! author : Abdel Said: https://github.com/abdelsaid
//! author : Ahmed Elkhatib
//! author : forabi https://github.com/forabi
//! author : Noureddine LOUAHEDJ : https://github.com/noureddinem
import moment from '../moment';
var pluralForm = function (n) {
return n === 0
? 0
: n === 1
? 1
: n === 2
? 2
: n % 100 >= 3 && n % 100 <= 10
? 3
: n % 100 >= 11
? 4
: 5;
},
plurals = {
s: [
'أقل من ثانية',
'ثانية واحدة',
['ثانيتان', 'ثانيتين'],
'%d ثوان',
'%d ثانية',
'%d ثانية',
],
m: [
'أقل من دقيقة',
'دقيقة واحدة',
['دقيقتان', 'دقيقتين'],
'%d دقائق',
'%d دقيقة',
'%d دقيقة',
],
h: [
'أقل من ساعة',
'ساعة واحدة',
['ساعتان', 'ساعتين'],
'%d ساعات',
'%d ساعة',
'%d ساعة',
],
d: [
'أقل من يوم',
'يوم واحد',
['يومان', 'يومين'],
'%d أيام',
'%d يومًا',
'%d يوم',
],
M: [
'أقل من شهر',
'شهر واحد',
['شهران', 'شهرين'],
'%d أشهر',
'%d شهرا',
'%d شهر',
],
y: [
'أقل من عام',
'عام واحد',
['عامان', 'عامين'],
'%d أعوام',
'%d عامًا',
'%d عام',
],
},
pluralize = function (u) {
return function (number, withoutSuffix, string, isFuture) {
var f = pluralForm(number),
str = plurals[u][pluralForm(number)];
if (f === 2) {
str = str[withoutSuffix ? 0 : 1];
}
return str.replace(/%d/i, number);
};
},
months = [
'جانفي',
'فيفري',
'مارس',
'أفريل',
'ماي',
'جوان',
'جويلية',
'أوت',
'سبتمبر',
'أكتوبر',
'نوفمبر',
'ديسمبر',
];
export default moment.defineLocale('ar-dz', {
months: months,
monthsShort: months,
weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),
weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),
weekdaysParseExact: true,
longDateFormat: {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L: 'D/\u200FM/\u200FYYYY',
LL: 'D MMMM YYYY',
LLL: 'D MMMM YYYY HH:mm',
LLLL: 'dddd D MMMM YYYY HH:mm',
},
meridiemParse: /ص|م/,
isPM: function (input) {
return 'م' === input;
},
meridiem: function (hour, minute, isLower) {
if (hour < 12) {
return 'ص';
} else {
return 'م';
}
},
calendar: {
sameDay: '[اليوم عند الساعة] LT',
nextDay: '[غدًا عند الساعة] LT',
nextWeek: 'dddd [عند الساعة] LT',
lastDay: '[أمس عند الساعة] LT',
lastWeek: 'dddd [عند الساعة] LT',
sameElse: 'L',
},
relativeTime: {
future: 'بعد %s',
past: 'منذ %s',
s: pluralize('s'),
ss: pluralize('s'),
m: pluralize('m'),
mm: pluralize('m'),
h: pluralize('h'),
hh: pluralize('h'),
d: pluralize('d'),
dd: pluralize('d'),
M: pluralize('M'),
MM: pluralize('M'),
y: pluralize('y'),
yy: pluralize('y'),
},
postformat: function (string) {
return string.replace(/,/g, '،');
},
week: {
dow: 0, // Sunday is the first day of the week.
doy: 4, // The week that contains Jan 4th is the first week of the year.
},
});
//! moment.js locale configuration
//! locale : Arabic (Kuwait) [ar-kw]
//! author : Nusret Parlak: https://github.com/nusretparlak
import moment from '../moment';
export default moment.defineLocale('ar-kw', {
months: 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split(
'_'
),
monthsShort:
'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split(
'_'
),
weekdays: 'الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
weekdaysShort: 'احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'),
weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),
weekdaysParseExact: true,
longDateFormat: {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L: 'DD/MM/YYYY',
LL: 'D MMMM YYYY',
LLL: 'D MMMM YYYY HH:mm',
LLLL: 'dddd D MMMM YYYY HH:mm',
},
calendar: {
sameDay: '[اليوم على الساعة] LT',
nextDay: '[غدا على الساعة] LT',
nextWeek: 'dddd [على الساعة] LT',
lastDay: '[أمس على الساعة] LT',
lastWeek: 'dddd [على الساعة] LT',
sameElse: 'L',
},
relativeTime: {
future: 'في %s',
past: 'منذ %s',
s: 'ثوان',
ss: '%d ثانية',
m: 'دقيقة',
mm: '%d دقائق',
h: 'ساعة',
hh: '%d ساعات',
d: 'يوم',
dd: '%d أيام',
M: 'شهر',
MM: '%d أشهر',
y: 'سنة',
yy: '%d سنوات',
},
week: {
dow: 0, // Sunday is the first day of the week.
doy: 12, // The week that contains Jan 12th is the first week of the year.
},
});
//! moment.js locale configuration
//! locale : Arabic (Libya) [ar-ly]
//! author : Ali Hmer: https://github.com/kikoanis
import moment from '../moment';
var symbolMap = {
1: '1',
2: '2',
3: '3',
4: '4',
5: '5',
6: '6',
7: '7',
8: '8',
9: '9',
0: '0',
},
pluralForm = function (n) {
return n === 0
? 0
: n === 1
? 1
: n === 2
? 2
: n % 100 >= 3 && n % 100 <= 10
? 3
: n % 100 >= 11
? 4
: 5;
},
plurals = {
s: [
'أقل من ثانية',
'ثانية واحدة',
['ثانيتان', 'ثانيتين'],
'%d ثوان',
'%d ثانية',
'%d ثانية',
],
m: [
'أقل من دقيقة',
'دقيقة واحدة',
['دقيقتان', 'دقيقتين'],
'%d دقائق',
'%d دقيقة',
'%d دقيقة',
],
h: [
'أقل من ساعة',
'ساعة واحدة',
['ساعتان', 'ساعتين'],
'%d ساعات',
'%d ساعة',
'%d ساعة',
],
d: [
'أقل من يوم',
'يوم واحد',
['يومان', 'يومين'],
'%d أيام',
'%d يومًا',
'%d يوم',
],
M: [
'أقل من شهر',
'شهر واحد',
['شهران', 'شهرين'],
'%d أشهر',
'%d شهرا',
'%d شهر',
],
y: [
'أقل من عام',
'عام واحد',
['عامان', 'عامين'],
'%d أعوام',
'%d عامًا',
'%d عام',
],
},
pluralize = function (u) {
return function (number, withoutSuffix, string, isFuture) {
var f = pluralForm(number),
str = plurals[u][pluralForm(number)];
if (f === 2) {
str = str[withoutSuffix ? 0 : 1];
}
return str.replace(/%d/i, number);
};
},
months = [
'يناير',
'فبراير',
'مارس',
'أبريل',
'مايو',
'يونيو',
'يوليو',
'أغسطس',
'سبتمبر',
'أكتوبر',
'نوفمبر',
'ديسمبر',
];
export default moment.defineLocale('ar-ly', {
months: months,
monthsShort: months,
weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),
weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),
weekdaysParseExact: true,
longDateFormat: {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L: 'D/\u200FM/\u200FYYYY',
LL: 'D MMMM YYYY',
LLL: 'D MMMM YYYY HH:mm',
LLLL: 'dddd D MMMM YYYY HH:mm',
},
meridiemParse: /ص|م/,
isPM: function (input) {
return 'م' === input;
},
meridiem: function (hour, minute, isLower) {
if (hour < 12) {
return 'ص';
} else {
return 'م';
}
},
calendar: {
sameDay: '[اليوم عند الساعة] LT',
nextDay: '[غدًا عند الساعة] LT',
nextWeek: 'dddd [عند الساعة] LT',
lastDay: '[أمس عند الساعة] LT',
lastWeek: 'dddd [عند الساعة] LT',
sameElse: 'L',
},
relativeTime: {
future: 'بعد %s',
past: 'منذ %s',
s: pluralize('s'),
ss: pluralize('s'),
m: pluralize('m'),
mm: pluralize('m'),
h: pluralize('h'),
hh: pluralize('h'),
d: pluralize('d'),
dd: pluralize('d'),
M: pluralize('M'),
MM: pluralize('M'),
y: pluralize('y'),
yy: pluralize('y'),
},
preparse: function (string) {
return string.replace(/،/g, ',');
},
postformat: function (string) {
return string
.replace(/\d/g, function (match) {
return symbolMap[match];
})
.replace(/,/g, '،');
},
week: {
dow: 6, // Saturday is the first day of the week.
doy: 12, // The week that contains Jan 12th is the first week of the year.
},
});
//! moment.js locale configuration
//! locale : Arabic (Morocco) [ar-ma]
//! author : ElFadili Yassine : https://github.com/ElFadiliY
//! author : Abdel Said : https://github.com/abdelsaid
import moment from '../moment';
export default moment.defineLocale('ar-ma', {
months: 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split(
'_'
),
monthsShort:
'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split(
'_'
),
weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
weekdaysShort: 'احد_اثنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'),
weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),
weekdaysParseExact: true,
longDateFormat: {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L: 'DD/MM/YYYY',
LL: 'D MMMM YYYY',
LLL: 'D MMMM YYYY HH:mm',
LLLL: 'dddd D MMMM YYYY HH:mm',
},
calendar: {
sameDay: '[اليوم على الساعة] LT',
nextDay: '[غدا على الساعة] LT',
nextWeek: 'dddd [على الساعة] LT',
lastDay: '[أمس على الساعة] LT',
lastWeek: 'dddd [على الساعة] LT',
sameElse: 'L',
},
relativeTime: {
future: 'في %s',
past: 'منذ %s',
s: 'ثوان',
ss: '%d ثانية',
m: 'دقيقة',
mm: '%d دقائق',
h: 'ساعة',
hh: '%d ساعات',
d: 'يوم',
dd: '%d أيام',
M: 'شهر',
MM: '%d أشهر',
y: 'سنة',
yy: '%d سنوات',
},
week: {
dow: 1, // Monday is the first day of the week.
doy: 4, // The week that contains Jan 4th is the first week of the year.
},
});
//! moment.js locale configuration
//! locale : Arabic (Saudi Arabia) [ar-sa]
//! author : Suhail Alkowaileet : https://github.com/xsoh
import moment from '../moment';
var symbolMap = {
1: '١',
2: '٢',
3: '٣',
4: '٤',
5: '٥',
6: '٦',
7: '٧',
8: '٨',
9: '٩',
0: '٠',
},
numberMap = {
'١': '1',
'٢': '2',
'٣': '3',
'٤': '4',
'٥': '5',
'٦': '6',
'٧': '7',
'٨': '8',
'٩': '9',
'٠': '0',
};
export default moment.defineLocale('ar-sa', {
months: 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split(
'_'
),
monthsShort:
'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split(
'_'
),
weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),
weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),
weekdaysParseExact: true,
longDateFormat: {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L: 'DD/MM/YYYY',
LL: 'D MMMM YYYY',
LLL: 'D MMMM YYYY HH:mm',
LLLL: 'dddd D MMMM YYYY HH:mm',
},
meridiemParse: /ص|م/,
isPM: function (input) {
return 'م' === input;
},
meridiem: function (hour, minute, isLower) {
if (hour < 12) {
return 'ص';
} else {
return 'م';
}
},
calendar: {
sameDay: '[اليوم على الساعة] LT',
nextDay: '[غدا على الساعة] LT',
nextWeek: 'dddd [على الساعة] LT',
lastDay: '[أمس على الساعة] LT',
lastWeek: 'dddd [على الساعة] LT',
sameElse: 'L',
},
relativeTime: {
future: 'في %s',
past: 'منذ %s',
s: 'ثوان',
ss: '%d ثانية',
m: 'دقيقة',
mm: '%d دقائق',
h: 'ساعة',
hh: '%d ساعات',
d: 'يوم',
dd: '%d أيام',
M: 'شهر',
MM: '%d أشهر',
y: 'سنة',
yy: '%d سنوات',
},
preparse: function (string) {
return string
.replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) {
return numberMap[match];
})
.replace(/،/g, ',');
},
postformat: function (string) {
return string
.replace(/\d/g, function (match) {
return symbolMap[match];
})
.replace(/,/g, '،');
},
week: {
dow: 0, // Sunday is the first day of the week.
doy: 6, // The week that contains Jan 6th is the first week of the year.
},
});
//! moment.js locale configuration
//! locale : Arabic (Tunisia) [ar-tn]
//! author : Nader Toukabri : https://github.com/naderio
import moment from '../moment';
export default moment.defineLocale('ar-tn', {
months: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split(
'_'
),
monthsShort:
'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split(
'_'
),
weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),
weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),
weekdaysParseExact: true,
longDateFormat: {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L: 'DD/MM/YYYY',
LL: 'D MMMM YYYY',
LLL: 'D MMMM YYYY HH:mm',
LLLL: 'dddd D MMMM YYYY HH:mm',
},
calendar: {
sameDay: '[اليوم على الساعة] LT',
nextDay: '[غدا على الساعة] LT',
nextWeek: 'dddd [على الساعة] LT',
lastDay: '[أمس على الساعة] LT',
lastWeek: 'dddd [على الساعة] LT',
sameElse: 'L',
},
relativeTime: {
future: 'في %s',
past: 'منذ %s',
s: 'ثوان',
ss: '%d ثانية',
m: 'دقيقة',
mm: '%d دقائق',
h: 'ساعة',
hh: '%d ساعات',
d: 'يوم',
dd: '%d أيام',
M: 'شهر',
MM: '%d أشهر',
y: 'سنة',
yy: '%d سنوات',
},
week: {
dow: 1, // Monday is the first day of the week.
doy: 4, // The week that contains Jan 4th is the first week of the year.
},
});
//! moment.js locale configuration
//! locale : Arabic [ar]
//! author : Abdel Said: https://github.com/abdelsaid
//! author : Ahmed Elkhatib
//! author : forabi https://github.com/forabi
import moment from '../moment';
var symbolMap = {
1: '١',
2: '٢',
3: '٣',
4: '٤',
5: '٥',
6: '٦',
7: '٧',
8: '٨',
9: '٩',
0: '٠',
},
numberMap = {
'١': '1',
'٢': '2',
'٣': '3',
'٤': '4',
'٥': '5',
'٦': '6',
'٧': '7',
'٨': '8',
'٩': '9',
'٠': '0',
},
pluralForm = function (n) {
return n === 0
? 0
: n === 1
? 1
: n === 2
? 2
: n % 100 >= 3 && n % 100 <= 10
? 3
: n % 100 >= 11
? 4
: 5;
},
plurals = {
s: [
'أقل من ثانية',
'ثانية واحدة',
['ثانيتان', 'ثانيتين'],
'%d ثوان',
'%d ثانية',
'%d ثانية',
],
m: [
'أقل من دقيقة',
'دقيقة واحدة',
['دقيقتان', 'دقيقتين'],
'%d دقائق',
'%d دقيقة',
'%d دقيقة',
],
h: [
'أقل من ساعة',
'ساعة واحدة',
['ساعتان', 'ساعتين'],
'%d ساعات',
'%d ساعة',
'%d ساعة',
],
d: [
'أقل من يوم',
'يوم واحد',
['يومان', 'يومين'],
'%d أيام',
'%d يومًا',
'%d يوم',
],
M: [
'أقل من شهر',
'شهر واحد',
['شهران', 'شهرين'],
'%d أشهر',
'%d شهرا',
'%d شهر',
],
y: [
'أقل من عام',
'عام واحد',
['عامان', 'عامين'],
'%d أعوام',
'%d عامًا',
'%d عام',
],
},
pluralize = function (u) {
return function (number, withoutSuffix, string, isFuture) {
var f = pluralForm(number),
str = plurals[u][pluralForm(number)];
if (f === 2) {
str = str[withoutSuffix ? 0 : 1];
}
return str.replace(/%d/i, number);
};
},
months = [
'يناير',
'فبراير',
'مارس',
'أبريل',
'مايو',
'يونيو',
'يوليو',
'أغسطس',
'سبتمبر',
'أكتوبر',
'نوفمبر',
'ديسمبر',
];
export default moment.defineLocale('ar', {
months: months,
monthsShort: months,
weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),
weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),
weekdaysParseExact: true,
longDateFormat: {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L: 'D/\u200FM/\u200FYYYY',
LL: 'D MMMM YYYY',
LLL: 'D MMMM YYYY HH:mm',
LLLL: 'dddd D MMMM YYYY HH:mm',
},
meridiemParse: /ص|م/,
isPM: function (input) {
return 'م' === input;
},
meridiem: function (hour, minute, isLower) {
if (hour < 12) {
return 'ص';
} else {
return 'م';
}
},
calendar: {
sameDay: '[اليوم عند الساعة] LT',
nextDay: '[غدًا عند الساعة] LT',
nextWeek: 'dddd [عند الساعة] LT',
lastDay: '[أمس عند الساعة] LT',
lastWeek: 'dddd [عند الساعة] LT',
sameElse: 'L',
},
relativeTime: {
future: 'بعد %s',
past: 'منذ %s',
s: pluralize('s'),
ss: pluralize('s'),
m: pluralize('m'),
mm: pluralize('m'),
h: pluralize('h'),
hh: pluralize('h'),
d: pluralize('d'),
dd: pluralize('d'),
M: pluralize('M'),
MM: pluralize('M'),
y: pluralize('y'),
yy: pluralize('y'),
},
preparse: function (string) {
return string
.replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) {
return numberMap[match];
})
.replace(/،/g, ',');
},
postformat: function (string) {
return string
.replace(/\d/g, function (match) {
return symbolMap[match];
})
.replace(/,/g, '،');
},
week: {
dow: 6, // Saturday is the first day of the week.
doy: 12, // The week that contains Jan 12th is the first week of the year.
},
});
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed. Click to expand it.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment