GitBucket
4.6.0
Toggle navigation
Sign in
Files
Branches
1
Tags
Issues
Pull Requests
Labels
Milestones
Wiki
08335
/
hivui-platform-template
hivui平台项目模板
Browse code
Merge branch 'master' of http://git.hieap.cn/gitbucket/git/08335/hivui-platform-template
master
commit
72cfb5c0696f52ed0f65811aa77c74cdff32f782
2 parents
7e98b09
+
9e9646f
hhb
authored
on 7 May
Showing
3 changed files
project/hivuiLogin/views/register.vue
project/hivuiMain/views/layout/index.vue
vite-plugin/vite-plugin-func.js
Ignore Space
Show notes
View
project/hivuiLogin/views/register.vue
<template> <div class="register"> <div class="register_hd"> <div class="register_logo" :style="register_logo_style"> <img :src="config.loginLogoImg"> </div> <div class="register_text">{{$t('hivuiLogin_register_title')}}</div> </div> <div class="register_main" :style="bgStyle"> <div class="register_box"> <h3>{{$t('hivuiLogin_register_box_title')}}</h3> <el-form ref="registerForm" :model="registerForm" :rules="registerRules"> <el-form-item class="register_field" prop="username"> <el-input ref="username" v-model="registerForm.username" type="text" :placeholder="$t('hivuiLogin_register_user')"></el-input> </el-form-item> <el-form-item class="register_field" prop="phone"> <el-input ref="phone" v-model="registerForm.phone" type="text" :placeholder="$t('hivuiLogin_register_phone')"></el-input> </el-form-item> <el-form-item class="register_field" prop="pw1"> <el-input ref="pw1" v-model="registerForm.pw1" type="password" :placeholder="$t('hivuiLogin_register_pw1')"></el-input> <pwStrength class="register_pwStrength" v-model="registerForm.pw1" :minPw="minPw"></pwStrength> </el-form-item> <el-form-item class="register_field" prop="pw2"> <el-input ref="pw2" v-model="registerForm.pw2" type="password" :placeholder="$t('hivuiLogin_register_pw2')"></el-input> </el-form-item> <el-form-item class="register_field register_row" prop="captcha"> <el-input ref="captcha" v-model="registerForm.captcha" type="text" :placeholder="$t('hivuiLogin_register_captcha')"></el-input> <el-button class="register_capbtn" :loading="captchaLoading" type="primary" :disabled="captchaTimer==0?false:true" @click="getCaptcha" >{{captchaTimer==0?$t('hivuiLogin_reset_getCaptcha'):(captchaTimer+$t('hivuiLogin_reset_getAgain'))}}</el-button> </el-form-item> <!-- <el-form-item class="register_field" prop="email"> <el-input ref="email" v-model="registerForm.email" type="text" placeholder="邮箱"></el-input> </el-form-item>--> <el-button class="register_submit" :loading="registerLoading" type="primary" @click="register" >{{$t('hivuiLogin_register_submit')}}</el-button> </el-form> <div class="register_tips"> {{$t('hivuiLogin_register_tiptext1')}} <span @click="goLoginPage">{{$t('hivuiLogin_register_tiptext2')}}</span> </div> </div> </div> <div class="register_ft" v-html="config.copyright"></div> </div> </template> <script> import _loginLogoImg from "../assets/Logo1.png" import _registerBgImg from "../assets/register/bg.png" import { captcha, register } from "../api/user"; import pwStrength from "../components/pwStrength"; import md5 from "js-md5"; export default { name: "register", components: { pwStrength }, data() { return { registerForm: { phone: "", pw1: "", pw2: "", captcha: "", email: "" }, minPw: 4, registerRules: { username: [ { required: true, message: this.$t('hivuiLogin_register_valid_user'), trigger: "blur" }, { validator: (rule, value, callback) => { if ((value + "").length > 20) { callback(new Error(this.$t('hivuiLogin_register_valid_user2'))); } else { callback(); } }, trigger: "blur" } ], phone: [ { required: true, message: this.$t('hivuiLogin_register_valid_phone'), trigger: "blur" }, { validator: (rule, value, callback) => { if (!/^[1]([3-9])[0-9]{9}$/.test(value)) { callback(new Error(this.$t('hivuiLogin_register_valid_phone2'))); } else { callback(); } }, trigger: "blur" } ], pw1: [ { required: true, message: this.$t('hivuiLogin_register_valid_pw'), trigger: "blur" }, { validator: (rule, value, callback) => { if ((value + "").length < this.minPw) { callback(new Error(this.$t('hivuiLogin_register_valid_pw_msg') + this.minPw + this.$t('hivuiLogin_register_valid_pw_msg2'))); } else { callback(); } }, trigger: "blur" } ], pw2: [ { required: true, message: this.$t('hivuiLogin_register_valid_pw2'), trigger: "blur" }, { validator: (rule, value, callback) => { if (value !== this.registerForm.pw1) { callback(new Error(this.$t('hivuiLogin_register_valid_pw2_msg'))); } else { callback(); } }, trigger: "blur" } ], captcha: [{ required: true, message: this.$t('hivuiLogin_register_valid_captcha'), trigger: "blur" }] /*email: [ { required: true, message: "请填写邮箱地址", trigger: "blur" } ]*/ }, captchaLoading: false, registerLoading: false, captchaTimer: 0, config: { title: window.customSysCofig?.loginTitle||this.$t('hivuiLogin_main_def_title'), loginLogoImg: window.customSysCofig?.loginLogo||_loginLogoImg, loginLogoImg_height: window.customSysCofig?.loginLogo_h||56, loginLogoImg_width: window.customSysCofig?.loginLogo_w||206, registerBgImg: window.customSysCofig?.registerBgImg||_registerBgImg, copyright: window.customSysCofig?.copyright||this.$t('hivuiLogin_main_def_copyright'), }, }; }, model: { prop: "value", event: "valuechange" }, props: { value: { type: Object } }, computed: { bgStyle() { return { "background-image": "url(" + this.config.registerBgImg + ")", }; }, register_logo_style(){ return { "width":(this.config.loginLogoImg_width / 1920) * 100+"vw", "height":(this.config.loginLogoImg_height / 1920) * 100+"vw", } } }, mounted() {}, methods: { //获取验证码 getCaptcha() { this.$refs.registerForm.validateField("phone", errMsg => { if (!errMsg) { let me = this; me.captchaTimer = 60; me.captchaLoading = true; captcha({ phone: me.registerForm.phone }) .then(res => { me.captchaLoading = false; }) .catch(err => { me.captchaLoading = false; }); let _timer = setInterval(() => { --me.captchaTimer; if (me.captchaTimer == 0) { clearInterval(_timer); } }, 1000); } }); }, //注册 register() { let me = this; this.$refs.registerForm.validate(valid => { if (valid) { me.registerLoading = true; register({ type: "phone", username:me.registerForm.username, phone: me.registerForm.phone, password: md5(me.registerForm.pw2), captcha: me.registerForm.captcha }) .then(res => { me.$message({ message: me.$t('hivuiLogin_register_success'), type: "success" }); setTimeout(() => { this.$router.push("/"); }, 1000 * 2); }) .catch(err => { me.registerLoading = false; }); } }); }, goLoginPage() { this.$router.push("/"); } } }; </script> <style lang="scss" scoped> @function px2vw($px) { @return ($px / 1920) * 100vw; } $headH: px2vw(130); $footH: px2vw(172); .register { height: 100%; overflow: hidden; .register_hd { height: $headH; display: flex; align-items: center; padding-top: px2vw(30); padding-left: px2vw(15); .register_logo { width: px2vw(206); height: px2vw(56); margin-right: px2vw(20); img { height: 100%; width: 100%; } } .register_text { font-size: px2vw(22); color: #333; position: relative; padding-left: px2vw(32); &:after { content: ""; display: block; height: px2vw(40); width: px2vw(1); background-color: #7ecef4; position: absolute; top: 0; left: px2vw(10); bottom: 0; margin: auto; } } } .register_main { height: calc(100% - #{$headH} - #{$footH}); position: relative; background: url("../assets/register/bg.png") no-repeat center center; background-size: cover; .register_box { position: absolute; bottom: 0; left: 0; right: 0; margin: auto; width: px2vw(1200); height: px2vw(655); border-radius: px2vw(3); background-color: #fff; padding: 0 px2vw(360) px2vw(40); h3 { text-align: center; line-height: px2vw(100); font-size: px2vw(24); color: #333; font-weight: bold; } .register_field { margin-bottom: px2vw(22); line-height: px2vw(48); ::v-deep.el-input__inner { line-height: px2vw(48); height: px2vw(48); } ::v-deep.el-form-item__content{ line-height: px2vw(50); font-size: px2vw(14); } ::v-deep.el-form-item__error{ padding-top: px2vw(4); } .register_pwStrength { margin-top: px2vw(10); } &.register_row { ::v-deep.el-form-item__content { display: flex; align-items: center; } } } .register_capbtn { width: px2vw(200); height: px2vw(48); line-height: px2vw(48); padding: 0; } .register_submit { height: px2vw(48); line-height: px2vw(48); padding-top: 0; width: 100%; margin-top: px2vw(10); } .register_tips { padding-top: px2vw(20); span { color: #3486d2; cursor: pointer; } } } } .register_ft { height: $footH; line-height: $footH; background-color: #e8f1fa; text-align: center; font-size: px2vw(16); color: #999; border-top: px2vw(1) solid #ccc; border-bottom: px2vw(1) solid #ccc; ::v-deep a{ margin-left:5px; color:#0f406c; &:hover{ color:#409eff; } } } } </style>
<template> <div class="register"> <div class="register_hd"> <div class="register_logo" :style="register_logo_style"> <img :src="config.loginLogoImg"> </div> <div class="register_text">{{$t('hivuiLogin_register_title')}}</div> </div> <div class="register_main" :style="bgStyle"> <div class="register_box"> <h3>{{$t('hivuiLogin_register_box_title')}}</h3> <el-form ref="registerForm" :model="registerForm" :rules="registerRules"> <el-form-item class="register_field" prop="username"> <el-input ref="username" v-model="registerForm.username" type="text" :placeholder="$t('hivuiLogin_register_user')"></el-input> </el-form-item> <el-form-item class="register_field" prop="phone"> <el-input ref="phone" v-model="registerForm.phone" type="text" :placeholder="$t('hivuiLogin_register_phone')"></el-input> </el-form-item> <el-form-item class="register_field" prop="pw1"> <el-input ref="pw1" v-model="registerForm.pw1" type="password" :placeholder="$t('hivuiLogin_register_pw1')"></el-input> <pwStrength class="register_pwStrength" v-model="registerForm.pw1" :minPw="minPw"></pwStrength> </el-form-item> <el-form-item class="register_field" prop="pw2"> <el-input ref="pw2" v-model="registerForm.pw2" type="password" :placeholder="$t('hivuiLogin_register_pw2')"></el-input> </el-form-item> <el-form-item class="register_field register_row" prop="captcha"> <el-input ref="captcha" v-model="registerForm.captcha" type="text" :placeholder="$t('hivuiLogin_register_captcha')"></el-input> <el-button class="register_capbtn" :loading="captchaLoading" type="primary" :disabled="captchaTimer==0?false:true" @click="getCaptcha" >{{captchaTimer==0?$t('hivuiLogin_reset_getCaptcha'):(captchaTimer+$t('hivuiLogin_reset_getAgain'))}}</el-button> </el-form-item> <!-- <el-form-item class="register_field" prop="email"> <el-input ref="email" v-model="registerForm.email" type="text" placeholder="邮箱"></el-input> </el-form-item>--> <el-button class="register_submit" :loading="registerLoading" type="primary" @click="register" >{{$t('hivuiLogin_register_submit')}}</el-button> </el-form> <div class="register_tips"> {{$t('hivuiLogin_register_tiptext1')}} <span @click="goLoginPage">{{$t('hivuiLogin_register_tiptext2')}}</span> </div> </div> </div> <div class="register_ft" v-html="config.copyright"></div> </div> </template> <script> import _loginLogoImg from "../assets/Logo1.png" import _registerBgImg from "../assets/register/bg.png" import { captcha, register } from "../api/user"; import pwStrength from "../components/pwStrength"; import md5 from "js-md5"; export default { name: "register", components: { pwStrength }, data() { return { registerForm: { phone: "", pw1: "", pw2: "", captcha: "", email: "" }, minPw: 4, registerRules: { username: [ { required: true, message: this.$t('hivuiLogin_register_valid_user'), trigger: "blur" }, { validator: (rule, value, callback) => { if ((value + "").length > 20) { callback(new Error(this.$t('hivuiLogin_register_valid_user2'))); } else { callback(); } }, trigger: "blur" } ], phone: [ { required: true, message: this.$t('hivuiLogin_register_valid_phone'), trigger: "blur" }, { validator: (rule, value, callback) => { if (!/^[1]([3-9])[0-9]{9}$/.test(value)) { callback(new Error(this.$t('hivuiLogin_register_valid_phone2'))); } else { callback(); } }, trigger: "blur" } ], pw1: [ { required: true, message: this.$t('hivuiLogin_register_valid_pw'), trigger: "blur" }, { validator: (rule, value, callback) => { if ((value + "").length < this.minPw) { callback(new Error(this.$t('hivuiLogin_register_valid_pw_msg') + this.minPw + this.$t('hivuiLogin_register_valid_pw_msg2'))); } else { callback(); } }, trigger: "blur" } ], pw2: [ { required: true, message: this.$t('hivuiLogin_register_valid_pw2'), trigger: "blur" }, { validator: (rule, value, callback) => { if (value !== this.registerForm.pw1) { callback(new Error(this.$t('hivuiLogin_register_valid_pw2_msg'))); } else { callback(); } }, trigger: "blur" } ], captcha: [{ required: true, message: this.$t('hivuiLogin_register_valid_captcha'), trigger: "blur" }] /*email: [ { required: true, message: "请填写邮箱地址", trigger: "blur" } ]*/ }, captchaLoading: false, registerLoading: false, captchaTimer: 0, config: { title: window.customSysCofig?.loginTitle||this.$t('hivuiLogin_main_def_title'), loginLogoImg: window.customSysCofig?.loginLogo||_loginLogoImg, loginLogoImg_height: window.customSysCofig?.loginLogo_h||56, loginLogoImg_width: window.customSysCofig?.loginLogo_w||236, registerBgImg: window.customSysCofig?.registerBgImg||_registerBgImg, copyright: window.customSysCofig?.copyright||this.$t('hivuiLogin_main_def_copyright'), }, }; }, model: { prop: "value", event: "valuechange" }, props: { value: { type: Object } }, computed: { bgStyle() { return { "background-image": "url(" + this.config.registerBgImg + ")", }; }, register_logo_style(){ return { "width":(this.config.loginLogoImg_width / 1920) * 100+"vw", "height":(this.config.loginLogoImg_height / 1920) * 100+"vw", } } }, mounted() {}, methods: { //获取验证码 getCaptcha() { this.$refs.registerForm.validateField("phone", errMsg => { if (!errMsg) { let me = this; me.captchaTimer = 60; me.captchaLoading = true; captcha({ phone: me.registerForm.phone }) .then(res => { me.captchaLoading = false; }) .catch(err => { me.captchaLoading = false; }); let _timer = setInterval(() => { --me.captchaTimer; if (me.captchaTimer == 0) { clearInterval(_timer); } }, 1000); } }); }, //注册 register() { let me = this; this.$refs.registerForm.validate(valid => { if (valid) { me.registerLoading = true; register({ type: "phone", username:me.registerForm.username, phone: me.registerForm.phone, password: md5(me.registerForm.pw2), captcha: me.registerForm.captcha }) .then(res => { me.$message({ message: me.$t('hivuiLogin_register_success'), type: "success" }); setTimeout(() => { this.$router.push("/"); }, 1000 * 2); }) .catch(err => { me.registerLoading = false; }); } }); }, goLoginPage() { this.$router.push("/"); } } }; </script> <style lang="scss" scoped> @function px2vw($px) { @return ($px / 1920) * 100vw; } $headH: px2vw(130); $footH: px2vw(172); .register { height: 100%; overflow: hidden; .register_hd { height: $headH; display: flex; align-items: center; padding-top: px2vw(30); padding-left: px2vw(15); .register_logo { width: px2vw(236); height: px2vw(56); margin-right: px2vw(20); img { height: 100%; width: 100%; } } .register_text { font-size: px2vw(22); color: #333; position: relative; padding-left: px2vw(32); &:after { content: ""; display: block; height: px2vw(40); width: px2vw(1); background-color: #7ecef4; position: absolute; top: 0; left: px2vw(10); bottom: 0; margin: auto; } } } .register_main { height: calc(100% - #{$headH} - #{$footH}); position: relative; background: url("../assets/register/bg.png") no-repeat center center; background-size: cover; .register_box { position: absolute; bottom: 0; left: 0; right: 0; margin: auto; width: px2vw(1200); height: px2vw(655); border-radius: px2vw(3); background-color: #fff; padding: 0 px2vw(360) px2vw(40); h3 { text-align: center; line-height: px2vw(100); font-size: px2vw(24); color: #333; font-weight: bold; } .register_field { margin-bottom: px2vw(22); line-height: px2vw(48); ::v-deep.el-input__inner { line-height: px2vw(48); height: px2vw(48); } ::v-deep.el-form-item__content{ line-height: px2vw(50); font-size: px2vw(14); } ::v-deep.el-form-item__error{ padding-top: px2vw(4); } .register_pwStrength { margin-top: px2vw(10); } &.register_row { ::v-deep.el-form-item__content { display: flex; align-items: center; } } } .register_capbtn { width: px2vw(200); height: px2vw(48); line-height: px2vw(48); padding: 0; } .register_submit { height: px2vw(48); line-height: px2vw(48); padding-top: 0; width: 100%; margin-top: px2vw(10); } .register_tips { padding-top: px2vw(20); span { color: #3486d2; cursor: pointer; } } } } .register_ft { height: $footH; line-height: $footH; background-color: #e8f1fa; text-align: center; font-size: px2vw(16); color: #999; border-top: px2vw(1) solid #ccc; border-bottom: px2vw(1) solid #ccc; ::v-deep a{ margin-left:5px; color:#0f406c; &:hover{ color:#409eff; } } } } </style>
Ignore Space
Show notes
View
project/hivuiMain/views/layout/index.vue
<template> <div v-if="layout == 'level'" class="pl-page" :class="isFullscreen?'showTab':''"> <div :style="fullScreenTabHandleStyle" @mouseenter="showTab"></div> <Header v-show="!isFullscreen" :hasTitle="hasTitle" :logoWidth="logoWidth" ref="Header" style="box-shadow: 0 5px 7px rgba(221,221,221,0.5);z-index:10"></Header> <!-- <Navbar></Navbar> --> <Sidebar ref="Sidebar" :hasTitle="hasTitle" :sideWidth="sideWidth" :totop="totop" style="z-index: 11"></Sidebar> <Main ref="Main" @onFullScreen="handleFullScreen" :style="{left:toleft, top:totop+'px'}"></Main> </div> <div v-else class="pl-page" :class="isFullscreen?'showTab':''"> <div :style="fullScreenTabHandleStyle" @mouseenter="showTab"></div> <Header ref="Header" :logoWidth="logoWidth" v-show="!isFullscreen"></Header> <Navbar ref="Navbar" v-show="!isFullscreen"></Navbar> <Sidebar ref="Sidebar" v-show="hasQuickNav&&!isFullscreen"></Sidebar> <Main ref="Main" @onFullScreen="handleFullScreen" :style="{left:hasQuickNav?71:0}"></Main> </div> </template> <script> import {baseURL,codeProjectName,requestUrl} from '@main/config' import {getMenus} from '@main/api/menu' import {checkUrl} from '@main/utils/index' import {Header,Navbar,Sidebar,Main} from "./components" import screenfull from 'screenfull' // import { setTimeout } from 'timers'; export default { components:{ Header,Navbar,Sidebar,Main }, provide(){ let me=this; return { addTab(item){ // url,title,uid,callback,nearest // this.addTab(item);//inject 提供的方法只能 传一个参数 me.addTab(item.ssoUrl||item.resUrl,item.name,item.resId,item.callback,item.nearest,item.openType); // me.addTab(url,title,uid,callback,nearest); }, showTab(){ // console.log('layout index vue : showTab') me.showTab(); }, hideTab(){ // console.log('layout index vue : hideTab') me.hideTab(); } } }, data(){ return { hasTitle: true, toleft: window.__sysConfig.isMenuWordwrap?(window.__sysConfig.leftMenuWidth?(window.__sysConfig.leftMenuWidth+"px"):'141px'):'71px', sideWidth: window.__sysConfig.isMenuWordwrap?(window.__sysConfig.leftMenuWidth?(window.__sysConfig.leftMenuWidth+"px"):'140px'):'70px', logoWidth:'140px', totop: 50, isFullscreen: false, top: '', left: '', mainTop: '', navTop: '', timeout: null, sysConfig: this.$store.state.app.config, } }, computed:{ hasQuickNav(){ return this.$store.getters.navs.length; }, layout(){ return window.localStorage.getItem('layout'); }, isTitle(){ return this.hasTitle; }, fullScreenTabHandleStyle(){ let baseStyle={ position: "absolute", left: 0, top: 0, "z-index": 10000, }; if(this.layout=="level"){ Object.assign(baseStyle,{ height: "100%", width: "1px", }); }else{ Object.assign(baseStyle,{ height: "1px", width: "100%", }); } return baseStyle; } }, methods:{ addTab(url,title,uid,callback,nearest,openType){ console.log('layout addTab :',baseURL,codeProjectName,url); let __url=url; if(!checkUrl(url)){ //根据setting配置是否带e5 __url=(window._global?location.origin:window.HIVUI_SETTING.serverUrl)+url; } if(openType==2){//弹窗 this.$refs.Main.menuOpenList.push({ title:title, url:__url, uid:uid, }); }else if(openType==3){//浏览器标签打开 window.open(__url,"_blank"); }else{//主界面框架标签打开 window.Sys.addTab(__url,title,uid,callback,nearest); } }, hideTitle(name){ this.hasTitle = name; this.toleft = name?'71px':'49px'; this.sideWidth = name?'70px':'48px' }, /** * 是否全屏并按键ESC键的方法 */ checkFull() { var isFull = document.fullscreenEnabled || window.fullScreen || document.webkitIsFullScreen || document.msFullscreenEnabled // to fix : false || undefined == undefined if (isFull === undefined) { isFull = false } return isFull }, handleFullScreen(){ screenfull.toggle() }, onchange(){ // console.log(this.isFullscreen) if(this.isFullscreen==true){ // this.$refs.Main.isFullscreen = true this.$refs.Sidebar.$el.style.top=0 this.$refs.Sidebar.$el.style.left=0 this.$refs.Main.$el.style.top=0 this.$refs.Main.$el.style.left=0 // console.log('222',this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style) this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.display='none' this.$refs.Sidebar.$el.style.display = 'none' this.$refs.Main.$refs['cmp-tabs'].resize() }else{ // console.log(222) // console.log('top',this.top) this.$refs['Sidebar'].$el.style.top=this.mainTop+this.navTop+'px' if(!this.sysConfig.isSinglePage){ this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.display='block'; } if(layout != 'level'&&hasQuickNav&&!isFullscreen){ this.$refs.Sidebar.$el.style.display = 'block'; } if(window.localStorage.getItem('layout') === 'level'){ this.$refs['Main'].$el.style.top=this.navTop+'px' this.$refs['Main'].$el.style.left=this.left }else{ this.$refs['Main'].$el.style.top=this.mainTop+this.navTop+'px' this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.top=this.mainTop+this.navTop+'px' this.$refs['Main'].$el.style.left=this.left this.$refs['Navbar'].$el.style.top=this.navTop+'px' this.$refs.Navbar.$el.style.display='block' } this.$refs.Main.$refs['cmp-tabs'].resize() } }, showTab(){ if(this.isFullscreen){ clearTimeout(this.timeout); this.timeout = setTimeout(()=>{ if(!this.sysConfig.isSinglePage){ this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.display='block' this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.top=this.mainTop+'px' } // this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.top='50px' // console.log(this.$refs.Main.$el.style.top) if(window.localStorage.getItem('layout') === 'level'){ this.$refs.Sidebar.$el.style.display = 'block' if(this.sysConfig.isSinglePage){ this.$refs.Sidebar.$el.style.top = '0px' }else{ this.$refs.Sidebar.$el.style.top = '39px' } }else{ // this.$refs.Sidebar.$el.style.display = 'block' this.$refs.Navbar.$el.style.display='none'; this.$refs.Navbar.$el.style.top=0 this.$refs.Navbar.$el.style.display='block' } // this.$refs.Main.$refs['cmp-tabs'].resize() },0); } }, hideTab(){ if(this.isFullscreen){ clearTimeout(this.timeout); this.timeout = setTimeout(()=>{ this.$refs.Main.$el.style.top=0 this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.display='none' if(window.localStorage.getItem('layout') === 'level'){ this.$refs.Sidebar.$el.style.display = 'none' }else{ this.$refs.Navbar.$el.style.display='none' } // this.$refs.Main.$refs['cmp-tabs'].resize() },0); } }, KeyDown(event) { if (event.keyCode === 122) { event.returnValue = false; this.handleFullScreen(); } } }, created(){ //单页模式强制左右布局 if(this.sysConfig.isSinglePage){ window.localStorage.setItem('layout','level'); }else if(this.sysConfig.layout&&!window.localStorage.getItem('layout')){ if(this.sysConfig.layout=="top"){ window.localStorage.setItem('layout','vertical'); }else if(this.sysConfig.layout=="left"){ window.localStorage.setItem('layout','level'); } } }, mounted(){ this.navTop = this.$refs.Header.$el.offsetHeight this.left = this.$refs.Main.$el.style.left console.log('left', this.isFullscreen) if(window.localStorage.getItem('layout') === 'level'){ this.totop = this.$refs.Header.$el.offsetHeight || 50 }else{ this.mainTop = this.$refs.Navbar.$el.offsetHeight // console.log('mainTop', this.mainTop) } this.onchange(); window.onresize = () => { // 全屏下监控是否按键了ESC if (!this.checkFull()) { // 全屏下按键esc后要执行的动作 this.isFullscreen = false } this.isFullscreen=screenfull.isFullscreen this.onchange() }, window.addEventListener("keydown", this.KeyDown, true);//监听按键事件 } } </script> <style lang="less" scoped> .menuOpenDialog{ ::v-deep .el-dialog__body{ padding-top:0; } } </style>
<template> <div v-if="layout == 'level'" class="pl-page" :class="isFullscreen?'showTab':''"> <div :style="fullScreenTabHandleStyle" @mouseenter="showTab"></div> <Header v-show="!isFullscreen" :hasTitle="hasTitle" :logoWidth="logoWidth" ref="Header" style="box-shadow: 0 5px 7px rgba(221,221,221,0.5);z-index:10"></Header> <!-- <Navbar></Navbar> --> <Sidebar ref="Sidebar" :hasTitle="hasTitle" :sideWidth="sideWidth" :totop="totop" style="z-index: 11"></Sidebar> <Main ref="Main" @onFullScreen="handleFullScreen" :style="{left:toleft, top:totop+'px'}"></Main> </div> <div v-else class="pl-page" :class="isFullscreen?'showTab':''"> <div :style="fullScreenTabHandleStyle" @mouseenter="showTab"></div> <Header ref="Header" :logoWidth="logoWidth" v-show="!isFullscreen"></Header> <Navbar ref="Navbar" v-show="!isFullscreen"></Navbar> <Sidebar ref="Sidebar" v-show="hasQuickNav&&!isFullscreen"></Sidebar> <Main ref="Main" @onFullScreen="handleFullScreen" :style="{left:hasQuickNav?71:0}"></Main> </div> </template> <script> import {baseURL,codeProjectName,requestUrl} from '@main/config' import {getMenus} from '@main/api/menu' import {checkUrl} from '@main/utils/index' import {Header,Navbar,Sidebar,Main} from "./components" import screenfull from 'screenfull' // import { setTimeout } from 'timers'; export default { components:{ Header,Navbar,Sidebar,Main }, provide(){ let me=this; return { addTab(item){ // url,title,uid,callback,nearest // this.addTab(item);//inject 提供的方法只能 传一个参数 me.addTab(item.ssoUrl||item.resUrl,item.name,item.resId,item.callback,item.nearest,item.openType); // me.addTab(url,title,uid,callback,nearest); }, showTab(){ // console.log('layout index vue : showTab') me.showTab(); }, hideTab(){ // console.log('layout index vue : hideTab') me.hideTab(); } } }, data(){ return { hasTitle: true, toleft: window.__sysConfig.isMenuWordwrap?(window.__sysConfig.leftMenuWidth?(window.__sysConfig.leftMenuWidth+"px"):'141px'):'71px', sideWidth: window.__sysConfig.isMenuWordwrap?(window.__sysConfig.leftMenuWidth?(window.__sysConfig.leftMenuWidth+"px"):'140px'):'70px', logoWidth:'140px', totop: 50, isFullscreen: false, top: '', left: '', mainTop: '', navTop: '', timeout: null, sysConfig: this.$store.state.app.config, } }, computed:{ hasQuickNav(){ return this.$store.getters.navs.length; }, layout(){ return window.localStorage.getItem('layout'); }, isTitle(){ return this.hasTitle; }, fullScreenTabHandleStyle(){ let baseStyle={ position: "absolute", left: 0, top: 0, "z-index": 10000, }; if(this.layout=="level"){ Object.assign(baseStyle,{ height: "100%", width: "1px", }); }else{ Object.assign(baseStyle,{ height: "1px", width: "100%", }); } return baseStyle; } }, methods:{ addTab(url,title,uid,callback,nearest,openType){ console.log('layout addTab :',baseURL,codeProjectName,url); let __url=url; if(!checkUrl(url)){ //根据setting配置是否带e5 __url=(window._global?location.origin:window.HIVUI_SETTING.serverUrl)+url; } if(openType==2){//弹窗 this.$refs.Main.menuOpenList.push({ title:title, url:__url, uid:uid, }); }else if(openType==3){//浏览器标签打开 window.open(__url,"_blank"); }else{//主界面框架标签打开 window.Sys.addTab(__url,title,uid,callback,nearest); } }, hideTitle(name){ this.hasTitle = name; this.toleft = name?'71px':'49px'; this.sideWidth = name?'70px':'48px' }, /** * 是否全屏并按键ESC键的方法 */ checkFull() { var isFull = document.fullscreenEnabled || window.fullScreen || document.webkitIsFullScreen || document.msFullscreenEnabled // to fix : false || undefined == undefined if (isFull === undefined) { isFull = false } return isFull }, handleFullScreen(){ screenfull.toggle() }, onchange(){ // console.log(this.isFullscreen) if(this.isFullscreen==true){ // this.$refs.Main.isFullscreen = true this.$refs.Sidebar.$el.style.top=0 this.$refs.Sidebar.$el.style.left=0 this.$refs.Main.$el.style.top=0 this.$refs.Main.$el.style.left=0 // console.log('222',this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style) this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.display='none' this.$refs.Sidebar.$el.style.display = 'none' this.$refs.Main.$refs['cmp-tabs'].resize() }else{ // console.log(222) // console.log('top',this.top) this.$refs['Sidebar'].$el.style.top=this.mainTop+this.navTop+'px' if(!this.sysConfig.isSinglePage){ this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.display='block'; } this.$refs.Sidebar.$el.style.display = 'block' if(window.localStorage.getItem('layout') === 'level'){ this.$refs['Main'].$el.style.top=this.navTop+'px' this.$refs['Main'].$el.style.left=this.left }else{ this.$refs['Main'].$el.style.top=this.mainTop+this.navTop+'px' this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.top=this.mainTop+this.navTop+'px' this.$refs['Main'].$el.style.left=this.left this.$refs['Navbar'].$el.style.top=this.navTop+'px' this.$refs.Navbar.$el.style.display='block' } this.$refs.Main.$refs['cmp-tabs'].resize() } }, showTab(){ if(this.isFullscreen){ clearTimeout(this.timeout); this.timeout = setTimeout(()=>{ if(!this.sysConfig.isSinglePage){ this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.display='block' this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.top=this.mainTop+'px' } // this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.top='50px' // console.log(this.$refs.Main.$el.style.top) if(window.localStorage.getItem('layout') === 'level'){ this.$refs.Sidebar.$el.style.display = 'block' if(this.sysConfig.isSinglePage){ this.$refs.Sidebar.$el.style.top = '0px' }else{ this.$refs.Sidebar.$el.style.top = '39px' } }else{ // this.$refs.Sidebar.$el.style.display = 'block' this.$refs.Navbar.$el.style.display='none'; this.$refs.Navbar.$el.style.top=0 this.$refs.Navbar.$el.style.display='block' } // this.$refs.Main.$refs['cmp-tabs'].resize() },0); } }, hideTab(){ if(this.isFullscreen){ clearTimeout(this.timeout); this.timeout = setTimeout(()=>{ this.$refs.Main.$el.style.top=0 this.$refs.Main.$refs['cmp-tabs'].$refs['domTabHead'].style.display='none' if(window.localStorage.getItem('layout') === 'level'){ this.$refs.Sidebar.$el.style.display = 'none' }else{ this.$refs.Navbar.$el.style.display='none' } // this.$refs.Main.$refs['cmp-tabs'].resize() },0); } }, KeyDown(event) { if (event.keyCode === 122) { event.returnValue = false; this.handleFullScreen(); } } }, created(){ //单页模式强制左右布局 if(this.sysConfig.isSinglePage){ window.localStorage.setItem('layout','level'); }else if(this.sysConfig.layout&&!window.localStorage.getItem('layout')){ if(this.sysConfig.layout=="top"){ window.localStorage.setItem('layout','vertical'); }else if(this.sysConfig.layout=="left"){ window.localStorage.setItem('layout','level'); } } }, mounted(){ this.navTop = this.$refs.Header.$el.offsetHeight this.left = this.$refs.Main.$el.style.left console.log('left', this.isFullscreen) if(window.localStorage.getItem('layout') === 'level'){ this.totop = this.$refs.Header.$el.offsetHeight || 50 }else{ this.mainTop = this.$refs.Navbar.$el.offsetHeight // console.log('mainTop', this.mainTop) } this.onchange(); window.onresize = () => { // 全屏下监控是否按键了ESC if (!this.checkFull()) { // 全屏下按键esc后要执行的动作 this.isFullscreen = false } this.isFullscreen=screenfull.isFullscreen this.onchange() }, window.addEventListener("keydown", this.KeyDown, true);//监听按键事件 } } </script> <style lang="less" scoped> .menuOpenDialog{ ::v-deep .el-dialog__body{ padding-top:0; } } </style>
Ignore Space
Show notes
View
vite-plugin/vite-plugin-func.js
var querystring = require('querystring'); // var url = require('url'); const fs = require('fs') // var https = require('https'); var request = require('request'); var ejs = require('ejs'); // let syncrequest = require('sync-request'); let syncRequest = function (url, params) { let options = { url: url, form: params }; return new Promise(function (resolve, reject) { request.get(options, function (error, response, body) { if (response && response.statusCode == 200) { resolve(body); } else { reject(error); } }); }); } function myPlugin(rawOptions) { let projectName = process.env.VITE_APP_PN.split("/")[0]; let userName = process.env.VITE_APP_PN.split("/")[1]; var previewPath = `${projectName}/setting/studio/preview.json` var setting try { let settingContent = fs.readFileSync(previewPath, { encoding: 'utf8' }); setting = JSON.parse(settingContent) } catch (e) { console.log("preview数据有错!") } var VITE_APP_BASE_API, VITE_APP_SERVER; if (setting) { VITE_APP_BASE_API = (setting.server || {}).VITE_APP_BASE_API || process.env.VITE_APP_BASE_API; VITE_APP_SERVER = (setting.server || {}).VITE_APP_SERVER || process.env.VITE_APP_SERVER; } else { VITE_APP_BASE_API = process.env.VITE_APP_BASE_API; VITE_APP_SERVER = process.env.VITE_APP_SERVER; } const options = { isProduction: process.env.NODE_ENV === 'production', ...rawOptions, VITE_APP_BASE_API: VITE_APP_BASE_API, VITE_APP_SERVER: VITE_APP_SERVER, VITE_APP_PN: process.env.VITE_APP_PN, root: process.cwd(), }; // var routerOption = { // url: `${VITE_APP_BASE_API}/map.html?pn=${process.env.VITE_APP_PN}`, // method: "GET", // json: true, // headers: { // "Content-Type": "application/json;charset=UTF-8" // } // } const routerMapLocal = ["/main.html", "/index.html", "/login.html", "/studio.html"] const routerMap = {}; // function getRountMap() { // syncRequest(routerOption, function (error, response, body) { // if (body) { // for (var i = 0; i < body.length; i++) { // let routerPath = body[i].value; // routerPath = routerPath.substr(routerPath.indexOf("/") + 1) + ".html" // routerMap["/" + body[i].key] = Object.assign({ // url: routerPath // }, body[i]) // } // } // }) // } getRountMap = async function () { let content = await syncRequest(`${VITE_APP_BASE_API}/map.html?pn=${process.env.VITE_APP_PN}`); if (content) { let body = JSON.parse(content); for (var i = 0; i < body.length; i++) { let routerPath = body[i].value; routerPath = routerPath.substr(routerPath.indexOf("/") + 1) + ".html" routerMap["/" + body[i].key] = Object.assign({ url: routerPath }, body[i]) } } } getRountMap(); const TokenKey = 'EAP-Token'; let postData; let config; return { name: 'vite-plugin-func', // 必须的,将会显示在 warning 和 error 中 configResolved(resolvedConfig) { // 存储最终解析的配置 config = resolvedConfig }, configureServer(server) { server.middlewares.use(async (req, res, next) => { var Cookies = {}; if (req.headers.cookie != null) { req.headers.cookie.split(';').forEach(l => { var parts = l.split('='); Cookies[parts[0].trim()] = (parts[1] || '').trim(); }); } const token = Cookies[TokenKey]; var param = req._parsedUrl.query; var result = {}; if (param) { let values = param.split("&"); for (let i = 0; i < values.length; i++) { const element = values[i]; let _val = element.split("="); result[_val[0]] = _val[1]; } } const pathname = req._parsedUrl.pathname; function isFlow(type) { return type.endsWith(".flow") || type.endsWith(".flowc"); } // 接口 function isInfc(type) { return type.endsWith(".infc") } function isFunc(type) { return type.endsWith(".func") } function isHtml(type) { return type.endsWith(".html") } function isStudio(type) { return type.endsWith("/studio.html") } function setUrlParam(path, key, value) { if (!key || !value) { return path; } if (path.indexOf("?") == -1) { path = `${path}?${key}=${value}`; } else { path = `${path}&${key}=${value}`; } return path; } // 渲染页面 function renderHtml(pcform, isGuest, body) { let content; try { content = fs.readFileSync(pcform, { encoding: 'utf8' }) } catch (e) { res.writeHead(404, { "Content-Type": "application/json;charset=UTF-8" }); res.end("pcform:" + pcform + "文件异常,请尝试重启桌面服务!"); return; } const statusCode = 200; if (!body) throw new Error(`No body text found for the ${statusCode} status code`); try { var html = ejs.render(content, options); } catch (e) { res.end(e.message); return; } let postDataStr = JSON.stringify(postData || {}); let varName = options.varName || 'viteRequestData'; let varGlobal = JSON.stringify(options.global || {}); let funcName = new Date().valueOf(); let queryScript = ` function _viteGetQuery${funcName}() { var url = window.location.search; var theRequest = new Object(); if (url.indexOf("?") != -1) { var str = url.substr(1); strs = str.split("&"); for(var i = 0; i < strs.length; i ++) { theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]); } } return theRequest; }` let titleStr = html.match(/<head(.*?)>/g)[0] || ""; if (!isStudio(pathname)) { html = html.replace( /<head(.*?)>/g, `${titleStr}<script>${queryScript};window.isGuest=${isGuest}; window.${varName} = Object.assign(_viteGetQuery${funcName}(),${postDataStr}); window._global=${varGlobal}</script> ` ) let titleEnd = html.match(/<\/head(.*?)>/g)[0] || ""; let lang = result["locale"] || Cookies["locale"] || "zh-CN"; lang = lang.replace("_", "-"); var sam = ""; var samDef = ""; if (pcform.indexOf("hivuiSam/index.html") != -1) {//统计分析 samDef = `<script src="/${projectName}/hivuiSam/lang/zh-CN.js"></script>` sam = `<script src="${VITE_APP_BASE_API}/lang/ref?pn=${process.env.VITE_APP_PN}&vmId=tpl&filePath=${userName}/${projectName}/hivuiSam/lang/def.language&locale=${lang}"></script>` }; var platfPlugin = ''; var platfPluginDef = ''; if (pcform.indexOf("hivuiBirt/index.html") != -1) {//平台插件 platfPluginDef = `<script src="/${projectName}/hivuiBirt/lang/zh-CN.js"></script>` platfPlugin = `<script src="${VITE_APP_BASE_API}/lang/ref?pn=${process.env.VITE_APP_PN}&vmId=tpl&filePath=${userName}/${projectName}/hivuiBirt/lang/def.language&locale=${lang}"></script>` }; let funcDefLangMap = { 'hivuiLogin/index.html': `/${projectName}/hivuiLogin/lang/zh-CN.js`, 'hivuiMain/index.html': `/${projectName}/hivuiMain/lang/zh-CN.js`, } let funcLangMap = { 'hivuiLogin/index.html': `${VITE_APP_BASE_API}/lang/ref?pn=${process.env.VITE_APP_PN}&vmId=tpl&filePath=${userName}/${projectName}/hivuiLogin/lang/def.language&locale=${lang}`, 'hivuiMain/index.html': `${VITE_APP_BASE_API}/lang/ref?pn=${process.env.VITE_APP_PN}&vmId=tpl&filePath=${userName}/${projectName}/hivuiMain/lang/def.language&locale=${lang}`, 'platf/permission': `${VITE_APP_BASE_API}/lang/ref?pn=${process.env.VITE_APP_PN}&vmId=scheme&bizPath=${projectName}.pro/setting.project_setrootdir/global.dir/rolescheme.roletp&locale=${lang}` } let curFuncLangScript = '' for (let k in funcDefLangMap) { if (pathname.indexOf(k) > -1 || (routerMap[pathname] && routerMap[pathname].url && routerMap[pathname].url.indexOf(k) > -1)) { curFuncLangScript += `<script src="${funcDefLangMap[k]}"></script>` break; } } for (let k in funcLangMap) { if (pathname.indexOf(k) > -1 || (routerMap[pathname] && routerMap[pathname].url && routerMap[pathname].url.indexOf(k) > -1)) { curFuncLangScript += `<script src="${funcLangMap[k]}"></script>` break; } } var viteData = html.match(/<vite>([\s\S]*)<\/vite>/); var viteTpl = "", viteprojectTpl = ""; if (viteData) { //流引入多语言 var viteDataJson = JSON.parse(html.match(/<vite>([\s\S]*)<\/vite>/)[1]); viteprojectTpl = `<script src="${VITE_APP_BASE_API}/lang/static?pn=${process.env.VITE_APP_PN}&vmId=${viteDataJson.project_vmid}&locale=${lang}"></script>` if (viteDataJson.module_vmid && viteDataJson.bizpath) viteTpl = `<script src="${VITE_APP_BASE_API}/lang/ref?pn=${process.env.VITE_APP_PN}&vmId=${viteDataJson.module_vmid}&bizPath=${viteDataJson.bizpath}&locale=${lang}"></script>` } html = html.replace( /<\/head(.*?)>/g, `<script src="/assets_platform/vue-i18n/vue-i18n.js"></script> <script src="/${projectName}/lang/element-ui/${lang}.js"></script> <script src="${VITE_APP_BASE_API}/lang/ref?pn=${process.env.VITE_APP_PN}&vmId=hiui&filePath=${userName}/${projectName}/lang/hi-ui/def.language&locale=${lang}"></script> ${curFuncLangScript} ${viteprojectTpl} ${viteTpl} ${samDef} ${platfPluginDef} ${sam} ${platfPlugin} <script> try{ window.global={ pName:"${projectName}", pUser:"${userName}", pn:"${projectName}/${userName}" } // 统一输出语言包 zh-CN 名 // if(!window.GLOBAL_LANG_TPL){ // console.log('不影响运行,提示:[[${req.url},当前模板语言包不存在]]') // } // if(!window.GLOBAL_LANG_HIUI){ // console.log('不影响运行,提示:[[${req.url},hiui语言包不存在]]') // } window.lang = window.lang ||{}; window.lang.keys = Object.assign({},window.GLOBAL_LANG_TPL||{},window.GLOBAL_LANG_HIUI||{},window.GLOBAL_LANG_PROJECT||{},window.GLOBAL_LANG_MODULE||{},window.GLOBAL_LANG_SCHEME||{}); Vue.prototype._i18n = new VueI18n({ locale: 'localelang', messages: { 'localelang':window.lang.keys, } }); (function(lang){ lang = lang.split('-'); lang= lang[0]+((lang[1]||'').charAt(0).toUpperCase() + (lang[1]||'').slice(1)); ELEMENT.locale(ELEMENT.lang[lang]) })('${lang}'); }catch(e){ console.log('语言包加载出错!') } </script> <script src="/assets_platform/customSysCfg/index.js"></script> <script src="/${projectName}/setting/desktop/base.js" type="text/javascript"></script> <script src="/${projectName}/setting/desktop/development.js" type="text/javascript"></script> ${titleEnd}`) } res.writeHead(statusCode, { "serverInfo": `${VITE_APP_BASE_API},${VITE_APP_SERVER}`, // 'Content-Length': html.length, 'Content-Type': 'html' }); res.write(html) res.end(); } function handleFunc(path) { // let token = Cookies[TokenKey]; let requestUrl = setUrlParam(path, "pn", process.env.VITE_APP_PN); if (param && !isFlow(pathname)) { requestUrl = requestUrl + "&" + param; } console.log("----requestUrl:", requestUrl, "token:", token); if (!isFlow(pathname)) { Object.assign(post_data, postData); } let lang = result["locale"] || Cookies["locale"] || "zh-CN"; lang = lang.replace("_", "-"); var requestOption = { url: requestUrl, method: isFlow(pathname) ? "GET" : "POST", json: true, body: post_data, headers: { "token": token, "Cookie": `locale=${lang}`, "Authorization": "Bearer " + token, "Content-Type": "application/json;charset=UTF-8" } } if (isFlow(pathname)) { requestOption["qs"] = post_data; } else if (isFunc(pathname)) { //页面流用表单提交 requestOption["form"] = post_data; } request(requestOption, requestCallback, (msg) => { res.writeHead(404, { "Content-Type": "application/json;charset=UTF-8" }); res.end(JSON.stringify(msg)); // console.log(msg) }); } function renderVm() { res.writeHead(200, { 'Content-Type': 'html' }); let projectName = process.env.VITE_APP_PN.split("/")[0]; let url = serverPath + req.url; url = setUrlParam(url, "pn", process.env.VITE_APP_PN); url = setUrlParam(url, "access_token", token); let html = ` <script src="/assets_platform/eap/eap.umd.min.js"></script> <script> window._global ={ env :"dev" } </script> <script src="/${projectName}/setting/desktop/development.js" type="text/javascript"></script> <script> window.location.href="${url}"; </script> ` res.end(html); } function requestCallback(error, response, body) { let fmodelpath = pathname; if (typeof body == "string") { try { body = JSON.parse(body); } catch (error) { res.writeHead(response.statusCode, { "Content-Type": "html" }); res.end(body); return; } } //console.log(error, response, body); if (!error && response.statusCode == 200) { let pcform; let designPath; let isGuest = false; if (body) { if (isFlow(fmodelpath) && body.outParameter) { pcform = body.outParameter.task.bizpcform; if (!result["locale"] && body.outParameter.locale) { result["locale"] = body.outParameter.locale; } } else if (isFunc(fmodelpath) || isInfc(fmodelpath)) { if (body && body.logicflow || isInfc(fmodelpath)) { //逻辑流 let statusCode = body.status || response.statusCode; res.writeHead(statusCode, { "Content-Type": "application/json;charset=UTF-8" }); res.end(JSON.stringify(body)); return; } else if (body.dataPack) { pcform = body.dataPack.path; designPath = body.dataPack.designPath; isGuest = body.dataPack.isGuest; if (!result["locale"] && body.dataPack.locale) { result["locale"] = body.dataPack.locale; } } } } if (!pcform) { res.writeHead(500, { "serverInfo": `${VITE_APP_BASE_API},${VITE_APP_SERVER}`, "Content-Type": "application/json;charset=UTF-8" }); res.end(JSON.stringify(body)); return; } if (designPath && (designPath.endsWith(".vm") || designPath.endsWith(".dvm"))) { renderVm(); return; } // var fullPath = "eaptpl/12112/mokuai/shitumulu/biaodan/dtv/1.0.0/desktop/index.html"; renderHtml(pcform, isGuest, body); } else { if (response && response.statusCode == 401) { res.writeHead(200, { "serverInfo": `${VITE_APP_BASE_API},${VITE_APP_SERVER}`, 'Content-Type': 'html' }); let projectName = process.env.VITE_APP_PN.split("/")[0]; let html = ` <script src="/assets_platform/eap/eap.umd.min.js"></script> <script> window._global ={ env :"dev" } </script> <script> if(top.window.SysPage&&top.window.SysPage.openMiniLogin){//小窗口 top.window.SysPage.openMiniLogin(true); }else{ window.location.href=window.HIVUI_SETTING.loginUrl; } </script> ` res.end(html); } else { res.writeHead(500, { "serverInfo": `${VITE_APP_BASE_API},${VITE_APP_SERVER}`, "Content-Type": "application/json;charset=UTF-8" }); res.end(JSON.stringify(body)); } //res.end(requestUrl + ":" + JSON.stringify(error) + JSON.stringify(body)); } } var serverPath = VITE_APP_BASE_API + VITE_APP_SERVER; if (req.url.indexOf("/development.js") != -1 || req.url.indexOf("/base.js") != -1 || req.url.indexOf("/studio/appsetting.js") != -1) { if (req.headers.referer) { if (req.headers.referer.startsWith("https")) { options["VITE_APP_BASE_API"] = options["VITE_APP_BASE_API"].replace("http://", "https://"); } else { options["VITE_APP_BASE_API"] = options["VITE_APP_BASE_API"].replace("https://", "http://"); } } let content, url; try { if (req.url.indexOf("/studio/appsetting.js") != -1) {//动态流程用本地文件 throw error(); } url = `${VITE_APP_BASE_API}/vm/render/${userName}/${projectName}/setting/desktop/${req.url.split("/").pop()}`; content = await syncRequest(url); } catch (e) { try { content = fs.readFileSync(req.url.substr(1), { encoding: 'utf8' }) } catch { res.writeHead(404, { "Content-Type": "application/json;charset=UTF-8" }); res.end("获取", req.url + "文件异常!"); return; } } try { var html = ejs.render(content, options); html = `// serverPath:${serverPath}\n\n` + html; } catch (e) { res.end(e.message); return; } res.end(html); return; } else if (!routerMap[pathname] && routerMapLocal.indexOf(pathname) != -1) { await getRountMap(); if (routerMap[pathname].attributes.custom_page) { let url = `${routerMap[pathname].attributes.custom_page}`; let html = `<script> window.location.href="${url}" </script> ` res.end(html); } else { let pcform = routerMap[pathname].url; renderHtml(pcform, false, {}, true) } } else if (routerMap[pathname]) { if (routerMap[pathname].attributes.custom_page) { let url = `${routerMap[pathname].attributes.custom_page}`; let html = `<script> window.location.href="${url}" </script> ` res.end(html); } else { let pcform = routerMap[pathname].url; renderHtml(pcform, false, {}, true) } } else if (isFlow(pathname) || isFunc(pathname) || isInfc(pathname)) { // let url = req.url; let post = ''; postData = ''; let path; let fmodelpath = pathname; // url.split("?")[0]; var post_data = {}; // var param = req.url.split("?")[1]; if (isFlow(fmodelpath)) { var fversion = ""; var ftaskguid = ""; var fbzid = ""; if (param) { fversion = result["_version"] || result["version"]; ftaskguid = result["_ftaskguid"] || result["ftaskguid"]; fbzid = result["fbzid"]; } //flow/open参数改地址栏,切岗位不能用post post_data = { fmodelpath: fmodelpath, fversion, ftaskguid, fbzid } if (result["fnumber"]) { post_data = Object.assign(post_data, { fnumber: result["fnumber"] }) } path = serverPath + `/flow/open?origin=pre&skip=false`; } else if (isInfc(fmodelpath)) { path = serverPath + fmodelpath; } else { var viewItemId = "" if (param) { viewItemId = result["__viewItemId"] || result["viewItemId"] || ""; } path = serverPath + fmodelpath + "?origin=pre&skip=false&viewItemId=" + viewItemId; } // let pn = url.split("/")[1]; req.on('data', (chunk) => { post += chunk; postData = querystring.parse(post); }); req.on('end', (chunk) => { handleFunc(path) }); return; } else { if (isHtml(pathname)) { renderHtml(pathname.substr(1), false, {}) } else { var newPath = `/render/${userName}`; var assets_platform = "/render/assets_platform"; if (pathname.indexOf(newPath) != -1) { req.url = req.url.replace(newPath, ""); } if (pathname.indexOf(assets_platform) != -1) { req.url = req.url.replace(assets_platform, "/assets_platform"); } next(); } } }) }, } } export default myPlugin;
var querystring = require('querystring'); // var url = require('url'); const fs = require('fs') // var https = require('https'); var request = require('request'); var ejs = require('ejs'); // let syncrequest = require('sync-request'); let syncRequest = function (url, params) { let options = { url: url, form: params }; return new Promise(function (resolve, reject) { request.get(options, function (error, response, body) { if (response && response.statusCode == 200) { resolve(body); } else { reject(error); } }); }); } function myPlugin(rawOptions) { let projectName = process.env.VITE_APP_PN.split("/")[0]; let userName = process.env.VITE_APP_PN.split("/")[1]; var previewPath = `${projectName}/setting/studio/preview.json` var setting try { let settingContent = fs.readFileSync(previewPath, { encoding: 'utf8' }); setting = JSON.parse(settingContent) } catch (e) { console.log("preview数据有错!") } var VITE_APP_BASE_API, VITE_APP_SERVER; if (setting) { VITE_APP_BASE_API = (setting.server || {}).VITE_APP_BASE_API || process.env.VITE_APP_BASE_API; VITE_APP_SERVER = (setting.server || {}).VITE_APP_SERVER || process.env.VITE_APP_SERVER; } else { VITE_APP_BASE_API = process.env.VITE_APP_BASE_API; VITE_APP_SERVER = process.env.VITE_APP_SERVER; } const options = { isProduction: process.env.NODE_ENV === 'production', ...rawOptions, VITE_APP_BASE_API: VITE_APP_BASE_API, VITE_APP_SERVER: VITE_APP_SERVER, VITE_APP_PN:process.env.VITE_APP_PN, root: process.cwd(), }; // var routerOption = { // url: `${VITE_APP_BASE_API}/map.html?pn=${process.env.VITE_APP_PN}`, // method: "GET", // json: true, // headers: { // "Content-Type": "application/json;charset=UTF-8" // } // } const routerMapLocal = ["/main.html", "/index.html", "/login.html","/studio.html"] const routerMap = {}; // function getRountMap() { // syncRequest(routerOption, function (error, response, body) { // if (body) { // for (var i = 0; i < body.length; i++) { // let routerPath = body[i].value; // routerPath = routerPath.substr(routerPath.indexOf("/") + 1) + ".html" // routerMap["/" + body[i].key] = Object.assign({ // url: routerPath // }, body[i]) // } // } // }) // } getRountMap = async function () { let content = await syncRequest(`${VITE_APP_BASE_API}/map.html?pn=${process.env.VITE_APP_PN}`); if (content) { let body = JSON.parse(content); for (var i = 0; i < body.length; i++) { let routerPath = body[i].value; routerPath = routerPath.substr(routerPath.indexOf("/") + 1) + ".html" routerMap["/" + body[i].key] = Object.assign({ url: routerPath }, body[i]) } } } getRountMap(); const TokenKey = 'EAP-Token'; let postData; let config; return { name: 'vite-plugin-func', // 必须的,将会显示在 warning 和 error 中 configResolved(resolvedConfig) { // 存储最终解析的配置 config = resolvedConfig }, configureServer(server) { server.middlewares.use(async (req, res, next) => { var Cookies = {}; if (req.headers.cookie != null) { req.headers.cookie.split(';').forEach(l => { var parts = l.split('='); Cookies[parts[0].trim()] = (parts[1] || '').trim(); }); } const token = Cookies[TokenKey]; var param = req._parsedUrl.query; var result = {}; if (param) { let values = param.split("&"); for (let i = 0; i < values.length; i++) { const element = values[i]; let _val = element.split("="); result[_val[0]] = _val[1]; } } const pathname = req._parsedUrl.pathname; function isFlow(type) { return type.endsWith(".flow") || type.endsWith(".flowc"); } // 接口 function isInfc(type) { return type.endsWith(".infc") } function isFunc(type) { return type.endsWith(".func") } function isHtml(type) { return type.endsWith(".html") } function isStudio(type) { return type.endsWith("/studio.html") } function setUrlParam(path, key, value) { if (!key || !value) { return path; } if (path.indexOf("?") == -1) { path = `${path}?${key}=${value}`; } else { path = `${path}&${key}=${value}`; } return path; } // 渲染页面 function renderHtml(pcform, isGuest, body) { let content; try { content = fs.readFileSync(pcform, { encoding: 'utf8' }) } catch (e) { res.writeHead(404, { "Content-Type": "application/json;charset=UTF-8" }); res.end("pcform:" + pcform + "文件异常,请尝试重启桌面服务!"); return; } const statusCode = 200; if (!body) throw new Error(`No body text found for the ${statusCode} status code`); try { var html = ejs.render(content, options); } catch (e) { res.end(e.message); return; } let postDataStr = JSON.stringify(postData || {}); let varName = options.varName || 'viteRequestData'; let varGlobal = JSON.stringify(options.global || {}); let funcName = new Date().valueOf(); let queryScript = ` function _viteGetQuery${funcName}() { var url = window.location.search; var theRequest = new Object(); if (url.indexOf("?") != -1) { var str = url.substr(1); strs = str.split("&"); for(var i = 0; i < strs.length; i ++) { theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]); } } return theRequest; }` let titleStr = html.match(/<head(.*?)>/g)[0] || ""; if (!isStudio(pathname)) { html = html.replace( /<head(.*?)>/g, `${titleStr}<script>${queryScript};window.isGuest=${isGuest}; window.${varName} = Object.assign(_viteGetQuery${funcName}(),${postDataStr}); window._global=${varGlobal}</script> ` ) let titleEnd = html.match(/<\/head(.*?)>/g)[0] || ""; let lang = result["locale"] || Cookies["locale"] || "zh-CN"; lang = lang.replace("_", "-"); var sam = ""; var samDef = ""; if (pcform.indexOf("hivuiSam/index.html") != -1) {//统计分析 samDef = `<script src="/${projectName}/hivuiSam/lang/zh-CN.js"></script>` sam = `<script src="${VITE_APP_BASE_API}/lang/ref?pn=${process.env.VITE_APP_PN}&vmId=tpl&filePath=${userName}/${projectName}/hivuiSam/lang/def.language&locale=${lang}"></script>` }; var platfPlugin = ''; var platfPluginDef = ''; if (pcform.indexOf("hivuiBirt/index.html") != -1) {//平台插件 platfPluginDef = `<script src="/${projectName}/hivuiBirt/lang/zh-CN.js"></script>` platfPlugin = `<script src="${VITE_APP_BASE_API}/lang/ref?pn=${process.env.VITE_APP_PN}&vmId=tpl&filePath=${userName}/${projectName}/hivuiBirt/lang/def.language&locale=${lang}"></script>` }; let funcDefLangMap = { 'hivuiLogin/index.html': `/${projectName}/hivuiLogin/lang/zh-CN.js`, 'hivuiMain/index.html': `/${projectName}/hivuiMain/lang/zh-CN.js`, } let funcLangMap = { 'hivuiLogin/index.html': `${VITE_APP_BASE_API}/lang/ref?pn=${process.env.VITE_APP_PN}&vmId=tpl&filePath=${userName}/${projectName}/hivuiLogin/lang/def.language&locale=${lang}`, 'hivuiMain/index.html': `${VITE_APP_BASE_API}/lang/ref?pn=${process.env.VITE_APP_PN}&vmId=tpl&filePath=${userName}/${projectName}/hivuiMain/lang/def.language&locale=${lang}`, 'platf/permission': `${VITE_APP_BASE_API}/lang/ref?pn=${process.env.VITE_APP_PN}&vmId=scheme&bizPath=${projectName}.pro/setting.project_setrootdir/global.dir/rolescheme.roletp&locale=${lang}` } let curFuncLangScript = '' for (let k in funcDefLangMap) { if (pathname.indexOf(k) > -1 || (routerMap[pathname] && routerMap[pathname].url && routerMap[pathname].url.indexOf(k) > -1)) { curFuncLangScript += `<script src="${funcDefLangMap[k]}"></script>` break; } } for (let k in funcLangMap) { if (pathname.indexOf(k) > -1 || (routerMap[pathname] && routerMap[pathname].url && routerMap[pathname].url.indexOf(k) > -1)) { curFuncLangScript += `<script src="${funcLangMap[k]}"></script>` break; } } var viteData = html.match(/<vite>([\s\S]*)<\/vite>/); var viteTpl = "", viteprojectTpl = ""; if (viteData) { //流引入多语言 var viteDataJson = JSON.parse(html.match(/<vite>([\s\S]*)<\/vite>/)[1]); viteprojectTpl = `<script src="${VITE_APP_BASE_API}/lang/static?pn=${process.env.VITE_APP_PN}&vmId=${viteDataJson.project_vmid}&locale=${lang}"></script>` if (viteDataJson.module_vmid && viteDataJson.bizpath) viteTpl = `<script src="${VITE_APP_BASE_API}/lang/ref?pn=${process.env.VITE_APP_PN}&vmId=${viteDataJson.module_vmid}&bizPath=${viteDataJson.bizpath}&locale=${lang}"></script>` } html = html.replace( /<\/head(.*?)>/g, `<script src="/assets_platform/vue-i18n/vue-i18n.js"></script> <script src="/${projectName}/lang/element-ui/${lang}.js"></script> <script src="${VITE_APP_BASE_API}/lang/ref?pn=${process.env.VITE_APP_PN}&vmId=hiui&filePath=${userName}/${projectName}/lang/hi-ui/def.language&locale=${lang}"></script> ${curFuncLangScript} ${viteprojectTpl} ${viteTpl} ${samDef} ${platfPluginDef} ${sam} ${platfPlugin} <script> try{ window.global={ pName:"${projectName}", pUser:"${userName}", pn:"${projectName}/${userName}" } // 统一输出语言包 zh-CN 名 // if(!window.GLOBAL_LANG_TPL){ // console.log('不影响运行,提示:[[${req.url},当前模板语言包不存在]]') // } // if(!window.GLOBAL_LANG_HIUI){ // console.log('不影响运行,提示:[[${req.url},hiui语言包不存在]]') // } window.lang = window.lang ||{}; window.lang.keys = Object.assign({},window.GLOBAL_LANG_TPL||{},window.GLOBAL_LANG_HIUI||{},window.GLOBAL_LANG_PROJECT||{},window.GLOBAL_LANG_MODULE||{},window.GLOBAL_LANG_SCHEME||{}); Vue.prototype._i18n = new VueI18n({ locale: 'localelang', messages: { 'localelang':window.lang.keys, } }); (function(lang){ lang = lang.split('-'); lang= lang[0]+((lang[1]||'').charAt(0).toUpperCase() + (lang[1]||'').slice(1)); ELEMENT.locale(ELEMENT.lang[lang]) })('${lang}'); }catch(e){ console.log('语言包加载出错!') } </script> <script src="/assets_platform/customSysCfg/index.js"></script> <script src="/${projectName}/setting/desktop/base.js" type="text/javascript"></script> <script src="/${projectName}/setting/desktop/development.js" type="text/javascript"></script> ${titleEnd}`) } res.writeHead(statusCode, { "serverInfo": `${VITE_APP_BASE_API},${VITE_APP_SERVER}`, // 'Content-Length': html.length, 'Content-Type': 'html' }); res.write(html) res.end(); } function handleFunc(path) { // let token = Cookies[TokenKey]; let requestUrl = setUrlParam(path, "pn", process.env.VITE_APP_PN); if (param && !isFlow(pathname)) { requestUrl = requestUrl + "&" + param; } console.log("----requestUrl:", requestUrl, "token:", token); Object.assign(post_data, postData); let lang = result["locale"] || Cookies["locale"] || "zh-CN"; lang = lang.replace("_", "-"); var requestOption = { url: requestUrl, method: isFlow(pathname) ? "GET" : "POST", json: true, body: post_data, headers: { "token": token, "Cookie": `locale=${lang}`, "Authorization": "Bearer " + token, "Content-Type": "application/json;charset=UTF-8" } } if (isFlow(pathname)) { requestOption["qs"] = post_data; } else if (isFunc(pathname)) { //页面流用表单提交 requestOption["form"] = post_data; } request(requestOption, requestCallback, (msg) => { res.writeHead(404, { "Content-Type": "application/json;charset=UTF-8" }); res.end(JSON.stringify(msg)); // console.log(msg) }); } function renderVm() { res.writeHead(200, { 'Content-Type': 'html' }); let projectName = process.env.VITE_APP_PN.split("/")[0]; let url = serverPath + req.url; url = setUrlParam(url, "pn", process.env.VITE_APP_PN); url = setUrlParam(url, "access_token", token); let html = ` <script src="/assets_platform/eap/eap.umd.min.js"></script> <script> window._global ={ env :"dev" } </script> <script src="/${projectName}/setting/desktop/development.js" type="text/javascript"></script> <script> window.location.href="${url}"; </script> ` res.end(html); } function requestCallback(error, response, body) { let fmodelpath = pathname; if (typeof body == "string") { try { body = JSON.parse(body); } catch (error) { res.writeHead(response.statusCode, { "Content-Type": "html" }); res.end(body); return; } } //console.log(error, response, body); if (!error && response.statusCode == 200) { let pcform; let designPath; let isGuest = false; if (body) { if (isFlow(fmodelpath) && body.outParameter) { pcform = body.outParameter.task.bizpcform; if (!result["locale"] && body.outParameter.locale) { result["locale"] = body.outParameter.locale; } } else if (isFunc(fmodelpath) || isInfc(fmodelpath)) { if (body && body.logicflow || isInfc(fmodelpath)) { //逻辑流 let statusCode = body.status || response.statusCode; res.writeHead(statusCode, { "Content-Type": "application/json;charset=UTF-8" }); res.end(JSON.stringify(body)); return; } else if (body.dataPack) { pcform = body.dataPack.path; designPath = body.dataPack.designPath; isGuest = body.dataPack.isGuest; if (!result["locale"] && body.dataPack.locale) { result["locale"] = body.dataPack.locale; } } } } if (!pcform) { res.writeHead(500, { "serverInfo": `${VITE_APP_BASE_API},${VITE_APP_SERVER}`, "Content-Type": "application/json;charset=UTF-8" }); res.end(JSON.stringify(body)); return; } if (designPath && (designPath.endsWith(".vm") || designPath.endsWith(".dvm"))) { renderVm(); return; } // var fullPath = "eaptpl/12112/mokuai/shitumulu/biaodan/dtv/1.0.0/desktop/index.html"; renderHtml(pcform, isGuest, body); } else { if (response && response.statusCode == 401) { res.writeHead(200, { "serverInfo": `${VITE_APP_BASE_API},${VITE_APP_SERVER}`, 'Content-Type': 'html' }); let projectName = process.env.VITE_APP_PN.split("/")[0]; let html = ` <script src="/assets_platform/eap/eap.umd.min.js"></script> <script> window._global ={ env :"dev" } </script> <script> if(top.window.SysPage&&top.window.SysPage.openMiniLogin){//小窗口 top.window.SysPage.openMiniLogin(true); }else{ window.location.href=window.HIVUI_SETTING.loginUrl; } </script> ` res.end(html); } else { res.writeHead(500, { "serverInfo": `${VITE_APP_BASE_API},${VITE_APP_SERVER}`, "Content-Type": "application/json;charset=UTF-8" }); res.end(JSON.stringify(body)); } //res.end(requestUrl + ":" + JSON.stringify(error) + JSON.stringify(body)); } } var serverPath = VITE_APP_BASE_API + VITE_APP_SERVER; if (req.url.indexOf("/development.js") != -1 || req.url.indexOf("/base.js") != -1 || req.url.indexOf("/studio/appsetting.js") != -1) { if (req.headers.referer) { if (req.headers.referer.startsWith("https")) { options["VITE_APP_BASE_API"] = options["VITE_APP_BASE_API"].replace("http://", "https://"); } else { options["VITE_APP_BASE_API"] = options["VITE_APP_BASE_API"].replace("https://", "http://"); } } let content, url; try { if (req.url.indexOf("/studio/appsetting.js") != -1) {//动态流程用本地文件 throw error(); } url = `${VITE_APP_BASE_API}/vm/render/${userName}/${projectName}/setting/desktop/${req.url.split("/").pop()}`; content = await syncRequest(url); } catch (e) { try { content = fs.readFileSync(req.url.substr(1), { encoding: 'utf8' }) } catch { res.writeHead(404, { "Content-Type": "application/json;charset=UTF-8" }); res.end("获取", req.url + "文件异常!"); return; } } try { var html = ejs.render(content, options); html=`// serverPath:${serverPath}\n\n`+html; } catch (e) { res.end(e.message); return; } res.end(html); return; } else if (!routerMap[pathname] && routerMapLocal.indexOf(pathname) != -1) { await getRountMap(); if (routerMap[pathname].attributes.custom_page) { let url = `${routerMap[pathname].attributes.custom_page}`; let html = `<script> window.location.href="${url}" </script> ` res.end(html); } else { let pcform = routerMap[pathname].url; renderHtml(pcform, false, {}, true) } } else if (routerMap[pathname]) { if (routerMap[pathname].attributes.custom_page) { let url = `${routerMap[pathname].attributes.custom_page}`; let html = `<script> window.location.href="${url}" </script> ` res.end(html); } else { let pcform = routerMap[pathname].url; renderHtml(pcform, false, {}, true) } } else if (isFlow(pathname) || isFunc(pathname) || isInfc(pathname)) { // let url = req.url; let post = ''; postData = ''; let path; let fmodelpath = pathname; // url.split("?")[0]; var post_data = {}; // var param = req.url.split("?")[1]; if (isFlow(fmodelpath)) { var fversion = ""; var ftaskguid = ""; var fbzid = ""; if (param) { fversion = result["_version"] || result["version"]; ftaskguid = result["_ftaskguid"] || result["ftaskguid"]; fbzid = result["fbzid"]; } //flow/open参数改地址栏,切岗位不能用post post_data = { fmodelpath: fmodelpath, fversion, ftaskguid, fbzid } if (result["fnumber"]) { post_data = Object.assign(post_data, { fnumber: result["fnumber"] }) } path = serverPath + `/flow/open?origin=pre&skip=false`; } else if (isInfc(fmodelpath)) { path = serverPath + fmodelpath; } else { var viewItemId = "" if (param) { viewItemId = result["__viewItemId"] || result["viewItemId"] || ""; } path = serverPath + fmodelpath + "?origin=pre&skip=false&viewItemId=" + viewItemId; } // let pn = url.split("/")[1]; req.on('data', (chunk) => { post += chunk; postData = querystring.parse(post); }); req.on('end', (chunk) => { handleFunc(path) }); return; } else { if (isHtml(pathname)) { renderHtml(pathname.substr(1), false, {}) } else { var newPath = `/render/${userName}`; var assets_platform = "/render/assets_platform"; if (pathname.indexOf(newPath) != -1) { req.url = req.url.replace(newPath, ""); } if (pathname.indexOf(assets_platform) != -1) { req.url = req.url.replace(assets_platform, "/assets_platform"); } next(); } } }) }, } } export default myPlugin;
Show line notes below