Commit ee7a1044 ee7a104476a53278cb6da2977734e8b5235718f1 by 杨俊

Init

0 parents
Showing 127 changed files with 5827 additions and 0 deletions
#VITE_API_URL=https://service.hising.orb.local
VITE_API_URL=https://hi-sing-service-dev.hikoon.com
VITE_OSS_ACCESS_KEY=LTAI4GKtcA6yTV6wnapivq7Y
VITE_OSS_ACCESS_SECRET=QPEt0HPEuRe7wIk2wZNtKPF6L0xMmQ
VITE_OSS_BUCKET=hisin-dev
VITE_OSS_REGION=oss-cn-beijing
VITE_OSS_HOST=https://hi-sing-cdn-dev.hikoon.com
VITE_OSS_ENDPOINT=https://hisin-dev.oss-cn-beijing.aliyuncs.com
VITE_SHOW_LOGIN_ACCOUNT=true
/*.json
/*.js
dist
\ No newline at end of file
const path = require('path');
module.exports = {
root: true,
parser: 'vue-eslint-parser',
parserOptions: {
// Parser that checks the content of the <script> tag
parser: '@typescript-eslint/parser',
sourceType: 'module',
ecmaVersion: 2020,
ecmaFeatures: {
jsx: true,
},
},
env: {
browser: true,
node: true,
},
plugins: ['@typescript-eslint'],
extends: [
// Airbnb JavaScript Style Guide https://github.com/airbnb/javascript
'airbnb-base',
'plugin:@typescript-eslint/recommended',
'plugin:import/recommended',
'plugin:import/typescript',
'plugin:vue/vue3-recommended',
'plugin:prettier/recommended',
],
settings: {
'import/resolver': {
typescript: {
project: path.resolve(__dirname, './tsconfig.json'),
},
},
},
globals: {
defineProps: 'readonly',
defineEmits: 'readonly',
defineExpose: 'readonly',
defineModel: 'readonly',
withDefaults: 'readonly',
},
rules: {
"prettier/prettier": 'off',
// 'prettier/prettier': 1,
'import/order': 0,
// Vue: Recommended rules to be closed or modify
'vue/require-default-prop': 0,
'vue/singleline-html-element-content-newline': 0,
'vue/max-attributes-per-line': 0,
// Vue: Add extra rules
'vue/custom-event-name-casing': [2, 'camelCase'],
'vue/no-v-text': 1,
'vue/padding-line-between-blocks': 1,
'vue/require-direct-export': 1,
'vue/multi-word-component-names': 0,
// Allow @ts-ignore comment
'@typescript-eslint/ban-ts-comment': 0,
'@typescript-eslint/no-unused-vars': 1,
'@typescript-eslint/no-empty-function': 1,
'@typescript-eslint/no-explicit-any': 0,
'@typescript-eslint/no-implicit-any': 0,
'camelcase': 'off',
'max-classes-per-file': 'off',
'@typescript-eslint/camelcase': 0,
'import/extensions': [
2,
'ignorePackages',
{
js: 'never',
jsx: 'never',
ts: 'never',
tsx: 'never',
},
],
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
'no-param-reassign': 0,
'no-return-assign': 0,
'no-shadow': 0,
'prefer-regex-literals': 0,
'import/no-extraneous-dependencies': 0,
'class-methods-use-this': 0,
"vue/first-attribute-linebreak": ["error", {
"singleline": "ignore",
"multiline": "ignore"
}]
},
};
node_modules
.DS_Store
.env.production
dist
.idea/*
dist-ssr
*.local
yarn.lock
/dist/*
.local
.output.js
/node_modules/**
**/*.svg
module.exports = {
tabWidth: 2,
semi: true,
printWidth: 140,
singleQuote: true,
quoteProps: 'consistent',
htmlWhitespaceSensitivity: 'strict',
vueIndentScriptAndStyle: true,
};
module.exports = {
extends: [
'stylelint-config-standard',
'stylelint-config-rational-order',
'stylelint-config-prettier',
'stylelint-config-recommended-vue',
],
defaultSeverity: 'warning',
plugins: ['stylelint-order'],
rules: {
'at-rule-no-unknown': [
true,
{
ignoreAtRules: ['plugin'],
},
],
'rule-empty-line-before': [
'always',
{
except: ['after-single-line-comment', 'first-nested'],
},
],
'selector-pseudo-class-no-unknown': [
true,
{
ignorePseudoClasses: ['deep'],
},
],
},
};
module.exports = {
plugins: ['@vue/babel-plugin-jsx'],
};
module.exports = {
extends: ['@commitlint/config-conventional'],
};
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// Generated by unplugin-vue-components
// Read more: https://github.com/vuejs/core/pull/3399
import '@vue/runtime-core'
export {}
declare module '@vue/runtime-core' {
export interface GlobalComponents {
RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView']
}
}
/**
* If you use the template method for development, you can use the unplugin-vue-components plugin to enable on-demand loading support.
* 按需引入
* https://github.com/antfu/unplugin-vue-components
* https://arco.design/vue/docs/start
* Although the Pro project is full of imported components, this plugin will be used by default.
* 虽然Pro项目中是全量引入组件,但此插件会默认使用。
*/
import Components from 'unplugin-vue-components/vite';
import { ArcoResolver } from 'unplugin-vue-components/resolvers';
export default function configArcoResolverPlugin() {
const arcoResolverPlugin = Components({
dirs: [], // Avoid parsing src/components. 避免解析到src/components
deep: false,
resolvers: [ArcoResolver()],
});
return arcoResolverPlugin;
}
/**
* Theme import
* 样式按需引入
* https://github.com/arco-design/arco-plugins/blob/main/packages/plugin-vite-vue/README.md
* https://arco.design/vue/docs/start
*/
import { vitePluginForArco } from '@arco-plugins/vite-vue';
export default function configArcoStyleImportPlugin() {
const arcoResolverPlugin = vitePluginForArco({});
return arcoResolverPlugin;
}
/**
* Used to package and output gzip. Note that this does not work properly in Vite, the specific reason is still being investigated
* gzip压缩
* https://github.com/anncwb/vite-plugin-compression
*/
import type { Plugin } from 'vite';
import compressPlugin from 'vite-plugin-compression';
export default function configCompressPlugin(
compress: 'gzip' | 'brotli',
deleteOriginFile = false
): Plugin | Plugin[] {
const plugins: Plugin[] = [];
if (compress === 'gzip') {
plugins.push(
compressPlugin({
ext: '.gz',
deleteOriginFile,
})
);
}
if (compress === 'brotli') {
plugins.push(
compressPlugin({
ext: '.br',
algorithm: 'brotliCompress',
deleteOriginFile,
})
);
}
return plugins;
}
/**
* Image resource files used to compress the output of the production environment
* 图片压缩
* https://github.com/anncwb/vite-plugin-imagemin
*/
import viteImagemin from 'vite-plugin-imagemin';
export default function configImageminPlugin() {
const imageminPlugin = viteImagemin({
gifsicle: {
optimizationLevel: 7,
interlaced: false,
},
optipng: {
optimizationLevel: 7,
},
mozjpeg: {
quality: 20,
},
pngquant: {
quality: [0.8, 0.9],
speed: 4,
},
svgo: {
plugins: [
{
name: 'removeViewBox',
},
{
name: 'removeEmptyAttrs',
active: false,
},
],
},
});
return imageminPlugin;
}
/**
* Generation packaging analysis
* 生成打包分析
*/
import visualizer from 'rollup-plugin-visualizer';
import { isReportMode } from '../utils';
export default function configVisualizerPlugin() {
if (isReportMode()) {
return visualizer({
filename: './node_modules/.cache/visualizer/stats.html',
open: true,
gzipSize: true,
brotliSize: true,
});
}
return [];
}
/**
* Whether to generate package preview
* 是否生成打包报告
*/
export default {};
export function isReportMode(): boolean {
return process.env.REPORT === 'true';
}
import { resolve } from 'path';
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import svgLoader from 'vite-svg-loader';
import configArcoStyleImportPlugin from './plugin/arcoStyleImport';
export default defineConfig({
plugins: [vue(), vueJsx(), svgLoader({ svgoConfig: {} }), configArcoStyleImportPlugin()],
resolve: {
alias: [
{
find: '@',
replacement: resolve(__dirname, '../src'),
},
{
find: 'assets',
replacement: resolve(__dirname, '../src/assets'),
},
{
find: 'vue-i18n',
replacement: 'vue-i18n/dist/vue-i18n.cjs.js', // Resolve the i18n warning issue
},
{
find: 'vue',
replacement: 'vue/dist/vue.esm-bundler.js', // compile template
},
],
extensions: ['.ts', '.js'],
},
define: {
'process.env': {},
'__VUE_PROD_HYDRATION_MISMATCH_DETAILS__': false,
},
css: {
preprocessorOptions: {
less: {
modifyVars: {
hack: `true; @import (reference) "${resolve('src/assets/style/breakpoint.less')}";`,
},
javascriptEnabled: true,
},
},
},
});
import { loadEnv, mergeConfig } from "vite";
import baseConfig from "./vite.config.base";
import configCompressPlugin from "./plugin/compress";
import configVisualizerPlugin from "./plugin/visualizer";
import configArcoResolverPlugin from "./plugin/arcoResolver";
import configImageminPlugin from "./plugin/imagemin";
import VitePluginOss from "vite-plugin-oss";
const config = loadEnv("production", "");
const ossPath = `vendor/user/asset${new Date()
.toLocaleString("zh")
.slice(0, 20)
.replace(/[\s/:]/g, "")}`;
export default mergeConfig(
{
mode: "production",
base: config.VITE_OSS_HOST,
server: {
https: true
},
plugins: [
configCompressPlugin("gzip"),
configVisualizerPlugin(),
configArcoResolverPlugin(),
configImageminPlugin(),
VitePluginOss({
from: `./dist/${ossPath}/**`,
accessKeyId: config.VITE_OSS_ACCESS_KEY,
accessKeySecret: config.VITE_OSS_ACCESS_SECRET,
bucket: config.VITE_OSS_BUCKET,
region: config.VITE_OSS_REGION,
quitWpOnError: true,
deleteOrigin: true,
deleteEmptyDir: true
})
],
build: {
assetsDir: ossPath,
rollupOptions: {
output: {
manualChunks: {
arco: ["@arco-design/web-vue"],
chart: ["echarts", "vue-echarts"],
vue: ["vue", "vue-router", "pinia", "@vueuse/core", "vue-i18n"]
}
}
},
chunkSizeWarningLimit: 2000
}
},
baseConfig
);
import { mergeConfig } from 'vite';
import eslint from 'vite-plugin-eslint';
import baseConfig from './vite.config.base';
export default mergeConfig(
{
mode: 'development',
server: {
open: true,
fs: {
strict: false,
},
},
plugins: [
eslint({
cache: false,
include: ['src/**/*.ts', 'src/**/*.tsx', 'src/**/*.vue'],
exclude: ['node_modules'],
}),
],
define: {
__VUE_PROD_HYDRATION_MISMATCH_DETAILS__: true,
},
},
baseConfig
);
import { mergeConfig } from 'vite';
import baseConfig from './vite.config.base';
import configCompressPlugin from './plugin/compress';
import configVisualizerPlugin from './plugin/visualizer';
import configArcoResolverPlugin from './plugin/arcoResolver';
import configImageminPlugin from './plugin/imagemin';
export default mergeConfig(
{
mode: 'production',
server: {
https: true,
},
plugins: [configCompressPlugin('gzip'), configVisualizerPlugin(), configArcoResolverPlugin(), configImageminPlugin()],
build: {
rollupOptions: {
output: {
manualChunks: {
arco: ['@arco-design/web-vue'],
chart: ['echarts', 'vue-echarts'],
vue: ['vue', 'vue-router', 'pinia', '@vueuse/core', 'vue-i18n'],
},
},
},
chunkSizeWarningLimit: 2000,
},
},
baseConfig
);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="shortcut icon" type="image/x-icon" href="https://hising-cdn.hikoon.com/file/20231201/nyaagyzd92c1701419974050pv0hv2xlsme.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="referrer" content="no-referrer"/>
<title>海星试唱</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
{
"name": "arco-design-pro-vue",
"description": "Arco Design Pro for Vue",
"version": "1.0.0",
"private": true,
"author": "ArcoDesign Team",
"license": "MIT",
"scripts": {
"dev": "vue-tsc --noEmit && vite --config ./config/vite.config.dev.ts",
"build": "vue-tsc --noEmit && vite build --config ./config/vite.config.prod.ts",
"build:cdn": "vue-tsc --noEmit && vite build --config ./config/vite.config.cdn.ts",
"report": "cross-env REPORT=true npm run build",
"preview": "npm run build && vite preview --host",
"type:check": "vue-tsc --noEmit --skipLibCheck",
"lint-staged": "npx lint-staged"
},
"lint-staged": {
"*.{js,ts,jsx,tsx}": [
"prettier --write",
"eslint --fix"
],
"*.vue": [
"stylelint --fix",
"prettier --write",
"eslint --fix"
],
"*.{less,css}": [
"stylelint --fix",
"prettier --write"
]
},
"dependencies": {
"@arco-design/web-vue": "^2.44.7",
"@vueuse/core": "^7.3.0",
"arco-design-pro-vue": "^2.7.2",
"axios": "^1.6.0",
"dayjs": "^1.11.5",
"echarts": "^5.4.0",
"lodash-es": "^4.17.21",
"mitt": "^3.0.0",
"nprogress": "^0.2.0",
"pinia": "^2.0.23",
"query-string": "^8.0.3",
"sortablejs": "^1.15.0",
"vue": "^3.3.11",
"vue-echarts": "^6.2.3",
"vue-i18n": "^9.2.2",
"vue-router": "^4.0.14",
"ali-oss": "^6.17.1",
"file-saver": "^2.0.5",
"rabbit-lyrics": "^2.1.1"
},
"devDependencies": {
"@types/ali-oss": "^6.16.3",
"@types/file-saver": "^2.0.5",
"@arco-plugins/vite-vue": "^1.4.5",
"@commitlint/cli": "^17.1.2",
"@commitlint/config-conventional": "^17.1.0",
"@types/lodash": "^4.14.186",
"@types/lodash-es": "^4.17.12",
"@types/nprogress": "^0.2.0",
"@types/sortablejs": "^1.15.0",
"@typescript-eslint/eslint-plugin": "^5.40.0",
"@typescript-eslint/parser": "^5.40.0",
"@vitejs/plugin-vue": "^3.1.2",
"@vitejs/plugin-vue-jsx": "^2.0.1",
"@vue/babel-plugin-jsx": "^1.1.1",
"@vueuse/router": "^10.3.0",
"consola": "^2.15.3",
"cross-env": "^7.0.3",
"eslint": "^8.25.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-prettier": "^8.5.0",
"eslint-import-resolver-typescript": "^3.5.1",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-vue": "^9.6.0",
"less": "^4.1.3",
"lint-staged": "^13.0.3",
"postcss-html": "^1.5.0",
"prettier": "^2.7.1",
"rollup": "^3.9.1",
"rollup-plugin-visualizer": "^5.8.2",
"stylelint": "^14.13.0",
"stylelint-config-prettier": "^9.0.3",
"stylelint-config-rational-order": "^0.1.2",
"stylelint-config-standard": "^29.0.0",
"stylelint-order": "^5.0.0",
"typescript": "^4.8.4",
"unplugin-vue-components": "^0.24.1",
"vite": "^3.2.5",
"vite-plugin-compression": "^0.5.1",
"vite-plugin-eslint": "^1.8.1",
"vite-plugin-imagemin": "^0.6.1",
"vite-plugin-oss": "^1.2.13",
"vite-svg-loader": "^3.6.0",
"vue-tsc": "^1.0.14"
},
"engines": {
"node": ">=14.0.0"
},
"resolutions": {
"bin-wrapper": "npm:bin-wrapper-china",
"rollup": "^2.56.3",
"gifsicle": "5.2.0"
},
"volta": {
"node": "18.3.0",
"yarn": "1.22.19"
}
}
<template>
<a-config-provider size="small">
<router-view />
</a-config-provider>
</template>
// eslint-disable-next-line max-classes-per-file
import { AnyObject, QueryForParams, ServiceResponse } from '@/types/global';
import axios from 'axios';
import { ActivityApply } from '@/types/activity-apply';
import { Activity, ActivityViewUser } from '@/types/activity';
export default class useActivityApi {
static statusOption = [
{ label: '处理中', value: 0 },
{ label: '已上架', value: 1 },
{ label: '已下架', value: 2 },
{ label: '已匹配', value: 3 },
{ label: '已发行', value: 5 },
{ label: '处理失败', value: 4 },
];
static weightOption = [
{ label: '无', value: 0 },
{ label: '低', value: 30 },
{ label: '中', value: 60 },
{ label: '高', value: 90 },
];
static workSingTypeOption = [
{ label: '自主上传', value: 1 },
{ label: '唱整首', value: 2 },
{ label: '唱片段', value: 3 },
];
static workSingStatusOption = [
{ label: '待采纳', value: 0 },
{ label: '已确认', value: 1 },
{ label: '不合适', value: 2 },
{ label: '未采纳', value: 3 },
{ label: '其他', value: 4 },
];
static songTypeOption = [
{ label: '歌曲', value: 1 },
{ label: 'Demo', value: 2 },
];
static async get(params: QueryForParams): Promise<ServiceResponse<Activity[]>> {
return axios.get('/activities', { params });
}
static async show(id: number, params?: QueryForParams): Promise<Activity> {
return axios.get(`/activities/${id}`, { params }).then((res) => Promise.resolve(res.data));
}
static async changeStatus(id: number, data: AnyObject) {
return axios.put<Activity>(`/activities/${id}/change-status`, data).then((res) => Promise.resolve(res.data));
}
static async update(id: number, data: AnyObject): Promise<Activity> {
return axios.put(`/activities/${id}`, data).then((res) => Promise.resolve(res.data));
}
static async destroy(id: number) {
return axios.delete(`/activities/${id}`).then((res) => Promise.resolve(res.data));
}
static async getManageUser(activityId: number, params: QueryForParams): Promise<any> {
return axios.get(`/audition/activities/${activityId}/managers`, { params });
}
static async createManage(data: AnyObject): Promise<any> {
return axios.post('/audition/activity-managers', data).then((res) => Promise.resolve(res.data));
}
static async updateManage(id: number, data: AnyObject): Promise<any> {
return axios.put(`/audition/activity-managers/${id}`, data).then((res) => Promise.resolve(res.data));
}
static async deleteManage(id: number): Promise<any> {
return axios.delete(`/audition/activity-managers/${id}`).then((res) => Promise.resolve(res.data));
}
static async getViewUser(activityId: number, params: QueryForParams): Promise<ServiceResponse<ActivityViewUser[]>> {
return axios.get(`/activities/${activityId}/views`, { params });
}
static async getLikeUser(activityId: number, params: QueryForParams): Promise<ServiceResponse<ActivityViewUser[]>> {
return axios.get(`/activities/${activityId}/collects`, { params });
}
}
export class useApply {
static auditStatusOption = [
{ label: '审核不通过', value: 2 },
{ label: '审核中', value: 0 },
];
static async get(params: QueryForParams): Promise<ServiceResponse<ActivityApply[]>> {
return axios.get('audition/applies', { params });
}
static async create(data: AnyObject) {
return axios.post('/activities', data).then((res) => Promise.resolve(res.data));
}
static async update(id: number, data: AnyObject) {
return axios.put(`audition/applies/${id}`, data).then((res) => Promise.resolve(res.data));
}
static async destroy(id: number) {
return axios.delete(`/audition/applies/${id}`);
}
}
import axios from "axios";
import { AuthorizedState } from "@/store/modules/authorized/type";
import FileSaver from "file-saver";
export default class useAuthApi {
static async info() {
return axios
.get<{
user: AuthorizedState;
permissions: string[];
menus: string[];
can_create_demo: number
}>("auth/info")
.then((res) => Promise.resolve(res.data));
}
static changePwd(data: { password: string; password_confirmation: string }) {
return axios.put("auth/change-pwd", data);
}
static async downloadFile(url: string, fileName: string) {
// ?response-content-type=Blob
FileSaver.saveAs(`${url}`, fileName + url.substring(url.lastIndexOf(".")));
}
}
import axios from 'axios';
import type { TableData } from '@arco-design/web-vue/es/table/interface';
export interface ContentDataRecord {
x: string;
y: number;
}
export function queryContentData() {
return axios.get<ContentDataRecord[]>('/api/content-data');
}
export interface PopularRecord {
key: number;
clickNumber: string;
title: string;
increases: number;
}
export function queryPopularList(params: { type: string }) {
return axios.get<TableData[]>('/api/popular/list', { params });
}
import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message } from '@arco-design/web-vue';
import { getToken } from '@/utils/auth';
export interface HttpResponse<T = unknown> {
status: 'success' | 'fail' | 'error';
msg: string;
code: number;
data: T;
}
export interface ServiceResponse<T = unknown> extends HttpResponse<T> {
meta: { current: number; limit: number; total: number };
}
if (import.meta.env.VITE_API_URL) {
axios.defaults.baseURL = import.meta.env.VITE_API_URL;
}
axios.interceptors.request.use(
// @ts-ignore
(config: AxiosRequestConfig) => {
if (!config.url?.startsWith('/provider')) {
config.baseURL = `${config.baseURL}/user`;
}
const token = getToken();
if (token) {
if (!config.headers) {
config.headers = {};
}
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
// do something
return Promise.reject(error);
}
);
// add response interceptors
axios.interceptors.response.use(
// @ts-ignore
async (response: AxiosResponse<ServiceResponse>): Promise<ServiceResponse | unknown> => {
if (response.data instanceof Blob) {
return Promise.resolve(response);
}
return Promise.resolve(response.data);
},
(error) => {
if (error.response.status === 401) {
// clearToken();
window.location.reload();
Message.warning({ id: 'token_lose', content: '登陆信息已失效,请重新登陆...' });
} else {
Message.error({
id: 'service_error',
content: error.response.data.msg || error.msg || 'Request Error',
duration: 5 * 1000,
});
}
return Promise.reject(error);
}
);
import axios from 'axios';
export interface MessageRecord {
id: number;
type: string;
title: string;
subTitle: string;
avatar?: string;
content: string;
time: string;
status: 0 | 1;
messageType?: number;
}
export type MessageListType = MessageRecord[];
export function queryMessageList() {
return axios.post<MessageListType>('/api/message/list');
}
interface MessageStatus {
ids: number[];
}
export function setMessageStatus(data: MessageStatus) {
return axios.post<MessageListType>('/api/message/read', data);
}
export interface ChatRecord {
id: number;
username: string;
content: string;
time: string;
isCollect: boolean;
}
export function queryChatList() {
return axios.post<ChatRecord[]>('/api/chat/list');
}
import { AnyObject } from '@/types/global';
import axios from 'axios';
export default class useProviderApi {
static sms(type: string, phone: string, area?: string) {
return axios.post('/provider/sms', { type, phone, area, platform: 'user' });
}
static async area() {
return axios.get('/provider/area');
}
static async config(params?: AnyObject) {
return axios.get('/provider/configs', { params })
}
static async login(type: 'phone' | 'email', data: object) {
return axios.post<{ access_token: string; refresh_token: string; nick_name: string }>('/provider/login', {
platform: 'user',
type,
...data,
});
}
}
import { QueryForParams } from '@/types/global';
import axios from 'axios';
export default class useUserApi {
static statusOption = [
{ label: '启用', value: 1 },
{ label: '禁用', value: 0 },
{ label: '注销', value: 2 },
];
static officialStatusOption = [
{ label: '已关注', value: 1 },
{ label: '未关注', value: 0 },
];
static sexOption = [
{ label: '男', value: 1 },
{ label: '女', value: 2 },
{ label: '无', value: 0 },
];
static scopeOption = [
{ label: '无权限', value: 0 },
{ label: '平台管理员', value: 1 },
{ label: '厂牌管理员', value: 2 },
];
static async manageSongs(id: number, params?: QueryForParams) {
return axios.get(`users/${id}/manage-songs`, { params });
}
}
No preview for this file type
<svg width="33" height="33" viewBox="0 0 33 33" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0)">
<path fill-rule="evenodd" clip-rule="evenodd" d="M5.37754 16.9795L12.7498 9.43027C14.7163 7.41663 17.9428 7.37837 19.9564 9.34482C19.9852 9.37297 20.0137 9.40145 20.0418 9.43027L20.1221 9.51243C22.1049 11.5429 22.1049 14.7847 20.1221 16.8152L12.7498 24.3644C10.7834 26.378 7.55686 26.4163 5.54322 24.4498C5.5144 24.4217 5.48592 24.3932 5.45777 24.3644L5.37754 24.2822C3.39468 22.2518 3.39468 19.0099 5.37754 16.9795Z" fill="#12D2AC"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M20.0479 9.43034L27.3399 16.8974C29.3674 18.9735 29.3674 22.2883 27.3399 24.3644C25.3735 26.3781 22.147 26.4163 20.1333 24.4499C20.1045 24.4217 20.076 24.3933 20.0479 24.3644L12.7558 16.8974C10.7284 14.8213 10.7284 11.5065 12.7558 9.43034C14.7223 7.4167 17.9488 7.37844 19.9624 9.34489C19.9912 9.37304 20.0197 9.40152 20.0479 9.43034Z" fill="#307AF2"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M20.1321 9.52163L23.6851 13.1599L16.3931 20.627L9.10103 13.1599L12.6541 9.52163C14.6707 7.45664 17.9794 7.4174 20.0444 9.434C20.074 9.46286 20.1032 9.49207 20.1321 9.52163Z" fill="#0057FE"/>
</g>
<defs>
<clipPath id="clip0">
<rect width="26" height="19" fill="white" transform="translate(3.5 7)"/>
</clipPath>
</defs>
</svg>
// ==============breakpoint============
// Extra small screen / phone
@screen-xs: 480px;
// Small screen / tablet
@screen-sm: 576px;
// Medium screen / desktop
@screen-md: 768px;
// Large screen / wide desktop
@screen-lg: 992px;
// Extra large screen / full hd
@screen-xl: 1200px;
// Extra extra large screen / large desktop
@screen-xxl: 1600px;
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
font-size: 14px;
background-color: var(--color-bg-1);
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
}
.echarts-tooltip-diy {
background: linear-gradient(304.17deg,
rgba(253, 254, 255, 0.6) -6.04%,
rgba(244, 247, 252, 0.6) 85.2%) !important;
border: none !important;
backdrop-filter: blur(10px) !important;
/* Note: backdrop-filter has minimal browser support */
border-radius: 6px !important;
.content-panel {
display: flex;
justify-content: space-between;
width: auto;
height: 32px;
margin-bottom: 4px;
padding: 0 9px;
line-height: 32px;
background: rgba(255, 255, 255, 0.8);
border-radius: 4px;
box-shadow: 6px 0 20px rgba(34, 87, 188, 0.1);
}
.tooltip-title {
margin: 0 0 10px 0;
}
p {
margin: 0;
}
.tooltip-title,
.tooltip-value {
font-size: 13px;
line-height: 15px;
display: flex;
align-items: center;
text-align: right;
color: #1d2129;
font-weight: bold;
}
.tooltip-value {
margin-left: 10px;
}
.tooltip-item-icon {
display: inline-block;
margin-right: 8px;
width: 10px;
height: 10px;
border-radius: 50%;
}
}
.general-card {
border-radius: 4px;
border: none;
&>.arco-card-header {
height: auto;
padding: 10px 20px 0 20px;
border: none;
&>.arco-card-header-title {
font-size: 15px;
}
}
&>.arco-card-body {
padding: 0 20px 20px 20px;
}
}
.split-line {
border-color: rgb(var(--gray-2));
}
.arco-table-cell {
.circle {
display: inline-block;
margin-right: 4px;
width: 6px;
height: 6px;
border-radius: 50%;
background-color: rgb(var(--blue-6));
&.pass {
background-color: rgb(var(--green-6));
}
&.warn {
background-color: rgb(var(--yellow-6));
}
&.err {
background-color: rgb(var(--red-6));
}
}
}
.mt-0 {
margin-bottom: 0;
}
.mt-20 {
margin-top: 20px;
}
.mb-0 {
margin-bottom: 0;
}
.color-grey {
color: rgba(44, 44, 44, 0.5)
}
.justify-center {
justify-content: center !important;
}
.retry {
div.arco-modal-header {
border-bottom: unset !important;
}
div.arco-modal-body {
padding: 0 24px 20px;
}
}
.link-hover:hover {
cursor: pointer !important;
}
\ No newline at end of file
This diff could not be displayed because it is too large.
<template>
<audio v-if="url" :id="uuid" :src="url" class="player" controls controlsList="nodownload noplaybackrate" @play="onPay" />
</template>
<script lang="ts" setup>
import { nanoid } from 'nanoid';
import { computed } from 'vue';
defineProps<{ url: string; name: string }>();
const uuid = computed(() => `audio-${nanoid()}`);
const onPay = (e: any) => {
const audios = document.getElementsByTagName('audio');
[].forEach.call(audios, (i: HTMLAudioElement) => i !== e.target && i.pause());
};
</script>
<style lang="less" scoped>
.player {
height: 30px;
width: 100%;
}
</style>
<template>
<Upload :accept="accept" :custom-request="onUpload" :on-before-upload="onBeforeUpload" :file-list="[]" :show-file-list="false">
<template #upload-button>
<Avatar :shape="shape" :size="size" trigger-type="mask">
<div v-if="!modelValue" class="no-avatar">
<icon-plus />
</div>
<img v-else :src="modelValue" style="width: 100%; height: 100%" alt="" />
<template #trigger-icon>
<icon-camera />
</template>
</Avatar>
</template>
</Upload>
</template>
<script lang="ts" setup>
import useOss from '@/hooks/oss';
import { IconCamera, IconPlus } from '@arco-design/web-vue/es/icon';
import { Avatar, Message, Upload, UploadRequest, useFormItem } from '@arco-design/web-vue';
import { computed, toRefs } from 'vue';
const props = withDefaults(
defineProps<{
modelValue?: string;
size?: number;
shape?: 'circle' | 'square';
accept?: string;
limit?: number;
}>(),
{
modelValue: '',
size: 80,
shape: 'circle',
accept: 'image/*',
limit: 5,
}
);
const { shape } = toRefs(props);
const borderRadius = computed(() => (shape.value === 'square' ? 'unset' : 'var(--border-radius-circle)'));
const { eventHandlers } = useFormItem();
const emits = defineEmits(['update:modelValue']);
const { upload } = useOss();
const onBeforeUpload = (file: File) => {
if (file.size > props.limit * 1024 * 1024) {
Message.warning(`${file.name} 文件超过${props.limit}MB,无法上传`);
return Promise.resolve(false);
}
return Promise.resolve(file);
};
const onUpload = (option: any): UploadRequest => {
const { fileItem } = option;
if (fileItem.file) {
upload(fileItem.file, 'image').then((res) => {
emits('update:modelValue', res?.url || '');
eventHandlers.value?.onChange?.();
});
}
return {};
};
</script>
<style lang="less" scoped>
:deep(.arco-avatar-text) {
width: 100%;
height: 100%;
overflow: hidden;
display: inline-block;
border-radius: v-bind(borderRadius);
}
.arco-avatar-image {
transform: unset !important;
}
.no-avatar {
top: 0;
left: 0;
display: flex;
position: absolute;
align-content: center;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
}
</style>
<template>
<a-breadcrumb class="container-breadcrumb">
<a-breadcrumb-item>
<icon-apps />
</a-breadcrumb-item>
<a-breadcrumb-item v-for="item in items" :key="item">
<router-link v-if="getRouteMeta(item)?.isRedirect" :to="{ name: item }">
{{ getRouteName(item) }}
</router-link>
<span v-else> {{ getRouteName(item) }}</span>
</a-breadcrumb-item>
</a-breadcrumb>
</template>
<script lang="ts" setup>
import { IconApps } from '@arco-design/web-vue/es/icon';
import { computed } from 'vue';
import { RouteMeta, RouteRecordNormalized, useRouter } from 'vue-router';
import { useAppStore } from '@/store';
import { storeToRefs } from 'pinia';
defineProps<{ items: string[] }>();
const router = useRouter();
const appStore = useAppStore();
const { appMenu } = storeToRefs(appStore);
const routes = computed(() => {
return router.getRoutes() as RouteRecordNormalized[];
});
const getRoute = (name: any) => {
return routes.value.find((el) => el.name === name);
};
const getRouteMeta = (name: any): RouteMeta | undefined => {
return getRoute(name)?.meta;
};
const getRouteName = (name: any) => {
return getRouteMeta(name)?.title || appMenu.value.find((item) => item.name === name)?.label || '';
};
</script>
<style lang="less" scoped>
.container-breadcrumb {
margin: 16px 0;
:deep(.arco-breadcrumb-item) {
color: rgb(var(--gray-6));
&:last-child {
color: rgb(var(--gray-8));
}
}
}
</style>
<template>
<VCharts v-if="renderChart" :option="options" :autoresize="autoresize" :style="{ width, height }" />
</template>
<script lang="ts">
import { defineComponent, ref, computed, nextTick } from 'vue';
import VCharts from 'vue-echarts';
import { useAppStore } from '@/store';
export default defineComponent({
components: {
VCharts,
},
props: {
options: {
type: Object,
default() {
return {};
},
},
autoresize: {
type: Boolean,
default: true,
},
width: {
type: String,
default: '100%',
},
height: {
type: String,
default: '100%',
},
},
setup() {
const appStore = useAppStore();
const theme = computed(() => {
if (appStore.theme === 'dark') return 'dark';
return '';
});
const renderChart = ref(false);
// wait container expand
nextTick(() => {
renderChart.value = true;
});
return {
theme,
renderChart,
};
},
});
</script>
<style scoped lang="less"></style>
<template>
<a-button :loading="loading" @click="onClick">
<template #icon>
<icon-download />
</template>
{{ label }}
</a-button>
</template>
<script lang="ts" setup>
import { IconDownload } from '@arco-design/web-vue/es/icon';
import useLoading from '@/hooks/loading';
const props = withDefaults(
defineProps<{
label: string;
onDownload: () => Promise<void>;
}>(),
{
label: '导出',
}
);
const { loading, setLoading } = useLoading(false);
const onClick = () => {
setLoading(true);
props.onDownload().finally(() => setLoading(false));
};
</script>
<style scoped></style>
<script setup lang="ts">
import TableColumn from '@/components/filter/table-column.vue';
import { Layout, LayoutSider, LayoutContent, Image, Form, FormItem, TypographyText, TableData } from '@arco-design/web-vue';
import { get } from 'lodash';
import { isString, isUndefined } from '@/utils';
const props = withDefaults(
defineProps<{
title?: string;
dataIndex?: string;
row?: string;
coverIndex?: string;
nameIndex?: string;
subIndex?: string;
tagIndex?: string;
projectIndex?: string;
hideSubTitle?: boolean;
}>(),
{
coverIndex: 'cover',
nameIndex: 'song_name',
subIndex: 'sub_title',
tagIndex: 'tags',
projectIndex: 'user',
}
);
const getRow = (record: TableData): TableData | undefined => {
if (isUndefined(props.row)) {
return record;
}
if (isString(props.row)) {
return get(record, props.row);
}
return props.row;
};
const getRowColumn = (record: TableData, key: string) => getRow(record)?.[key];
</script>
<template>
<TableColumn v-bind="$attrs" :title="title" :data-index="dataIndex">
<template #default="{ record }">
<Layout>
<LayoutSider :width="104" class="left">
<Image show-loader :height="100" :width="100" fit="cover" :src="getRowColumn(record, coverIndex)" />
</LayoutSider>
<LayoutContent>
<Form auto-label-width label-align="left" :model="record" style="height: 100%; justify-content: space-between">
<FormItem label="歌曲名称" :show-colon="true" row-class="mb-0">
<TypographyText :ellipsis="{ rows: 1, showTooltip: true }">
{{ getRowColumn(record, nameIndex) }}
</TypographyText>
</FormItem>
<FormItem v-if="!hideSubTitle" label="推荐语" :show-colon="true" row-class="mb-0">
<TypographyText :ellipsis="{ rows: 1, showTooltip: true }">
{{ getRowColumn(record, subIndex) }}
</TypographyText>
</FormItem>
<FormItem label="歌曲标签" :show-colon="true" row-class="mb-0">
<TypographyText :ellipsis="{ rows: 1, showTooltip: true }">
{{
getRowColumn(record, tagIndex)
.map((item: any) => item.name)
.join('、')
}}
</TypographyText>
</FormItem>
<FormItem label="关联用户" :show-colon="true" row-class="mb-0">
<TypographyText :ellipsis="{ rows: 1, showTooltip: true }">
{{ getRowColumn(record, projectIndex)?.nick_name }}
</TypographyText>
</FormItem>
</Form>
</LayoutContent>
</Layout>
</template>
</TableColumn>
</template>
<style lang="less" scoped>
:deep(.arco-typography) {
margin-bottom: 0;
width: 100%;
text-align: left;
}
.left {
margin-top: 5px;
box-shadow: unset;
margin-right: 5px;
}
</style>
<script setup lang="ts">
import { Avatar, TableColumn } from '@arco-design/web-vue';
import { get } from 'lodash';
const props = defineProps<{ title?: string; dataIndex?: string; width?: number }>();
const getValue = (record: object) => {
return get(record, props.dataIndex || '', '');
};
</script>
<template>
<TableColumn v-bind="$attrs" :title="title" :data-index="dataIndex" :width="width || 60">
<template #cell="{ record }">
<Avatar :size="40" shape="circle">
<img alt="" :src="getValue(record)" :width="40" :height="40" />
</Avatar>
</template>
</TableColumn>
</template>
<style scoped lang="less"></style>
<script setup lang="ts">
import { get } from "lodash";
import TableColumn from "@/components/filter/table-column.vue";
import dayjs from "dayjs";
withDefaults(defineProps<{ title?: string; dataIndex: string; split?: boolean }>(), { split: true });
const getValue = (record: object, path: string) => {
return get(record, path, "");
};
</script>
<template>
<TableColumn v-bind="$attrs" :title="title" :data-index="dataIndex">
<template #default="{ record }">
<template v-if="dataIndex && !getValue(record, dataIndex)">
<span style="color: rgba(0, 0, 0, 0.3)"></span>
</template>
<template v-else-if="split">
<div>{{ dayjs(getValue(record, dataIndex))?.format("YYYY-MM-DD") || "" }}</div>
<div>{{ dayjs(getValue(record, dataIndex))?.format("HH:mm:ss") || "" }}</div>
</template>
<template v-else>{{ getValue(record, dataIndex) }}</template>
</template>
</TableColumn>
</template>
<style scoped lang="less"></style>
<script setup lang="ts">
import { Options } from '@/types/global';
import { eq, get } from 'lodash';
import TableColumn from '@/components/filter/table-column.vue';
const props = defineProps<{ title?: string; dataIndex?: string; option: Options[]; darkValue?: string | number }>();
const getValue = (record: object) => {
return get(record, props.dataIndex || '', '');
};
</script>
<template>
<TableColumn v-bind="$attrs" :title="title" :data-index="dataIndex">
<template #default="{ record }">
<template v-if="darkValue !== undefined && eq(getValue(record), darkValue)">
<span style="color: rgba(44, 44, 44, 0.5)"> {{ option.find((item) => item.value === getValue(record))?.label || '未知' }}</span>
</template>
<template v-else> {{ option.find((item) => item.value === getValue(record))?.label || '未知' }}</template>
</template>
</TableColumn>
</template>
<style scoped lang="less"></style>
<script setup lang="ts">
import TableColumn from '@/components/filter/table-column.vue';
import { Link } from '@arco-design/web-vue';
import { AnyObject } from '@/types/global';
defineProps<{
title?: string;
dataIndex?: string;
linkStyle?: object;
formatter: (record: AnyObject) => string;
to: (record: AnyObject) => void;
}>();
</script>
<template>
<TableColumn v-bind="$attrs" :title="title" :data-index="dataIndex">
<template #default="{ record }">
<Link v-if="!!formatter(record)" class="link" :style="linkStyle" :hoverable="false" @click.stop="to(record)">{{
formatter(record)
}}</Link>
<span v-else style="color: rgba(44, 44, 44, 0.5)"></span>
</template>
</TableColumn>
</template>
<style scoped lang="less">
.link:hover {
cursor: pointer;
}
</style>
<script setup lang="ts">
import { get } from 'lodash';
import TableColumn from '@/components/filter/table-column.vue';
const props = defineProps<{ title?: string; dataIndex?: string; nickIndex?: string; realIndex?: string }>();
const fullName = (record: object) => {
let name = '';
if (props.nickIndex && get(record, props.nickIndex, '')) {
name += get(record, props.nickIndex, '');
}
if (props.realIndex && get(record, props.realIndex)) {
name += `(${get(record, props.realIndex, '')})`;
}
return name;
};
</script>
<template>
<TableColumn v-bind="$attrs" :title="title" :data-index="dataIndex">
<template #default="{ record }"> {{ fullName(record) }}</template>
</TableColumn>
</template>
<style scoped lang="less"></style>
<script setup lang="ts">
import { eq, get } from 'lodash';
import TableColumn from '@/components/filter/table-column.vue';
const props = withDefaults(
defineProps<{ title?: string; dataIndex?: string; darkValue?: string | number; prefix?: string; suffix?: string }>(),
{ prefix: '', suffix: '' }
);
const getValue = (record: object) => {
return get(record, props.dataIndex || '', '');
};
</script>
<template>
<TableColumn v-bind="$attrs" :title="title" :data-index="dataIndex">
<template #default="{ record }">
<template v-if="darkValue !== undefined && eq(getValue(record), darkValue)">
<span style="color: rgba(44, 44, 44, 0.5)">{{ `${prefix} 0 ${suffix}` }}</span>
</template>
<template v-else> {{ `${prefix} ${getValue(record)} ${suffix}` }} </template>
</template>
</TableColumn>
</template>
<style scoped lang="less"></style>
<script setup lang="ts">
import { get } from "lodash";
import TableColumn from "@/components/filter/table-column.vue";
withDefaults(defineProps<{ title?: string; dataIndex: string; areaIndex?: string }>(), {
areaIndex: "area_code"
});
const getValue = (record: object, path: string) => {
return get(record, path, "");
};
</script>
<template>
<TableColumn v-bind="$attrs" :title="title" :data-index="dataIndex">
<template #default="{ record }"> {{ `(+${getValue(record, areaIndex)}) ${getValue(record, dataIndex)}` }}</template>
</TableColumn>
</template>
<style scoped lang="less"></style>
<script setup lang="ts">
import { GridItem, FormItem } from '@arco-design/web-vue';
</script>
<template>
<GridItem>
<FormItem class="form-item" row-class="mb-0" v-bind="$attrs" :show-colon="true">
<slot />
</FormItem>
</GridItem>
</template>
<style scoped lang="less">
.form-item {
:deep(.arco-picker) {
width: 100%;
}
}
</style>
<script setup lang="ts">
import { AnyObject } from "@/types/global";
import { Layout, LayoutContent, LayoutSider, Form, Space, Grid } from "@arco-design/web-vue";
import IconButton from "@/components/icon-button/index.vue";
type PropType = {
model?: AnyObject;
loading?: boolean;
searchLabel?: string;
searchIcon?: string;
resetLabel?: string;
resetIcon?: string;
hideSearch?: boolean;
hideReset?: boolean;
inline?: boolean;
split?: number;
size?: "mini" | "small" | "medium" | "large";
hideDivider?: boolean;
};
const props = withDefaults(defineProps<PropType>(), {
loading: false,
searchLabel: "搜索",
searchIcon: "search",
resetLabel: "重置",
resetIcon: "refresh",
hideSearch: false,
hideReset: false,
hideDivider: false,
inline: false,
split: 3,
size: "small"
});
defineEmits<{ (e?: "search"): void; (e?: "reset"): void }>();
const layoutStyle = { marginBottom: "12px" };
const layoutRightStyle = props.hideSearch && props.hideReset ? {} : { borderLeft: "1px solid var(--color-neutral-3)" };
if (!props.hideDivider) {
Object.assign(layoutStyle, { paddingBottom: "12px", borderBottom: "1px solid var(--color-neutral-3)" });
}
</script>
<template>
<Layout :style="layoutStyle">
<LayoutContent>
<Form auto-label-width :model="model || {}" label-align="right" :size="size">
<Grid :cols="split as number" :col-gap="12" :row-gap="12">
<slot :size="size" />
</Grid>
</Form>
</LayoutContent>
<LayoutSider class="right" :style="layoutRightStyle">
<Space :size="12" :direction="inline ? 'horizontal' : 'vertical'">
<IconButton
v-if="!hideSearch"
:size="size"
:icon="searchIcon"
:label="searchLabel"
type="primary"
:loading="loading"
@click="$emit('search')"
/>
<IconButton v-if="!hideReset" :size="size" :icon="resetIcon" :label="resetLabel" @click="$emit('reset')" />
<slot name="button" />
</Space>
</LayoutSider>
</Layout>
</template>
<style scoped lang="less">
.right {
border-left: 1px solid var(--color-neutral-3);
margin-left: 12px;
padding-left: 12px;
box-shadow: unset;
width: auto !important;
}
</style>
<script setup lang="ts">
import { Space, TableData } from "@arco-design/web-vue";
import TableColumn from "@/components/filter/table-column.vue";
withDefaults(defineProps<{ title?: string; dataIndex?: string; direction?: "vertical" | "horizontal" }>(), {
direction: "horizontal"
});
</script>
<template>
<TableColumn v-bind="$attrs" :title="title" :data-index="dataIndex" :tooltip="false">
<template #default="{ record, rowIndex }: { record: TableData, rowIndex?: number }">
<Space :direction="direction" fill>
<slot name="default" :record="record" :index="rowIndex" />
</Space>
</template>
</TableColumn>
</template>
<style scoped lang="less"></style>
<script setup lang="ts">
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { TableColumn, TableData, TableSortable } from '@arco-design/web-vue';
type PropType = { title?: string; dataIndex?: string; tooltip?: boolean; ellipsis?: boolean; hasSort?: boolean };
const sortable = { sortDirections: ['ascend', 'descend'], sorter: true, defaultSortOrder: '' } as TableSortable;
withDefaults(defineProps<PropType>(), { tooltip: true, hasSort: false });
</script>
<template>
<TableColumn
v-bind="$attrs"
:title="title"
:data-index="dataIndex"
:tooltip="tooltip as boolean"
:ellipsis="ellipsis || tooltip as boolean"
:sortable="hasSort ? sortable : undefined as any"
>
<template v-if="$slots.default" #cell="{ record, rowIndex }: { record: TableData, rowIndex: number }">
<slot name="default" :record="record" :index="rowIndex" />
</template>
</TableColumn>
</template>
<style scoped lang="less"></style>
<script setup lang="ts">
import { computed, ref } from 'vue';
import { Col, Row, Table } from '@arco-design/web-vue';
import { AnyObject, sizeType } from '@/types/global';
import usePagination from '@/hooks/pagination';
type PropType = {
loading?: boolean;
rowKey?: string;
hoverType?: string;
simplePage?: boolean;
pageSize?: number;
size?: sizeType;
onQuery: (params?: AnyObject) => Promise<any>;
};
defineEmits<{ (e: 'rowSort', dataIndex: string, direction: string): void }>();
const props = withDefaults(defineProps<PropType>(), { loading: false, rowKey: 'id', size: 'small', pageSize: 20 });
const { pagination, setPage, setPageSize, setTotal } = usePagination({
simple: props.simplePage,
size: props.size,
pageSize: props.pageSize,
});
const list = ref<any[]>([]);
const tableRef = ref();
const pageQueryParams = computed(() => {
return { page: pagination.value.current, pageSize: pagination.value.pageSize };
});
const hoverType = computed(() => props.hoverType || 'default');
const onFetch = () =>
props.onQuery(pageQueryParams.value).then(({ data, meta }) => {
list.value = data;
setPage(meta.current);
setTotal(meta.total);
setPageSize(meta.limit);
});
const onPageChange = (page: number) => {
setPage(page || 1);
onFetch();
};
const onSizeChange = (size: number) => {
setPageSize(size);
setPage(1);
onFetch();
};
const onPush = (row: unknown) => {
list.value.unshift(row);
// eslint-disable-next-line no-plusplus
++pagination.value.total;
};
const onRemove = (index: number) => {
list.value.splice(index, 1);
// eslint-disable-next-line no-plusplus
--pagination.value.total;
};
const resetSort = () => tableRef.value?.clearSorters();
const getCount = () => pagination.value.total;
const formatSortType = (type: string): string => type?.replace('end', '') ?? '';
defineExpose({ onFetch, onPageChange, onSizeChange, resetSort, getCount, onPush, onRemove });
</script>
<template>
<Row justify="space-between" align="center">
<Col flex="1" class="table-tool-item" style="text-align: left">
<slot name="tool" :size="size" />
</Col>
<Col flex="auto" class="table-tool-item" style="text-align: right">
<slot name="tool-right" :size="size" />
</Col>
</Row>
<Table ref="tableRef" v-bind="$attrs" :row-key="rowKey as string" :loading="loading as boolean" :size="size as sizeType"
:data="list" :pagination="pagination" :bordered="false" :table-layout-fixed="true" @page-change="onPageChange"
@page-size-change="onSizeChange"
@sorter-change="(dataIndex, direction) => $emit('rowSort', dataIndex, formatSortType(direction))">
<template #columns>
<slot />
</template>
</Table>
</template>
<style lang="less" scoped>
:deep(.arco-table-cell) {
padding: 5px 8px !important;
:hover {
cursor: v-bind(hoverType);
}
&>.arco-table-td-content .arco-btn-size-small {
padding: 5px !important;
}
}
:deep(.table-tool-item) {
>* {
margin-bottom: 12px !important;
}
}
</style>
<script setup lang="ts">
import TableColumn from '@/components/filter/table-column.vue';
import { Avatar } from '@arco-design/web-vue';
import { get } from 'lodash';
import { User } from '@/types/user';
import { isString, isUndefined } from '@/utils';
const props = withDefaults(
defineProps<{
title?: string;
dataIndex?: string;
user?: string | Pick<User, 'id' | 'nick_name' | 'real_name' | 'identity'>;
showHref?: boolean;
showAvatar?: boolean;
showRealName?: boolean;
darkValue?: string;
nickIndex?: string;
realIndex?: string;
avatarIndex?: string;
roleIndex?: string;
linkStyle?: object;
}>(),
{
dataIndex: 'id',
nickIndex: 'nick_name',
realIndex: 'real_name',
avatarIndex: 'avatar',
roleIndex: 'identity',
}
);
const getUser = (record: object): Pick<User, 'id' | 'nick_name' | 'real_name' | 'identity'> | undefined => {
if (isUndefined(props.user)) {
return record as User;
}
if (isString(props.user)) {
return get(record, props.user);
}
return get(props, 'user') as User;
};
const getName = (record: object): string => {
const user = getUser(record);
if (!user) {
return '';
}
if (props.showRealName) {
return `${get(user, props.nickIndex, '')}(${get(user, props.realIndex)})`;
}
return get(user, props.nickIndex, '');
};
</script>
<template>
<TableColumn v-bind="$attrs" :title="title" :data-index="dataIndex">
<template #default="{ record }">
<template v-if="darkValue !== undefined && getName(record) === darkValue">
<span style="color: rgba(44, 44, 44, 0.5)"></span>
</template>
<template v-else>
<Avatar v-if="showAvatar" style="margin-right: 8px" :size="34" shape="circle" :image-url="getUser(record)?.[avatarIndex]" />
{{ getName(record) }}
</template>
</template>
</TableColumn>
</template>
<style scoped lang="less"></style>
<template>
<Button v-bind="$attrs" :size="size" :type="type" :loading="loading" :status="status" @click="() => emits('click')">
<template v-if="icon && iconAlign === 'left'" #icon>
<component :is="Icon[iconName]" />
</template>
{{ label }}
<component :is="Icon[iconName]" v-if="icon && iconAlign === 'right'" style="margin-left: 6px" />
</Button>
</template>
<script lang="ts" setup>
import { Button } from '@arco-design/web-vue';
import * as Icon from '@arco-design/web-vue/es/icon';
import { computed } from 'vue';
import { camelCase, upperFirst } from 'lodash';
const props = withDefaults(
defineProps<{
loading?: boolean;
label?: string;
icon?: string;
iconAlign?: 'left' | 'right';
type?: 'primary' | 'secondary' | 'outline' | 'dashed' | 'text';
shape?: 'square' | 'round' | 'circle';
status?: 'normal' | 'warning' | 'success' | 'danger';
size?: 'mini' | 'small' | 'medium' | 'large';
}>(),
{
loading: false,
iconAlign: 'left',
type: 'secondary',
shape: 'square',
status: 'normal',
size: 'small',
}
);
const emits = defineEmits(['click']);
const iconName = computed(() => upperFirst(camelCase(`icon-${props.icon}`)));
</script>
<style scoped></style>
<template>
<Upload :accept="accept" :custom-request="onUpload" :file-list="[]" :show-file-list="false">
<template #upload-button>
<div class="arco-upload-list-item">
<Image
v-if="modelValue"
:style="{ minHeight }"
:width="width"
:height="height"
:preview="false"
:src="modelValue"
:fit="fit"
show-loader
/>
<div v-else :style="style" class="arco-upload-picture-card">
<div class="arco-upload-picture-card-text">
<IconPlus />
</div>
</div>
</div>
</template>
</Upload>
</template>
<script lang="ts" setup>
import useOss from '@/hooks/oss';
import { computed } from 'vue';
import { IconPlus } from '@arco-design/web-vue/es/icon';
import { UploadRequest, useFormItem, Upload, Image } from '@arco-design/web-vue';
type PropType = {
modelValue?: string;
accept?: string;
width?: number | string;
height?: number | string;
minHeight?: string;
fit?: 'none' | 'contain' | 'cover' | 'fill' | 'scale-down' | undefined;
};
const props = withDefaults(defineProps<PropType>(), {
modelValue: '',
accept: 'image/*',
width: 80,
height: 'auto',
minHeight: '100%',
fit: 'cover',
});
const emits = defineEmits(['update:modelValue']);
const { eventHandlers } = useFormItem();
const style = computed(() => {
return {
width: `${props.width}px`,
height: props.height.constructor === String ? 'auto' : `${props.height}px`,
maxWidth: '100%',
maxHeight: '100%',
minHeight: '80px',
};
});
const { upload } = useOss();
const onUpload = (option: any): UploadRequest => {
const { fileItem } = option;
if (fileItem.file) {
upload(fileItem.file, 'image').then((res) => {
emits('update:modelValue', res?.url || '');
eventHandlers.value?.onChange?.();
});
}
return {};
};
</script>
<style lang="less" scoped>
:deep(.arco-avatar-text) {
width: 100%;
height: 100%;
}
:deep(.arco-upload-list-item) {
margin-top: 0 !important;
}
.no-avatar {
position: absolute;
display: flex;
align-content: center;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
top: 0;
left: 0;
}
</style>
import { App } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { BarChart, LineChart, PieChart, RadarChart } from 'echarts/charts';
import { GridComponent, TooltipComponent, LegendComponent, DataZoomComponent, GraphicComponent } from 'echarts/components';
import AudioPlayer from '@/components/audio-player/index.vue';
import Chart from './chart/index.vue';
import Breadcrumb from './breadcrumb/index.vue';
import AvatarUpload from './avatar-upload/index.vue';
import InputUpload from './input-upload/index.vue';
import ImageUpload from './image-upload/index.vue';
import RouterButton from './router-button/index.vue';
import ExportButton from './export-button/index.vue';
import IconButton from './icon-button/index.vue';
import TagSelect from './tag-select/index.vue';
import UserSelect from './user-select/index.vue';
import FilterSearch from './filter/search.vue';
import FilterSearchItem from './filter/search-item.vue';
import FilterTable from './filter/table.vue';
import FilterTableColumn from './filter/table-column.vue';
import PageView from './page-view/index.vue';
// Manually introduce ECharts modules to reduce packing size
use([
CanvasRenderer,
BarChart,
LineChart,
PieChart,
RadarChart,
GridComponent,
TooltipComponent,
LegendComponent,
DataZoomComponent,
GraphicComponent,
]);
export default {
install(Vue: App) {
Vue.component('Chart', Chart);
Vue.component('Breadcrumb', Breadcrumb);
Vue.component('AvatarUpload', AvatarUpload);
Vue.component('InputUpload', InputUpload);
Vue.component('ImageUpload', ImageUpload);
Vue.component('RouterButton', RouterButton);
Vue.component('ExportButton', ExportButton);
Vue.component('IconButton', IconButton);
Vue.component('AudioPlayer', AudioPlayer);
Vue.component('TagSelect', TagSelect);
Vue.component('UserSelect', UserSelect);
Vue.component('FilterSearch', FilterSearch);
Vue.component('FilterSearchItem', FilterSearchItem);
Vue.component('FilterTable', FilterTable);
Vue.component('FilterTableColumn', FilterTableColumn);
Vue.component('PageView', PageView);
},
};
<template>
<Upload
v-bind="$attrs"
:on-before-upload="onBeforeUpload"
:custom-request="onUpload"
:file-list="[]"
:show-file-list="false"
style="width: 100%"
>
<template #upload-button>
<Input :model-value="modelValue" :readonly="true" :placeholder="placeholder">
<template #suffix>
<Progress v-if="loading" :percent="percent" size="mini" />
<IconUpload v-else />
</template>
</Input>
</template>
</Upload>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import { IconUpload } from '@arco-design/web-vue/es/icon';
import useLoading from '@/hooks/loading';
import useOss from '@/hooks/oss';
import { Input, Message, Progress, Upload, UploadRequest, useFormItem } from '@arco-design/web-vue';
import { startsWith } from 'lodash';
type FileType = { name: string; url: string; size: number; type: string; width?: number; height?: number; duration?: number };
const props = defineProps({
modelValue: { type: String, default: '' },
prefix: { type: String, default: 'file' },
limit: { type: Number, default: 0 },
placeholder: { type: String, default: '请选择' },
});
const emits = defineEmits<{
(e: 'update:modelValue', value: string): void;
(e: 'success', value: FileType): void;
(e: 'choose-file', value: File): void;
}>();
const { eventHandlers } = useFormItem();
const { loading, setLoading } = useLoading(false);
const { upload } = useOss();
const percent = ref<number>(0);
const onBeforeUpload = (file: File & { width?: number; height?: number; duration?: number }) => {
if (props.limit !== 0 && file.size > props.limit * 1024 * 1024) {
Message.warning(`${file.name} 文件超过${props.limit}MB,无法上传`);
return Promise.resolve(false);
}
if (startsWith(file.type, 'image/')) {
const imgObj = new Image();
imgObj.src = URL.createObjectURL(file);
imgObj.onload = () => {
file.width = imgObj.width;
file.height = imgObj.height;
};
}
if (startsWith(file.type, 'audio/') || startsWith(file.type, 'video/')) {
const audioElement = new Audio(URL.createObjectURL(file));
audioElement.addEventListener('loadedmetadata', () => {
file.duration = audioElement.duration * 1000;
});
}
return Promise.resolve(file);
};
const onProgress = (p: number) => {
percent.value = p;
};
const onUpload = (option: any): UploadRequest => {
const { fileItem } = option;
if (fileItem.file) {
setLoading(true);
// eslint-disable-next-line vue/custom-event-name-casing
emits('choose-file', fileItem.file as File);
upload(fileItem.file, props.prefix, onProgress)
.then((res) => {
emits('update:modelValue', res?.url || '');
eventHandlers.value?.onChange?.();
fileItem.percent = 100;
fileItem.url = res?.url || '';
fileItem.status = 'done';
emits('success', {
name: fileItem.name,
url: fileItem.url,
size: fileItem.file.size,
type: fileItem.file.type,
width: fileItem.file.width || 0,
height: fileItem.file.height || 0,
duration: fileItem.file.duration || 0,
});
})
.finally(() => {
setLoading(false);
});
}
return {};
};
</script>
<style lang="less" scoped>
::v-deep(.arco-input-append) {
padding: 0;
}
</style>
<script setup lang="ts">
withDefaults(defineProps<{ hasCard?: boolean; hasBread?: boolean; loading?: boolean }>(), {
loading: false,
});
</script>
<template>
<div class="container">
<breadcrumb v-if="hasBread && $route.meta?.breadcrumb" :items="$route.meta?.breadcrumb" />
<a-spin style="width: 100%" :loading="loading as boolean">
<a-card v-if="hasCard" :bordered="false">
<slot />
</a-card>
<slot v-else />
</a-spin>
</div>
</template>
<style scoped lang="less">
.container {
padding: 0 30px 20px 20px;
}
</style>
<template>
<a-button v-if="type === 'Button'" type="text" size="small" @click="onClick">
<slot>详情</slot>
</a-button>
<a-link v-else class="link" :hoverable="false" @click="onClick">
<a-typography-text type="primary" :style="textStyle" :ellipsis="{ rows: 1, showTooltip: showTooltip }">
<slot>详情</slot>
</a-typography-text>
</a-link>
</template>
<script lang="ts" setup>
import { RouteParamsRaw, useRouter } from 'vue-router';
import { AnyObject } from '@/types/global';
const props = withDefaults(
defineProps<{
name: string;
params?: AnyObject;
type: 'Button' | 'link';
showTooltip: boolean;
}>(),
{
name: '',
type: 'Button',
params: undefined,
showTooltip: true,
}
);
const textStyle = { marginBottom: 0 };
const router = useRouter();
const onClick = () => {
router.push({
name: props.name,
params: (props.params as RouteParamsRaw) || {},
});
};
</script>
<style lang="less" scoped>
.link {
width: 100%;
padding: 1px 0;
display: block !important;
}
</style>
<template>
<Select
v-bind="$attrs"
v-model="value"
:options="options"
:fallback-option="false"
:placeholder="placeholder"
:virtual-list-props="{ height: 200 }"
:field-names="{ value: 'id', label: 'name' }"
@exceed-limit="onTagExceedLimitError"
/>
</template>
<script lang="ts" setup>
import { Message, Select } from '@arco-design/web-vue';
import { computed, onMounted } from 'vue';
import { Tag } from '@/types/tag';
import { storeToRefs } from 'pinia';
import { useSelectionStore } from '@/store';
import { isArray } from '@arco-design/web-vue/es/_utils/is';
interface propType {
modelValue?: number | string | number[];
placeholder?: string;
}
const props = withDefaults(defineProps<propType>(), { placeholder: '请选择' });
const emits = defineEmits<{ (e: 'update:modelValue', value: unknown): void }>();
const onTagExceedLimitError = () => Message.warning({ content: '关联标签最多选中3个', duration: 1500 });
const value = computed({
get: () => props.modelValue,
set: (val) => emits('update:modelValue', val),
});
const { getTagOptions } = storeToRefs(useSelectionStore());
const options = computed(() => getTagOptions.value.filter((item: Tag) => item.type === 1));
const tagIds = computed(() => options.value?.map((item: Tag) => item.id));
onMounted(() => {
if (isArray(props.modelValue)) {
value.value = props.modelValue?.filter((item: number) => tagIds.value?.indexOf(item) !== -1) || [];
}
});
</script>
<style scoped></style>
<script setup lang="ts">
import { ref } from 'vue';
import { Select } from '@arco-design/web-vue';
import { useSelectionStore } from '@/store';
import { storeToRefs } from 'pinia';
const { getUserOptions } = storeToRefs(useSelectionStore());
const loading = ref<boolean>(false);
const fieldName = { value: 'id', label: 'nick_name' };
</script>
<template>
<Select
v-bind="$attrs"
placeholder="请选择"
:loading="loading"
:multiple="true"
:options="getUserOptions"
:field-names="fieldName"
:allow-search="true"
:virtual-list-props="{ height: 200 }"
/>
</template>
<style scoped lang="less"></style>
import { App } from 'vue';
import permission from './permission';
export default {
install(Vue: App) {
Vue.directive('permission', permission);
},
};
import { DirectiveBinding } from 'vue';
import { useAuthorizedStore } from '@/store';
function checkPermission(el: HTMLElement, binding: DirectiveBinding) {
const { value } = binding;
const userStore = useAuthorizedStore();
const { permissions } = userStore;
if (Array.isArray(value)) {
if (value.length > 0) {
const hasPermission = value.filter((item: string) => permissions.includes(item));
if (hasPermission.length === 0 && el.parentNode) {
if (el.parentNode.childElementCount === 1) {
// @ts-ignore
el.parentNode.remove();
} else {
el.parentNode.removeChild(el);
}
}
}
} else {
throw new Error(`need roles! Like v-permission="['admin','user']"`);
}
}
export default {
mounted(el: HTMLElement, binding: DirectiveBinding) {
checkPermission(el, binding);
},
updated(el: HTMLElement, binding: DirectiveBinding) {
checkPermission(el, binding);
},
};
/// <reference types="vite/client" />
declare module '*.vue' {
import { DefineComponent } from 'vue';
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types
const component: DefineComponent<{}, {}, any>;
export default component;
}
interface ImportMetaEnv {
readonly VITE_API_BASE_URL: string;
}
import { computed } from 'vue';
import { EChartsOption } from 'echarts';
import { useAppStore } from '@/store';
// for code hints
// import { SeriesOption } from 'echarts';
// Because there are so many configuration items, this provides a relatively convenient code hint.
// When using vue, pay attention to the reactive issues. It is necessary to ensure that corresponding functions can be triggered, TypeScript does not report errors, and code writing is convenient.
interface optionsFn {
(isDark: boolean): EChartsOption;
}
export default function useChartOption(sourceOption: optionsFn) {
const appStore = useAppStore();
const isDark = computed(() => {
return appStore.theme === 'dark';
});
// echarts support https://echarts.apache.org/zh/theme-builder.html
// It's not used here
// TODO echarts themes
const chartOption = computed<EChartsOption>(() => {
return sourceOption(isDark.value);
});
return {
chartOption,
};
}
import { ref } from 'vue';
export default function useLoading(initValue = false) {
const loading = ref(initValue);
const setLoading = (value: boolean) => {
loading.value = value;
};
const toggle = () => {
loading.value = !loading.value;
};
return {
loading,
setLoading,
toggle,
};
}
import OSS from "ali-oss";
import { Message } from "@arco-design/web-vue";
let ossClient: OSS;
const createOssClient = () => {
if (!ossClient) {
ossClient = new OSS({
accessKeyId: import.meta.env.VITE_OSS_ACCESS_KEY,
accessKeySecret: import.meta.env.VITE_OSS_ACCESS_SECRET,
bucket: import.meta.env.VITE_OSS_BUCKET,
region: import.meta.env.VITE_OSS_REGION,
endpoint: import.meta.env.VITE_OSS_ENDPOINT,
cname: true,
timeout: 90000
});
}
return ossClient;
};
export default function useOss() {
const getFileName = () => {
function rx() {
return Math.random().toString(36).substring(2);
}
return `${rx()}${new Date().getTime()}${rx()}`;
};
const getFileDir = () => {
return new Date().toISOString().slice(0, 10).replace(/-/g, "");
};
const getFileType = (file: File) => {
return file.name?.split(".")?.pop()?.toLowerCase();
};
const getHost = () => {
if (import.meta.env.VITE_OSS_HOST && import.meta.env.VITE_OSS_HOST.length !== 0) {
return import.meta.env.VITE_OSS_HOST;
}
return import.meta.env.VITE_OSS_ENDPOINT;
};
return {
ossClient,
async upload(
file: File,
prefix: string,
onProgress?: (percent: number) => void
): Promise<{ url: string; name: string; response: unknown }> {
return createOssClient()
.multipartUpload(`${prefix}/${getFileDir()}/${getFileName()}.${getFileType(file)}`, file, { progress: onProgress })
.then((res) => {
return Promise.resolve({
response: res.res,
url: `${getHost()}/${res.name}`,
name: `${getFileName()}.${getFileType(file)}`
});
})
.catch(() => {
Message.error({ content: "上传失败" });
// eslint-disable-next-line prefer-promise-reject-errors
return Promise.reject(false);
});
}
};
}
import { ref } from 'vue';
import { Pagination } from '@/types/global';
interface Config {
pageSize?: number;
showTotal?: boolean;
showPageSize?: boolean;
size?: 'mini' | 'small' | 'medium' | 'large';
simple?: boolean;
hideOnSinglePage?: boolean;
}
export default function usePagination(config: Config = {}) {
const defaultPagination = {
total: 0,
current: 1,
pageSize: config.pageSize ?? 20,
pageSizeOptions: [config.pageSize ?? 20, (config.pageSize ?? 20) * 2, (config.pageSize ?? 20) * 3, (config.pageSize ?? 20) * 5],
showTotal: config.showTotal ?? true,
showPageSize: config.showPageSize ?? true,
size: config.size ?? 'medium',
simple: config.simple ?? false,
hideOnSinglePage: config.hideOnSinglePage ?? false,
};
const pagination = ref<Pagination>(defaultPagination);
// eslint-disable-next-line no-return-assign
const setPage = (page: number) => (pagination.value.current = page);
// eslint-disable-next-line no-return-assign
const setPageSize = (size: number) => (pagination.value.pageSize = size);
// eslint-disable-next-line no-return-assign
const setTotal = (total: number) => (pagination.value.total = total);
// eslint-disable-next-line no-return-assign
const resetPagination = () => (pagination.value = defaultPagination);
const incrementTotal = (increment = 1) => setTotal(pagination.value.total + increment);
const decrementTotal = (increment = 1) => setTotal(pagination.value.total - increment);
return {
pagination,
setPage,
setPageSize,
setTotal,
resetPagination,
incrementTotal,
decrementTotal,
};
}
import { RouteLocationNormalized, RouteRecordRaw } from 'vue-router';
import { useAuthorizedStore } from '@/store';
export default function usePermission() {
const userStore = useAuthorizedStore();
return {
accessRouter(route: RouteLocationNormalized | RouteRecordRaw) {
return (
!route.meta?.requiresAuth ||
!route.meta?.roles ||
route.meta?.roles?.includes('*') ||
userStore.permissions?.filter((item) => route.meta?.roles?.includes(item))?.length !== 0
);
},
checkPermission(binding: string[] | string): boolean {
const userStore = useAuthorizedStore();
const { permissions } = userStore;
if (Array.isArray(binding) && binding.length > 0) {
const hasPermission = binding.filter((item: string) => permissions.includes(item));
return hasPermission.length !== 0;
}
return permissions.includes(binding as string);
},
// You can add any rules you want
};
}
import { ref, UnwrapRef } from 'vue';
import { AxiosResponse } from 'axios';
import { HttpResponse } from '@/api/interceptor';
import useLoading from './loading';
// use to fetch list
// Don't use async function. It doesn't work in async function.
// Use the bind function to add parameters
// example: useRequest(api.bind(null, {}))
export default function useRequest<T>(
api: () => Promise<AxiosResponse<HttpResponse>>,
defaultValue = [] as unknown as T,
isLoading = true
) {
const { loading, setLoading } = useLoading(isLoading);
const response = ref<T>(defaultValue);
api()
.then((res) => {
response.value = res.data as unknown as UnwrapRef<T>;
})
.finally(() => {
setLoading(false);
});
return { loading, response };
}
import { onMounted, onBeforeMount, onBeforeUnmount } from 'vue';
import { useDebounceFn } from '@vueuse/core';
import { useAppStore } from '@/store';
import { addEventListen, removeEventListen } from '@/utils/event';
const WIDTH = 992; // https://arco.design/vue/component/grid#responsivevalue
function queryDevice() {
const rect = document.body.getBoundingClientRect();
return rect.width - 1 < WIDTH;
}
export default function useResponsive(immediate?: boolean) {
const appStore = useAppStore();
function resizeHandler() {
if (!document.hidden) {
const isMobile = queryDevice();
appStore.toggleDevice(isMobile ? 'mobile' : 'desktop');
appStore.toggleMenu(isMobile);
}
}
const debounceFn = useDebounceFn(resizeHandler, 100);
onMounted(() => {
if (immediate) debounceFn();
});
onBeforeMount(() => {
addEventListen(window, 'resize', debounceFn);
});
onBeforeUnmount(() => {
removeEventListen(window, 'resize', debounceFn);
});
}
import { computed } from 'vue';
import { useAppStore } from '@/store';
export default function useThemes() {
const appStore = useAppStore();
const isDark = computed(() => {
return appStore.theme === 'dark';
});
return {
isDark,
};
}
import { ref } from 'vue';
export default function useVisible(initValue = false) {
const visible = ref(initValue);
const setVisible = (value: boolean) => {
visible.value = value;
};
const toggle = () => {
visible.value = !visible.value;
};
return {
visible,
setVisible,
toggle,
};
}
<script lang="tsx">
import { compile, computed, defineComponent, h, ref, watch } from "vue";
import { RouteRecordRaw, useRoute, useRouter } from "vue-router";
import { useAppStore } from "@/store";
import usePermission from "@/hooks/permission";
import { last, orderBy } from "lodash";
import { storeToRefs } from "pinia";
export default defineComponent({
emit: ["collapse"],
setup() {
const appStore = useAppStore();
const permission = usePermission();
const router = useRouter();
const route = useRoute();
const { appMenu } = storeToRefs(appStore);
const collapsed = ref(false);
const selectedKey = ref<string[]>([]);
const openKey = ref<string[]>([]);
const goto = (item: RouteRecordRaw) => router.push({ name: item.name });
const syncServicePermission = (item: RouteRecordRaw) => {
if (item.meta) {
const serverConfig = appMenu.value.find((menu) => item.name === menu.name);
item.meta.title = serverConfig?.label || item.meta?.title || "";
item.meta.order = serverConfig?.weight || item.meta?.order || 0;
item.meta.icon = serverConfig?.icon || item.meta?.icon || "";
}
item.children?.map((child) => syncServicePermission(child));
return item;
};
const appRoute = computed((): RouteRecordRaw[] => {
return router
.getRoutes()
.find((el) => el.name === "root")
?.children.filter((element) => element.meta?.hideInMenu !== true)
.map((item: RouteRecordRaw) => syncServicePermission(item)) as RouteRecordRaw[];
});
const menuTree = computed((): RouteRecordRaw[] => {
function travel(_routes: RouteRecordRaw[], layer: number) {
if (!_routes) return null;
const collector: any = orderBy(_routes, "meta.order", "desc").map((element) => {
// no access
if (!permission.accessRouter(element)) {
return null;
}
// leaf node
if (!element.children) {
return element;
}
// route filter hideInMenu true
element.children = element.children.filter((x) => x.meta?.hideInMenu !== true);
// Associated child node
const subItem = travel(element.children, layer);
if (subItem.length) {
element.children = subItem;
return element;
}
// the else logic
if (layer > 1) {
element.children = subItem;
return element;
}
if (element.meta?.hideInMenu === false) {
return element;
}
return null;
});
return collector.filter(Boolean);
}
return travel(appRoute.value, 0);
});
watch(
route,
(newVal) => {
if (newVal.meta.requiresAuth) {
const key = newVal.meta.hideInMenu ? last(newVal.matched)?.meta?.menuSelectKey : last(newVal.matched)?.name;
selectedKey.value = [key as string];
openKey.value = [...(newVal.meta.breadcrumb || [])];
}
},
{ immediate: true }
);
watch(
() => appStore.menuCollapse,
(newVal) => {
collapsed.value = newVal;
},
{ immediate: true }
);
const setCollapse = (val: boolean) => {
appStore.updateSettings({ menuCollapse: val });
};
const renderSubMenu = () => {
function travel(_route: RouteRecordRaw[], nodes = []) {
if (_route) {
_route.forEach((element) => {
// This is demo, modify nodes as needed
const icon = element?.meta?.icon ? `<${element?.meta?.icon}/>` : ``;
let r;
if (element && element.children && element.children.length !== 0) {
r = (
<a-sub-menu key={element?.name} title={element.meta?.title} v-slots={{ icon: () => h(compile(icon)) }}>
{element?.children?.map((elem) => {
return (
<a-menu-item key={elem.name} onClick={() => goto(elem)}>
{elem.meta?.title}
{travel(elem.children ?? [])}
</a-menu-item>
);
})}
</a-sub-menu>
);
} else {
r = (
<a-menu-item key={element?.name} v-slots={{ icon: () => h(compile(icon)) }}
onClick={() => goto(element)}>
{element.meta?.title}
</a-menu-item>
);
}
nodes.push(r as never);
});
}
return nodes;
}
return travel(menuTree.value);
};
return () => (
<a-menu
v-model:collapsed={collapsed.value}
show-collapse-button
auto-open={false}
v-model:selected-keys={selectedKey.value}
v-model:open-keys={openKey.value}
auto-open-selected={true}
auto-scroll-into-view={true}
level-indent={34}
style={{ height: "100%" }}
onCollapse={setCollapse}
>
{renderSubMenu()}
</a-menu>
);
}
});
</script>
<style lang="less" scoped>
:deep(.arco-menu-inner) {
.arco-menu-inline-header {
display: flex;
align-items: center;
}
.arco-icon {
&:not(.arco-icon-down) {
font-size: 18px;
}
}
}
</style>
<template>
<div class="navbar">
<div class="left-side">
<a-space>
<img alt="logo" src="//p3-armor.byteimg.com/tos-cn-i-49unhts6dw/dfdba5317c0c20ce20e64fac803d52bc.svg~tplv-49unhts6dw-image.image" />
<a-typography-title :heading="5" :style="{ margin: 0, fontSize: '18px' }"> 海星试唱</a-typography-title>
</a-space>
</div>
<ul class="right-side">
<!-- <li>-->
<!-- <toggle-theme-button />-->
<!-- </li>-->
<!-- <li>-->
<!-- <a-tooltip :content="$t('settings.navbar.alerts')">-->
<!-- <div class="message-box-trigger">-->
<!-- <a-badge :count="9" dot>-->
<!-- <a-button-->
<!-- :shape="'circle'"-->
<!-- class="nav-btn"-->
<!-- type="outline"-->
<!-- @click="setPopoverVisible"-->
<!-- >-->
<!-- <icon-notification />-->
<!-- </a-button>-->
<!-- </a-badge>-->
<!-- </div>-->
<!-- </a-tooltip>-->
<!-- <a-popover-->
<!-- :arrow-style="{ display: 'none' }"-->
<!-- :content-style="{ padding: 0, minWidth: '400px' }"-->
<!-- content-class="message-popover"-->
<!-- trigger="click"-->
<!-- >-->
<!-- <div ref="refBtn" class="ref-btn"></div>-->
<!-- <template #content>-->
<!-- <message-box />-->
<!-- </template>-->
<!-- </a-popover>-->
<!-- </li>-->
<li>
<a-dropdown trigger="hover">
<a-space align="center">
<a-avatar v-if="avatar" :size="32" :image-url="avatar" />
<div :style="{ color: theme === 'dark' ? 'white' : 'black', lineHeight: '32px' }">
<span>{{ name }}</span>
<icon-down />
</div>
</a-space>
<template #content>
<!-- <a-doption>-->
<!-- <a-space @click="switchRoles">-->
<!-- <icon-tag />-->
<!-- <span>-->
<!-- {{ $t('messageBox.switchRoles') }}-->
<!-- </span>-->
<!-- </a-space>-->
<!-- </a-doption>-->
<!-- <a-doption>-->
<!-- <a-space @click="handleChangePwd">-->
<!-- <icon-lock />-->
<!-- <span>修改密码</span>-->
<!-- </a-space>-->
<!-- </a-doption>-->
<a-doption>
<a-space @click="handleLogout">
<icon-export />
<span> 退出登录 </span>
</a-space>
</a-doption>
</template>
</a-dropdown>
</li>
</ul>
</div>
</template>
<script lang="ts" setup>
import { computed } from 'vue';
import { useAppStore, useAuthorizedStore } from '@/store';
// import useUser from '@/hooks/user';
// import ToggleThemeButton from '@/layout/components/toggle-theme-button.vue';
import { IconDown, IconExport } from '@arco-design/web-vue/es/icon';
const appStore = useAppStore();
const authorized = useAuthorizedStore();
const avatar = computed(() => {
return authorized.avatar;
});
const name = computed(() => {
return authorized.nick_name;
});
const { theme } = appStore;
// const theme = computed(() => {
// return appStore.theme;
// });
// const setVisible = () => {
// appStore.updateSettings({ globalSettings: true });
// };
// const refBtn = ref();
// const triggerBtn = ref();
// const setPopoverVisible = () => {
// const event = new MouseEvent('click', {
// view: window,
// bubbles: true,
// cancelable: true,
// });
// refBtn.value.dispatchEvent(event);
// };
const handleLogout = () => authorized.logout();
// const handleChangePwd = () => useUser().resetPwd();
// const setDropDownVisible = () => {
// const event = new MouseEvent('click', {
// view: window,
// bubbles: true,
// cancelable: true,
// });
// triggerBtn.value.dispatchEvent(event);
// };
</script>
<style lang="less" scoped>
.navbar {
display: flex;
justify-content: space-between;
height: 100%;
background-color: var(--color-bg-2);
border-bottom: 1px solid var(--color-border);
}
.left-side {
display: flex;
align-items: center;
padding-left: 20px;
}
.right-side {
display: flex;
padding-right: 10px;
list-style: none;
:deep(.locale-select) {
border-radius: 20px;
}
li {
display: flex;
align-items: center;
padding: 0 10px;
}
a {
color: var(--color-text-1);
text-decoration: none;
}
.nav-btn {
border-color: rgb(var(--gray-2));
color: rgb(var(--gray-8));
font-size: 16px;
}
.trigger-btn,
.ref-btn {
position: absolute;
bottom: 14px;
}
.trigger-btn {
margin-left: 14px;
}
}
</style>
<style lang="less">
.message-popover {
.arco-popover-content {
margin-top: 0;
}
}
.arco-dropdown-open .arco-icon-down {
transform: rotate(180deg);
}
</style>
<template>
<a-layout class="layout">
<div class="layout-navbar">
<Navbar />
</div>
<a-layout>
<a-layout>
<a-layout-sider
v-if="menu"
:breakpoint="'xl'"
:collapsed="collapse"
:collapsible="true"
:hide-trigger="true"
:style="{ paddingTop: '60px' }"
:width="menuWidth"
class="layout-sider"
@collapse="setCollapsed"
>
<div class="menu-wrapper">
<Menu />
</div>
</a-layout-sider>
<a-layout :style="paddingStyle" class="layout-content">
<a-layout-content>
<router-view />
</a-layout-content>
</a-layout>
</a-layout>
</a-layout>
</a-layout>
</template>
<script lang="ts">
import { computed, defineComponent, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useAppStore, useAuthorizedStore } from "@/store";
import usePermission from "@/hooks/permission";
import Menu from "@/layout/components/menu.vue";
import Navbar from "@/layout/components/navbar.vue";
export default defineComponent({
// eslint-disable-next-line vue/no-reserved-component-names
components: { Navbar, Menu },
setup() {
const appStore = useAppStore();
const authorizedStore = useAuthorizedStore();
const router = useRouter();
const route = useRoute();
const permission = usePermission();
const navbarHeight = `60px`;
const menu = computed(() => appStore.menu);
const menuWidth = computed(() => {
return appStore.menuCollapse ? 48 : appStore.menuWidth;
});
const collapse = computed(() => {
return appStore.menuCollapse;
});
const paddingStyle = computed(() => {
const paddingLeft = menu.value ? { paddingLeft: `${menuWidth.value}px` } : {};
const paddingTop = { paddingTop: navbarHeight };
return { ...paddingLeft, ...paddingTop };
});
const setCollapsed = (val: boolean) => {
appStore.updateSettings({ menuCollapse: val });
};
watch(
() => authorizedStore.permissions,
(roleValue) => {
if (roleValue && !permission.accessRouter(route)) router.push({ name: "notFound" });
}
);
return {
menu,
menuWidth,
paddingStyle,
collapse,
setCollapsed
};
}
});
</script>
<style lang="less" scoped>
@nav-size-height: 60px;
@layout-max-width: 1100px;
.layout {
width: 100%;
height: 100%;
}
.layout-navbar {
position: fixed;
top: 0;
left: 0;
z-index: 100;
width: 100%;
min-width: @layout-max-width;
height: @nav-size-height;
}
.layout-sider {
position: fixed;
top: 0;
left: 0;
z-index: 99;
height: 100%;
&::after {
position: absolute;
top: 0;
right: -1px;
display: block;
width: 1px;
height: 100%;
background-color: var(--color-border);
content: '';
}
> :deep(.arco-layout-sider-children) {
overflow-y: hidden;
}
}
.menu-wrapper {
height: 100%;
overflow: auto;
overflow-x: hidden;
:deep(.arco-menu) {
::-webkit-scrollbar {
width: 12px;
height: 4px;
}
::-webkit-scrollbar-thumb {
border: 4px solid transparent;
background-clip: padding-box;
border-radius: 7px;
background-color: var(--color-text-4);
}
::-webkit-scrollbar-thumb:hover {
background-color: var(--color-text-3);
}
}
}
.layout-content {
min-width: @layout-max-width;
min-height: 100vh;
overflow-y: hidden;
background-color: var(--color-fill-2);
transition: padding-left 0.2s;
}
</style>
import { createApp } from 'vue';
import ArcoVue from '@arco-design/web-vue';
import ArcoVueIcon from '@arco-design/web-vue/es/icon';
import globalComponents from '@/components';
import store from './store';
import router from './router';
import directive from './directive';
import App from './App.vue';
import '@/assets/style/global.less';
import '@/api/interceptor';
const app = createApp(App);
app.use(ArcoVue, {});
app.use(ArcoVueIcon);
app.use(store);
app.use(router);
app.use(globalComponents);
app.use(directive);
app.mount('#app');
import { createRouter, createWebHistory, LocationQueryRaw } from 'vue-router';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css';
import usePermission from '@/hooks/permission';
import { clearToken, isLogin } from '@/utils/auth';
import PageLayout from '@/layout/index.vue';
import { useAuthorizedStore } from '@/store';
import appRoutes from './modules';
NProgress.configure({ showSpinner: false }); // NProgress Configuration
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/login',
name: 'login',
component: () => import('@/views/login/index.vue'),
meta: {
title: '登陆',
requiresAuth: false,
},
},
{
name: 'root',
path: '/',
component: PageLayout,
redirect: '/demos',
children: appRoutes,
},
{
path: '/:pathMatch(.*)*',
name: 'notFound',
redirect: '/exception/404',
meta: {
requiresAuth: true,
},
},
],
scrollBehavior() {
return { top: 0 };
},
});
router.beforeEach(async (to, from, next) => {
NProgress.start();
const authorizedStore = useAuthorizedStore();
if (from.name !== undefined) {
to.meta.from = from.name;
}
async function crossroads() {
const Permission = usePermission();
if (Permission.accessRouter(to)) {
next();
} else {
next({ name: 'exception-403' });
}
NProgress.done();
}
if (isLogin()) {
if (authorizedStore.permissions.length) {
await crossroads();
} else {
try {
await authorizedStore.syncInfo();
await crossroads();
} catch (error) {
clearToken();
next({ name: 'login', query: { path: to.path } as LocationQueryRaw });
NProgress.done();
}
}
} else {
if (to.name === 'login') {
next();
NProgress.done();
return;
}
if (to.name === 'root') {
next({ name: 'login' });
} else {
next({ name: 'login', query: { path: to.path } as LocationQueryRaw });
}
NProgress.done();
}
});
router.afterEach(async (to) => {
sessionStorage.setItem(
'route',
to.meta?.breadcrumb?.toString() ||
to.matched
?.slice(1)
.map((item) => item.name)
.toString() ||
'dashboard'
);
});
export default router;
export default [
{
path: "demos",
name: "audition-demo",
component: () => import("@/views/demo/index.vue"),
meta: {
title: "Demo管理",
icon: "icon-dashboard",
requiresAuth: true,
hideInMenu: false,
isRedirect: true,
roles: ["*"],
breadcrumb: ["audition-demo"],
reload: true
}
},
{
path: "demos/:id(\\d+)",
name: "audition-demo-show",
component: () => import("@/views/demo-show/index.vue"),
meta: {
title: "详情",
requiresAuth: false,
hideInMenu: true,
reload: true,
menuSelectKey: "audition-demo",
roles: ["*"],
breadcrumb: ["audition-demo", "audition-demo-show"]
}
}
];
export default {
path: 'exception',
name: 'exception',
component: () => import('@/views/exception/index.vue'),
meta: {
title: '异常页',
requiresAuth: true,
icon: 'icon-exclamation-circle',
hideInMenu: true,
},
children: [
{
path: '403',
name: 'exception-403',
component: () => import('@/views/exception/403/index.vue'),
meta: {
title: '403',
requiresAuth: true,
roles: ['*'],
},
},
{
path: '404',
name: 'exception-404',
component: () => import('@/views/exception/404/index.vue'),
meta: {
title: '404',
requiresAuth: true,
roles: ['*'],
hideInMenu: true,
},
},
{
path: '500',
name: 'exception-500',
component: () => import('@/views/exception/500/index.vue'),
meta: {
title: '500',
requiresAuth: true,
roles: ['*'],
},
},
],
};
import Exception from "./exception";
import Demo from "./demo";
export default [...Demo, Exception];
import 'vue-router';
declare module 'vue-router' {
interface RouteMeta {
// options
roles?: string[];
// every route must declare
requiresAuth: boolean; // need login
icon?: string;
// menu select key
menuSelectKey?: string;
hideInMenu?: boolean;
isRedirect?: boolean;
title?: string;
order?: number;
breadcrumb?: string[];
}
}
import { createPinia } from 'pinia';
import useAppStore from './modules/app';
// eslint-disable-next-line import/no-cycle
import useAuthorizedStore from './modules/authorized';
import useSelectionStore from '@/store/modules/selection';
const pinia = createPinia();
export { useAppStore, useSelectionStore, useAuthorizedStore };
export default pinia;
import { defineStore } from 'pinia';
import type { RouteRecordNormalized } from 'vue-router';
import { AppState } from './types';
const useAppStore = defineStore('app', {
state: (): AppState => ({
theme: 'light',
colorWeak: false,
navbar: true,
menu: true,
topMenu: false,
hideMenu: false,
menuCollapse: false,
footer: true,
themeColor: '#165DFF',
menuWidth: 220,
globalSettings: false,
device: 'desktop',
tabBar: false,
permissions: [],
}),
getters: {
appCurrentSetting(state: AppState): AppState {
return { ...state };
},
appDevice(state: AppState) {
return state.device;
},
appAsyncMenus(state: AppState): RouteRecordNormalized[] {
return state.serverMenu as unknown as RouteRecordNormalized[];
},
appMenu(state: AppState) {
return state.permissions?.filter((item) => item.type === 'Menu') || [];
},
},
actions: {
// Update app settings
updateSettings(partial: Partial<AppState>) {
// @ts-ignore-next-line
this.$patch(partial);
},
// Change theme color
toggleTheme(dark: boolean) {
if (dark) {
this.theme = 'dark';
document.body.setAttribute('arco-theme', 'dark');
} else {
this.theme = 'light';
document.body.removeAttribute('arco-theme');
}
},
toggleDevice(device: string) {
this.device = device;
},
toggleMenu(value: boolean) {
this.hideMenu = value;
},
setPermissions(permissions = []) {
this.$patch({ permissions });
},
},
});
export default useAppStore;
export interface SystemPermission {
id: number;
name: string;
type: 'Menu' | 'Button';
label: string;
icon: string;
parent_id: number;
weight: number;
parent?: SystemPermission;
children?: SystemPermission[];
created_at: string;
updated_at: string;
}
export interface AppState {
theme: string;
colorWeak: boolean;
navbar: boolean;
menu: boolean;
topMenu: boolean;
hideMenu: boolean;
menuCollapse: boolean;
themeColor: string;
menuWidth: number;
globalSettings: boolean;
device: string;
permissions: SystemPermission[];
[key: string]: unknown;
}
import { defineStore } from "pinia";
import { clearToken } from "@/utils/auth";
import useAuthApi from "@/api/auth";
import { AuthorizedState } from "./type";
import { Message } from "@arco-design/web-vue";
import { removeRouteListener } from "@/utils/route-listener";
// eslint-disable-next-line import/no-cycle
import { useAppStore } from "@/store";
const useAuthorizedStore = defineStore("authorized", {
state: (): AuthorizedState => ({
id: undefined,
nick_name: undefined,
avatar: undefined,
permissions: [],
can_create_demo: 0
}),
getters: {
authorizedInfo(state: AuthorizedState): AuthorizedState {
return { ...state };
},
getKey(state: AuthorizedState): number {
return state.id || 0;
},
isCreateDemo(state: AuthorizedState) {
return state.can_create_demo;
}
},
actions: {
setInfo(partial: Partial<AuthorizedState>) {
// @ts-ignore
this.$patch(partial);
},
async syncInfo() {
const { user, permissions, menus, can_create_demo } = await useAuthApi.info();
this.setInfo({ ...user, can_create_demo, permissions });
useAppStore().setPermissions(menus as any);
},
async logout() {
this.$reset();
clearToken();
removeRouteListener();
window.location.reload();
Message.success("登出成功");
},
async syncToken() {
// TODO
// const { data } = await refreshToken();
// setToken(data.access_token);
}
}
});
export default useAuthorizedStore;
export interface AuthorizedState {
id?: number;
nick_name?: string;
avatar?: string;
permissions: string[];
[key: string]: unknown;
}
import { defineStore } from 'pinia';
import { Selection } from '@/store/modules/selection/type';
import { AnyObject } from '@/types/global';
import { SystemConfig } from '@/types/system-config';
import axios from 'axios';
import { Tag } from '@/types/tag';
const useSelectionStore = defineStore('selection', {
state: (): Selection => ({
user: [],
project: [],
tag: [],
config: [],
}),
getters: {
getUserOptions(state) {
return state.user;
},
getTagOptions(state) {
return state.tag;
},
projectOptions(state) {
return state.project;
},
lyricTool(state): string {
return state.config.find((item) => item.identifier === 'activity_lyric_tool')?.content || '';
},
activityLang(state): SystemConfig | undefined {
return state.config.find((item) => item.identifier === 'activity_lang');
},
activityLangOptions(state): SystemConfig[] {
return state.config.filter((item) => item.parent_id === this.activityLang?.id);
},
activitySpeed(state): SystemConfig | undefined {
return state.config.find((item) => item.identifier === 'activity_speed');
},
activitySpeedOptions(state): SystemConfig[] {
return state.config.filter((item) => item.parent_id === this.activitySpeed?.id);
},
activitySex(state): SystemConfig | undefined {
return state.config.find((item) => item.identifier === 'activity_sex');
},
activitySexOptions(state): SystemConfig[] {
return state.config.filter((item) => item.parent_id === this.activitySex?.id);
},
activityTagOptions(state): Pick<Tag, 'id' | 'name' | 'type'>[] {
return state.tag.filter((item) => item.type === 1);
},
activityAudioAccept(state): string {
return state.config.find((item) => item.identifier === 'activity_audio_accept')?.content || 'audio/*';
},
activityTrackAccept(state): string {
return state.config.find((item) => item.identifier === 'activity_track_accept')?.content || '*';
},
appleDemoCover(state): string {
return state.config.find((item) => item.identifier === 'activity_demo_cover')?.content || '';
},
},
actions: {
queryUser(params?: AnyObject) {
axios.get('/provider/users', { params }).then(({ data }) => {
this.user = data;
});
},
queryTag(params?: AnyObject) {
axios.get('/provider/tags',{ params }).then(({ data }) => {
this.tag = data;
});
},
queryConfig(params?: AnyObject) {
axios.get('/provider/configs', { params }).then(({ data }) => {
this.config = data;
});
},
},
});
export default useSelectionStore;
import { User } from '@/types/user';
import { Project } from '@/types/project';
import { Tag } from '@/types/tag';
import { SystemConfig } from '@/types/system-config';
export interface Selection {
user: User[];
project: Project[];
tag: Tag[];
config: SystemConfig[];
}
import { Project } from '@/types/project';
import { Tag } from '@/types/tag';
import { User } from '@/types/user';
export interface ActivityExpand {
tag_ids: number[];
lyricist: { ids: number[]; supplement: string[] };
composer: { ids: number[]; supplement: string[] };
arranger: { ids: number[]; supplement: string[] };
guide_source: { name: string; url: string; size: number };
karaoke_source: { name: string; url: string; size: number };
track_source: { name: string; url: string; size: number };
}
export interface ActivityApplyRecord {
id: number;
created_at: string;
audit_msg: string;
}
export interface ActivityApply {
id: number;
cover: string;
song_name: string;
sub_title?: string;
lang: string[];
speed: string;
lyric: string;
clip_lyric: string;
sex: string;
project_id: number;
estimate_release_at: string;
audit_status: number;
expand: ActivityExpand;
project?: Project;
tags?: Tag[];
user?: User;
apply_records?: ActivityApplyRecord[];
}
export type ActivityApplyFormStep1 = Pick<ActivityApply, 'cover' | 'song_name' | 'sub_title' | 'lang' | 'speed'> &
Pick<ActivityExpand, 'tag_ids'>;
export type ActivityApplyFormStep2 = Pick<ActivityApply, 'project_id' | 'sex' | 'estimate_release_at'> &
Pick<ActivityExpand, 'lyricist' | 'composer' | 'arranger'>;
export type ActivityApplyFormStep3 = Pick<ActivityApply, 'song_name' | 'lyric' | 'clip_lyric'> &
Pick<ActivityExpand, 'guide_source' | 'karaoke_source' | 'track_source'>;
export type ActivityApplyForm = ActivityApplyFormStep1 & ActivityApplyFormStep2 & ActivityApplyFormStep3;
import { Project } from '@/types/project';
import { Tag } from '@/types/tag';
import { FileStatus } from '@arco-design/web-vue/es/upload/interfaces';
import { User } from '@/types/user';
import { ActivityExpand } from '@/types/activity-apply';
export type ActivityMaterialType = 'GuideDinging' | 'Accompany';
export type ActivityMaterialTone = -3 | -2 | -1 | 0 | 1 | 2 | 3;
export interface ActivityMaterialOption {
type: ActivityMaterialType;
tone: ActivityMaterialTone;
label: string;
}
export interface ActivityMaterial {
id: string;
type: ActivityMaterialType;
url: string;
name: string;
tone: ActivityMaterialTone;
file?: File;
percent?: number;
status?: FileStatus;
response?: string;
created_at?: string;
}
export interface ActivitySendLink {
type: string;
url: string;
}
export interface ActivityRecommendIntro {
id: number;
content: string;
}
export interface ActivityApplyRecord {
id: number;
audit_user_id: number;
audit_msg: string;
created_at?: string;
updated_at?: string;
}
export interface Activity {
id: number;
song_name: string;
song_type?: number;
sub_title: string;
cover: string;
user_id: number;
project_id: number;
guide: string;
karaoke: string;
guide_source?: string;
karaoke_source?: string;
lyric: string;
clip_lyric: string;
weight: number;
audit_status: number;
status: number;
match_at: string;
created_at: string;
updated_at: string;
submit_works_count?: number;
views_count?: number;
collections_count?: number;
is_official?: number;
send_url?: ActivitySendLink[];
user?: Pick<User, 'id' | 'nick_name' | 'real_name' | 'role'>;
project?: Project;
tags?: Tag[];
materials?: ActivityMaterial[];
recommend_intros?: ActivityRecommendIntro[];
apply_records?: ActivityApplyRecord[];
estimate_release_at: string;
expand?: ActivityExpand;
links?: User[];
}
export type ActivityViewUser = Pick<User, 'id' | 'avatar' | 'nick_name' | 'real_name' | 'sex' | 'role'> & {
listen_count: number;
collection_count: number;
submit_work: number;
last_listen_at: number;
};
// eslint-disable-next-line import/no-cycle
import { User } from '@/types/user';
export interface Admin extends User {
creator?: User;
role?: 'ProjectUser' | 'SystemUser' | 'Admin';
company: string;
activities_count?: number;
singers_count?: number;
submit_activities_count?: number;
accept_activities_count?: number;
checked_activities_count?: number;
}
import { CallbackDataParams } from 'echarts/types/dist/shared';
export interface ToolTipFormatterParams extends CallbackDataParams {
axisDim: string;
axisIndex: number;
axisType: string;
axisId: string;
axisValue: string;
axisValueLabel: string;
}
export interface AnyObject {
[key: string]: unknown;
}
export interface Options {
value: unknown;
label: string;
}
export interface MoreRowValue<T = object> {
type: string;
row: T;
index?: number;
}
export interface QueryForParams {
[key: string]: unknown;
sortBy?: string;
sortType?: 'desc' | 'asc' | '';
}
export interface QueryForPaginationParams extends QueryForParams {
page?: number;
pageSize?: number;
}
export type sizeType = 'mini' | 'small' | 'medium' | 'large';
export interface AttributeData {
[key: string]: unknown;
}
export interface Pagination {
current: number;
pageSize: number;
total: number;
showTotal?: boolean;
showPageSize?: boolean;
pageSizeOptions?: number[];
}
export type SortType = 'descend' | 'ascend' | '' | string;
export interface Sort {
column: string;
type: SortType | string;
}
export interface GeneralChart {
xAxis: string[];
data: Array<{ name: string; value: number[] }>;
}
export interface HttpResponse<T = unknown> {
status: 'success' | 'fail' | 'error';
msg: string;
code: number;
data: T;
}
export interface ServiceResponse<T = unknown> extends HttpResponse<T> {
meta: { current: number; limit: number; total: number };
}
export interface MockParams {
url: string;
type: string;
body: string;
}
// eslint-disable-next-line import/no-cycle
import { Admin } from '@/types/admin';
import { User } from '@/types/user';
export interface Project {
id: number;
name: string;
user?: Admin;
master?: User;
status: number;
created_at?: string;
updated_at?: string;
up_count?: number;
down_count?: number;
finish_count?: number;
is_promote?: number;
is_official?: number;
is_can_apply?: number;
is_can_manage?: number;
is_can_demo_apply?: number;
head_cover: string;
cover: string;
intro: string;
managers_count?: number;
activities_count?: number;
send_count?: number;
managers?: Admin[];
}
export interface SystemConfig {
id: number;
parent_id: number;
name: string;
content: string;
remark: string;
identifier: string;
children?: SystemConfig[];
}
// eslint-disable-next-line import/no-cycle
import { Admin } from '@/types/admin';
export interface Tag {
id: number;
name: string;
type: number;
created_at: string;
updated_at: string;
user?: Admin;
}
// eslint-disable-next-line import/no-cycle
import { Project } from '@/types/project';
// eslint-disable-next-line import/no-cycle
import { Tag } from '@/types/tag';
// eslint-disable-next-line import/no-cycle
export interface User {
id: number;
avatar?: string;
nick_name: string;
real_name: string;
phone: string;
email: string;
business_id: 0;
business?: User;
province?: string;
city?: string;
role?: 'Singer' | 'Business' | 'ProjectUser' | 'SystemUser' | 'Admin';
remarks?: string;
like_activities_count?: number;
sound?: string;
status?: number;
last_login?: string;
created_at?: string;
updated_at?: string;
projects?: Project[];
tags?: Tag[];
styles?: Tag[];
voices?: Tag[];
skills?: Tag[];
identity: number;
[key: string]: unknown;
}
import RabbitLyrics from 'rabbit-lyrics';
import parseLyrics from 'rabbit-lyrics/src/parseLyrics';
// @ts-ignore
export default class AudioSyncLyric extends RabbitLyrics {
public startTime = 0;
public setStartTime(time: number) {
this.startTime = time || 0;
this.render();
this.mediaElement.addEventListener('timeupdate', this.synchronize);
}
private render(): void {
// Add class names
this.lyricsElement.classList.add('rabbit-lyrics');
this.lyricsElement.classList.add(`rabbit-lyrics--${this.viewMode}`);
this.lyricsElement.classList.add(`rabbit-lyrics--${this.alignment}`);
this.lyricsElement.textContent = null;
// Render lyrics lines
this.lyricsLines = parseLyrics(this.lyrics).map((line) => {
const lineElement = document.createElement('div');
lineElement.className = 'rabbit-lyrics__line';
lineElement.addEventListener('click', () => {
this.mediaElement.currentTime = line.startsAt - this.startTime;
this.synchronize();
});
const lineContent = line.content.map((inline) => {
const inlineElement = document.createElement('span');
inlineElement.className = 'rabbit-lyrics__inline';
inlineElement.textContent = inline.content;
lineElement.append(inlineElement);
return { ...inline, element: inlineElement };
});
this.lyricsElement.append(lineElement);
return { ...line, content: lineContent, element: lineElement };
});
this.synchronize();
}
private synchronize = () => {
const time = this.startTime + this.mediaElement.currentTime;
let changed = false; // If here are active lines changed
const activeLines = this.lyricsLines.filter((line) => {
if (time >= line.startsAt && time < line.endsAt) {
// If line should be active
if (!line.element.classList.contains('rabbit-lyrics__line--active')) {
// If it hasn't been activated
changed = true;
line.element.classList.add('rabbit-lyrics__line--active');
}
line.content.forEach((inline) => {
if (time >= inline.startsAt) {
inline.element.classList.add('rabbit-lyrics__inline--active');
} else {
inline.element.classList.remove('rabbit-lyrics__inline--active');
}
});
return true;
}
// If line should be inactive
if (line.element.classList.contains('rabbit-lyrics__line--active')) {
// If it hasn't been deactivated
changed = true;
line.element.classList.remove('rabbit-lyrics__line--active');
line.content.forEach((inline) => {
inline.element.classList.remove('rabbit-lyrics__inline--active');
});
}
return false;
});
if (changed && activeLines.length > 0) {
// Calculate scroll top. Vertically align active lines in middle
const activeLinesOffsetTop =
(activeLines[0].element.offsetTop +
activeLines[activeLines.length - 1].element.offsetTop +
activeLines[activeLines.length - 1].element.offsetHeight) /
2;
this.lyricsElement.scrollTop = activeLinesOffsetTop - this.lyricsElement.clientHeight / 2;
}
};
}
const isLogin = () => {
return !!localStorage.getItem('access_token');
};
const getToken = () => {
return localStorage.getItem('access_token') || localStorage.getItem('refresh_token');
};
const setToken = (accessToken: string, refreshToken: string) => {
localStorage.setItem('access_token', accessToken);
localStorage.setItem('refresh_token', refreshToken);
};
const clearToken = () => {
localStorage.removeItem('access_token');
localStorage.removeItem('refresh_token');
};
export { isLogin, getToken, setToken, clearToken };
import { AnyObject } from '@/types/global';
import { createVNode, Ref, VNode } from 'vue';
import { Form, FormItem, Input, InputNumber, Textarea, Modal, Select } from '@arco-design/web-vue';
import InputUpload from '@/components/input-upload/index.vue';
import { RenderContent } from '@arco-design/web-vue/es/_utils/types';
import { ModalConfig } from '@arco-design/web-vue/es/modal/interface';
import { set } from 'lodash';
export function createModalVNode(content: RenderContent, props?: object & Omit<ModalConfig, 'content'>) {
return Modal.open({
content,
titleAlign: 'start',
closable: false,
escToClose: false,
maskClosable: false,
okButtonProps: { size: 'small' },
cancelButtonProps: { size: 'small' },
...props,
});
}
export function createFormVNode(props?: AnyObject, children?: VNode | VNode[] | undefined): VNode {
return createVNode(Form, { autoLabelWidth: true, ...props }, () => children);
}
export function createFormItemVNode(props?: AnyObject, children?: string | VNode | VNode[]): VNode {
return createVNode(FormItem, { showColon: true, ...props }, () => children);
}
export function createSelectVNode(value: Ref, options: AnyObject[], props?: AnyObject): VNode {
return createVNode(Select, {
options,
'modelValue': value.value,
'placeholder': '请选择',
'onUpdate:modelValue': (val?: unknown) => set(value, 'value', val),
...props,
});
}
export function createSelectionFormItemVNode(value: Ref, options: AnyObject[], itemProps?: AnyObject, props?: AnyObject): VNode {
return createFormItemVNode(itemProps, createSelectVNode(value, options, props));
}
export function createInputVNode(value: Ref, props?: AnyObject): VNode {
return createVNode(Input, {
'modelValue': value.value,
'placeholder': '请输入',
'onUpdate:modelValue': (val?: string) => set(value, 'value', val || ''),
...props,
});
}
export function createInputFormItemVNode(value: Ref, itemProps?: AnyObject, props?: AnyObject): VNode {
return createFormItemVNode(itemProps, createInputVNode(value, props));
}
export function createInputNumberVNode(value: Ref, props?: AnyObject): VNode {
return createVNode(InputNumber, {
'modelValue': value.value,
'placeholder': '请输入',
'onUpdate:modelValue': (val?: string) => set(value, 'value', val || 0),
'min': 0,
'max': 255,
...props,
});
}
export function createInputNumberFormItemVNode(value: Ref, itemProps?: AnyObject, props?: AnyObject): VNode {
return createFormItemVNode(itemProps, createInputNumberVNode(value, props));
}
export function createTextareaVNode(value: Ref, props?: AnyObject) {
return createVNode(Textarea, {
'modelValue': value.value,
'placeholder': '请输入',
'onUpdate:modelValue': (val?: string) => set(value, 'value', val || 0),
'max-length': 500,
'show-word-limit': true,
'auto-size': { minRows: 3, maxRows: 6 },
...props,
});
}
export function createTextareaFormItemVNode(value: Ref, itemProps?: AnyObject, props?: AnyObject) {
return createFormItemVNode(itemProps, createTextareaVNode(value, props));
}
export function createInputUploadVNode(value: Ref, props?: AnyObject): VNode {
return createVNode(InputUpload, {
'modelValue': value.value,
'placeholder': '请选择',
'onUpdate:modelValue': (val?: string) => set(value, 'value', val || 0),
...props,
});
}
export function createInputUploadFormItemVNode(value: Ref, itemProps?: AnyObject, props?: AnyObject): VNode {
return createFormItemVNode(itemProps, createInputUploadVNode(value, props));
}
// const debug = import.meta.env.MODE !== 'production';
// export default debug;
export const debug = import.meta.env.MODE !== 'production';
export const ossConfig = {
accessKeyId: import.meta.env.VITE_OSS_ACCESS_KEY as string,
accessKeySecret: import.meta.env.VITE_OSS_ACCESS_SECRET as string,
bucket: import.meta.env.VITE_OSS_BUCKET,
region: import.meta.env.VITE_OSS_REGION,
host: import.meta.env.VITE_OSS_HOST,
endpoint: import.meta.env.VITE_OSS_ENDPOINT,
};
export const apiHost = import.meta.env.VITE_API_HOST;
export const showLoginAccount = import.meta.env.VITE_SHOW_LOGIN_ACCOUNT;
export const isProduction = import.meta.env.VITE_ENV === 'production';
export function addEventListen(target: Window | HTMLElement, event: string, handler: EventListenerOrEventListenerObject, capture = false) {
if (target.addEventListener && typeof target.addEventListener === 'function') {
target.addEventListener(event, handler, capture);
}
}
export function removeEventListen(
target: Window | HTMLElement,
event: string,
handler: EventListenerOrEventListenerObject,
capture = false
) {
if (target.removeEventListener && typeof target.removeEventListener === 'function') {
target.removeEventListener(event, handler, capture);
}
}
import { compact } from 'lodash';
const opt = Object.prototype.toString;
export const bytesForHuman = (bytes: number, decimals = 2) => {
const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
let i = 0;
// eslint-disable-next-line no-plusplus
for (i; bytes > 1024; i++) {
bytes /= 1024;
}
return `${parseFloat(bytes.toFixed(decimals))} ${units[i]}`;
};
export const audioBufferToWav = (audioBuffer: AudioBuffer, len: number) => {
const numOfChan = audioBuffer.numberOfChannels;
const length = len * numOfChan * 2 + 44;
const buffer = new ArrayBuffer(length);
const view = new DataView(buffer);
const channels = [];
let i;
let sample;
let offset = 0;
let pos = 0;
// write WAVE header
// eslint-disable-next-line no-use-before-define
setUint32(0x46464952); // "RIFF"
// eslint-disable-next-line no-use-before-define
setUint32(length - 8); // file length - 8
// eslint-disable-next-line no-use-before-define
setUint32(0x45564157); // "WAVE"
// eslint-disable-next-line no-use-before-define
setUint32(0x20746d66); // "fmt " chunk
// eslint-disable-next-line no-use-before-define
setUint32(16); // length = 16
// eslint-disable-next-line no-use-before-define
setUint16(1); // PCM (uncompressed)
// eslint-disable-next-line no-use-before-define
setUint16(numOfChan);
// eslint-disable-next-line no-use-before-define
setUint32(audioBuffer.sampleRate);
// eslint-disable-next-line no-use-before-define
setUint32(audioBuffer.sampleRate * 2 * numOfChan); // avg. bytes/sec
// eslint-disable-next-line no-use-before-define
setUint16(numOfChan * 2); // block-align
// eslint-disable-next-line no-use-before-define
setUint16(16); // 16-bit (hardcoded in this demo)
// eslint-disable-next-line no-use-before-define
setUint32(0x61746164); // "data" - chunk
// eslint-disable-next-line no-use-before-define
setUint32(length - pos - 4); // chunk length
// write interleaved data
// eslint-disable-next-line no-plusplus
for (i = 0; i < audioBuffer.numberOfChannels; i++) {
// @ts-ignore
channels.push(audioBuffer.getChannelData(i));
}
while (pos < length) {
// eslint-disable-next-line no-plusplus
for (i = 0; i < numOfChan; i++) {
// interleave channels
sample = Math.max(-1, Math.min(1, channels[i][offset])); // clamp
// eslint-disable-next-line no-bitwise
sample = (0.5 + sample < 0 ? sample * 32768 : sample * 32767) | 0; // scale to 16-bit signed int
view.setInt16(pos, sample, true); // write 16-bit sample
pos += 2;
}
// eslint-disable-next-line no-plusplus
offset++; // next source sample
}
// create Blob
return new Blob([buffer], { type: 'audio/wav' });
function setUint16(data: number) {
view.setUint16(pos, data, true);
pos += 2;
}
function setUint32(data: number) {
view.setUint32(pos, data, true);
pos += 4;
}
};
export const getLyricTimeArr = (lyric: string): string[] => {
const times: string[] = [];
lyric.split('\n').forEach((item) => {
item = item.replace(/(^\s*)|(\s*$)/g, '');
times.push(item.substring(item.indexOf('[') + 1, item.indexOf(']')));
});
return compact(times);
};
export function isUndefined(obj: any): obj is undefined {
return obj === undefined;
}
export function isString(obj: any): obj is string {
return opt.call(obj) === '[object String]';
}
export const promiseToBoolean = (callback: Promise<any>) => callback.then(() => true).catch(() => false);
const opt = Object.prototype.toString;
export function isArray(obj: any): obj is any[] {
return opt.call(obj) === '[object Array]';
}
export function isObject(obj: any): obj is { [key: string]: any } {
return opt.call(obj) === '[object Object]';
}
export function isString(obj: any): obj is string {
return opt.call(obj) === '[object String]';
}
export function isNumber(obj: any): obj is number {
return opt.call(obj) === '[object Number]' && obj === obj; // eslint-disable-line
}
export function isRegExp(obj: any) {
return opt.call(obj) === '[object RegExp]';
}
export function isFile(obj: any): obj is File {
return opt.call(obj) === '[object File]';
}
export function isBlob(obj: any): obj is Blob {
return opt.call(obj) === '[object Blob]';
}
export function isUndefined(obj: any): obj is undefined {
return obj === undefined;
}
export function isNull(obj: any): obj is null {
return obj === null;
}
export function isFunction(obj: any): obj is (...args: any[]) => any {
return typeof obj === 'function';
}
export function isEmptyObject(obj: any): boolean {
return isObject(obj) && Object.keys(obj).length === 0;
}
export function isExist(obj: any): boolean {
return obj || obj === 0;
}
export function isWindow(el: any): el is Window {
return el === window;
}
import { App, ComponentPublicInstance } from 'vue';
import axios from 'axios';
export default function handleError(Vue: App, baseUrl: string) {
if (!baseUrl) {
return;
}
Vue.config.errorHandler = (
err: unknown,
instance: ComponentPublicInstance | null,
info: string
) => {
// send error info
axios.post(`${baseUrl}/report-error`, {
err,
instance,
info,
// location: window.location.href,
// message: err.message,
// stack: err.stack,
// browserInfo: getBrowserInfo(),
// user info
// dom info
// url info
// ...
});
};
}
/**
* Listening to routes alone would waste rendering performance. Use the publish-subscribe model for distribution management
* 单独监听路由会浪费渲染性能。使用发布订阅模式去进行分发管理。
*/
import mitt, { Handler } from 'mitt';
import type { RouteLocationNormalized } from 'vue-router';
const emitter = mitt();
const key = Symbol('ROUTE_CHANGE');
let latestRoute: RouteLocationNormalized;
export function setRouteEmitter(to: RouteLocationNormalized) {
emitter.emit(key, to);
latestRoute = to;
}
export function listenerRouteChange(handler: (route: RouteLocationNormalized) => void, immediate = true) {
emitter.on(key, handler as Handler);
if (immediate && latestRoute) {
handler(latestRoute);
}
}
export function removeRouteListener() {
emitter.off(key);
}
<script setup lang="ts">
import { Activity } from "@/types/activity";
import { computed } from "vue";
import { User } from "@/types/user";
import UserTag from "@/views/demo-show/components/user-tag.vue";
import { unionBy } from "lodash";
import useActivityApi from "@/api/activity";
const props = defineProps<{ data: Activity }>();
const links = computed(() => {
return unionBy(props.data.links || [], "id");
});
const inSideLyricist = computed(
(): User[] => links.value?.filter((item: User) => props.data.expand?.lyricist?.ids?.indexOf(item.id) !== -1) || []
);
const outSideLyricist = computed(() => props.data.expand?.lyricist?.supplement || []);
const inSideComposer = computed(
(): User[] => links.value?.filter((item: User) => props.data.expand?.composer?.ids?.indexOf(item.id) !== -1) || []
);
const outSideComposer = computed(() => props.data?.expand?.composer?.supplement || []);
</script>
<template>
<a-card v-show="data" :bordered="false">
<a-form :model="data" auto-label-width label-align="left">
<a-layout>
<a-layout-sider :width="130" style="background: none; box-shadow: none; padding-top: 6px">
<a-image show-loader :height="130" :width="130" :src="data.cover" />
</a-layout-sider>
<a-layout-content style="margin-left: 16px">
<a-form-item :hide-label="true">
<div class="title">{{ data.song_name }}</div>
<a-tag v-for="item in data.tags" :key="item.id" size="small" style="margin-right: 5px">
{{ item.name }}
</a-tag>
<span style="font-size: 10px">
{{ useActivityApi.statusOption.find((item) => item.value === data.status)?.label }}
</span>
</a-form-item>
<a-form-item :label-col-style="{ flex: 0 }" :wrapper-col-style="{ flex: 'unset', width: 'inherit' }"
:show-colon="true" label="关联用户">
<div v-if="data?.user">{{ data.user?.nick_name }}</div>
<div v-else></div>
</a-form-item>
<a-form-item style="margin-bottom: 0 !important" hide-label>
<a-form-item :label-col-style="{ flex: 0 }" :show-colon="true" label="作词">
<user-tag v-for="item in inSideLyricist" :key="item.id" :user="{ nick_name: item.nick_name }"
style="margin-right: 5px" />
<user-tag v-for="item in outSideLyricist" :key="`lyricist-${item}`" :user="{ nick_name: item }"
style="margin-right: 5px" />
</a-form-item>
<a-form-item :label-col-style="{ flex: 0 }" :show-colon="true" label="作曲">
<user-tag v-for="item in inSideComposer" :key="item.id" :user="{ nick_name: item.nick_name }"
style="margin-right: 5px" />
<user-tag v-for="item in outSideComposer" :key="`lyricist-${item}`" :user="{ nick_name: item }"
style="margin-right: 5px" />
</a-form-item>
</a-form-item>
<a-form-item style="margin-bottom: 0 !important" :label-col-style="{ flex: 0 }" :show-colon="true"
label="创建信息">
<span v-if="data?.user" style="margin-right: 8px">{{ data.user.nick_name }}</span>
<span style="margin-right: 8px">{{ data.created_at }} </span>
</a-form-item>
</a-layout-content>
</a-layout>
</a-form>
</a-card>
</template>
<style lang="less" scoped>
.arco-form-item {
margin-bottom: 10px;
}
.arco-form-item-label-col {
flex: 0;
}
.title {
font-size: 16px;
font-weight: bold;
margin-right: 8px;
}
.right {
margin: 0 20px;
min-width: 600px;
}
</style>
<script setup lang="ts">
import { Modal, Textarea } from "@arco-design/web-vue";
import { computed, h } from "vue";
import { useAppStore } from "@/store";
import useAuthApi from "@/api/auth";
import { Activity } from "@/types/activity";
type MaterialData = { title: string; type: string; content: string; name?: string; size?: string; };
const props = defineProps<{ data: Pick<Activity, "expand" | "lyric" | "song_name">; hideTrack?: boolean }>();
const appStore = useAppStore();
const theme = computed(() => appStore.theme);
const lyricStyle = computed(() =>
theme.value === "light" ? { border: "none", backgroundColor: "white" } : {
border: "none",
backgroundColor: "#2a2a2b"
}
);
const bytesForHuman = (bytes: number, decimals = 2) => {
const units = ["B", "KB", "MB", "GB", "TB", "PB"];
let i = 0;
// eslint-disable-next-line no-plusplus
for (i; bytes > 1024; i++) {
bytes /= 1024;
}
return `${parseFloat(bytes.toFixed(decimals))} ${units[i]}`;
};
const onDownload = (record: MaterialData) => useAuthApi.downloadFile(record.content, `${props.data.song_name}(${record.title})`);
const onViewLyric = (lyric: string) => {
Modal.open({
content: () => h(Textarea, { defaultValue: lyric, autoSize: { maxRows: 20 }, style: lyricStyle.value }),
footer: false,
closable: false
});
};
const materials = computed((): MaterialData[] => {
return [
{
title: "音频",
type: "guide",
name: props.data.expand?.guide_source?.name || "",
content: props.data.expand?.guide_source?.url || "",
size: bytesForHuman(props.data.expand?.guide_source?.size || 0)
},
{
title: "伴奏",
type: "karaoke",
name: props.data.expand?.karaoke_source?.name || "",
content: props.data.expand?.karaoke_source?.url || "",
size: bytesForHuman(props.data.expand?.karaoke_source?.size || 0)
},
{ title: "歌词", type: "Lyric", content: props.data.lyric }
];
});
</script>
<template>
<a-table row-key="type" :data="materials" :bordered="false" :table-layout-fixed="true" :pagination="false">
<template #columns>
<a-table-column title="物料类型" align="center" data-index="title" :width="140" />
<a-table-column title="音频播放" data-index="content">
<template #cell="{ record }">
<template v-if="record.content">
<audio-player v-if="['guide', 'karaoke'].indexOf(record.type) !== -1" :name="record.type"
:url="record.content" />
<div v-if="record.type === 'track'">{{ [record.name, record.size].join(",") }}</div>
</template>
</template>
</a-table-column>
<a-table-column title="操作" align="center" :width="200">
<template #cell="{ record }">
<template v-if="record.content">
<a-button v-if="record.type === 'Lyric'" type="primary" size="small" @click="onViewLyric(record.content)">
查看
</a-button>
<a-button v-else type="primary" size="small" @click="onDownload(record)">下载</a-button>
</template>
</template>
</a-table-column>
</template>
</a-table>
</template>
<style scoped lang="less"></style>
<script setup lang="ts">
import { computed } from 'vue';
const props = defineProps<{ user: { id?: number; nick_name: string } }>();
const cursor = computed(() => (props.user.id ? 'pointer' : 'default'));
</script>
<template>
<a-tag class="link" size="small" @click="() => user.id && $router.push({ name: 'user-show', params: { id: user.id } })">
<span>{{ user.nick_name }}</span>
<icon-right v-if="user.id" style="margin-left: 8px" />
</a-tag>
</template>
<style scoped lang="less">
.link:hover {
cursor: v-bind(cursor);
}
</style>
<script setup lang="ts" name="audition-demo-show">
import { useRoute, useRouter } from "vue-router";
import { onMounted, ref } from "vue";
import useActivityApi from "@/api/activity";
import BasicCard from "@/views/demo-show/components/basic-card.vue";
import MaterialTable from "@/views/demo-show/components/material-table.vue";
import { useRouteQuery } from "@vueuse/router";
import useLoading from "@/hooks/loading";
import { Activity } from "@/types/activity";
const activityKey = Number(useRoute().params.id);
const tabKey = useRouteQuery("tabKey", "material");
const activity = ref<Activity>();
const { loading, setLoading } = useLoading(false);
const router = useRouter();
onMounted(async () => {
setLoading(true);
await useActivityApi
.show(activityKey, {
songType: 2,
setWith: [
"project:id,name,is_promote,is_can_manage",
"tags:id,name",
"user:id,nick_name,real_name,identity",
"links:id,nick_name,identity"
],
setColumn: ["id", "song_name", "cover", "lyric", "expand", "status", "created_at", "song_type", "project_id", "user_id"]
})
.then((data: Activity) => {
activity.value = data;
})
.catch(() => router.replace({ name: "exception-404" }))
.finally(() => setLoading(false));
});
</script>
<template>
<page-view has-bread>
<a-spin :loading="loading" style="width: 100%">
<basic-card v-if="activity" :data="activity as Activity" />
</a-spin>
<a-card style="margin-top: 16px">
<a-tabs v-model:active-key="tabKey" :animation="true" :header-padding="false" :justify="true" type="rounded">
<a-tab-pane key="material" title="歌曲物料">
<material-table v-if="activity" :data="activity" />
</a-tab-pane>
</a-tabs>
</a-card>
</page-view>
</template>
<style lang="less" scoped>
textarea.arco-textarea::-webkit-scrollbar {
display: none;
}
</style>
<script setup lang="ts">
import { Space } from '@arco-design/web-vue';
import { computed, onMounted, ref } from 'vue';
import axios from 'axios';
import { audioBufferToWav } from '@/utils';
import AudioSyncLyric from '@/utils/audioSyncLyric';
const props = defineProps<{
src: string | File | ArrayBuffer;
lyric: string;
startWithLyric?: boolean;
startTime?: string;
endTime?: string;
}>();
const audioRef = ref();
const lyricRef = ref();
const source = ref();
const onPay = (e: any) => {
const audios = document.getElementsByTagName('audio');
[].forEach.call(audios, (i: HTMLAudioElement) => i !== e.target && i.pause());
};
const convertDurationToSeconds = (duration: string) => {
const timeArray = duration.split(':'); // 将时间字符串拆分为时、分、秒的数组
switch (timeArray.length) {
case 1:
return parseFloat(timeArray[0]);
case 2:
return parseInt(timeArray[0], 10) * 60 + parseFloat(timeArray[1]);
case 3:
return parseInt(timeArray[0], 10) * 3600 + parseInt(timeArray[1], 10) * 60 + parseFloat(timeArray[2]);
default:
return 0;
}
};
const startTime = computed((): number => convertDurationToSeconds(props.startTime ?? '00:00.00'));
const endTime = computed((): number | undefined => (props.endTime ? convertDurationToSeconds(props.endTime) : undefined));
const getResult = async (): Promise<ArrayBuffer> => {
if (props.src instanceof Blob) {
return props.src.arrayBuffer();
}
if (props.src instanceof ArrayBuffer) {
return Promise.resolve(props.src);
}
return axios
.get(`${props.src}?response-content-type=Blob`, { responseType: 'blob', timeout: 60000 })
.then(({ data }) => Promise.resolve(data.arrayBuffer()));
};
onMounted(async () => {
// eslint-disable-next-line no-new
new AudioSyncLyric(lyricRef.value, audioRef.value).setStartTime(startTime.value);
const result: ArrayBuffer = await getResult();
const audioCtx = new AudioContext();
const audioBuffer = await audioCtx.decodeAudioData(result);
const { numberOfChannels, sampleRate, duration } = audioBuffer;
const start = startTime.value; // 从第几秒开始复制
const end = endTime.value || duration; // 复制到第几秒结束
// eslint-disable-next-line no-bitwise
const startOffset = (start * sampleRate) >> 0; // 起始位置 = 开始时间 * 采样率
// eslint-disable-next-line no-bitwise
const endOffset = (end * sampleRate) >> 0; // 结束位置 = 结束时间 * 采样率
const frameCount = endOffset - startOffset; // 音频帧数/长度 = 结束位置 - 起始位置
const newAudioBuffer = audioCtx.createBuffer(numberOfChannels, frameCount, sampleRate);
// eslint-disable-next-line no-plusplus
for (let i = 0; i < numberOfChannels; i++) {
newAudioBuffer.getChannelData(i).set(audioBuffer.getChannelData(i).slice(startOffset, endOffset));
}
const blob = audioBufferToWav(newAudioBuffer, frameCount);
source.value = URL.createObjectURL(blob);
});
</script>
<template>
<Space direction="vertical" fill>
<audio ref="audioRef" :src="source" class="audio" controls controlsList="nodownload noplaybackrate" @play="onPay" />
<div ref="lyricRef" class="lyric">{{ lyric }}</div>
</Space>
</template>
<style scoped lang="less">
.audio {
height: 30px;
width: 100%;
outline: none;
}
.lyric {
border: none !important;
background-color: #f7f8fa;
:deep(.rabbit-lyrics__line) {
padding: 0.3em 1em !important;
}
:deep(.rabbit-lyrics__inline) {
color: #818181;
}
:deep(.rabbit-lyrics__inline.rabbit-lyrics__inline--active) {
font-size: 16px;
font-weight: 500;
color: black;
}
}
</style>
<script setup lang="ts">
import { useSelectionStore } from "@/store";
import {
Layout,
LayoutSider,
LayoutContent,
LayoutFooter,
Step,
Steps,
Space,
Divider,
Link
} from "@arco-design/web-vue";
import Step1FormContent from "@/views/demo/components/step1-form-content.vue";
import Step2FormContent from "@/views/demo/components/step2-form-content.vue";
import Step3FormContent from "@/views/demo/components/step3-form-content.vue";
import IconButton from "@/components/icon-button/index.vue";
import { AnyObject } from "@/types/global";
import useLoading from "@/hooks/loading";
import { computed, markRaw, ref } from "vue";
import { cloneDeep } from "lodash";
const props = defineProps<{
initValue: AnyObject;
filterProject?: (value: unknown) => boolean;
onSubmit: (data: AnyObject) => Promise<any>;
}>();
const { loading, setLoading } = useLoading(false);
const formRef = ref();
const formValue = ref({ ...cloneDeep(props.initValue) });
const stepItems = [
{ value: 1, label: "基本信息", template: markRaw(Step1FormContent) },
{ value: 2, label: "补充信息", template: markRaw(Step2FormContent) },
{ value: 3, label: "上传文件", template: markRaw(Step3FormContent) }
];
const currentStep = ref(1);
const currentContent = computed(() => stepItems.find((item) => item.value === currentStep.value)?.template);
const nextBtnLabel = computed(() => (currentStep.value === 3 ? "提交" : "下一步"));
const onPrev = (): void => {
currentStep.value = Math.max(1, currentStep.value - 1);
};
const onNext = () => {
formRef.value.onValid(async () => {
if (currentStep.value === stepItems.length) {
setLoading(true);
props.onSubmit(formValue.value).finally(() => setLoading(false));
}
currentStep.value = Math.min(stepItems.length, currentStep.value + 1);
});
};
</script>
<template>
<Layout>
<Layout has-sider>
<LayoutSider :width="120" class="aside">
<Steps :current="currentStep" direction="vertical" :small="true">
<Step v-for="item in stepItems" :key="item.value">{{ item.label }}</Step>
</Steps>
</LayoutSider>
<LayoutContent class="main">
<component :is="currentContent" ref="formRef" v-model="formValue" v-model:loading="loading"
:filter-project="filterProject" />
</LayoutContent>
</Layout>
<LayoutFooter>
<Divider style="margin-top: 8px; margin-bottom: 20px" />
<Link :href="useSelectionStore().lyricTool" :hoverable="false" class="link-hover" icon>歌词制作工具</Link>
<Space style="float: right">
<IconButton v-show="currentStep !== 1" icon="left" label="上一步" @click="onPrev" />
<IconButton icon="right" icon-align="right" :loading="loading" :label="nextBtnLabel" @click="onNext" />
</Space>
</LayoutFooter>
</Layout>
</template>
<style scoped lang="less">
.aside {
box-shadow: unset !important;
border-right: 1px solid var(--color-border);
margin-right: 20px;
background-color: transparent;
}
.main {
min-width: 640px;
}
</style>
<script setup lang="ts">
import { Form, FormItem, Input } from '@arco-design/web-vue';
import { computed, ref } from 'vue';
import AvatarUpload from '@/components/avatar-upload/index.vue';
import TagSelect from '@/components/tag-select/index.vue';
import { FieldRule, FormInstance } from '@arco-design/web-vue/es/form';
import { get, set } from 'lodash';
import { useVModels } from '@vueuse/core';
const props = withDefaults(defineProps<{ loading?: boolean; modelValue?: any; filterProject?: (value: any) => boolean }>(), {
filterProject: () => true,
});
const emits = defineEmits(['update:modelValue', 'update:loading']);
const formRef = ref<FormInstance>();
const { modelValue: formValue } = useVModels(props, emits);
const formRule = {
'cover': [{ type: 'string', required: true, message: '请上传活动封面' }],
'song_name': [{ type: 'string', required: true, message: '请输入歌曲名称' }],
'expand.tag_ids': [
{ type: 'array', required: false, message: '请选择关联标签' },
{ type: 'array', maxLength: 3, message: '关联标签最多选中3个' },
],
'project_id': [{ type: 'number', min: 1, required: true, message: '请选择关联厂牌' }],
} as Record<string, FieldRule[]>;
const tagIds = computed({
get: () => get(formValue.value, 'expand.tag_ids', []),
set: (val) => set(formValue.value, 'expand.tag_ids', val),
});
defineExpose({
onValid: (callback?: () => void) => formRef.value?.validate((errors) => !errors && callback?.()),
});
</script>
<template>
<Form ref="formRef" :model="formValue" :rules="formRule" :auto-label-width="true" size="small">
<FormItem label="封面图片" field="cover" :show-colon="true">
<AvatarUpload v-model="formValue.cover" :size="100" shape="square" />
</FormItem>
<FormItem label="歌曲名称" field="song_name" :show-colon="true">
<Input v-model="formValue.song_name" :max-length="100" :show-word-limit="true" placeholder="请输入" />
</FormItem>
<FormItem label="曲风标签" field="expand.tag_ids" :show-colon="true">
<TagSelect v-model="tagIds" :multiple="true" :limit="3" placeholder="请选择" limit-error-msg="关联标签最多选中3个" />
</FormItem>
</Form>
</template>
<style scoped lang="less"></style>
<script setup lang="ts">
import { Form, FormItem, InputTag } from '@arco-design/web-vue';
import UserSelect from '@/components/user-select/index.vue';
import { ref, computed } from 'vue';
import { FieldRule, FormInstance } from '@arco-design/web-vue/es/form';
import { useVModels } from '@vueuse/core';
import { get, set } from 'lodash';
const props = defineProps<{ loading?: boolean; modelValue?: any }>();
const emits = defineEmits(['update:modelValue', 'update:loading']);
const formRef = ref<FormInstance>();
const { modelValue: formValue } = useVModels(props, emits);
const lyricistIds = computed({
get: () => get(formValue.value, 'expand.lyricist.ids', []),
set: (val) => set(formValue.value, 'expand.lyricist.ids', val),
});
const lyricistSupplement = computed({
get: () => get(formValue.value, 'expand.lyricist.supplement', []),
set: (val) => set(formValue.value, 'expand.lyricist.supplement', val),
});
const composerIds = computed({
get: () => get(formValue.value, 'expand.composer.ids', []),
set: (val) => set(formValue.value, 'expand.composer.ids', val),
});
const composerSupplement = computed({
get: () => get(formValue.value, 'expand.composer.supplement', []),
set: (val) => set(formValue.value, 'expand.composer.supplement', val),
});
const checkMaxUser = (value: any, cb: (error?: string) => void) => (value && value.length > 2 ? cb('最大选择2人') : false);
const formRule = {
'expand.lyricist.supplement': [{ type: 'array', validator: (value, cb) => checkMaxUser(value, cb) }],
'expand.composer.supplement': [{ type: 'array', validator: (value, cb) => checkMaxUser(value, cb) }],
'estimate_release_at': [{ required: true, message: '请选择预计发布时间' }],
} as Record<string, FieldRule[]>;
defineExpose({
onValid: (callback?: () => void) => formRef.value?.validate((errors) => !errors && callback?.()),
});
</script>
<template>
<Form ref="formRef" :model="formValue" :rules="formRule" :auto-label-width="true" size="small">
<FormItem label="词作者(用户)" field="expand.lyricist.ids" :show-colon="true">
<UserSelect v-model="lyricistIds" placeholder="请选择用户" :multiple="true" :allow-search="true" :limit="2" />
</FormItem>
<FormItem label="词作者(未注册)" field="expand.lyricist.supplement" :show-colon="true">
<InputTag v-model="lyricistSupplement" placeholder="输入完成回车键分隔" :max-tag-count="2" :unique-value="true" />
<template #extra>
<div>注意:上方填1项即可,歌曲信息中【用户】可点击跳转用户主页,【未注册】仅显示;</div>
</template>
</FormItem>
<FormItem label="曲作者(用户)" field="expand.composer.ids" :show-colon="true">
<UserSelect v-model="composerIds" placeholder="请选择用户" :multiple="true" :allow-search="true" :limit="2" />
</FormItem>
<FormItem label="曲作者(未注册)" field="expand.composer.supplement" :show-colon="true">
<InputTag v-model="composerSupplement" placeholder="输入完成回车键分隔" :max-tag-count="2" :unique-value="true" />
<template #extra>
<div>注意:上方填1项即可,歌曲信息中【用户】可点击跳转用户主页,【未注册】仅显示;</div>
</template>
</FormItem>
</Form>
</template>
<style scoped lang="less"></style>
<script setup lang="ts">
import { ref, computed, createVNode } from 'vue';
import { FieldRule, FormInstance } from '@arco-design/web-vue/es/form';
import { useVModels } from '@vueuse/core';
import { Form, FormItem, Link, Textarea, TypographyText } from '@arco-design/web-vue';
import InputUpload from '@/components/input-upload/index.vue';
import { useSelectionStore } from '@/store';
import { get, set } from 'lodash';
import axios from 'axios';
import AudioPreview from '@/views/demo/components/audio-preview.vue';
import AudioPlayer from '@/components/audio-player/index.vue';
import { createModalVNode } from '@/utils/createVNode';
import useAuthApi from "@/api/auth";
const props = defineProps<{ loading?: boolean; modelValue?: any }>();
const emits = defineEmits(['update:modelValue', 'update:loading']);
const formRef = ref<FormInstance>();
const { loading, modelValue: formValue } = useVModels(props, emits);
const guideSourceUrl = computed({
get: () => get(formValue.value, 'expand.guide_source.url', ''),
set: (val) => set(formValue.value, 'expand.guide_source.url', val),
});
const karaokeSourceUrl = computed({
get: () => get(formValue.value, 'expand.karaoke_source.url', ''),
set: (val) => set(formValue.value, 'expand.karaoke_source.url', val),
});
const onUpdateGuide = (file: { name: string; url: string; size: number }) => {
set(formValue.value, 'expand.guide_source', { name: file.name, url: file.url, size: file.size });
};
const onUpdateKaraoke = (file: { name: string; url: string; size: number }) => {
set(formValue.value, 'expand.karaoke_source', { name: file.name, url: file.url, size: file.size });
};
const { activityAudioAccept } = useSelectionStore();
const formRule = {
'expand.guide_source.url': [{ required: true, message: '请上传导唱文件' }],
'expand.karaoke_source.url': [{ required: false, message: '请上传伴奏文件' }],
'lyric': [{ type: 'string', required: true, message: '请填写歌词内容' }],
'clip_lyric': [{ type: 'string', required: true, message: '请填写推荐歌词内容' }],
} as Record<string, FieldRule[]>;
const onDownload = (url: string, fileName: string) => useAuthApi.downloadFile(url, `${formValue.value.song_name}(${fileName})`);
const onFormatLyric = (key: string) => {
formValue.value[key] = formValue.value[key].replace(/(\n[\s\t]*\r*\n)/g, '\n').replace(/^[\n\r\t]*|[\n\r\t]*$/g, '');
};
const guideFile = ref<File | undefined>();
const getGuideFile = async () => {
if (!guideFile.value) {
guideFile.value = await axios
.get(`${guideSourceUrl.value}?response-content-type=Blob`, { responseType: 'blob', timeout: 60000 })
.then(({ data }) => Promise.resolve(data));
}
return guideFile.value;
};
const onAudioPreview = async () => {
const src = await getGuideFile();
createModalVNode(() => createVNode(AudioPreview, { src, lyric: formValue.value.lyric }), {
title: '预览歌词-整首',
footer: false,
closable: true,
});
};
defineExpose({
onValid: (callback?: () => void) => formRef.value?.validate((errors) => !errors && callback?.()),
});
</script>
<template>
<Form ref="formRef" :model="formValue" :rules="formRule" :auto-label-width="true" size="small">
<FormItem label="音频文件" field="expand.guide_source.url" :show-colon="true">
<InputUpload v-model="guideSourceUrl" :accept="activityAudioAccept" :limit="100" @success="onUpdateGuide"
@choose-file="(file: any) => (guideFile = file)" @update:loading="(value: boolean) => (loading = value)" />
</FormItem>
<FormItem v-if="guideSourceUrl">
<template #label>
<Link icon @click="onDownload(guideSourceUrl, '音频文件')">下载音频</Link>
</template>
<AudioPlayer name="音频文件" :url="guideSourceUrl" />
</FormItem>
<FormItem label="伴奏文件" field="expand.karaoke_source.url" :show-colon="true">
<InputUpload v-model="karaokeSourceUrl" :accept="activityAudioAccept" :limit="100" @success="onUpdateKaraoke"
@update:loading="(value: boolean) => (loading = value)" />
</FormItem>
<FormItem v-if="karaokeSourceUrl">
<template #label>
<Link icon @click="onDownload(karaokeSourceUrl, '伴奏文件')">下载伴奏</Link>
</template>
<AudioPlayer name="伴奏文件" :url="karaokeSourceUrl" />
</FormItem>
<FormItem class="lyric" label="歌词文本" field="lyric" :show-colon="true">
<Textarea v-model="formValue.lyric" :auto-size="{ minRows: 6, maxRows: 6 }" placeholder="请粘贴带时间的lrc歌词文本至输入框"
@blur="() => onFormatLyric('lyric')" />
<!-- <template #extra>
<Link :hoverable="false" :disabled="!guideSourceUrl || !formValue.lyric" @click="onAudioPreview"> 预览歌词</Link>
</template> -->
</FormItem>
<TypographyText type="danger" style="font-size: 13px">
注意:demo上架后,存在于您的私库。需要在App应用内,您的个人主页下,进行1对1分享给对方试听
</TypographyText>
</Form>
</template>
<style scoped lang="less">
.lyric {
:deep(.arco-form-item-extra) {
width: 100%;
text-align: right;
}
}
</style>
<script setup lang="ts" name="audition-demo">
import { createVNode, onMounted, ref } from "vue";
import useLoading from "@/hooks/loading";
import useActivityApi, { useApply } from "@/api/activity";
import EnumTableColumn from "@/components/filter/enum-table-column.vue";
import DateTableColumn from "@/components/filter/date-table-column.vue";
import ActivityTableColumn from "@/components/filter/activity-table-column.vue";
import { AnyObject, AttributeData } from "@/types/global";
import ActivityForm from "@/views/demo/components/form-content.vue";
import { Message, TableData } from "@arco-design/web-vue";
import { createInputVNode, createModalVNode } from "@/utils/createVNode";
import { useAuthorizedStore, useSelectionStore } from "@/store";
import { promiseToBoolean } from "@/utils";
import { tryOnMounted } from "@vueuse/core";
const props = defineProps<{
initFilter?: AttributeData;
hideSearchItem?: string[];
hideTool?: boolean;
hideCreate?: boolean;
exportName?: string;
queryHook?: () => void;
}>();
const { statusOption, get, update, destroy, changeStatus } = useActivityApi;
const { loading, setLoading } = useLoading(false);
const filter = ref({
songName: "",
projectName: "",
tagName: "",
status: [],
createBetween: [],
songType: 2,
setSort: ["-id"]
});
const tableRef = ref();
const { isCreateDemo } = useAuthorizedStore();
const onQuery = async (params: object) => {
setLoading(true);
props.queryHook?.();
return get({
...filter.value,
...params,
setColumn: ["id", "song_name", "cover", "user_id", "lyric", "expand", "status", "created_at"],
setWith: ["user:id,real_name,nick_name,identity", "tags:id,name"]
}).finally(() => setLoading(false));
};
const onSort = (column: string, type: string) => {
filter.value.setSort = type ? [(type === "desc" ? "-" : "") + column, "-id"] : ["-id"];
tableRef.value?.onFetch();
};
const onSearch = () => tableRef.value?.onPageChange(1);
const handleCreate = () => {
const dialog = createModalVNode(
() =>
createVNode(ActivityForm, {
initValue: { song_type: 2, cover: useSelectionStore().appleDemoCover, is_push: 0, expand: { push_type: [] } },
onSubmit: (data: AnyObject) =>
useApply.create(data).then(() => {
Message.success(`申请上架Demo:${data.song_name}`);
tableRef.value?.onFetch();
dialog.close();
})
}),
{ title: "创建Demo", footer: false, closable: true, width: "auto" }
);
};
const onUpdate = (record: TableData) => {
const dialog = createModalVNode(
() =>
createVNode(ActivityForm, {
initValue: record,
onSubmit: (attribute: AnyObject) =>
update(record.id, Object.assign(attribute, { song_type: 2 })).then(() => {
Message.success(`编辑Demo:${record.song_name}`);
tableRef.value?.onFetch();
dialog.close();
})
}),
{ title: "编辑Demo", footer: false, width: "auto", closable: true }
);
};
const onDown = (record: TableData) => {
const msg = ref<string>("");
createModalVNode(
() =>
createInputVNode(msg, {
"placeholder": "请输入下架原因",
"maxLength": 20,
"show-word-limit": true
}),
{
title: "变更状态",
titleAlign: "start",
okText: "下架",
onBeforeOk: (done) =>
changeStatus(record.id, { status: "down", msg: msg.value })
.then(() => {
tableRef.value?.onFetch();
done(true);
})
.catch(() => done(false))
}
);
};
const onUp = (record: TableData, status: "up" | "reUp") => {
createModalVNode(`请确认是否上架歌曲:${record.song_name}`, {
title: "变更状态",
titleAlign: "start",
okText: "上架",
onBeforeOk: (done) =>
changeStatus(record.id, { status })
.then(() => {
tableRef.value?.onFetch();
done(true);
})
.catch(() => done(false))
});
};
const onDelete = (row: TableData) =>
createModalVNode(`确认要将Demo:${row.song_name} 删除吗?`, {
title: "删除操作",
onBeforeOk: () => promiseToBoolean(destroy(row.id)),
onOk: () => tableRef.value?.onFetch()
});
const onReset = () => {
filter.value = {
songName: "",
projectName: "",
tagName: "",
status: [],
createBetween: [],
...props.initFilter,
songType: 2,
setSort: ["-id"]
};
tableRef.value?.resetSort();
onSearch();
};
onMounted(() => onReset());
tryOnMounted(async () => {
useSelectionStore().queryUser({ fetchType: "all", status: 1 });
useSelectionStore().queryTag({ fetchType: "all", type: 1 });
useSelectionStore().queryConfig({
fetchType: "all",
identifier: ["activity_demo_cover", "activity_lyric_tool", "activity_audio_accept"]
});
});
</script>
<template>
<page-view has-bread has-card>
<filter-search :model="filter" :loading="loading" @search="onSearch" @reset="onReset">
<filter-search-item label="歌曲名称" field="song_name">
<a-input v-model="filter.songName" allow-clear placeholder="请输入搜索歌曲名称" />
</filter-search-item>
<filter-search-item label="标签名称" field="tagName">
<a-input v-model="filter.tagName" allow-clear placeholder="请输入搜索标签名称" />
</filter-search-item>
<filter-search-item label="状态" field="status">
<a-select v-model="filter.status" :options="statusOption" allow-clear multiple placeholder="请选择搜索状态" />
</filter-search-item>
<filter-search-item label="创建时间" field="createBetween">
<a-range-picker v-model="filter.createBetween" show-time
:time-picker-props="{ defaultValue: ['00:00:00', '23:59:59'] }" />
</filter-search-item>
</filter-search>
<filter-table ref="tableRef" :loading="loading" :on-query="onQuery" @row-sort="onSort">
<template #tool="{ size }">
<a-button v-if="isCreateDemo" :size="size" type="primary" @click="handleCreate">上架Demo</a-button>
</template>
<template #tool-right>
<div class="tipsBox">
<span>注意:如果上传后状态为“处理中”,需要“</span><i>编辑</i><span>”或“</span><i>下架</i><span>”,请点击“</span><i>搜索</i><span>”或</span><i>刷新浏览器</i>
</div>
</template>
<activity-table-column data-index="id" title="试唱歌曲" :width="560" hide-sub-title />
<date-table-column data-index="created_at" title="创建时间" :width="110" split has-sort />
<enum-table-column data-index="status" title="状态" :option="statusOption" :width="110" has-sort />
<a-table-column :width="90" align="center" data-index="operations" fixed="right" title="操作">
<template #cell="{ record }">
<a-space direction="vertical" fill>
<a-link :hoverable="false" class="link-hover"
@click="$router.push({ name: 'audition-demo-show', params: { id: record.id } })">
查看
</a-link>
<a-link v-if="record.status === 1" :hoverable="false" class="link-hover" @click="onDown(record)">下架
</a-link>
<a-link v-if="record.status === 2" :hoverable="false" class="link-hover" @click="onUp(record, 'up')">上架
</a-link>
<a-link v-if="record.status !== 0 && record.status !== 5" :hoverable="false" class="link-hover"
@click="onUpdate(record)">
编辑
</a-link>
<a-link v-if="record.status === 2" :hoverable="false" class="link-hover" @click="onDelete(record)">删除
</a-link>
</a-space>
</template>
</a-table-column>
</filter-table>
</page-view>
</template>
<style scoped lang="less">
:deep(.arco-table-cell) {
padding: 5px 16px !important;
}
.tipsBox {
font-size: 14px;
span {
color: #333;
}
i {
color: red;
font-style: normal;
}
}
</style>
<template>
<div class="container">
<Breadcrumb :items="['exception', 'exception-403']" />
<div class="content">
<a-result class="result" status="403" subtitle="对不起,您没有访问该资源的权限" />
<a-button key="back" type="primary" @click="goBack"> 返回</a-button>
</div>
</div>
</template>
<script lang="ts" setup>
import { useRouter } from 'vue-router';
const router = useRouter();
const goBack = () => router.back();
</script>
<template>
<div class="container">
<Breadcrumb :items="['exception', 'exception-404']" />
<div class="content">
<a-result class="result" status="404" subtitle="抱歉,页面不见了~"></a-result>
<div class="operation-row">
<!-- <a-button key="again" style="margin-right: 16px"> 重试</a-button>-->
<a-button key="back" type="primary" @click="goBack"> 返回</a-button>
</div>
</div>
</div>
</template>
<script lang="ts" setup>
import { useRouter } from 'vue-router';
const router = useRouter();
const goBack = () => router.back();
</script>
<template>
<div class="container">
<Breadcrumb :items="['exception', 'exception-500']" />
<div class="content">
<a-result class="result" status="500" subtitle="抱歉,服务器出了点问题~" />
<a-button key="back" type="primary" @click="goBack">返回</a-button>
</div>
</div>
</template>
<script lang="ts" setup>
import { useRouter } from 'vue-router';
const router = useRouter();
const goBack = () => router.back();
</script>
<style lang="less" scoped></style>
<template>
<router-view />
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({});
</script>
<style lang="less" scoped>
.container {
// position: relative;
// display: flex;
// flex-direction: column;
// align-items: center;
// justify-content: center;
// height: 100%;
// text-align: center;
// background-color: var(--color-bg-1);
padding: 0 30px 20px 20px;
height: calc(100% - 20px);
:deep(.content) {
position: relative;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
text-align: center;
background-color: var(--color-bg-1);
border-radius: 4px;
}
}
</style>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { FormInstance, Message } from '@arco-design/web-vue';
import { useIntervalFn } from '@vueuse/core';
import useProviderApi from '@/api/provider';
import { union, map } from 'lodash-es';
import useLoading from '@/hooks/loading';
const emits = defineEmits(['login']);
const { loading, setLoading } = useLoading();
const countTime = ref<number>(0);
const areaOption = ref<string[]>([]);
onMounted(() => {
useProviderApi.area().then(({ data }) => (areaOption.value = union(map(data, (item) => item.identifier))));
});
const formRef = ref<FormInstance>();
const formValue = reactive({ area: '+86', phone: '', code: '' });
const formRule = {
phone: [{ required: true, message: '请输入手机号' }],
code: [{ required: true, message: '请输入验证码' }],
};
const formatCode = (value: string) => {
formValue.code = value.replace(/\D/g, '').slice(0, 6);
};
const { pause, resume } = useIntervalFn(() => {
// eslint-disable-next-line no-unused-expressions
countTime.value <= 0 ? pause() : (countTime.value -= 1);
}, 1000);
const onSend = async () => {
if (countTime.value !== 0 || (await formRef.value?.validateField('phone'))) {
return;
}
useProviderApi.sms('login', formValue.phone, formValue.area).then(() => {
Message.success('短信发送成功,请注意查收!');
countTime.value = 60;
resume();
});
};
const onLogin = () => {
formRef.value?.validate((errors) => {
if (!errors) {
setLoading(true);
useProviderApi
.login('phone', formValue)
.then(({ data }) => emits('login', data))
.finally(() => setLoading(false));
}
});
};
</script>
<template>
<a-form ref="formRef" :model="formValue" :rules="formRule" class="login-form" layout="vertical">
<a-form-item field="phone" hide-label>
<a-select v-model="formValue.area" style="flex: 100px; margin-right: 15px" :options="areaOption"
:virtual-list-props="{ height: 200 }" />
<a-input v-model="formValue.phone" style="flex: auto" placeholder="请输入登陆手机号" :max-length="11">
<template #prefix>
<icon-phone />
</template>
</a-input>
</a-form-item>
<a-form-item field="code" hide-label>
<a-input v-model="formValue.code" hide-button :max-length="6" placeholder="验证码" @input="formatCode">
<template #prefix>
<icon-message />
</template>
<template #suffix>
<a-link type="text" class="form-sms-btn" :disabled="countTime !== 0" @click="onSend()">
{{ countTime <= 0 ? '获取验证码' : countTime + 's' }} </a-link>
</template>
</a-input>
</a-form-item>
<a-form-item style="margin-bottom: 0" hide-label>
<a-button type="primary" :long="true" :loading="loading" @click="onLogin">登录</a-button>
</a-form-item>
</a-form>
</template>
<style lang="less" scoped>
.login-form {
&-error-msg {
height: 32px;
color: rgb(var(--red-6));
line-height: 32px;
}
}
.form-sms-btn {
padding-left: -12px;
font-size: 12px;
}
</style>
<script setup lang="ts">
import { setToken } from '@/utils/auth';
import PhoneContent from '@/views/login/components/phone-content.vue';
import { Message } from '@arco-design/web-vue';
import { useRouter } from 'vue-router';
type LoginData = { access_token: string; refresh_token: string; nick_name: string };
const router = useRouter();
const onLogin = ({ access_token, refresh_token, nick_name }: LoginData) => {
setToken(access_token, refresh_token);
Message.success(`欢迎回来,管理员:${nick_name}`);
const { path } = router.currentRoute.value.query;
// router.replace((path as string) || '/dashboard');
router.replace((path as string) || '/demos');
};
</script>
<template>
<div class="container">
<div class="banner">
<div class="banner-inner"></div>
</div>
<div class="content">
<div class="content-inner">
<div class="login-form-wrapper">
<div class="login-form-title">海星试唱</div>
<div class="login-form-sub-title">个人管理后台</div>
<a-card :bordered="true" :hoverable="true">
<a-tabs size="small" :justify-="true" :animation="true" lazy-load>
<a-tab-pane key="phone" title="手机号">
<phone-content @login="onLogin" />
</a-tab-pane>
</a-tabs>
</a-card>
</div>
</div>
</div>
</div>
</template>
<style lang="less" scoped>
.container {
display: flex;
height: 100vh;
.banner {
width: 550px;
}
.content {
position: relative;
display: flex;
flex: 1;
align-items: center;
justify-content: center;
padding-bottom: 40px;
.login-form-wrapper {
width: 380px;
}
.login-form-title {
color: var(--color-text-1);
font-weight: 500;
font-size: 30px;
line-height: 46px;
text-align: center;
}
.login-form-sub-title {
color: var(--color-text-3);
font-size: 16px;
line-height: 24px;
text-align: center;
margin-bottom: 16px;
}
}
.footer {
position: absolute;
right: 0;
bottom: 0;
width: 100%;
}
}
.banner {
display: flex;
align-items: center;
justify-content: center;
&-inner {
flex: 1;
height: 100%;
background-image: url('assets/image/user-login-bg.jpg');
background-size: cover;
}
}
</style>
{
"compilerOptions": {
"target": "ES2020",
"module": "ES2020",
"moduleResolution": "node",
"strict": true,
"jsx": "preserve",
"noImplicitAny": false,
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"baseUrl": ".",
"paths": {
"@/*": [
"src/*"
],
"assets/*": [
"src/assets/*"
]
},
"lib": [
"es2020",
"dom"
],
"skipLibCheck": true,
"terserOptions": {
"compress": {
"drop_console": true,
"drop_debugger": true
}
}
},
"include": [
"src/**/*",
"src/**/*.vue"
],
"exclude": [
"node_modules"
]
}