整理前端代码风格

This commit is contained in:
John Smith 2022-01-04 21:41:12 +08:00
parent 03a2801099
commit 36345c37ab
25 changed files with 309 additions and 218 deletions

79
frontend/.eslintrc.js Normal file
View File

@ -0,0 +1,79 @@
module.exports = {
"root": true,
"env": {
"browser": true,
"node": true
},
"parserOptions": {
"parser": "babel-eslint"
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"rules": {
"array-bracket-spacing": ["error", "never"], // 数组括号内不加空格
"arrow-parens": ["error", "as-needed"], // 箭头函数单个参数不加括号
"arrow-spacing": "error", // 箭头前后加空格
"block-spacing": "error", // 块大括号内加空格
"brace-style": "error", // 大括号不独占一行
"comma-spacing": "error", // 逗号前面不加空格,后面加空格
"comma-style": "error", // 逗号在语句后面而不是下一条的前面
"computed-property-spacing": "error", // 计算属性名前后不加空格
"curly": "error", // 禁止省略大括号
"dot-notation": "error", // 使用点访问成员
"eol-last": "error", // 文件末尾加换行符
"func-call-spacing": "error", // 调用函数名和括号间不加空格
"func-style": ["error", "declaration", { "allowArrowFunctions": true }], // 使用函数定义语法,而不是把函数表达式赋值到变量
"indent": ["error", 2], // 缩进2空格
"key-spacing": ["error", { "mode": "minimum" }],
"keyword-spacing": "error", // 关键词前后加空格
"lines-between-class-members": "error", // 类成员定义间加空格
"max-lines-per-function": ["error", 150], // 每个函数最多行数
"max-nested-callbacks": ["error", 3], // 每个函数最多嵌套回调数
"new-parens": "error", // new调用构造函数加空格
"no-array-constructor": "error", // 使用数组字面量,而不是数组构造函数
"no-floating-decimal": "error", // 禁止省略浮点数首尾的0
"no-implicit-coercion": "error", // 禁止隐式转换
"no-empty": ["error", { "allowEmptyCatch": true }], // 禁止空的块除了catch
"no-extra-parens": ["error", "all", { "nestedBinaryExpressions": false }], // 禁止多余的括号
"no-labels": "error", // 禁止使用标签
"no-lone-blocks": "error", // 禁止没用的块
"no-mixed-operators": "error", // 禁止混用不同优先级的操作符而不加括号
"no-multi-spaces": ["error", { "ignoreEOLComments": true }], // 禁止多个空格,除了行尾注释前
"no-multiple-empty-lines": "error", // 最多2个连续空行
"no-nested-ternary": "error", // 禁止嵌套三元表达式
"no-sequences": "error", // 禁止使用逗号操作符
"no-tabs": "error", // 禁止使用tab
"no-trailing-spaces": ["error", { "skipBlankLines": true }], // 禁止行尾的空格,除了空行
"no-unused-expressions": "error", // 禁止没用的表达式
"no-useless-concat": "error", // 禁止没用的字符串连接
"no-useless-rename": "error", // 禁止没用的模块导入重命名、解构赋值重命名
"no-useless-return": "error", // 禁止没用的return
"no-var": "error", // 禁止使用var声明变量
"no-void": "error", // 禁止使用void
"no-whitespace-before-property": "error", // 禁止访问属性的点前后加空格
"object-curly-spacing": ["error", "always"], // 对象字面量括号内加空格
"operator-assignment": "error", // 尽量使用+=
"operator-linebreak": ["error", "before"], // 操作符放行首
"prefer-object-spread": "error", // 使用{...obj}而不是Object.assign
"prefer-rest-params": "error", // 使用...args而不是arguments
"prefer-spread": "error", // 使用func(...args)而不是apply
"prefer-template": "error", // 使用模板字符串,而不是字符串连接
"rest-spread-spacing": ["error", "never"], // 解包操作符不加空格
"semi": ["error", "never"], // 禁止使用多余的分号
"semi-spacing": "error", // 分号前面不加空格,后面加空格
"semi-style": "error", // 分号在语句后面而不是下一条的前面
"space-before-blocks": "error", // 块大括号前加空格
"space-before-function-paren": ["error", "never"], // 函数定义名称和括号间不加空格
"space-in-parens": "error", // 括号内不加空格
"space-infix-ops": "error", // 二元操作符前后加空格
"space-unary-ops": "error", // 关键词一元操作符后加空格,符号一元操作符不加
"spaced-comment": ["error", "always", { "block": { "balanced": true } }], // 注释前面加空格
"template-curly-spacing": "error", // 模板字符串中变量大括号内不加空格
"no-shadow": "warn", // 变量名和外部作用域重复
"no-console": "off", // 线上尽量不要用console输出看不到的
}
}

14
frontend/jsconfig.json Normal file
View File

@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "es2015",
"module": "esnext",
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
}
},
"include": [
"./src/**/*.js",
"./src/**/*.vue"
]
}

View File

@ -37,7 +37,7 @@ const AUTH_REPLY_CODE_OK = 0
// const AUTH_REPLY_CODE_TOKEN_ERROR = -101 // const AUTH_REPLY_CODE_TOKEN_ERROR = -101
const HEARTBEAT_INTERVAL = 10 * 1000 const HEARTBEAT_INTERVAL = 10 * 1000
const RECEIVE_TIMEOUT = HEARTBEAT_INTERVAL + 5 * 1000 const RECEIVE_TIMEOUT = HEARTBEAT_INTERVAL + (5 * 1000)
let textEncoder = new TextEncoder() let textEncoder = new TextEncoder()
let textDecoder = new TextDecoder() let textDecoder = new TextDecoder()
@ -147,7 +147,7 @@ export default class ChatClientDirect {
} }
onReceiveTimeout() { onReceiveTimeout() {
window.console.warn('接收消息超时') console.warn('接收消息超时')
this.discardWebsocket() this.discardWebsocket()
} }
@ -178,14 +178,14 @@ export default class ChatClientDirect {
return return
} }
this.retryCount++ this.retryCount++
window.console.warn('掉线重连中', this.retryCount) console.warn('掉线重连中', this.retryCount)
window.setTimeout(this.wsConnect.bind(this), 1000) window.setTimeout(this.wsConnect.bind(this), 1000)
} }
onWsMessage(event) { onWsMessage(event) {
this.refreshReceiveTimeoutTimer() this.refreshReceiveTimeoutTimer()
if (!(event.data instanceof ArrayBuffer)) { if (!(event.data instanceof ArrayBuffer)) {
window.console.warn('未知的websocket消息类型data=', event.data) console.warn('未知的websocket消息类型data=', event.data)
return return
} }
@ -231,7 +231,7 @@ export default class ChatClientDirect {
default: { default: {
// 未知消息 // 未知消息
let body = new Uint8Array(data.buffer, offset + rawHeaderSize, packLen - rawHeaderSize) let body = new Uint8Array(data.buffer, offset + rawHeaderSize, packLen - rawHeaderSize)
window.console.warn('未知包类型operation=', operation, dataView, body) console.warn('未知包类型operation=', operation, dataView, body)
break break
} }
} }
@ -255,7 +255,7 @@ export default class ChatClientDirect {
body = JSON.parse(textDecoder.decode(body)) body = JSON.parse(textDecoder.decode(body))
this.handlerCommand(body) this.handlerCommand(body)
} catch (e) { } catch (e) {
window.console.error('body=', body) console.error('body=', body)
throw e throw e
} }
} }
@ -266,7 +266,7 @@ export default class ChatClientDirect {
// 认证响应 // 认证响应
body = JSON.parse(textDecoder.decode(body)) body = JSON.parse(textDecoder.decode(body))
if (body.code !== AUTH_REPLY_CODE_OK) { if (body.code !== AUTH_REPLY_CODE_OK) {
window.console.error('认证响应错误body=', body) console.error('认证响应错误body=', body)
// 这里应该重新获取token再重连的但前端没有用到token所以不重新init了 // 这里应该重新获取token再重连的但前端没有用到token所以不重新init了
this.discardWebsocket() this.discardWebsocket()
throw new Error('认证响应错误') throw new Error('认证响应错误')
@ -276,7 +276,7 @@ export default class ChatClientDirect {
} }
default: { default: {
// 未知消息 // 未知消息
window.console.warn('未知包类型operation=', operation, dataView, body) console.warn('未知包类型operation=', operation, dataView, body)
break break
} }
} }
@ -329,10 +329,10 @@ export default class ChatClientDirect {
authorType: authorType, authorType: authorType,
content: info[1], content: info[1],
privilegeType: privilegeType, privilegeType: privilegeType,
isGiftDanmaku: !!info[0][9], isGiftDanmaku: Boolean(info[0][9]),
authorLevel: info[4][0], authorLevel: info[4][0],
isNewbie: info[2][5] < 10000, isNewbie: info[2][5] < 10000,
isMobileVerified: !!info[2][6], isMobileVerified: Boolean(info[2][6]),
medalLevel: roomId === this.roomId ? medalLevel : 0, medalLevel: roomId === this.roomId ? medalLevel : 0,
id: getUuid4Hex(), id: getUuid4Hex(),
translation: '', translation: '',

View File

@ -11,7 +11,7 @@ const COMMAND_UPDATE_TRANSLATION = 7
const CONTENT_TYPE_EMOTICON = 1 const CONTENT_TYPE_EMOTICON = 1
const HEARTBEAT_INTERVAL = 10 * 1000 const HEARTBEAT_INTERVAL = 10 * 1000
const RECEIVE_TIMEOUT = HEARTBEAT_INTERVAL + 5 * 1000 const RECEIVE_TIMEOUT = HEARTBEAT_INTERVAL + (5 * 1000)
export default class ChatClientRelay { export default class ChatClientRelay {
constructor(roomId, autoTranslate) { constructor(roomId, autoTranslate) {
@ -86,7 +86,7 @@ export default class ChatClientRelay {
} }
onReceiveTimeout() { onReceiveTimeout() {
window.console.warn('接收消息超时') console.warn('接收消息超时')
this.receiveTimeoutTimerId = null this.receiveTimeoutTimerId = null
// 直接丢弃阻塞的websocket不等onclose回调了 // 直接丢弃阻塞的websocket不等onclose回调了
@ -109,7 +109,7 @@ export default class ChatClientRelay {
if (this.isDestroying) { if (this.isDestroying) {
return return
} }
window.console.warn(`掉线重连中${++this.retryCount}`) console.warn(`掉线重连中${++this.retryCount}`)
window.setTimeout(this.wsConnect.bind(this), 1000) window.setTimeout(this.wsConnect.bind(this), 1000)
} }
@ -140,10 +140,10 @@ export default class ChatClientRelay {
authorType: data[3], authorType: data[3],
content: data[4], content: data[4],
privilegeType: data[5], privilegeType: data[5],
isGiftDanmaku: !!data[6], isGiftDanmaku: Boolean(data[6]),
authorLevel: data[7], authorLevel: data[7],
isNewbie: !!data[8], isNewbie: Boolean(data[8]),
isMobileVerified: !!data[9], isMobileVerified: Boolean(data[9]),
medalLevel: data[10], medalLevel: data[10],
id: data[11], id: data[11],
translation: data[12], translation: data[12],

View File

@ -188,7 +188,7 @@ function randomChoose (nodes) {
} }
function randInt(min, max) { function randInt(min, max) {
return Math.floor(min + (max - min + 1) * Math.random()) return Math.floor(min + ((max - min + 1) * Math.random()))
} }
export default class ChatClientTest { export default class ChatClientTest {

View File

@ -9,9 +9,9 @@
<div id="header-content-primary-column" class="style-scope yt-live-chat-membership-item-renderer"> <div id="header-content-primary-column" class="style-scope yt-live-chat-membership-item-renderer">
<div id="header-content-inner-column" class="style-scope yt-live-chat-membership-item-renderer"> <div id="header-content-inner-column" class="style-scope yt-live-chat-membership-item-renderer">
<yt-live-chat-author-chip class="style-scope yt-live-chat-membership-item-renderer"> <yt-live-chat-author-chip class="style-scope yt-live-chat-membership-item-renderer">
<span id="author-name" dir="auto" class="member style-scope yt-live-chat-author-chip">{{ <span id="author-name" dir="auto" class="member style-scope yt-live-chat-author-chip">
authorName <template>{{ authorName }}</template>
}}<!-- 这里是已验证勋章 --> <!-- 这里是已验证勋章 -->
<span id="chip-badges" class="style-scope yt-live-chat-author-chip"></span> <span id="chip-badges" class="style-scope yt-live-chat-author-chip"></span>
</span> </span>
<span id="chat-badges" class="style-scope yt-live-chat-author-chip"> <span id="chat-badges" class="style-scope yt-live-chat-author-chip">

View File

@ -23,9 +23,7 @@
</div> </div>
</div> </div>
<div id="content" class="style-scope yt-live-chat-paid-message-renderer"> <div id="content" class="style-scope yt-live-chat-paid-message-renderer">
<div id="message" dir="auto" class="style-scope yt-live-chat-paid-message-renderer">{{ <div id="message" dir="auto" class="style-scope yt-live-chat-paid-message-renderer">{{ content }}</div>
content
}}</div>
</div> </div>
</div> </div>
</yt-live-chat-paid-message-renderer> </yt-live-chat-paid-message-renderer>
@ -53,7 +51,7 @@ export default {
return constants.getPriceConfig(this.price).colors return constants.getPriceConfig(this.price).colors
}, },
priceText() { priceText() {
return 'CN¥' + utils.formatCurrency(this.price) return `CN¥${utils.formatCurrency(this.price)}`
}, },
timeText() { timeText() {
return utils.getTimeTextHourMin(this.time) return utils.getTimeTextHourMin(this.time)

View File

@ -73,7 +73,7 @@ export default {
color = [0, 0, 0] color = [0, 0, 0]
let t = (this.repeated - 2) / (10 - 2) let t = (this.repeated - 2) / (10 - 2)
for (let i = 0; i < 3; i++) { for (let i = 0; i < 3; i++) {
color[i] = REPEATED_MARK_COLOR_START[i] + (REPEATED_MARK_COLOR_END[i] - REPEATED_MARK_COLOR_START[i]) * t color[i] = REPEATED_MARK_COLOR_START[i] + ((REPEATED_MARK_COLOR_END[i] - REPEATED_MARK_COLOR_START[i]) * t)
} }
} }
return `hsl(${color[0]}, ${color[1]}%, ${color[2]}%)` return `hsl(${color[0]}, ${color[1]}%, ${color[2]}%)`

View File

@ -142,7 +142,7 @@ export default {
color2 = config.colors.headerBg color2 = config.colors.headerBg
} }
let pinTime = this.getPinTime(message) let pinTime = this.getPinTime(message)
let progress = (1 - (this.curTime - message.addTime) / (60 * 1000) / pinTime) * 100 let progress = (1 - ((this.curTime - message.addTime) / (60 * 1000) / pinTime)) * 100
if (progress < 0) { if (progress < 0) {
progress = 0 progress = 0
} else if (progress > 100) { } else if (progress > 100) {
@ -160,7 +160,7 @@ export default {
if (message.type === constants.MESSAGE_TYPE_MEMBER) { if (message.type === constants.MESSAGE_TYPE_MEMBER) {
return 'Member' return 'Member'
} }
return 'CN¥' + formatCurrency(message.price) return `CN¥${formatCurrency(message.price)}`
}, },
getPinTime(message) { getPinTime(message) {
if (message.type === constants.MESSAGE_TYPE_MEMBER) { if (message.type === constants.MESSAGE_TYPE_MEMBER) {

View File

@ -100,7 +100,7 @@ export const PRICE_CONFIGS = [
pinTime: 0 pinTime: 0
}, },
{ // $1蓝 { // $1蓝
price: 1 * EXCHANGE_RATE, price: EXCHANGE_RATE,
colors: { colors: {
contentBg: 'rgba(30,136,229,1)', contentBg: 'rgba(30,136,229,1)',
headerBg: 'rgba(21,101,192,1)', headerBg: 'rgba(21,101,192,1)',

View File

@ -468,7 +468,7 @@ export default {
this.lastSmoothChatMessageAddMs = performance.now() this.lastSmoothChatMessageAddMs = performance.now()
} }
let interval = performance.now() - this.lastSmoothChatMessageAddMs let interval = performance.now() - this.lastSmoothChatMessageAddMs
this.chatRateMs = 0.9 * this.chatRateMs + 0.1 * interval this.chatRateMs = (0.9 * this.chatRateMs) + (0.1 * interval)
if (this.isSmoothed) { if (this.isSmoothed) {
if (this.chatRateMs < 400) { if (this.chatRateMs < 400) {
this.isSmoothed = false this.isSmoothed = false

View File

@ -34,8 +34,8 @@
{ locale: 'zh', name: '中文' }, { locale: 'zh', name: '中文' },
{ locale: 'ja', name: '日本語' }, { locale: 'ja', name: '日本語' },
{ locale: 'en', name: 'English' } { locale: 'en', name: 'English' }
]" :key="locale" ]"
@click="onSelectLanguage(locale)" :key="locale" @click="onSelectLanguage(locale)"
>{{ name }}</el-menu-item> >{{ name }}</el-menu-item>
</el-submenu> </el-submenu>
</el-menu> </el-menu>

View File

@ -10,7 +10,7 @@ export function toBool (val) {
if (typeof val === 'string') { if (typeof val === 'string') {
return ['false', 'no', 'off', '0', ''].indexOf(val.toLowerCase()) === -1 return ['false', 'no', 'off', '0', ''].indexOf(val.toLowerCase()) === -1
} }
return !!val return Boolean(val)
} }
export function toInt(val, _default) { export function toInt(val, _default) {
@ -29,7 +29,7 @@ export function formatCurrency (price) {
export function getTimeTextHourMin(date) { export function getTimeTextHourMin(date) {
let hour = date.getHours() let hour = date.getHours()
let min = ('00' + date.getMinutes()).slice(-2) let min = `00${date.getMinutes()}`.slice(-2)
return `${hour}:${min}` return `${hour}:${min}`
} }

View File

@ -189,7 +189,7 @@ export default {
try { try {
this.serverConfig = (await axios.get('/api/server_info')).data.config this.serverConfig = (await axios.get('/api/server_info')).data.config
} catch (e) { } catch (e) {
this.$message.error('Failed to fetch server information: ' + e) this.$message.error(`Failed to fetch server information: ${e}`)
} }
}, },
enterRoom() { enterRoom() {

View File

@ -477,8 +477,8 @@ yt-live-chat-text-message-renderer #message::before {
content: ""; content: "";
display: inline-block; display: inline-block;
position: absolute; position: absolute;
top: ${this.form.showUserNames ? ((this.form.userNameLineHeight || this.form.userNameFontSize) + 10) : 20}px; top: ${this.form.showUserNames ? (this.form.userNameLineHeight || this.form.userNameFontSize) + 10 : 20}px;
left: ${this.form.showAvatars ? (this.form.avatarSize + this.form.avatarSize / 4 - 8) : -8}px; left: ${this.form.showAvatars ? this.form.avatarSize + (this.form.avatarSize / 4) - 8 : -8}px;
border: 8px solid transparent; border: 8px solid transparent;
border-right: 18px solid; border-right: 18px solid;
transform: rotate(35deg); transform: rotate(35deg);

View File

@ -113,13 +113,13 @@ export function getAnimationStyle (config) {
: ` transform: translateX(${config.reverseSlide ? 16 : -16}px);` : ` transform: translateX(${config.reverseSlide ? 16 : -16}px);`
} }`) } }`)
curTime += config.fadeInTime curTime += config.fadeInTime
keyframes.push(` ${(curTime / totalTime) * 100}% { opacity: 1; transform: none; }`) keyframes.push(` ${curTime / totalTime * 100}% { opacity: 1; transform: none; }`)
} }
if (config.animateOut) { if (config.animateOut) {
curTime += config.animateOutWaitTime * 1000 curTime += config.animateOutWaitTime * 1000
keyframes.push(` ${(curTime / totalTime) * 100}% { opacity: 1; transform: none; }`) keyframes.push(` ${curTime / totalTime * 100}% { opacity: 1; transform: none; }`)
curTime += config.fadeOutTime curTime += config.fadeOutTime
keyframes.push(` ${(curTime / totalTime) * 100}% { opacity: 0;${!config.slide ? '' keyframes.push(` ${curTime / totalTime * 100}% { opacity: 0;${!config.slide ? ''
: ` transform: translateX(${config.reverseSlide ? -16 : 16}px);` : ` transform: translateX(${config.reverseSlide ? -16 : 16}px);`
} }`) } }`)
} }