1
0
mirror of https://github.com/ialley-workshop-open/uni-halo.git synced 2026-11-13 22:11:42 +08:00

chore: 批量新增项目依赖、工具函数、页面与组件资源

1. 新增mp-html、qs等生产依赖,补全项目基础库
2. 新增平台判断、缓存、工具函数等通用工具集
3. 新增标签页、网站浏览页、关于页等业务页面
4. 新增分类卡片、通知弹窗等业务组件
5. 新增uts-progressNotification、liu-poster、uhalo-upgrade等uni模块
6. 补充audio/video组件样式补件,修复uni-components路径缺失问题
7. 新增环境变量Halo个人令牌配置项
8. 重构store导出结构,新增appConfig/halo/setting三个状态模块
9. 新增tsconfig编译目标配置,适配更高版本ES语法
This commit is contained in:
小莫唐尼
2026-08-31 19:56:16 +08:00
parent ba5b77568b
commit 067f3ed98a
147 changed files with 20866 additions and 325 deletions
@@ -0,0 +1,11 @@
// 以下项目可以删减或更换顺序,但不能添加或更改名字
export default {
// 普通标签的菜单项
node: ['大小', '斜体', '粗体', '下划线', '居中', '缩进', '上移', '下移', '删除'],
// 图片的菜单项
img: ['换图', '宽度', '超链接', '预览图', '禁用预览', '上移', '下移', '删除'],
// 链接的菜单项
link: ['更换链接', '上移', '下移', '删除'],
// 音视频的菜单项
media: ['封面', '循环', '自动播放', '上移', '下移', '删除']
}
@@ -0,0 +1,532 @@
/**
* @fileoverview editable 插件
*/
import config from './config'
import Parser from '../parser'
function Editable (vm) {
this.vm = vm
this.editHistory = [] // 历史记录
this.editI = -1 // 历史记录指针
vm._mask = [] // 蒙版被点击时进行的操作
vm._setData = function (path, val) {
const paths = path.split('.')
let target = vm
for (let i = 0; i < paths.length - 1; i++) {
target = target[paths[i]]
}
vm.$set(target, paths.pop(), val)
}
/**
* @description 移动历史记录指针
* @param {Number} num 移动距离
*/
const move = num => {
setTimeout(() => {
const item = this.editHistory[this.editI + num]
if (item) {
this.editI += num
vm._setData(item.key, item.value)
}
}, 200)
}
vm.undo = () => move(-1) // 撤销
vm.redo = () => move(1) // 重做
/**
* @description 更新记录
* @param {String} path 更新内容路径
* @param {*} oldVal 旧值
* @param {*} newVal 新值
* @param {Boolean} set 是否更新到视图
* @private
*/
vm._editVal = (path, oldVal, newVal, set) => {
// 当前指针后的内容去除
while (this.editI < this.editHistory.length - 1) {
this.editHistory.pop()
}
// 最多存储 30 条操作记录
while (this.editHistory.length > 30) {
this.editHistory.pop()
this.editI--
}
const last = this.editHistory[this.editHistory.length - 1]
if (!last || last.key !== path) {
if (last) {
// 去掉上一次的新值
this.editHistory.pop()
this.editI--
}
// 存入这一次的旧值
this.editHistory.push({
key: path,
value: oldVal
})
this.editI++
}
// 存入本次的新值
this.editHistory.push({
key: path,
value: newVal
})
this.editI++
// 更新到视图
if (set) {
vm._setData(path, newVal)
}
}
/**
* @description 获取菜单项
* @private
*/
vm._getItem = function (node, up, down) {
let items
let i
if (node.name === 'img') {
items = config.img.slice(0)
if (!vm.getSrc) {
i = items.indexOf('换图')
if (i !== -1) {
items.splice(i, 1)
}
i = items.indexOf('超链接')
if (i !== -1) {
items.splice(i, 1)
}
i = items.indexOf('预览图')
if (i !== -1) {
items.splice(i, 1)
}
}
i = items.indexOf('禁用预览')
if (i !== -1 && node.attrs.ignore) {
items[i] = '启用预览'
}
} else if (node.name === 'a') {
items = config.link.slice(0)
if (!vm.getSrc) {
i = items.indexOf('更换链接')
if (i !== -1) {
items.splice(i, 1)
}
}
} else if (node.name === 'video' || node.name === 'audio') {
items = config.media.slice(0)
i = items.indexOf('封面')
if (!vm.getSrc && i !== -1) {
items.splice(i, 1)
}
i = items.indexOf('循环')
if (node.attrs.loop && i !== -1) {
items[i] = '不循环'
}
i = items.indexOf('自动播放')
if (node.attrs.autoplay && i !== -1) {
items[i] = '不自动播放'
}
} else {
items = config.node.slice(0)
}
if (!up) {
i = items.indexOf('上移')
if (i !== -1) {
items.splice(i, 1)
}
}
if (!down) {
i = items.indexOf('下移')
if (i !== -1) {
items.splice(i, 1)
}
}
return items
}
/**
* @description 显示 tooltip
* @param {object} obj
* @private
*/
vm._tooltip = function (obj) {
vm.$set(vm, 'tooltip', {
top: obj.top,
items: obj.items
})
vm._tooltipcb = obj.success
}
/**
* @description 显示滚动条
* @param {object} obj
* @private
*/
vm._slider = function (obj) {
vm.$set(vm, 'slider', {
min: obj.min,
max: obj.max,
value: obj.value,
top: obj.top
})
vm._slideringcb = obj.changing
vm._slidercb = obj.change
}
/**
* @description 点击蒙版
* @private
*/
vm._maskTap = function () {
// 隐藏所有悬浮窗
while (vm._mask.length) {
(vm._mask.pop())()
}
if (vm.tooltip) {
vm.$set(vm, 'tooltip', null)
}
if (vm.slider) {
vm.$set(vm, 'slider', null)
}
}
/**
* @description 插入节点
* @param {Object} node
*/
function insert (node) {
if (vm._edit) {
vm._edit.insert(node)
} else {
const nodes = vm.nodes.slice(0)
nodes.push(node)
vm._editVal('nodes', vm.nodes, nodes, true)
}
}
/**
* @description 在光标处插入指定 html 内容
* @param {String} html 内容
*/
vm.insertHtml = html => {
this.inserting = true
const arr = new Parser(vm).parse(html)
this.inserting = undefined
for (let i = 0; i < arr.length; i++) {
insert(arr[i])
}
}
/**
* @description 在光标处插入图片
*/
vm.insertImg = function () {
vm.getSrc && vm.getSrc('img').then(src => {
if (typeof src === 'string') {
src = [src]
}
const parser = new Parser(vm)
for (let i = 0; i < src.length; i++) {
insert({
name: 'img',
attrs: {
src: parser.getUrl(src[i])
}
})
}
}).catch(() => { })
}
/**
* @description 在光标处插入一个链接
*/
vm.insertLink = function () {
vm.getSrc && vm.getSrc('link').then(url => {
insert({
name: 'a',
attrs: {
href: url
},
children: [{
type: 'text',
text: url
}]
})
}).catch(() => { })
}
/**
* @description 在光标处插入一个表格
* @param {Number} rows 行数
* @param {Number} cols 列数
*/
vm.insertTable = function (rows, cols) {
const table = {
name: 'table',
attrs: {
style: 'display:table;width:100%;margin:10px 0;text-align:center;border-spacing:0;border-collapse:collapse;border:1px solid gray'
},
children: []
}
for (let i = 0; i < rows; i++) {
const tr = {
name: 'tr',
attrs: {},
children: []
}
for (let j = 0; j < cols; j++) {
tr.children.push({
name: 'td',
attrs: {
style: 'padding:2px;border:1px solid gray'
},
children: [{
type: 'text',
text: ''
}]
})
}
table.children.push(tr)
}
insert(table)
}
/**
* @description 插入视频/音频
* @param {Object} node
*/
function insertMedia (node) {
if (typeof node.src === 'string') {
node.src = [node.src]
}
const parser = new Parser(vm)
// 拼接主域名
for (let i = 0; i < node.src.length; i++) {
node.src[i] = parser.getUrl(node.src[i])
}
insert({
name: 'div',
attrs: {
style: 'text-align:center'
},
children: [node]
})
}
/**
* @description 在光标处插入一个视频
*/
vm.insertVideo = function () {
vm.getSrc && vm.getSrc('video').then(src => {
insertMedia({
name: 'video',
attrs: {
controls: 'T'
},
children: [],
src,
// #ifdef APP-PLUS
html: `<video src="${src}" style="width:100%;height:100%"></video>`
// #endif
})
}).catch(() => { })
}
/**
* @description 在光标处插入一个音频
*/
vm.insertAudio = function () {
vm.getSrc && vm.getSrc('audio').then(attrs => {
let src
if (attrs.src) {
src = attrs.src
attrs.src = undefined
} else {
src = attrs
attrs = {}
}
attrs.controls = 'T'
insertMedia({
name: 'audio',
attrs,
children: [],
src
})
}).catch(() => { })
}
/**
* @description 在光标处插入一段文本
*/
vm.insertText = function () {
insert({
name: 'p',
attrs: {},
children: [{
type: 'text',
text: ''
}]
})
}
/**
* @description 清空内容
*/
vm.clear = function () {
vm._maskTap()
vm._edit = undefined
vm.$set(vm, 'nodes', [{
name: 'p',
attrs: {},
children: [{
type: 'text',
text: ''
}]
}])
}
/**
* @description 获取编辑后的 html
*/
vm.getContent = function () {
let html = '';
// 递归遍历获取
(function traversal (nodes, table) {
for (let i = 0; i < nodes.length; i++) {
let item = nodes[i]
if (item.type === 'text') {
html += item.text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>').replace(/\xa0/g, '&nbsp;') // 编码实体
} else {
if (item.name === 'img') {
item.attrs.i = ''
// 还原被转换的 svg
if ((item.attrs.src || '').includes('data:image/svg+xml;utf8,')) {
html += item.attrs.src.substr(24).replace(/%23/g, '#').replace('<svg', '<svg style="' + (item.attrs.style || '') + '"')
continue
}
} else if (item.name === 'video' || item.name === 'audio') {
// 还原 video 和 audio 的 source
item = JSON.parse(JSON.stringify(item))
if (item.src.length > 1) {
item.children = []
for (let j = 0; j < item.src.length; j++) {
item.children.push({
name: 'source',
attrs: {
src: item.src[j]
}
})
}
} else {
item.attrs.src = item.src[0]
}
} else if (item.name === 'div' && (item.attrs.style || '').includes('overflow:auto') && (item.children[0] || {}).name === 'table') {
// 还原滚动层
item = item.children[0]
}
// 还原 table
if (item.name === 'table') {
item = JSON.parse(JSON.stringify(item))
table = item.attrs
if ((item.attrs.style || '').includes('display:grid')) {
item.attrs.style = item.attrs.style.split('display:grid')[0]
const children = [{
name: 'tr',
attrs: {},
children: []
}]
for (let j = 0; j < item.children.length; j++) {
item.children[j].attrs.style = item.children[j].attrs.style.replace(/grid-[^;]+;*/g, '')
if (item.children[j].r !== children.length) {
children.push({
name: 'tr',
attrs: {},
children: [item.children[j]]
})
} else {
children[children.length - 1].children.push(item.children[j])
}
}
item.children = children
}
}
html += '<' + item.name
for (const attr in item.attrs) {
let val = item.attrs[attr]
if (!val) continue
if (val === 'T' || val === true) {
// bool 型省略值
html += ' ' + attr
continue
} else if (item.name[0] === 't' && attr === 'style' && table) {
// 取消为了显示 table 添加的 style
val = val.replace(/;*display:table[^;]*/, '')
if (table.border) {
val = val.replace(/border[^;]+;*/g, $ => $.includes('collapse') ? $ : '')
}
if (table.cellpadding) {
val = val.replace(/padding[^;]+;*/g, '')
}
if (!val) continue
}
html += ' ' + attr + '="' + val.replace(/"/g, '&quot;') + '"'
}
html += '>'
if (item.children) {
traversal(item.children, table)
html += '</' + item.name + '>'
}
}
}
})(vm.nodes)
// 其他插件处理
for (let i = vm.plugins.length; i--;) {
if (vm.plugins[i].onGetContent) {
html = vm.plugins[i].onGetContent(html) || html
}
}
return html
}
}
Editable.prototype.onUpdate = function (content, config) {
if (this.vm.editable) {
this.vm._maskTap()
config.entities.amp = '&'
if (!this.inserting) {
this.vm._edit = undefined
if (!content) {
setTimeout(() => {
this.vm.$set(this.vm, 'nodes', [{
name: 'p',
attrs: {},
children: [{
type: 'text',
text: ''
}]
}])
}, 0)
}
}
}
}
Editable.prototype.onParse = function (node) {
// 空白单元格可编辑
if (this.vm.editable && (node.name === 'td' || node.name === 'th') && !this.vm.getText(node.children)) {
node.children.push({
type: 'text',
text: ''
})
}
}
export default Editable
@@ -0,0 +1,203 @@
/**
* @fileoverview emoji 插件
*/
const reg = /\[(\S+?)\]/g
const data = {
笑脸: '😄',
生病: '😷',
破涕为笑: '😂',
吐舌: '😝',
脸红: '😳',
恐惧: '😱',
失望: '😔',
无语: '😒',
眨眼: '😉',
酷: '😎',
哭: '😭',
痴迷: '😍',
吻: '😘',
思考: '🤔',
困惑: '😕',
颠倒: '🙃',
钱: '🤑',
惊讶: '😲',
白眼: '🙄',
叹气: '😤',
睡觉: '😴',
书呆子: '🤓',
愤怒: '😡',
面无表情: '😑',
张嘴: '😮',
量体温: '🤒',
呕吐: '🤮',
光环: '😇',
幽灵: '👻',
外星人: '👽',
机器人: '🤖',
捂眼镜: '🙈',
捂耳朵: '🙉',
捂嘴: '🙊',
婴儿: '👶',
男孩: '👦',
女孩: '👧',
男人: '👨',
女人: '👩',
老人: '👴',
老妇人: '👵',
警察: '👮',
王子: '🤴',
公主: '🤴',
举手: '🙋',
跑步: '🏃',
家庭: '👪',
眼睛: '👀',
鼻子: '👃',
耳朵: '👂',
舌头: '👅',
嘴: '👄',
心: '❤️',
心碎: '💔',
雪人: '☃️',
情书: '💌',
大便: '💩',
闹钟: '⏰',
眼镜: '👓',
雨伞: '☂️',
音乐: '🎵',
话筒: '🎤',
游戏机: '🎮',
喇叭: '📢',
耳机: '🎧',
礼物: '🎁',
电话: '📞',
电脑: '💻',
打印机: '🖨️',
手电筒: '🔦',
灯泡: '💡',
书本: '📖',
信封: '✉️',
药丸: '💊',
口红: '💄',
手机: '📱',
相机: '📷',
电视: '📺',
中: '🀄',
垃圾桶: '🚮',
厕所: '🚾',
感叹号: '❗',
禁: '🈲',
可: '🉑',
彩虹: '🌈',
旋风: '🌀',
雷电: '⚡',
雪花: '❄️',
星星: '⭐',
水滴: '💧',
玫瑰: '🌹',
加油: '💪',
左: '👈',
右: '👉',
上: '👆',
下: '👇',
手掌: '🖐️',
好的: '👌',
好: '👍',
差: '👎',
胜利: '✌',
拳头: '👊',
挥手: '👋',
鼓掌: '👏',
猴子: '🐒',
狗: '🐶',
狼: '🐺',
猫: '🐱',
老虎: '🐯',
马: '🐎',
独角兽: '🦄',
斑马: '🦓',
鹿: '🦌',
牛: '🐮',
猪: '🐷',
羊: '🐏',
长颈鹿: '🦒',
大象: '🐘',
老鼠: '🐭',
蝙蝠: '🦇',
刺猬: '🦔',
熊猫: '🐼',
鸽子: '🕊️',
鸭子: '🦆',
兔子: '🐇',
老鹰: '🦅',
青蛙: '🐸',
蛇: '🐍',
龙: '🐉',
鲸鱼: '🐳',
海豚: '🐬',
足球: '⚽',
棒球: '⚾',
篮球: '🏀',
排球: '🏐',
橄榄球: '🏉',
网球: '🎾',
骰子: '🎲',
鸡腿: '🍗',
蛋糕: '🎂',
啤酒: '🍺',
饺子: '🥟',
汉堡: '🍔',
薯条: '🍟',
意大利面: '🍝',
干杯: '🥂',
筷子: '🥢',
糖果: '🍬',
奶瓶: '🍼',
爆米花: '🍿',
邮局: '🏤',
医院: '🏥',
银行: '🏦',
酒店: '🏨',
学校: '🏫',
城堡: '🏰',
火车: '🚂',
高铁: '🚄',
地铁: '🚇',
公交: '🚌',
救护车: '🚑',
消防车: '🚒',
警车: '🚓',
出租车: '🚕',
汽车: '🚗',
货车: '🚛',
自行车: '🚲',
摩托: '🛵',
红绿灯: '🚥',
帆船: '⛵',
游轮: '🛳️',
轮船: '⛴️',
飞机: '✈️',
直升机: '🚁',
缆车: '🚠',
警告: '⚠️',
禁止: '⛔'
}
function Emoji () {
}
Emoji.prototype.onUpdate = function (content) {
return content.replace(reg, ($, $1) => {
if (data[$1]) return data[$1]
return $
})
}
Emoji.prototype.onGetContent = function (content) {
for (const item in data) {
content = content.replace(new RegExp(data[item], 'g'), '[' + item + ']')
}
return content
}
export default Emoji
@@ -0,0 +1,5 @@
export default {
copyByLongPress: true, // 是否需要长按代码块时显示复制代码内容菜单
showLanguageName: true, // 是否在代码块右上角显示语言的名称
showLineNumber: true // 是否显示行号
}
@@ -0,0 +1,96 @@
/**
* @fileoverview highlight 插件
* Include prismjs (https://prismjs.com)
*/
import prism from './prism.min'
import config from './config'
import Parser from '../parser'
function Highlight (vm) {
this.vm = vm
}
Highlight.prototype.onParse = function (node, vm) {
if (node.name === 'pre') {
if (vm.options.editable) {
node.attrs.class = (node.attrs.class || '') + ' hl-pre'
return
}
let i
for (i = node.children.length; i--;) {
if (node.children[i].name === 'code') break
}
if (i === -1) return
const code = node.children[i]
let className = code.attrs.class + ' ' + node.attrs.class
i = className.indexOf('language-')
if (i === -1) {
i = className.indexOf('lang-')
if (i === -1) {
className = 'language-text'
i = 9
} else {
i += 5
}
} else {
i += 9
}
let j
for (j = i; j < className.length; j++) {
if (className[j] === ' ') break
}
const lang = className.substring(i, j)
if (code.children.length) {
const text = this.vm.getText(code.children).replace(/&amp;/g, '&')
if (!text) return
if (node.c) {
node.c = undefined
}
if (prism.languages[lang]) {
code.children = (new Parser(this.vm).parse(
// 加一层 pre 保留空白符
'<pre>' + prism.highlight(text, prism.languages[lang], lang).replace(/token /g, 'hl-') + '</pre>'))[0].children
}
node.attrs.class = 'hl-pre'
code.attrs.class = 'hl-code'
if (config.showLanguageName) {
node.children.push({
name: 'div',
attrs: {
class: 'hl-language',
style: 'user-select:none'
},
children: [{
type: 'text',
text: lang
}]
})
}
if (config.copyByLongPress) {
node.attrs.style += (node.attrs.style || '') + ';user-select:none'
node.attrs['data-content'] = text
vm.expose()
}
if (config.showLineNumber) {
const line = text.split('\n').length; const children = []
for (let k = line; k--;) {
children.push({
name: 'span',
attrs: {
class: 'span'
}
})
}
node.children.push({
name: 'span',
attrs: {
class: 'line-numbers-rows'
},
children
})
}
}
}
}
export default Highlight
@@ -0,0 +1,7 @@
/**
* prism.min.js 类型声明(mp-html highlight 插件依赖的压缩脚本)
* 文件为第三方压缩 JS,不参与类型检查,仅声明模块导出
*/
declare const prism: any
export default prism
File diff suppressed because one or more lines are too long
@@ -0,0 +1,138 @@
const data = {
name: 'imgcache',
prefix: 'imgcache_'
}
function ImgCache (vm) {
this.vm = vm // 保存实例在其他周期使用
this.i = 0 // 用于标记第几张图
vm.imgCache = {
get list () {
return uni
.getStorageInfoSync()
.keys.filter((key) => key.startsWith(data.prefix))
.map((key) => key.split(data.prefix)[1])
},
get (url) {
return uni.getStorageSync(data.prefix + url)
},
delete (url) {
const path = uni.getStorageSync(data.prefix + url)
if (!path) return false
plus.io.resolveLocalFileSystemURL(path, (entry) => {
entry.remove()
})
uni.removeStorageSync(data.prefix + url)
return true
},
async add (url) {
const filename = await download(url)
if (filename) {
uni.setStorageSync(data.prefix + url, filename)
return 'file://' + plus.io.convertLocalFileSystemURL(filename)
}
return null
},
clear () {
uni
.getStorageInfoSync()
.keys.filter((key) => key.startsWith(data.prefix))
.forEach((key) => {
uni.removeStorageSync(key)
})
plus.io.resolveLocalFileSystemURL(`_doc/${data.name}/`, (entry) => {
entry.removeRecursively(
(entry) => {
console.log(`${data.name}缓存删除成功`, entry)
},
(e) => {
console.log(`${data.name}缓存删除失败`, e)
}
)
})
}
}
}
// #ifdef APP-PLUS
ImgCache.prototype.onParse = function (node, parser) {
// 启用本插件 && 解析图片标签 && 拥有src属性 && 是网络图片
if (
this.vm.ImgCache &&
node.name === 'img' &&
node.attrs.src &&
/^https?:\/\//.test(node.attrs.src)
) {
const src = node.attrs.src
node.attrs.src = ''
node.attrs.i = this.vm.imgList.length + this.i++
parser.expose()
async function getUrl (path) {
if (await resolveFile(path)) return path
const filename = await download(src)
filename && uni.setStorageSync(data.prefix + src, filename)
return filename
}
uni.getStorage({
key: data.prefix + src,
success: async (res) => {
const path = await getUrl(res.data)
const url = path
? 'file://' + plus.io.convertLocalFileSystemURL(path)
: src
node.attrs.src = url
this.vm.imgList[node.attrs.i] = path || src
},
fail: async () => {
const path = await getUrl()
const url = path
? 'file://' + plus.io.convertLocalFileSystemURL(path)
: src
node.attrs.src = url
this.vm.imgList[node.attrs.i] = path || src
}
})
}
}
const taskQueue = new Set()
function download (url) {
return new Promise((resolve) => {
if (taskQueue.has(url)) return
taskQueue.add(url)
const suffix = /.+\.(jpg|jpeg|png|bmp|gif|webp)/.exec(url)
const name = `${makeid(8)}_${Date.now()}${suffix ? '.' + suffix[1] : ''}`
const task = plus.downloader.createDownload(
url,
{ filename: `_doc/${data.name}/${name}` },
(download, status) => {
taskQueue.delete(url)
resolve(status === 200 ? download.filename : null)
}
)
task.start()
})
}
// 判断文件存在
function resolveFile (url) {
return new Promise((resolve) => {
plus.io.resolveLocalFileSystemURL(url, resolve, () => resolve(null))
})
}
// 生成uuid
function makeid (length) {
let result = ''
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length))
}
return result
}
// #endif
export default ImgCache
@@ -0,0 +1,34 @@
/**
* @fileoverview markdown 插件
* Include marked (https://github.com/markedjs/marked)
* Include github-markdown-css (https://github.com/sindresorhus/github-markdown-css)
*/
import marked from './marked.min'
let index = 0
function Markdown (vm) {
this.vm = vm
vm._ids = {}
}
Markdown.prototype.onUpdate = function (content) {
if (this.vm.markdown) {
return marked(content)
}
}
Markdown.prototype.onParse = function (node, vm) {
if (vm.options.markdown) {
// 中文 id 需要转换,否则无法跳转
if (vm.options.useAnchor && node.attrs && /[\u4e00-\u9fa5]/.test(node.attrs.id)) {
const id = 't' + index++
this.vm._ids[node.attrs.id] = id
node.attrs.id = id
}
if (node.name === 'p' || node.name === 'table' || node.name === 'tr' || node.name === 'th' || node.name === 'td' || node.name === 'blockquote' || node.name === 'pre' || node.name === 'code') {
node.attrs.class = `md-${node.name} ${node.attrs.class || ''}`
}
}
}
export default Markdown
@@ -0,0 +1,7 @@
/**
* marked.min.js 类型声明(mp-html markdown 插件依赖的压缩脚本)
* 文件为第三方压缩 JS,不参与类型检查,仅声明模块导出
*/
declare const marked: any
export default marked
File diff suppressed because one or more lines are too long
@@ -0,0 +1,579 @@
<template>
<view id="_root" :class="(selectable?'_select ':'')+'_root'" :style="(editable?'min-height:200px;':'')+containerStyle" @tap="_containTap">
<slot v-if="!nodes[0]" />
<!-- #ifndef APP-PLUS-NVUE -->
<node v-else :childs="nodes" :opts="[lazyLoad,loadingImg,errorImg,showImgMenu,selectable,editable,placeholder,'nodes']" name="span" />
<!-- #endif -->
<!-- #ifdef APP-PLUS-NVUE -->
<web-view ref="web" src="/static/app-plus/mp-html/local.html" :style="'margin-top:-2px;height:' + height + 'px'" @onPostMessage="_onMessage" />
<!-- #endif -->
<view v-if="tooltip" class="_tooltip_contain" :style="'top:'+tooltip.top+'px'">
<view class="_tooltip">
<view v-for="(item, index) in tooltip.items" v-bind:key="index" class="_tooltip_item" :data-i="index" @tap="_tooltipTap">{{item}}</view>
</view>
</view>
<view v-if="slider" class="_slider" :style="'top:'+slider.top+'px'">
<slider :value="slider.value" :min="slider.min" :max="slider.max" handle-size="14" block-size="14" show-value activeColor="white" style="padding:3px" @changing="_sliderChanging" @change="_sliderChange" />
</view>
</view>
</template>
<script>
/**
* mp-html v2.4.0
* @description 富文本组件
* @tutorial https://github.com/jin-yufeng/mp-html
* @property {String} container-style 容器的样式
* @property {String} content 用于渲染的 html 字符串
* @property {Boolean} copy-link 是否允许外部链接被点击时自动复制
* @property {String} domain 主域名,用于拼接链接
* @property {String} error-img 图片出错时的占位图链接
* @property {Boolean} lazy-load 是否开启图片懒加载
* @property {string} loading-img 图片加载过程中的占位图链接
* @property {Boolean} pause-video 是否在播放一个视频时自动暂停其他视频
* @property {Boolean} preview-img 是否允许图片被点击时自动预览
* @property {Boolean} scroll-table 是否给每个表格添加一个滚动层使其能单独横向滚动
* @property {Boolean | String} selectable 是否开启长按复制
* @property {Boolean} set-title 是否将 title 标签的内容设置到页面标题
* @property {Boolean} show-img-menu 是否允许图片被长按时显示菜单
* @property {Object} tag-style 标签的默认样式
* @property {Boolean | Number} use-anchor 是否使用锚点链接
* @event {Function} load dom 结构加载完毕时触发
* @event {Function} ready 所有图片加载完毕时触发
* @event {Function} imgtap 图片被点击时触发
* @event {Function} linktap 链接被点击时触发
* @event {Function} play 音视频播放时触发
* @event {Function} error 媒体加载出错时触发
*/
// #ifndef APP-PLUS-NVUE
import node from './node/node'
// #endif
import Parser from './parser'
import markdown from './markdown/index.js'
import emoji from './emoji/index.js'
import highlight from './highlight/index.js'
import style from './style/index.js'
import imgCache from './img-cache/index.js'
import editable from './editable/index.js'
const plugins=[markdown,emoji,highlight,style,imgCache,editable,]
// #ifdef APP-PLUS-NVUE
const dom = weex.requireModule('dom')
// #endif
export default {
name: 'mp-html',
data() {
return {
tooltip: null,
slider: null,
nodes: [],
// #ifdef APP-PLUS-NVUE
height: 3
// #endif
}
},
props: {
editable: Boolean,
placeholder: String,
ImgCache: Boolean,
markdown: Boolean,
containerStyle: {
type: String,
default: ''
},
content: {
type: String,
default: ''
},
copyLink: {
type: [Boolean, String],
default: true
},
domain: String,
errorImg: {
type: String,
default: ''
},
lazyLoad: {
type: [Boolean, String],
default: false
},
loadingImg: {
type: String,
default: ''
},
pauseVideo: {
type: [Boolean, String],
default: true
},
previewImg: {
type: [Boolean, String],
default: true
},
scrollTable: [Boolean, String],
selectable: [Boolean, String],
setTitle: {
type: [Boolean, String],
default: true
},
showImgMenu: {
type: [Boolean, String],
default: true
},
tagStyle: Object,
useAnchor: [Boolean, Number]
},
// #ifdef VUE3
emits: ['load', 'ready', 'imgtap', 'linktap', 'play', 'error'],
// #endif
// #ifndef APP-PLUS-NVUE
components: {
node
},
// #endif
watch: {
editable(val) {
this.setContent(val ? this.content : this.getContent())
if (!val)
this._maskTap()
},
content (content) {
this.setContent(content)
}
},
created () {
this.plugins = []
for (let i = plugins.length; i--;) {
this.plugins.push(new plugins[i](this))
}
},
mounted () {
if ((this.content || this.editable) && !this.nodes.length) {
this.setContent(this.content)
}
},
beforeDestroy () {
this._hook('onDetached')
},
methods: {
_containTap() {
if (!this._lock && !this.slider) {
this._edit = undefined
this._maskTap()
}
},
_tooltipTap(e) {
this._tooltipcb(e.currentTarget.dataset.i)
this.$set(this, 'tooltip', null)
},
_sliderChanging(e) {
this._slideringcb(e.detail.value)
},
_sliderChange(e) {
this._slidercb(e.detail.value)
},
/**
* @description 将锚点跳转的范围限定在一个 scroll-view 内
* @param {Object} page scroll-view 所在页面的示例
* @param {String} selector scroll-view 的选择器
* @param {String} scrollTop scroll-view scroll-top 属性绑定的变量名
*/
in (page, selector, scrollTop) {
// #ifndef APP-PLUS-NVUE
if (page && selector && scrollTop) {
this._in = {
page,
selector,
scrollTop
}
}
// #endif
},
/**
* @description 锚点跳转
* @param {String} id 要跳转的锚点 id
* @param {Number} offset 跳转位置的偏移量
* @returns {Promise}
*/
navigateTo (id, offset) {
id = this._ids[decodeURI(id)] || id
return new Promise((resolve, reject) => {
if (!this.useAnchor) {
reject(Error('Anchor is disabled'))
return
}
offset = offset || parseInt(this.useAnchor) || 0
// #ifdef APP-PLUS-NVUE
if (!id) {
dom.scrollToElement(this.$refs.web, {
offset
})
resolve()
} else {
this._navigateTo = {
resolve,
reject,
offset
}
this.$refs.web.evalJs('uni.postMessage({data:{action:"getOffset",offset:(document.getElementById(' + id + ')||{}).offsetTop}})')
}
// #endif
// #ifndef APP-PLUS-NVUE
let deep = ' '
// #ifdef MP-WEIXIN || MP-QQ || MP-TOUTIAO
deep = '>>>'
// #endif
const selector = uni.createSelectorQuery()
// #ifndef MP-ALIPAY
.in(this._in ? this._in.page : this)
// #endif
.select((this._in ? this._in.selector : '._root') + (id ? `${deep}#${id}` : '')).boundingClientRect()
if (this._in) {
selector.select(this._in.selector).scrollOffset()
.select(this._in.selector).boundingClientRect()
} else {
// 获取 scroll-view 的位置和滚动距离
selector.selectViewport().scrollOffset() // 获取窗口的滚动距离
}
selector.exec(res => {
if (!res[0]) {
reject(Error('Label not found'))
return
}
const scrollTop = res[1].scrollTop + res[0].top - (res[2] ? res[2].top : 0) + offset
if (this._in) {
// scroll-view 跳转
this._in.page[this._in.scrollTop] = scrollTop
} else {
// 页面跳转
uni.pageScrollTo({
scrollTop,
duration: 300
})
}
resolve()
})
// #endif
})
},
/**
* @description 获取文本内容
* @return {String}
*/
getText (nodes) {
let text = '';
(function traversal (nodes) {
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i]
if (node.type === 'text') {
text += node.text.replace(/&amp;/g, '&')
} else if (node.name === 'br') {
text += '\n'
} else {
// 块级标签前后加换行
const isBlock = node.name === 'p' || node.name === 'div' || node.name === 'tr' || node.name === 'li' || (node.name[0] === 'h' && node.name[1] > '0' && node.name[1] < '7')
if (isBlock && text && text[text.length - 1] !== '\n') {
text += '\n'
}
// 递归获取子节点的文本
if (node.children) {
traversal(node.children)
}
if (isBlock && text[text.length - 1] !== '\n') {
text += '\n'
} else if (node.name === 'td' || node.name === 'th') {
text += '\t'
}
}
}
})(nodes || this.nodes)
return text
},
/**
* @description 获取内容大小和位置
* @return {Promise}
*/
getRect () {
return new Promise((resolve, reject) => {
uni.createSelectorQuery()
// #ifndef MP-ALIPAY
.in(this)
// #endif
.select('#_root').boundingClientRect().exec(res => res[0] ? resolve(res[0]) : reject(Error('Root label not found')))
})
},
/**
* @description 暂停播放媒体
*/
pauseMedia () {
for (let i = (this._videos || []).length; i--;) {
this._videos[i].pause()
}
// #ifdef APP-PLUS
const command = 'for(var e=document.getElementsByTagName("video"),i=e.length;i--;)e[i].pause()'
// #ifndef APP-PLUS-NVUE
let page = this.$parent
while (!page.$scope) page = page.$parent
page.$scope.$getAppWebview().evalJS(command)
// #endif
// #ifdef APP-PLUS-NVUE
this.$refs.web.evalJs(command)
// #endif
// #endif
},
/**
* @description 设置媒体播放速率
* @param {Number} rate 播放速率
*/
setPlaybackRate (rate) {
this.playbackRate = rate
for (let i = (this._videos || []).length; i--;) {
this._videos[i].playbackRate(rate)
}
// #ifdef APP-PLUS
const command = 'for(var e=document.getElementsByTagName("video"),i=e.length;i--;)e[i].playbackRate=' + rate
// #ifndef APP-PLUS-NVUE
let page = this.$parent
while (!page.$scope) page = page.$parent
page.$scope.$getAppWebview().evalJS(command)
// #endif
// #ifdef APP-PLUS-NVUE
this.$refs.web.evalJs(command)
// #endif
// #endif
},
/**
* @description 设置内容
* @param {String} content html 内容
* @param {Boolean} append 是否在尾部追加
*/
setContent (content, append) {
if (!append || !this.imgList) {
this.imgList = []
}
const nodes = new Parser(this).parse(content)
// #ifdef APP-PLUS-NVUE
if (this._ready) {
this._set(nodes, append)
}
// #endif
this.$set(this, 'nodes', append ? (this.nodes || []).concat(nodes) : nodes)
// #ifndef APP-PLUS-NVUE
this._videos = []
this.$nextTick(() => {
this._hook('onLoad')
this.$emit('load')
})
if (this.lazyLoad || this.imgList._unloadimgs < this.imgList.length / 2) {
// 设置懒加载,每 350ms 获取高度,不变则认为加载完毕
let height
const callback = rect => {
// 350ms 总高度无变化就触发 ready 事件
if (rect.height === height) {
this.$emit('ready', rect)
} else {
height = rect.height
setTimeout(() => {
this.getRect().then(callback)
}, 350)
}
}
this.getRect().then(callback)
} else {
// 未设置懒加载,等待所有图片加载完毕
if (!this.imgList._unloadimgs) {
this.getRect(rect => {
this.$emit('ready', rect)
})
}
}
// #endif
},
/**
* @description 调用插件钩子函数
*/
_hook (name) {
for (let i = plugins.length; i--;) {
if (this.plugins[i][name]) {
this.plugins[i][name]()
}
}
},
// #ifdef APP-PLUS-NVUE
/**
* @description 设置内容
*/
_set (nodes, append) {
this.$refs.web.evalJs('setContent(' + JSON.stringify(nodes) + ',' + JSON.stringify([this.containerStyle.replace(/(?:margin|padding)[^;]+/g, ''), this.errorImg, this.loadingImg, this.pauseVideo, this.scrollTable, this.selectable]) + ',' + append + ')')
},
/**
* @description 接收到 web-view 消息
*/
_onMessage (e) {
const message = e.detail.data[0]
switch (message.action) {
// web-view 初始化完毕
case 'onJSBridgeReady':
this._ready = true
if (this.nodes) {
this._set(this.nodes)
}
break
// 内容 dom 加载完毕
case 'onLoad':
this.height = message.height
this._hook('onLoad')
this.$emit('load')
break
// 所有图片加载完毕
case 'onReady':
this.getRect().then(res => {
this.$emit('ready', res)
}).catch(() => { })
break
// 总高度发生变化
case 'onHeightChange':
this.height = message.height
break
// 图片点击
case 'onImgTap':
this.$emit('imgtap', message.attrs)
if (this.previewImg) {
uni.previewImage({
current: parseInt(message.attrs.i),
urls: this.imgList
})
}
break
// 链接点击
case 'onLinkTap': {
const href = message.attrs.href
this.$emit('linktap', message.attrs)
if (href) {
// 锚点跳转
if (href[0] === '#') {
if (this.useAnchor) {
dom.scrollToElement(this.$refs.web, {
offset: message.offset
})
}
} else if (href.includes('://')) {
// 打开外链
if (this.copyLink) {
plus.runtime.openWeb(href)
}
} else {
uni.navigateTo({
url: href,
fail () {
uni.switchTab({
url: href
})
}
})
}
}
break
}
case 'onPlay':
this.$emit('play')
break
// 获取到锚点的偏移量
case 'getOffset':
if (typeof message.offset === 'number') {
dom.scrollToElement(this.$refs.web, {
offset: message.offset + this._navigateTo.offset
})
this._navigateTo.resolve()
} else {
this._navigateTo.reject(Error('Label not found'))
}
break
// 点击
case 'onClick':
this.$emit('tap')
this.$emit('click')
break
// 出错
case 'onError':
this.$emit('error', {
source: message.source,
attrs: message.attrs
})
}
}
// #endif
}
}
</script>
<style>
/* #ifndef APP-PLUS-NVUE */
/* 根节点样式 */
._root {
padding: 1px 0;
overflow-x: auto;
overflow-y: hidden;
-webkit-overflow-scrolling: touch;
}
/* 长按复制 */
._select {
user-select: text;
}
/* #endif */
/* 提示条 */
._tooltip_contain {
position: absolute;
right: 20px;
left: 20px;
text-align: center;
}
._tooltip {
box-sizing: border-box;
display: inline-block;
width: auto;
max-width: 100%;
height: 30px;
padding: 0 3px;
overflow: scroll;
font-size: 14px;
line-height: 30px;
white-space: nowrap;
}
._tooltip_item {
display: inline-block;
width: auto;
padding: 0 2vw;
line-height: 30px;
background-color: black;
color: white;
}
/* 图片宽度滚动条 */
._slider {
position: absolute;
left: 20px;
width: 220px;
}
._tooltip,
._slider {
background-color: black;
border-radius: 3px;
opacity: 0.75;
}
</style>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,129 @@
/**
* @fileoverview style 插件
*/
// #ifndef APP-PLUS-NVUE
import Parser from './parser'
// #endif
function Style () {
this.styles = []
}
// #ifndef APP-PLUS-NVUE
Style.prototype.onParse = function (node, vm) {
// 获取样式
if (node.name === 'style' && node.children.length && node.children[0].type === 'text') {
this.styles = this.styles.concat(new Parser().parse(node.children[0].text))
} else if (node.name) {
// 匹配样式(对非文本标签)
// 存储不同优先级的样式 name < class < id < 后代
let matched = ['', '', '', '']
for (let i = 0, len = this.styles.length; i < len; i++) {
const item = this.styles[i]
let res = match(node, item.key || item.list[item.list.length - 1])
let j
if (res) {
// 后代选择器
if (!item.key) {
j = item.list.length - 2
for (let k = vm.stack.length; j >= 0 && k--;) {
// 子选择器
if (item.list[j] === '>') {
// 错误情况
if (j < 1 || j > item.list.length - 2) break
if (match(vm.stack[k], item.list[j - 1])) {
j -= 2
} else {
j++
}
} else if (match(vm.stack[k], item.list[j])) {
j--
}
}
res = 4
}
if (item.key || j < 0) {
// 添加伪类
if (item.pseudo && node.children) {
let text
item.style = item.style.replace(/content:([^;]+)/, (_, $1) => {
text = $1.replace(/['"]/g, '')
// 处理 attr 函数
.replace(/attr\((.+?)\)/, (_, $1) => node.attrs[$1.trim()] || '')
// 编码 \xxx
.replace(/\\(\w{4})/, (_, $1) => String.fromCharCode(parseInt($1, 16)))
return ''
})
const pseudo = {
name: 'span',
attrs: {
style: item.style
},
children: [{
type: 'text',
text
}]
}
if (item.pseudo === 'before') {
node.children.unshift(pseudo)
} else {
node.children.push(pseudo)
}
} else {
matched[res - 1] += item.style + (item.style[item.style.length - 1] === ';' ? '' : ';')
}
}
}
}
matched = matched.join('')
if (matched.length > 2) {
node.attrs.style = matched + (node.attrs.style || '')
}
}
}
/**
* @description 匹配样式
* @param {object} node 要匹配的标签
* @param {string|string[]} keys 选择器
* @returns {number} 0:不匹配;1:name 匹配;2:class 匹配;3:id 匹配
*/
function match (node, keys) {
function matchItem (key) {
if (key[0] === '#') {
// 匹配 id
if (node.attrs.id && node.attrs.id.trim() === key.substr(1)) return 3
} else if (key[0] === '.') {
// 匹配 class
key = key.substr(1)
const selectors = (node.attrs.class || '').split(' ')
for (let i = 0; i < selectors.length; i++) {
if (selectors[i].trim() === key) return 2
}
} else if (node.name === key) {
// 匹配 name
return 1
}
return 0
}
// 多选择器交集
if (keys instanceof Array) {
let res = 0
for (let j = 0; j < keys.length; j++) {
const tmp = matchItem(keys[j])
// 任意一个不匹配就失败
if (!tmp) return 0
// 优先级最大的一个作为最终优先级
if (tmp > res) {
res = tmp
}
}
return res
}
return matchItem(keys)
}
// #endif
export default Style
@@ -0,0 +1,175 @@
const blank = {
' ': true,
'\n': true,
'\t': true,
'\r': true,
'\f': true
}
function Parser () {
this.styles = []
this.selectors = []
}
/**
* @description 解析 css 字符串
* @param {string} content css 内容
*/
Parser.prototype.parse = function (content) {
new Lexer(this).parse(content)
return this.styles
}
/**
* @description 解析到一个选择器
* @param {string} name 名称
*/
Parser.prototype.onSelector = function (name) {
// 不支持的选择器
if (name.includes('[') || name.includes('*') || name.includes('@')) return
const selector = {}
// 伪类
if (name.includes(':')) {
const info = name.split(':')
const pseudo = info.pop()
if (pseudo === 'before' || pseudo === 'after') {
selector.pseudo = pseudo
name = info[0]
} else return
}
// 分割交集选择器
function splitItem (str) {
const arr = []
let i, start
for (i = 1, start = 0; i < str.length; i++) {
if (str[i] === '.' || str[i] === '#') {
arr.push(str.substring(start, i))
start = i
}
}
if (!arr.length) {
return str
} else {
arr.push(str.substring(start, i))
return arr
}
}
// 后代选择器
if (name.includes(' ')) {
selector.list = []
const list = name.split(' ')
for (let i = 0; i < list.length; i++) {
if (list[i].length) {
// 拆分子选择器
const arr = list[i].split('>')
for (let j = 0; j < arr.length; j++) {
selector.list.push(splitItem(arr[j]))
if (j < arr.length - 1) {
selector.list.push('>')
}
}
}
}
} else {
selector.key = splitItem(name)
}
this.selectors.push(selector)
}
/**
* @description 解析到选择器内容
* @param {string} content 内容
*/
Parser.prototype.onContent = function (content) {
// 并集选择器
for (let i = 0; i < this.selectors.length; i++) {
this.selectors[i].style = content
}
this.styles = this.styles.concat(this.selectors)
this.selectors = []
}
/**
* @description css 词法分析器
* @param {object} handler 高层处理器
*/
function Lexer (handler) {
this.selector = ''
this.style = ''
this.handler = handler
}
Lexer.prototype.parse = function (content) {
this.i = 0
this.content = content
this.state = this.blank
for (let len = content.length; this.i < len; this.i++) {
this.state(content[this.i])
}
}
Lexer.prototype.comment = function () {
this.i = this.content.indexOf('*/', this.i) + 1
if (!this.i) {
this.i = this.content.length
}
}
Lexer.prototype.blank = function (c) {
if (!blank[c]) {
if (c === '/' && this.content[this.i + 1] === '*') {
this.comment()
return
}
this.selector += c
this.state = this.name
}
}
Lexer.prototype.name = function (c) {
if (c === '/' && this.content[this.i + 1] === '*') {
this.comment()
return
}
if (c === '{' || c === ',' || c === ';') {
this.handler.onSelector(this.selector.trimEnd())
this.selector = ''
if (c !== '{') {
while (blank[this.content[++this.i]]);
}
if (this.content[this.i] === '{') {
this.floor = 1
this.state = this.val
} else {
this.selector += this.content[this.i]
}
} else if (blank[c]) {
this.selector += ' '
} else {
this.selector += c
}
}
Lexer.prototype.val = function (c) {
if (c === '/' && this.content[this.i + 1] === '*') {
this.comment()
return
}
if (c === '{') {
this.floor++
} else if (c === '}') {
this.floor--
if (!this.floor) {
this.handler.onContent(this.style)
this.style = ''
this.state = this.blank
return
}
}
this.style += c
}
export default Parser
@@ -0,0 +1 @@
"use strict";function t(t){for(var e=Object.create(null),n=t.attributes.length;n--;)e[t.attributes[n].name]=t.attributes[n].value;return e}function e(){a[1]&&(this.src=a[1],this.onerror=null),this.onclick=null,this.ontouchstart=null,uni.postMessage({data:{action:"onError",source:"img",attrs:t(this)}})}function n(){window.unloadimgs-=1,0===window.unloadimgs&&uni.postMessage({data:{action:"onReady"}})}function o(r,s,c){for(var d=0;d<r.length;d++)!function(d){var u=r[d],l=void 0;if(u.type&&"node"!==u.type)l=document.createTextNode(u.text.replace(/&amp;/g,"&"));else{var g=u.name;"svg"===g&&(c="http://www.w3.org/2000/svg"),"html"!==g&&"body"!==g||(g="div"),l=c?document.createElementNS(c,g):document.createElement(g);for(var p in u.attrs)l.setAttribute(p,u.attrs[p]);if(u.children&&o(u.children,l,c),"img"===g){if(window.unloadimgs+=1,l.onload=n,l.onerror=n,!l.src&&l.getAttribute("data-src")&&(l.src=l.getAttribute("data-src")),u.attrs.ignore||(l.onclick=function(e){e.stopPropagation(),uni.postMessage({data:{action:"onImgTap",attrs:t(this)}})}),a[2]){var h=new Image;h.src=l.src,l.src=a[2],h.onload=function(){l.src=this.src},h.onerror=function(){l.onerror()}}l.onerror=e}else if("a"===g)l.addEventListener("click",function(e){e.stopPropagation(),e.preventDefault();var n,o=this.getAttribute("href");o&&"#"===o[0]&&(n=(document.getElementById(o.substr(1))||{}).offsetTop),uni.postMessage({data:{action:"onLinkTap",attrs:t(this),offset:n}})},!0);else if("video"===g||"audio"===g)i.push(l),u.attrs.autoplay||u.attrs.controls||l.setAttribute("controls","true"),l.onplay=function(){if(uni.postMessage({data:{action:"onPlay"}}),a[3])for(var t=0;t<i.length;t++)i[t]!==this&&i[t].pause()},l.onerror=function(){uni.postMessage({data:{action:"onError",source:g,attrs:t(this)}})};else if("table"===g&&a[4]&&!l.style.cssText.includes("inline")){var f=document.createElement("div");f.style.overflow="auto",f.appendChild(l),l=f}else"svg"===g&&(c=void 0)}s.appendChild(l)}(d)}document.addEventListener("UniAppJSBridgeReady",function(){document.body.onclick=function(){return uni.postMessage({data:{action:"onClick"}})},uni.postMessage({data:{action:"onJSBridgeReady"}})});var a,i=[];window.setContent=function(t,e,n){var r=document.getElementById("content");e[0]&&(document.body.style.cssText=e[0]),e[5]||(r.style.userSelect="none"),n||(r.innerHTML="",i=[]),a=e,window.unloadimgs=0;var s=document.createDocumentFragment();o(t,s),r.appendChild(s);var c=r.scrollHeight;uni.postMessage({data:{action:"onLoad",height:c}}),window.unloadimgs||uni.postMessage({data:{action:"onReady",height:c}}),clearInterval(window.timer),window.timer=setInterval(function(){r.scrollHeight!==c&&(c=r.scrollHeight,uni.postMessage({data:{action:"onHeightChange",height:c}}))},350)},window.onunload=function(){clearInterval(window.timer)};
@@ -0,0 +1 @@
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e=e||self).uni=n()}(this,(function(){"use strict";try{var e={};Object.defineProperty(e,"passive",{get:function(){!0}}),window.addEventListener("test-passive",null,e)}catch(e){}var n=Object.prototype.hasOwnProperty;function t(e,t){return n.call(e,t)}var i=[],a=function(e,n){var t={options:{timestamp:+new Date},name:e,arg:n};if(window.__dcloud_weex_postMessage||window.__dcloud_weex_){if("postMessage"===e){var a={data:[n]};return window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessage(a):window.__dcloud_weex_.postMessage(JSON.stringify(a))}var o={type:"WEB_INVOKE_APPSERVICE",args:{data:t,webviewIds:i}};window.__dcloud_weex_postMessage?window.__dcloud_weex_postMessageToService(o):window.__dcloud_weex_.postMessageToService(JSON.stringify(o))}if(!window.plus)return window.parent.postMessage({type:"WEB_INVOKE_APPSERVICE",data:t,pageId:""},"*");if(0===i.length){var r=plus.webview.currentWebview();if(!r)throw new Error("plus.webview.currentWebview() is undefined");var d=r.parent(),s="";s=d?d.id:r.id,i.push(s)}if(plus.webview.getWebviewById("__uniapp__service"))plus.webview.postMessageToUniNView({type:"WEB_INVOKE_APPSERVICE",args:{data:t,webviewIds:i}},"__uniapp__service");else{var w=JSON.stringify(t);plus.webview.getLaunchWebview().evalJS('UniPlusBridge.subscribeHandler("'.concat("WEB_INVOKE_APPSERVICE",'",').concat(w,",").concat(JSON.stringify(i),");"))}},o={navigateTo:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;a("navigateTo",{url:encodeURI(n)})},navigateBack:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.delta;a("navigateBack",{delta:parseInt(n)||1})},switchTab:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;a("switchTab",{url:encodeURI(n)})},reLaunch:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;a("reLaunch",{url:encodeURI(n)})},redirectTo:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.url;a("redirectTo",{url:encodeURI(n)})},getEnv:function(e){window.plus?e({plus:!0}):e({h5:!0})},postMessage:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};a("postMessage",e.data||{})}},r=/uni-app/i.test(navigator.userAgent),d=/Html5Plus/i.test(navigator.userAgent),s=/complete|loaded|interactive/;var w=window.my&&navigator.userAgent.indexOf("AlipayClient")>-1;var u=window.swan&&window.swan.webView&&/swan/i.test(navigator.userAgent);var c=window.qq&&window.qq.miniProgram&&/QQ/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var g=window.tt&&window.tt.miniProgram&&/toutiaomicroapp/i.test(navigator.userAgent);var v=window.wx&&window.wx.miniProgram&&/micromessenger/i.test(navigator.userAgent)&&/miniProgram/i.test(navigator.userAgent);var p=window.qa&&/quickapp/i.test(navigator.userAgent);for(var l,_=function(){window.UniAppJSBridge=!0,document.dispatchEvent(new CustomEvent("UniAppJSBridgeReady",{bubbles:!0,cancelable:!0}))},f=[function(e){if(r||d)return window.__dcloud_weex_postMessage||window.__dcloud_weex_?document.addEventListener("DOMContentLoaded",e):window.plus&&s.test(document.readyState)?setTimeout(e,0):document.addEventListener("plusready",e),o},function(e){if(v)return window.WeixinJSBridge&&window.WeixinJSBridge.invoke?setTimeout(e,0):document.addEventListener("WeixinJSBridgeReady",e),window.wx.miniProgram},function(e){if(c)return window.QQJSBridge&&window.QQJSBridge.invoke?setTimeout(e,0):document.addEventListener("QQJSBridgeReady",e),window.qq.miniProgram},function(e){if(w){document.addEventListener("DOMContentLoaded",e);var n=window.my;return{navigateTo:n.navigateTo,navigateBack:n.navigateBack,switchTab:n.switchTab,reLaunch:n.reLaunch,redirectTo:n.redirectTo,postMessage:n.postMessage,getEnv:n.getEnv}}},function(e){if(u)return document.addEventListener("DOMContentLoaded",e),window.swan.webView},function(e){if(g)return document.addEventListener("DOMContentLoaded",e),window.tt.miniProgram},function(e){if(p){window.QaJSBridge&&window.QaJSBridge.invoke?setTimeout(e,0):document.addEventListener("QaJSBridgeReady",e);var n=window.qa;return{navigateTo:n.navigateTo,navigateBack:n.navigateBack,switchTab:n.switchTab,reLaunch:n.reLaunch,redirectTo:n.redirectTo,postMessage:n.postMessage,getEnv:n.getEnv}}},function(e){return document.addEventListener("DOMContentLoaded",e),o}],m=0;m<f.length&&!(l=f[m](_));m++);l||(l={});var E="undefined"!=typeof uni?uni:{};if(!E.navigateTo)for(var b in l)t(l,b)&&(E[b]=l[b]);return E.webView=l,E}));
@@ -0,0 +1 @@
<style>.hl-code,.hl-pre{color:#ccc;background:0 0;font-family:Consolas,Monaco,'Andale Mono','Ubuntu Mono',monospace;font-size:1em;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}.hl-pre{padding:1em;margin:.5em 0;overflow:auto}.hl-pre{background:#2d2d2d}.hl-block-comment,.hl-cdata,.hl-comment,.hl-doctype,.hl-prolog{color:#999}.hl-punctuation{color:#ccc}.hl-attr-name,.hl-deleted,.hl-namespace,.hl-tag{color:#e2777a}.hl-function-name{color:#6196cc}.hl-boolean,.hl-function,.hl-number{color:#f08d49}.hl-class-name,.hl-constant,.hl-property,.hl-symbol{color:#f8c555}.hl-atrule,.hl-builtin,.hl-important,.hl-keyword,.hl-selector{color:#cc99cd}.hl-attr-value,.hl-char,.hl-regex,.hl-string,.hl-variable{color:#7ec699}.hl-entity,.hl-operator,.hl-url{color:#67cdcc}.hl-bold,.hl-important{font-weight:700}.hl-italic{font-style:italic}.hl-entity{cursor:help}.hl-inserted{color:green}</style><style>.md-p{margin-block-start:1em;margin-block-end:1em}.md-blockquote,.md-table{margin-bottom:16px}.md-table{box-sizing:border-box;width:100%;overflow:auto;border-spacing:0;border-collapse:collapse}.md-tr{background-color:#fff;border-top:1px solid #c6cbd1}.md-table .md-tr:nth-child(2n){background-color:#f6f8fa}.md-td,.md-th{padding:6px 13px!important;border:1px solid #dfe2e5}.md-th{font-weight:600}.md-blockquote{padding:0 1em;color:#6a737d;border-left:.25em solid #dfe2e5}.md-code{padding:.2em .4em;font-family:SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace;font-size:85%;background-color:rgba(27,31,35,.05);border-radius:3px}.md-pre .md-code{padding:0;font-size:100%;background:0 0;border:0}.hl-pre{position:relative}.hl-code{overflow:auto;display:block}.hl-language{font-size:12px;font-weight:600;position:absolute;right:8px;text-align:right;top:3px}.hl-pre{padding-top:1.5em}.hl-pre{font-size:14px;padding-left:3.8em;counter-reset:linenumber}.line-numbers-rows{position:absolute;pointer-events:none;top:1.5em;font-size:100%;left:0;width:3em;letter-spacing:-1px;border-right:1px solid #999;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.line-numbers-rows .span{display:block;counter-increment:linenumber}.line-numbers-rows .span:before{content:counter(linenumber);color:#999;display:block;padding-right:.8em;text-align:right}._address,._article,._aside,._body,._caption,._center,._cite,._footer,._header,._html,._nav,._pre,._section{display:block}._video{width:300px;height:225px;display:inline-block;background-color:#000}</style><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"><style>body,html{width:100%;height:100%;overflow-x:scroll;overflow-y:hidden}body{margin:0}video{width:300px;height:225px}img{max-width:100%;-webkit-touch-callout:none}</style></head><body><div id="content" style="overflow:hidden"></div><script type="text/javascript" src="./js/uni.webview.min.js"></script><script type="text/javascript" src="./js/handler.js"></script></body>
@@ -0,0 +1,166 @@
<script lang="ts" setup>
/**
* 相册图片查看弹窗(源自旧项目 components/album-photo-viewer,新建复刻)
* 双列瀑布流展示相册照片,支持大图预览
*/
import { computed, ref, watch } from 'vue'
import { checkImageUrl } from '@/utils/url'
const props = withDefaults(defineProps<{
show: boolean
albumName?: string
photos?: IAlbumPhoto[]
loading?: boolean
}>(), {
albumName: '',
photos: () => [],
loading: false,
})
const emit = defineEmits<{
(e: 'update:show', show: boolean): void
}>()
export interface IAlbumPhoto {
name?: string
url?: string
title?: string
takenDate?: string
location?: string
description?: string
[key: string]: unknown
}
const isShow = ref(false)
watch(() => props.show, (val) => {
isShow.value = val
})
/** 预处理图片路径(相对路径拼接 BASE_API) */
const photoList = computed<IAlbumPhoto[]>(() =>
(props.photos || []).map(photo => ({
...photo,
url: checkImageUrl(photo.url || ''),
})),
)
/** 左列(偶数位照片,瀑布流错落) */
const leftPhotos = computed(() => photoList.value.filter((_, index) => index % 2 === 0))
/** 右列(奇数位照片) */
const rightPhotos = computed(() => photoList.value.filter((_, index) => index % 2 === 1))
function handleClose() {
isShow.value = false
emit('update:show', false)
}
/** 预览大图 */
function handlePreview(url?: string) {
const urls = photoList.value.map(photo => photo.url || '')
if (urls.length === 0) {
uni.showToast({ title: '相册暂无照片', icon: 'none' })
return
}
uni.previewImage({
current: url || urls[0],
urls,
})
}
</script>
<template>
<wd-popup v-model="isShow" position="center" custom-style="width:94vw;height:82vh;border-radius:12rpx;" @close="handleClose">
<view class="album-photo-viewer h-full w-full flex flex-col overflow-hidden rounded-xl bg-white">
<!-- 头部 -->
<view class="viewer-header box-border flex shrink-0 items-center justify-between border-b border-black/5 px-7 py-6">
<text class="viewer-title flex-1 overflow-hidden text-ellipsis whitespace-nowrap text-[32rpx] text-[#333] font-bold">{{ albumName }}</text>
<view class="viewer-close h-14 w-14 flex shrink-0 items-center justify-center rounded-full bg-black/5" @click="handleClose">
<wd-icon name="close" size="16px" color="#666" />
</view>
</view>
<!-- 照片列表 -->
<scroll-view class="viewer-body box-border min-h-0 flex-1" scroll-y :show-scrollbar="false">
<view v-if="loading" class="viewer-empty box-border h-full flex items-center justify-center p-10">
<view class="viewer-loading flex flex-col items-center">
<view class="loading-text mt-7 text-[28rpx] text-[#56bbf9]">
照片正在努力加载中啦~
</view>
</view>
</view>
<view v-else-if="photoList.length === 0" class="viewer-empty box-border h-full flex items-center justify-center p-10">
<wd-empty description="这个相册暂时还没有照片~" />
</view>
<view v-else class="photo-list box-border flex items-start p-5">
<!-- 左列 -->
<view class="photo-column box-border min-w-0 flex-1">
<view v-for="photo in leftPhotos" :key="photo.name" class="photo-card mb-6 box-border overflow-hidden rounded-xl bg-white shadow-sm">
<image
class="photo-image w-full"
:src="photo.url"
mode="widthFix"
lazy-load
@click="handlePreview(photo.url)"
/>
<view class="photo-info box-border px-6 py-5">
<view v-if="photo.title" class="photo-title mb-3 text-[30rpx] text-[#333] font-bold">
{{ photo.title }}
</view>
<view v-if="photo.takenDate || photo.location" class="photo-meta mb-3 flex flex-wrap items-center">
<text v-if="photo.takenDate" class="meta-item mr-8 text-[24rpx] text-[#999]">{{ photo.takenDate }}</text>
<text v-if="photo.location" class="meta-item mr-8 text-[24rpx] text-[#999]">{{ photo.location }}</text>
</view>
<view v-if="photo.description" class="photo-desc text-[26rpx] text-[#666] leading-[1.6]">
{{ photo.description }}
</view>
</view>
</view>
</view>
<!-- 右列 -->
<view class="photo-column box-border min-w-0 flex-1">
<view v-for="photo in rightPhotos" :key="photo.name" class="photo-card mb-6 box-border overflow-hidden rounded-xl bg-white shadow-sm">
<image
class="photo-image w-full"
:src="photo.url"
mode="widthFix"
lazy-load
@click="handlePreview(photo.url)"
/>
<view class="photo-info box-border px-6 py-5">
<view v-if="photo.title" class="photo-title mb-3 text-[30rpx] text-[#333] font-bold">
{{ photo.title }}
</view>
<view v-if="photo.takenDate || photo.location" class="photo-meta mb-3 flex flex-wrap items-center">
<text v-if="photo.takenDate" class="meta-item mr-8 text-[24rpx] text-[#999]">{{ photo.takenDate }}</text>
<text v-if="photo.location" class="meta-item mr-8 text-[24rpx] text-[#999]">{{ photo.location }}</text>
</view>
<view v-if="photo.description" class="photo-desc text-[26rpx] text-[#666] leading-[1.6]">
{{ photo.description }}
</view>
</view>
</view>
</view>
</view>
</scroll-view>
<!-- 底部关闭 -->
<view class="viewer-footer box-border shrink-0 border-t border-black/5 px-7 py-5">
<view class="viewer-footer-btn h-20 flex items-center justify-center rounded-[40rpx]" style="background: linear-gradient(135deg, #f88ca2, #ff6b9d); box-shadow: 0 4rpx 24rpx rgb(248 140 162 / 35%);" @click="handleClose">
<text class="footer-text text-[30rpx] text-white font-bold">关 闭</text>
</view>
</view>
</view>
</wd-popup>
</template>
<style scoped>
.album-photo-viewer {
/* 布局全部由 UnoCSS 原子类实现 */
.photo-column:first-child {
margin-right: 20rpx;
}
}
</style>
@@ -0,0 +1,107 @@
<script lang="ts" setup>
/**
* 相册密码解锁弹窗(源自旧项目 components/album-unlock-modal,新建复刻)
* 输入密码解锁加密相册
*/
import { ref, watch } from 'vue'
import { unlockAlbum } from '@/api/uni-halo'
const props = withDefaults(defineProps<{
show: boolean
albumName?: string
albumKey?: string
}>(), {
albumName: '',
albumKey: '',
})
const emit = defineEmits<{
(e: 'update:show', show: boolean): void
(e: 'success', data: { albumKey: string, token: string, photos: unknown[] }): void
}>()
const isShow = ref(false)
const password = ref('')
const loading = ref(false)
watch(() => props.show, (val) => {
isShow.value = val
})
function handleOnCancel() {
password.value = ''
isShow.value = false
emit('update:show', false)
}
async function handleOnConfirm() {
if (!password.value.trim()) {
uni.showToast({ title: '请输入密码', icon: 'none' })
return
}
loading.value = true
try {
const res = await unlockAlbum(props.albumKey, password.value)
if (res.data && (res.data as { token?: string }).token) {
password.value = ''
isShow.value = false
emit('update:show', false)
emit('success', {
albumKey: props.albumKey,
token: (res.data as { token: string }).token,
photos: (res.data as { photos?: unknown[] }).photos || [],
})
uni.showToast({ title: '解锁成功', icon: 'success' })
}
}
catch (e) {
console.error('解锁失败', e)
password.value = ''
uni.showToast({ title: '密码错误,请重试', icon: 'none' })
}
finally {
loading.value = false
}
}
</script>
<template>
<wd-dialog
v-model="isShow"
title="相册密码"
:show-cancel="true"
confirm-text="解锁"
confirm-button-color="#f88ca2"
@cancel="handleOnCancel"
@confirm="handleOnConfirm"
>
<view class="unlock-modal-content py-5">
<view class="album-info flex flex-col items-center">
<view class="lock-icon mb-5 text-[80rpx]">
🔒
</view>
<view class="album-name mb-3 text-[32rpx] text-[#333] font-bold">
{{ albumName }}
</view>
<view class="tip-text text-[26rpx] text-[#999]">
此相册已加密,请输入密码查看
</view>
</view>
<wd-input
v-model="password"
:password="true"
placeholder="请输入相册密码"
align="center"
clearable
class="password-input mt-9"
/>
</view>
</wd-dialog>
</template>
<style scoped>
.unlock-modal-content {
/* 布局全部由 UnoCSS 原子类实现 */
}
</style>
@@ -0,0 +1,339 @@
<script lang="ts" setup>
/**
* 文章卡片(源自旧项目 components/article-card,新建复刻)
* 支持布局:左图右文(lr_image_text)/左文右图(lr_text_image)/上图下文(tb_image_text)/上文下图(tb_text_image)/仅文字(only_text)
*/
import { computed } from 'vue'
import dayjs from 'dayjs'
import { checkThumbnailUrl } from '@/utils/url'
import { useSettingStore } from '@/store/setting'
import type { IPost } from '@/api/types/halo'
const props = withDefaults(defineProps<{
/** 来源页面(home 时跟随首页布局) */
from?: string
article: IPost
}>(), {
from: '',
})
const emit = defineEmits<{
(e: 'on-click', article: IPost): void
}>()
const settingStore = useSettingStore()
/** 卡片布局 class(由全局设置 layout 决定) */
const cardType = computed(() => {
const layout = settingStore.settings.layout
// 首页双列时强制上图下文布局,除非显式指定其他
if (props.from === 'home' && layout.home === 'h_row_col2') {
if (!['tb_image_text', 'tb_text_image', 'only_text'].includes(layout.cardType)) {
return [props.from, layout.home, 'tb_image_text']
}
return [props.from, layout.home, layout.cardType]
}
return [layout.home, layout.cardType]
})
/** 发布时间格式化 yyyy-MM-dd */
const publishTimeText = computed(() => {
const time = props.article.spec.publishTime
return time ? dayjs(time).format('YYYY-MM-DD') : ''
})
/** 阅读数(兼容 status.stats.visits 与旧版顶层 stats.visit) */
const visitCount = computed(() => {
return props.article.status?.stats?.visits ?? props.article.stats?.visit ?? 0
})
function handleClick() {
emit('on-click', props.article)
}
</script>
<template>
<view class="uh-article-card mb-3 flex overflow-hidden rounded-xl bg-white p-2.5 shadow-sm" :class="cardType" @click="handleClick">
<view class="left">
<image class="thumbnail" :src="checkThumbnailUrl(article.spec.cover)" mode="aspectFill" lazy-load />
</view>
<view class="right">
<view class="title">
<text v-if="article.spec.pinned" class="is-top">置顶</text>
<text class="title-text text-overflow">{{ article.spec.title }}</text>
</view>
<view class="content text-overflow-2">
{{ article.status?.excerpt }}
</view>
<view class="foot">
<view class="create-time">
<text class="time-label">发布时间:</text>
{{ publishTimeText }}
</view>
<view class="visits">
浏览
<text class="number">{{ visitCount }}</text>
次
</view>
</view>
</view>
</view>
</template>
<style scoped lang="scss">
.uh-article-card {
box-sizing: border-box;
margin: 0 24rpx;
&.h_row_col1 {
align-items: center;
}
&.home.h_row_col2 {
margin: 12rpx;
.left {
width: 100%;
height: 200rpx;
.thumbnail :deep(uni-image) {
border-radius: 6rpx 6rpx 0 0 !important;
}
}
.right {
.title {
display: flex;
align-items: center;
font-size: 26rpx;
font-weight: bold;
.is-top {
height: 36rpx;
margin-right: 10rpx;
line-height: 36rpx;
transform: scale(0.9);
}
}
.foot {
justify-content: space-between;
.create-time {
font-size: 24rpx;
.time-label {
display: none;
}
}
.visits {
font-size: 24rpx;
margin-left: 0;
}
}
}
&.tb_text_image {
padding: 12rpx;
.left .thumbnail :deep(uni-image) {
border-radius: 6rpx !important;
}
}
&.only_text {
padding: 24rpx;
.right .foot {
.create-time .time-label {
display: none;
}
.visits {
font-size: 24rpx;
}
}
}
}
&.lr_text_image {
.left {
order: 2;
padding-left: 30rpx;
}
.right {
order: 1;
padding-left: 0;
}
}
&.tb_image_text {
flex-direction: column;
padding: 24rpx;
.left {
width: 100%;
height: 340rpx;
.thumbnail :deep(uni-image) {
border-radius: 6rpx 6rpx 0 0 !important;
}
}
.right {
padding-left: 0;
padding: 24rpx 0 0;
width: 100%;
.foot {
justify-content: flex-start;
.create-time .time-label {
display: inline-block;
}
.visits {
margin-left: 24rpx;
}
}
}
}
&.tb_text_image {
flex-direction: column;
.left {
width: 100%;
height: 340rpx;
order: 2;
margin-top: 24rpx;
}
.right {
padding-left: 0;
width: 100%;
order: 1;
.foot {
justify-content: flex-start;
.create-time .time-label {
display: inline-block;
}
.visits {
margin-left: 24rpx;
}
}
}
}
&.only_text {
padding: 36rpx;
.left {
display: none;
}
.right {
padding-left: 0;
.content {
margin-top: 24rpx;
}
.foot {
justify-content: flex-start;
margin-top: 24rpx;
.create-time .time-label {
display: inline-block;
}
.visits {
margin-left: 24rpx;
}
}
}
}
.left {
width: 240rpx;
height: 180rpx;
.thumbnail {
width: 100%;
height: 100%;
border-radius: 12rpx;
}
}
.right {
width: 0;
flex-grow: 1;
display: flex;
flex-direction: column;
padding-left: 30rpx;
box-sizing: border-box;
.title {
display: flex;
align-items: center;
font-size: 30rpx;
.is-top {
height: 40rpx;
padding: 0 12rpx;
margin-right: 10rpx;
line-height: 40rpx;
font-size: 24rpx;
white-space: nowrap;
vertical-align: 4rpx;
color: #fff;
background-color: rgba(33, 150, 243, 1);
border-radius: 6rpx 12rpx;
}
&-text {
color: #303133;
}
}
.content {
display: -webkit-box;
font-size: 26rpx;
color: #909399;
height: 80rpx;
margin-top: 14rpx;
line-height: 42rpx;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.foot {
display: flex;
font-size: 24rpx;
justify-content: space-between;
align-items: center;
color: #909399;
margin-top: 18rpx;
.create-time {
font-size: 26rpx;
.time-label {
display: none;
}
}
.visits .number {
padding: 0 6rpx;
font-size: 26rpx;
}
}
}
}
</style>
@@ -0,0 +1,118 @@
<script lang="ts" setup>
/**
* 文章迷你卡片(源自旧项目 components/article-min-card,新建复刻)
* 用于分类页 list-post 视图的文章列表
*/
import { computed } from 'vue'
import dayjs from 'dayjs'
import { checkThumbnailUrl } from '@/utils/url'
import type { IPost } from '@/api/types/halo'
const props = defineProps<{
article: IPost
}>()
const emit = defineEmits<{
(e: 'on-click', article: IPost): void
}>()
const publishTimeText = computed(() => {
const time = props.article.spec.publishTime
return time ? dayjs(time).format('YYYY-MM-DD') : ''
})
const visitCount = computed(() => {
return props.article.status?.stats?.visits ?? props.article.stats?.visit ?? 0
})
function handleClick() {
emit('on-click', props.article)
}
</script>
<template>
<view class="uh-article-min-card mx-6 mb-6 flex overflow-hidden rounded-xl bg-white p-2 shadow-sm" @click="handleClick">
<view class="left">
<image class="thumbnail" :src="checkThumbnailUrl(article.spec.cover)" mode="aspectFill" lazy-load />
</view>
<view class="right">
<view class="title text-overflow">
{{ article.spec.title }}
</view>
<view class="content text-overflow">
{{ article.status?.excerpt }}
</view>
<view class="foot">
<view class="create-time">
<text class="time-label">发布时间:</text>
{{ publishTimeText }}
</view>
<view class="visits">
浏览
<text class="number">{{ visitCount }}</text>
次
</view>
</view>
</view>
</view>
</template>
<style scoped lang="scss">
.uh-article-min-card {
box-sizing: border-box;
box-shadow: 0 2rpx 24rpx rgb(0 0 0 / 3%);
.left {
width: 180rpx;
height: 130rpx;
.thumbnail {
width: 100%;
height: 100%;
border-radius: 12rpx;
}
}
.right {
width: 0;
flex-grow: 1;
display: flex;
flex-direction: column;
padding-left: 20rpx;
.title {
font-size: 28rpx;
font-weight: 600;
color: #303133;
}
.content {
font-size: 26rpx;
color: #909399;
margin-top: 14rpx;
}
.foot {
display: flex;
font-size: 24rpx;
justify-content: space-between;
align-items: center;
color: #909399;
margin-top: 14rpx;
.create-time {
font-size: 24rpx;
.time-label {
display: none;
}
}
.visits .number {
padding: 0 6rpx;
font-size: 24rpx;
}
}
}
}
</style>
@@ -0,0 +1,116 @@
<script lang="ts" setup>
/**
* 音频播放器(新建复刻,替代 uni 内置 <audio> 组件)
* 背景:新版 @dcloudio/uni-h5(3.0.0-4070+)已移除 Audio 组件导出,
* H5 端直接使用 <audio> 会编译报错(Cannot find module / Audio is not exported)。
* 本组件基于 uni.createInnerAudioContext 实现,跨端(H5/小程序/APP)一致,不依赖内置 audio 组件。
*/
import { onBeforeUnmount, onMounted, ref } from 'vue'
const props = defineProps<{
/** 音频地址 */
src: string
/** 封面图 */
poster?: string
/** 音频名称 */
name?: string
/** 作者 */
author?: string
}>()
const isPlaying = ref(false)
const progress = ref(0)
const duration = ref(0)
let audioContext: UniApp.InnerAudioContext | null = null
onMounted(() => {
if (!props.src)
return
audioContext = uni.createInnerAudioContext()
audioContext.src = props.src
audioContext.autoplay = false
audioContext.onTimeUpdate(() => {
if (audioContext?.duration) {
duration.value = audioContext.duration
progress.value = (audioContext.currentTime / audioContext.duration) * 100
}
})
audioContext.onPlay(() => {
isPlaying.value = true
})
audioContext.onPause(() => {
isPlaying.value = false
})
audioContext.onStop(() => {
isPlaying.value = false
progress.value = 0
})
audioContext.onEnded(() => {
isPlaying.value = false
progress.value = 0
})
audioContext.onError(() => {
isPlaying.value = false
uni.showToast({ icon: 'none', title: '音频加载失败' })
})
})
function handleTogglePlay() {
if (!audioContext)
return
if (isPlaying.value) {
audioContext.pause()
}
else {
audioContext.play()
}
}
function handleSeek(e: { detail: { value: number } }) {
if (!audioContext?.duration)
return
const percent = e.detail.value
audioContext.seek(percent / 100 * audioContext.duration)
progress.value = percent
}
onBeforeUnmount(() => {
audioContext?.destroy()
audioContext = null
})
</script>
<template>
<view class="uh-audio-player box-border flex w-full items-center gap-4 rounded-xl px-6 py-4" style="background-color: #f6f7f8;">
<!-- 播放/暂停按钮 -->
<view class="play-btn flex h-[72rpx] w-[72rpx] shrink-0 items-center justify-center rounded-full" style="background-color: #03a9f4;" @click="handleTogglePlay">
<view v-if="!isPlaying" class="play-icon ml-1 border-y-[16rpx] border-l-[24rpx] border-y-transparent border-l-white" />
<view v-else class="pause-icon flex gap-2">
<view class="h-[28rpx] w-[8rpx] rounded-sm bg-white" />
<view class="h-[28rpx] w-[8rpx] rounded-sm bg-white" />
</view>
</view>
<!-- 音频信息 + 进度条 -->
<view class="info flex min-w-0 flex-1 flex-col gap-2">
<view class="audio-name overflow-hidden text-ellipsis whitespace-nowrap text-[26rpx] text-[#333]">
{{ name || '音频' }}
</view>
<view class="flex items-center gap-3">
<text class="time text-[20rpx] text-[#999]">
{{ isPlaying ? '播放中' : (duration ? '已就绪' : '待播放') }}
</text>
<view class="progress-bar h-[8rpx] flex-1 overflow-hidden rounded-full" style="background-color: #e5e5e5;" @click="handleSeek">
<view class="progress-inner h-full rounded-full" style="background-color: #03a9f4; width: 0%;" :style="{ width: `${progress}%` }" />
</view>
</view>
</view>
</view>
</template>
@@ -0,0 +1,54 @@
<script lang="ts" setup>
/**
* 分类小卡片(源自旧项目 components/category-mini-card,新建复刻)
*/
import { computed } from 'vue'
import { checkThumbnailUrl } from '@/utils/url'
import type { ICategory } from '@/api/types/halo'
const props = defineProps<{
category: ICategory
}>()
const cover = computed(() => checkThumbnailUrl(props.category.spec.cover))
</script>
<template>
<view class="uh-category-mini-card relative inline-block h-[180rpx] w-[260rpx] overflow-hidden rounded-xl text-center text-white">
<image class="img" :src="cover" mode="aspectFill" lazy-load />
<view class="content absolute inset-0 z-3 flex flex-col items-center justify-center">
<view class="name text-[30rpx] font-bold">
{{ category.spec.displayName }}
</view>
<text class="label mt-1 text-[24rpx]">共 {{ category.postCount ?? 0 }} 篇</text>
</view>
</view>
</template>
<style scoped lang="scss">
.uh-category-mini-card {
background-color: #fff;
box-shadow: 0 2rpx 24rpx rgb(0 0 0 / 3%);
&::before {
content: '';
position: absolute;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgb(0 0 0 / 25%);
backdrop-filter: blur(3rpx);
}
.img {
width: 100%;
height: 100%;
}
.name {
color: inherit;
}
}
</style>
@@ -0,0 +1,157 @@
<script lang="ts" setup>
/**
* 评论条目(源自旧项目 components/comment-item,新建复刻)
*/
import { computed } from 'vue'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import { checkAvatarUrl } from '@/utils/url'
import { useSettingStore } from '@/store/setting'
import type { IComment } from '@/api/types/halo'
const props = withDefaults(defineProps<{
comment: IComment
isChild?: boolean
useActions?: boolean
useSolid?: boolean
useContentBg?: boolean
disallowComment?: boolean
postName?: string
classItem?: string[]
}>(), {
isChild: false,
useActions: true,
useSolid: true,
useContentBg: true,
disallowComment: false,
postName: '',
classItem: () => [],
})
const emit = defineEmits<{
(e: 'on-comment', data: { type: string, comment: IComment }): void
(e: 'on-copy', raw: string): void
(e: 'on-detail', comment: IComment): void
}>()
dayjs.extend(relativeTime)
dayjs.locale('zh-cn')
const settingStore = useSettingStore()
const globalAppSettings = computed(() => settingStore.settings)
const avatar = computed(() => checkAvatarUrl(props.comment.spec.owner.avatar))
/** 评论时间 */
const createTimeText = computed(() => {
const time = props.comment.spec.creationTime
return time ? dayjs(time).format('YYYY年MM月DD日') : ''
})
const createTimeAgo = computed(() => {
const time = props.comment.spec.creationTime
return time ? `${dayjs(time).fromNow(true)}前` : ''
})
function handleOnImageError() {
// 头像加载失败时回退默认头像(由 checkAvatarUrl 兜底,此处保持简单)
}
function handleOnCopy() {
emit('on-copy', props.comment.spec.raw)
}
function handleOnReply() {
emit('on-comment', { type: 'user', comment: props.comment })
}
function handleOnDetail() {
emit('on-detail', props.comment)
}
</script>
<template>
<view
v-if="comment"
class="comment-item mt-7 box-border flex flex-col pt-6"
:class="{ 'child-comment-item': isChild, 'no-solid': !useSolid, ...classItem }"
>
<view class="comment-item-user flex items-center">
<image
class="user-avatar box-border h-[70rpx] w-[70rpx] shrink-0 border-4 border-white shadow-sm"
:class="{ 'is-radius': globalAppSettings.isAvatarRadius }"
:src="avatar"
mode="aspectFill"
@error="handleOnImageError"
/>
<view class="user-info w-0 flex-1 pl-7">
<view class="author text-[26rpx] text-[#606266]">
<text class="text-grey text-size-m">{{ comment.spec.owner.displayName }}</text>
</view>
<view class="mt-1 flex">
<view class="time text-grey text-[22rpx] text-[#999]">
<text>{{ createTimeText }}</text>
<text class="ml-3">{{ createTimeAgo }}</text>
</view>
</view>
</view>
<view v-if="useActions" class="actions flex gap-4">
<view v-if="!disallowComment" class="action-btn px-1 py-0.5 text-[24rpx] text-blue" @click="handleOnReply">
回复
</view>
<view class="action-btn text-grey px-1 py-0.5 text-[24rpx]" @click="handleOnCopy">
复制
</view>
</view>
</view>
<view
class="comment-item-content ml-[98rpx] mt-3 box-border text-[28rpx] text-[#303133] leading-[1.8]"
:class="{ 'has-bg': useContentBg, 'not-ml': isChild }"
@click="handleOnDetail"
v-html="comment.spec.raw"
/>
</view>
</template>
<style scoped lang="scss">
.comment-item {
border-top: 2rpx solid #f5f5f5;
&.child-comment-item {
padding-top: 0;
margin-left: 80rpx;
border: 0;
}
&.no-solid {
border: 0;
margin-top: 0 !important;
}
.comment-item-user {
.user-avatar {
border-radius: 12rpx;
&.is-radius {
border-radius: 50%;
}
}
.user-info {
.time {
margin-top: 8rpx;
}
}
}
.comment-item-content {
&.has-bg {
background-color: #fafafa;
padding: 6rpx 24rpx;
}
&.not-ml {
margin-left: 98rpx;
}
}
}
</style>
@@ -0,0 +1,206 @@
<script lang="ts" setup>
/**
* 评论列表(源自旧项目 components/comment-list,新建复刻)
* 支持一级/二级评论展示、刷新、回复入口
*/
import { ref } from 'vue'
import { getPostCommentList } from '@/api/halo'
import type { IComment, ICommentListRes } from '@/api/types/halo'
const props = withDefaults(defineProps<{
disallowComment?: boolean
postName: string
post: { metadata: { name: string } }
}>(), {
disallowComment: false,
})
const emit = defineEmits<{
(e: 'on-comment', data: { isComment: boolean, postName: string, title: string }): void
(e: 'on-comment-detail', data: { postName: string, comment: IComment }): void
(e: 'on-loaded', list: IComment[]): void
}>()
const loading = ref<'loading' | 'success' | 'error'>('loading')
const queryParams = ref({
group: 'content.halo.run',
kind: 'Post',
version: 'v1alpha1',
name: props.postName,
page: 1,
size: 50,
withReplies: true,
replySize: 10,
})
const result = ref<ICommentListRes | null>(null)
const dataList = ref<IComment[]>([])
async function handleGetData() {
loading.value = 'loading'
try {
const res = await getPostCommentList({ ...queryParams.value })
result.value = res.data
dataList.value = res.data.items
loading.value = 'success'
emit('on-loaded', dataList.value)
}
catch (err) {
console.error('获取评论失败', err)
loading.value = 'error'
}
}
function handleToComment(data?: { type: string, comment: IComment }) {
if (props.disallowComment) {
uni.showToast({ icon: 'none', title: '文章已禁止评论!' })
return
}
if (data) {
// 回复某条评论
emit('on-comment', {
isComment: false,
postName: data.comment.metadata.name,
title: data.comment.spec.owner.displayName,
})
}
else {
// 新增评论
emit('on-comment', {
isComment: true,
postName: props.post.metadata.name,
title: '新增评论',
})
}
}
function handleCopyContent(content: string) {
uni.setClipboardData({
data: content,
showToast: false,
success: () => {
uni.showToast({ icon: 'none', title: '内容已复制成功!' })
},
})
}
function handleShowCommentDetail(comment: IComment) {
emit('on-comment-detail', {
postName: props.postName,
comment,
})
}
handleGetData()
</script>
<template>
<view class="uh-comment-list">
<!-- 顶部区域 -->
<view class="comment-list-head relative box-border pl-6 text-[30rpx] font-bold">
<view class="title">
<text>评论列表</text>
<text class="count text-[28rpx] font-normal">({{ result?.total || 0 }}条)</text>
</view>
<view class="refresh flex items-center gap-1.5 text-[26rpx] text-[#666] font-normal" @click="handleGetData">
<wd-icon name="refresh" size="14px" color="#909399" />
<text class="refresh-text ml-1.5">刷新</text>
</view>
</view>
<!-- 内容区域 -->
<view class="comment-list-content mt-6 pb-9">
<view v-if="loading !== 'success'" class="loading-wrap h-[506rpx] w-full flex items-center justify-center">
<view v-if="loading === 'loading'" class="loading flex flex-col items-center justify-center">
<view class="loading-text text-[26rpx] text-[#999]">
加载中,请稍等...
</view>
</view>
<view v-else-if="loading === 'error'" class="error flex flex-col items-center">
<text class="text-grey">加载失败</text>
<wd-button v-if="!disallowComment" size="small" plain type="primary" class="mt-2" @click="handleGetData">
刷新试试
</wd-button>
</view>
</view>
<block v-else>
<view v-if="disallowComment && dataList.length !== 0" class="disallow-tip rounded-xl bg-[#fef0f0] px-3 py-2 text-[26rpx] text-[#f56c6c]">
Ծ‸Ծ 博主已设置该文章禁止评论!
</view>
<view v-if="dataList.length === 0" class="empty pt-5">
<view class="empty-box flex flex-col items-center">
<wd-empty :description="disallowComment ? '暂无评论' : '暂无评论'" />
<view v-if="disallowComment" class="empty-tip mt-1.5 text-[24rpx] text-[#f56c6c]">
- 文章已开启禁止评论 -
</view>
<wd-button v-else size="small" plain type="primary" class="mt-2" @click="handleToComment()">
抢沙发
</wd-button>
</view>
</view>
<block v-else>
<!-- 一级评论 -->
<template v-for="comment in dataList" :key="comment.metadata.name">
<uh-comment-item
:use-content-bg="false"
:is-child="false"
:comment="comment"
:post-name="postName"
:disallow-comment="disallowComment"
@on-copy="handleCopyContent"
@on-comment="handleToComment"
@on-detail="handleShowCommentDetail"
/>
<!-- 二级评论 -->
<template v-if="comment.replies && comment.replies.length !== 0">
<uh-comment-item
v-for="childComment in comment.replies"
:key="childComment.metadata.name"
:use-content-bg="false"
:is-child="true"
:comment="childComment"
:post-name="postName"
:disallow-comment="disallowComment"
@on-copy="handleCopyContent"
@on-comment="handleToComment"
@on-detail="handleShowCommentDetail"
/>
</template>
</template>
</block>
</block>
</view>
</view>
</template>
<style scoped lang="scss">
.uh-comment-list {
.comment-list-head {
display: flex;
align-items: center;
justify-content: space-between;
&::before {
content: '';
position: absolute;
left: 0;
top: 8rpx;
width: 8rpx;
height: 26rpx;
background-color: rgb(3 174 252);
border-radius: 6rpx;
}
}
.comment-list-content {
.loading-wrap {
.loading-text {
/* 无额外样式 */
}
}
}
}
</style>
@@ -0,0 +1,321 @@
<script lang="ts" setup>
/**
* 评论弹窗(源自旧项目 components/comment-modal,新建复刻)
* 支持新增评论 / 回复评论,含匿名评论验证码(cookie 链路)
*/
import { computed, ref, watch } from 'vue'
import { addPostComment, addPostCommentReply } from '@/api/halo'
import { getCommentWidgetCaptcha, getCommentWidgetConfig } from '@/api/uni-halo'
import { setCache } from '@/utils/storage'
import { deepMerge } from '@/utils/merge'
const props = withDefaults(defineProps<{
show: boolean
isComment?: boolean
title?: string
postName: string
}>(), {
isComment: false,
title: '',
})
const emit = defineEmits<{
(e: 'on-close', data: { isSubmit: boolean, refresh: boolean }): void
}>()
const isShow = ref(false)
interface ICaptchaConfig {
security?: {
captcha?: {
anonymousCommentCaptcha?: boolean
[key: string]: unknown
}
}
editor?: {
placeholder?: string
}
[key: string]: unknown
}
interface ICommentForm {
allowNotification: boolean
author: string
avatar: string
authorUrl: string
content: string
email: string
postName: string
captchaCode?: string
}
const config = ref<ICaptchaConfig>({
security: {
captcha: {
anonymousCommentCaptcha: false,
},
},
editor: {
placeholder: '请输入内容,不超过200字符...',
},
})
const captchaData = ref<{ image: string, status: 'loading' | 'success' | 'fail' }>({
image: '',
status: 'loading',
})
const form = ref<ICommentForm>({
allowNotification: true,
author: '',
avatar: '',
authorUrl: '',
content: '',
email: '',
postName: props.postName,
captchaCode: undefined,
})
const calcTitle = computed(() => {
if (props.isComment)
return props.title || '新增评论'
return `回复用户:${props.title}`
})
function handleResetForm() {
form.value = {
allowNotification: true,
author: '',
avatar: '',
authorUrl: '',
content: '',
email: '',
postName: props.postName,
captchaCode: undefined,
}
}
/** 获取评论组件配置(验证码开关) */
async function handleGetConfig() {
try {
const res = await getCommentWidgetConfig()
config.value = deepMerge(config.value as Record<string, unknown>, res.data as Record<string, unknown>) as ICaptchaConfig
if (config.value?.security?.captcha?.anonymousCommentCaptcha) {
handleGetCaptchaImage()
}
}
catch (err) {
console.error('获取验证码配置失败', err)
}
}
/** 获取评论验证码图片 */
async function handleGetCaptchaImage() {
captchaData.value.status = 'loading'
try {
const res = await getCommentWidgetCaptcha()
form.value.captchaCode = undefined
captchaData.value.image = res.data as unknown as string
captchaData.value.status = 'success'
}
catch (err) {
console.error('获取验证码失败', err)
captchaData.value.status = 'fail'
captchaData.value.image = ''
}
}
/** 初始化访客信息 */
function handleInitVisitor() {
const visitor = uni.getStorageSync('Visitor')
if (!visitor)
return
try {
const v = JSON.parse(visitor)
form.value.author = v.author || ''
form.value.avatar = v.avatar || ''
form.value.email = v.email || ''
form.value.authorUrl = v.authorUrl || ''
}
catch {
// ignore
}
}
/** 保存访客信息 */
function handleSetVisitor() {
setCache('Visitor', {
author: form.value.author,
avatar: form.value.avatar,
email: form.value.email,
authorUrl: form.value.authorUrl,
})
}
/** 提交校验 */
function validateForm(): boolean {
if (!form.value.content.trim()) {
uni.showToast({ icon: 'none', title: '请填写评论内容' })
return false
}
if (!form.value.author.trim()) {
uni.showToast({ icon: 'none', title: '请填写昵称' })
return false
}
if (!form.value.email.trim()) {
uni.showToast({ icon: 'none', title: '请填写邮箱' })
return false
}
if (config.value?.security?.captcha?.anonymousCommentCaptcha && !form.value.captchaCode?.trim()) {
uni.showToast({ icon: 'none', title: '请填写验证码结果!' })
return false
}
return true
}
async function handleHandle() {
if (!validateForm())
return
uni.showLoading({ title: '正在提交...' })
try {
if (props.isComment) {
// 新增评论
await addPostComment({
raw: form.value.content,
content: form.value.content,
owner: {
displayName: form.value.author,
email: form.value.email,
website: form.value.authorUrl,
},
subjectRef: {
group: 'content.halo.run',
kind: 'Post',
name: form.value.postName,
version: 'v1alpha1',
},
captchaCode: config.value?.security?.captcha?.anonymousCommentCaptcha ? form.value.captchaCode : undefined,
})
uni.showToast({ icon: 'none', title: '评论成功,可能需要审核!' })
}
else {
// 回复评论
await addPostCommentReply(form.value.postName, {
raw: form.value.content,
content: form.value.content,
owner: {
displayName: form.value.author,
email: form.value.email,
website: form.value.authorUrl,
},
captchaCode: config.value?.security?.captcha?.anonymousCommentCaptcha ? form.value.captchaCode : undefined,
})
uni.showToast({ icon: 'none', title: '回复成功,可能需要审核!' })
}
handleSetVisitor()
handleClose(true)
handleResetForm()
}
catch (err) {
console.error('评论提交失败', err)
if (config.value?.security?.captcha?.anonymousCommentCaptcha) {
captchaData.value.status = 'success'
form.value.captchaCode = undefined
handleGetCaptchaImage()
}
uni.showToast({ icon: 'none', title: '提交失败' })
}
finally {
uni.hideLoading()
}
}
function handleOnChange(isOpen: boolean) {
isShow.value = isOpen
if (!isOpen) {
emit('on-close', { isSubmit: false, refresh: false })
}
}
function handleClose(refresh = false) {
isShow.value = false
emit('on-close', { isSubmit: true, refresh })
}
watch(() => props.show, (newVal) => {
if (!newVal)
return
isShow.value = true
handleResetForm()
form.value.postName = props.postName
handleGetConfig()
handleInitVisitor()
})
</script>
<template>
<wd-popup v-model="isShow" position="bottom" custom-style="border-radius:12rpx 12rpx 0 0;" @close="handleOnChange(false)">
<view class="uh-comment-modal box-border max-h-[71vh] overflow-y-auto p-3">
<view class="title my-6 text-center text-[32rpx] font-bold">
{{ calcTitle }}
</view>
<view class="form">
<view class="form-item mb-5 flex items-center">
<textarea
v-model="form.content"
class="content-input box-border w-full rounded-xl bg-[#f5f5f5] p-5 text-[26rpx]"
:placeholder="config.editor?.placeholder || '请输入内容,不超过200字符...'"
:maxlength="200"
style="height: 200rpx;"
/>
</view>
<view class="form-item mb-5 flex items-center">
<text class="label w-[140rpx] shrink-0 text-[26rpx] text-[#666]">我的昵称</text>
<input v-model="form.author" class="input h-[72rpx] flex-1 rounded-xl bg-[#f5f5f5] px-5 text-[26rpx]" placeholder="请输入您的昵称...">
</view>
<view class="form-item mb-5 flex items-center">
<text class="label w-[140rpx] shrink-0 text-[26rpx] text-[#666]">我的邮箱</text>
<input v-model="form.email" class="input h-[72rpx] flex-1 rounded-xl bg-[#f5f5f5] px-5 text-[26rpx]" placeholder="请输入您的邮箱...">
</view>
<view class="form-item mb-5 flex items-center">
<text class="label w-[140rpx] shrink-0 text-[26rpx] text-[#666]">我的网站</text>
<input v-model="form.authorUrl" class="input h-[72rpx] flex-1 rounded-xl bg-[#f5f5f5] px-5 text-[26rpx]" placeholder="请输入您的网址...">
</view>
<!-- 匿名评论验证码 -->
<view v-if="config?.security?.captcha?.anonymousCommentCaptcha" class="form-item mb-5 flex items-center">
<text class="label w-[140rpx] shrink-0 text-[26rpx] text-[#666]">验证码</text>
<view class="captcha-row flex flex-1 items-center gap-4">
<input v-model="form.captchaCode" class="input h-[72rpx] flex-1 rounded-xl bg-[#f5f5f5] px-5 text-[26rpx]" placeholder="请输入验证码结果">
<view class="captcha-wrapper h-[68rpx] w-[200rpx] flex shrink-0 items-center justify-center">
<text v-if="captchaData.status === 'loading'" class="captcha-tip text-[24rpx] text-[#999]">获取中...</text>
<text v-else-if="captchaData.status === 'fail'" class="captcha-tip text-[24rpx] text-[#f56c6c]" @click="handleGetCaptchaImage()">请重试</text>
<image v-else :src="captchaData.image" class="captcha-img h-full w-full" mode="aspectFit" @click="handleGetCaptchaImage()" />
</view>
</view>
</view>
<view class="submit-btn my-6">
<wd-button type="primary" block size="medium" @click="handleHandle">
提交
</wd-button>
</view>
</view>
</view>
</wd-popup>
</template>
<style scoped lang="scss">
.uh-comment-modal {
.content-input {
min-height: 200rpx;
}
}
</style>
+189
View File
@@ -0,0 +1,189 @@
<script lang="ts" setup>
/**
* 贡献热度图(源自旧项目 components/heatmap,新建复刻,精简版)
* 按日期统计文章发布数量,以年度格子图展示
*/
import { computed, ref } from 'vue'
import dayjs from 'dayjs'
export interface IHeatmapDay {
date: string
count: number
}
const props = withDefaults(defineProps<{
chartData?: IHeatmapDay[]
}>(), {
chartData: () => [],
})
const weeks = ['一', '二', '三', '四', '五', '六', '日']
const currentYear = ref(new Date().getFullYear())
const currentMonth = ref(new Date().getMonth() + 1)
const intensityColors = ['#ebedf0', '#dbeafe', '#93c5fd', '#3b82f6', '#1e40af']
const yearOptions = computed(() => {
const years = new Set<number>()
props.chartData.forEach((item) => {
years.add(dayjs(item.date).year())
})
years.add(new Date().getFullYear())
return [...years].sort((a, b) => b - a)
})
/** 当前年份数据 key(date -> count) */
const yearDataMap = computed(() => {
const map: Record<string, number> = {}
props.chartData.forEach((item) => {
if (dayjs(item.date).year() === currentYear.value) {
map[item.date] = item.count
}
})
return map
})
/** 本年第一天是周几(用于前置空位) */
const firstDayOffset = computed(() => {
const firstDay = new Date(currentYear.value, 0, 1)
const weekday = firstDay.getDay() // 0=周日
return weekday === 0 ? 6 : weekday - 1
})
/** 一年天数(闰年处理) */
const daysInYear = computed(() => {
return (new Date(currentYear.value, 11, 31).getDate() === 31
&& new Date(currentYear.value, 11, 31).getMonth() === 11)
? 365
: 366
})
/** 单元格列表:前置空位 + 全年每日 */
const displayCells = computed(() => {
const cells: { date: string, count: number, isEmpty: boolean }[] = []
for (let i = 0; i < firstDayOffset.value; i++) {
cells.push({ date: '', count: 0, isEmpty: true })
}
for (let day = 1; day <= daysInYear.value; day++) {
const date = dayjs(`${currentYear.value}-01-01`).add(day - 1, 'day').format('YYYY-MM-DD')
cells.push({ date, count: yearDataMap.value[date] || 0, isEmpty: false })
}
return cells
})
/** 颜色分级 */
function getDayColor(day: { count: number, isEmpty: boolean }): string {
if (day.isEmpty)
return 'transparent'
if (day.count === 0)
return intensityColors[0]
if (day.count <= 2)
return intensityColors[1]
if (day.count <= 4)
return intensityColors[2]
if (day.count <= 6)
return intensityColors[3]
return intensityColors[4]
}
function getDayTip(day: { date: string, count: number, isEmpty: boolean }): string {
if (day.isEmpty)
return ''
return `${day.date}:${day.count} 篇`
}
/** 累计总数 */
const totalCount = computed(() => props.chartData.reduce((sum, item) => sum + item.count, 0))
/** 本年总数 */
const currentYearCount = computed(() => Object.values(yearDataMap.value).reduce((sum, n) => sum + n, 0))
/** 月份标签(按 5 周跨度取整月位置,简化:每两月一个标签) */
const monthLabels = computed(() => {
const labels: { index: number, name: string }[] = []
for (let m = 0; m < 12; m++) {
labels.push({ index: m * 5, name: `${m + 1}月` })
}
return labels
})
function changeYear(value: number) {
currentYear.value = value
}
</script>
<template>
<view class="uh-heatmap box-border w-full rounded-xl bg-white p-3">
<view class="header mb-6 flex items-center justify-between">
<view class="title text-[28rpx] text-[#303133] font-bold">
{{ currentYear }}年 文章发布趋势
</view>
<view class="controls flex gap-3">
<view
v-for="year in yearOptions"
:key="year"
class="year-btn rounded-lg px-4 py-0.5 text-[24rpx] text-[#999]"
:class="{ active: year === currentYear }"
@click="changeYear(year)"
>
{{ year }}
</view>
</view>
</view>
<view class="heatmap-container flex gap-2">
<view class="weeks flex flex-col gap-1 pt-8">
<view v-for="(week, index) in weeks" :key="index" class="week-label h-5 text-[16rpx] text-[#999] leading-5">
{{ week }}
</view>
</view>
<view class="heatmap-content flex-1 overflow-x-auto">
<view class="months mb-1 flex">
<view v-for="month in monthLabels" :key="month.index" class="month-label w-[100rpx] shrink-0 text-[16rpx] text-[#999]">
{{ month.name }}
</view>
</view>
<view class="days-container h-[220rpx] flex flex-wrap gap-1">
<view
v-for="(day, index) in displayCells"
:key="index"
class="day-cell box-border h-6 w-6 rounded"
:style="{ backgroundColor: getDayColor(day) }"
@click="getDayTip(day)"
/>
</view>
</view>
</view>
<view class="footer mt-6 flex items-center justify-between">
<view class="releases-count text-[24rpx] text-[#666]">
<text>累计 {{ totalCount }} 篇</text>
<text class="divider mx-2">丨</text>
<text>本年 {{ currentYearCount }} 篇</text>
</view>
<view class="legend flex items-center gap-1">
<text class="legend-text text-[20rpx] text-[#999]">少</text>
<view
v-for="(color, index) in intensityColors"
:key="index"
class="day-cell legend-day-cell h-5 w-5"
:style="{ backgroundColor: color }"
/>
<text class="legend-text text-[20rpx] text-[#999]">多</text>
</view>
</view>
</view>
</template>
<style scoped lang="scss">
.uh-heatmap {
.year-btn {
background-color: #f5f5f5;
&.active {
color: #fff;
background-color: #03a9f4;
}
}
}
</style>
@@ -0,0 +1,85 @@
<script lang="ts" setup>
/**
* 通知弹窗(源自旧项目 components/notify-dialog,新建复刻)
* wd-popup + mp-html 渲染 markdown 内容,可选跳转外链
*/
import { ref, watch } from 'vue'
import { checkIsUrl } from '@/utils/url'
import { markdownConfig } from '@/config/markdown'
const props = defineProps<{
show: boolean
title: string
content: string
url: string
}>()
const emit = defineEmits<{
(e: 'on-change', show: boolean): void
}>()
const isShow = ref(props.show)
watch(() => props.show, (val) => {
isShow.value = val
})
function handleOnChange(e: unknown) {
isShow.value = false
emit('on-change', Boolean(e))
}
function handleToWebview() {
if (checkIsUrl(props.url)) {
uni.navigateTo({
url: `/pages-blog/website/website?data=${JSON.stringify({
title: props.title,
url: encodeURIComponent(props.url),
})}`,
success: () => {
handleOnChange(false)
},
})
}
}
</script>
<template>
<wd-popup v-model="isShow" width="80vw" position="center" custom-style="border-radius:12rpx;" @close="handleOnChange(false)">
<view class="uh-notify-dialog box-border w-[80vw] p-3">
<view class="text-overflow-2 mb-6 text-center font-bold">
{{ title }}
</view>
<view class="content-box">
<scroll-view scroll-y :style="{ height: url ? '600rpx' : '680rpx' }">
<mp-html
class="evan-markdown"
lazy-load
:domain="markdownConfig.domain ?? ''"
:loading-img="markdownConfig.loadingGif"
scroll-table
selectable
:tag-style="markdownConfig.tagStyle"
:container-style="markdownConfig.containStyle"
:content="content"
:markdown="true"
:show-line-number="true"
:show-language-name="true"
copy-by-long-press
/>
</scroll-view>
</view>
<view v-if="url" class="mt-6 flex justify-center">
<wd-button size="small" type="primary" @click="handleToWebview">
点击跳转内容链接
</wd-button>
</view>
</view>
</wd-popup>
</template>
<style scoped lang="scss">
.uh-notify-dialog {
/* 无额外样式,布局全部由 UnoCSS 原子类实现 */
}
</style>
@@ -0,0 +1,135 @@
<script lang="ts" setup>
/**
* 插件不可用提示(源自旧项目 components/plugin-unavailable,新建复刻)
* 当依赖的 Halo 插件未安装/未启用时展示:插件 logo、名称、错误标签、描述、插件地址、复制/反馈按钮
*/
import { computed } from 'vue'
import { NeedPlugins } from '@/utils/plugin'
const props = withDefaults(defineProps<{
/** 插件名称(与 NeedPlugins 中的 id 对应) */
pluginId: string
errorText?: string
useDecoration?: boolean
useBorder?: boolean
customStyle?: Record<string, string>
}>(), {
errorText: '',
useDecoration: true,
useBorder: true,
customStyle: () => ({}),
})
const emit = defineEmits<{
(e: 'on-refresh'): void
}>()
/** 插件信息(未在清单中时兜底) */
const pluginInfo = computed(() => {
const info = NeedPlugins.get(props.pluginId)
return info || {
id: props.pluginId,
name: props.pluginId,
desc: '',
logo: '',
url: '',
}
})
const defaultStyle = {
width: '80vw',
borderRadius: '24rpx',
}
const calcCustomStyle = computed(() => ({
...defaultStyle,
...props.customStyle,
}))
function copy() {
if (!pluginInfo.value.url)
return
uni.setClipboardData({
data: pluginInfo.value.url,
showToast: false,
success: () => {
uni.showToast({ icon: 'none', title: '插件地址已复制' })
},
})
}
</script>
<template>
<view
v-if="pluginInfo"
class="uh-plugin-unavailable mx-auto my-auto box-border flex flex-col gap-6 p-10 text-[28rpx]"
:class="{ border: useBorder, decoration: useDecoration }"
:style="[calcCustomStyle]"
>
<!-- 图标 -->
<image class="plugin-logo box-border h-[120rpx] w-[120rpx] rounded-3xl" :src="pluginInfo.logo" mode="scaleToFill" />
<!-- 名称 -->
<view class="plugin-name box-border text-[32rpx] text-[#333] font-bold">
{{ pluginInfo.name }}
</view>
<!-- 错误标签 -->
<view class="plugin-error box-border rounded-[36rpx] px-4 py-1.5 text-[24rpx] font-bold" style="background-color: rgb(255 61 49 / 7.5%); color: rgb(255 61 49);">
未安装/启用插件
</view>
<!-- 描述 -->
<view class="plugin-desc box-border w-[60vw] text-center text-[24rpx] text-[#64748b]">
{{ pluginInfo.desc }}
</view>
<!-- 自定义错误提示 -->
<view v-if="errorText" class="plugin-tip box-border border-2 rounded-xl border-dashed px-5 py-2.5 text-[24rpx]" style="border-color: #f2c97d; color: #f0a020;">
{{ errorText }}
</view>
<!-- 插件地址 -->
<view class="plugin-url box-border w-full overflow-hidden text-ellipsis whitespace-nowrap rounded-xl bg-[#f1f5f9] px-6 py-4 text-[24rpx] text-[#666]">
插件地址:{{ pluginInfo.url }}
</view>
<!-- 反馈按钮/复制地址 -->
<view class="plugin-btns box-border w-full">
<!-- #ifndef MP-WEIXIN -->
<wd-button type="primary" block size="medium" @click="copy">
复制地址
</wd-button>
<!-- #endif -->
<!-- #ifdef MP-WEIXIN -->
<view class="flex gap-3">
<wd-button type="primary" plain block size="medium" @click="copy">
复制地址
</wd-button>
<wd-button type="warning" plain block size="medium" open-type="contact">
提交反馈
</wd-button>
</view>
<!-- #endif -->
</view>
<!-- 刷新按钮 -->
<view class="flex justify-center">
<wd-button size="small" plain type="info" @click="emit('on-refresh')">
刷新试试
</wd-button>
</view>
<view class="plugin-copyright text-[20rpx] text-[#999]" style="transform: scale(0.9) translateY(20px);">
提示:请确保 Halo 博客已安装相关插件
</view>
</view>
</template>
<style scoped lang="scss">
.uh-plugin-unavailable {
&.border {
border: 2rpx solid #eee;
}
&.decoration {
background-color: rgb(255 255 255 / 95%);
box-shadow: 0 0 12rpx rgb(226 232 240 / 35%);
backdrop-filter: blur(6rpx);
border-top: 12rpx solid rgb(3 169 244);
}
}
</style>
@@ -0,0 +1,157 @@
<script lang="ts" setup>
/**
* 受限阅读骨架屏(源自旧项目 components/restrict-read-skeleton,新建复刻)
* 受限内容遮挡 + 提示文字 + 验证按钮
*/
withDefaults(defineProps<{
loading?: boolean
hover?: boolean
buttonText?: string
buttonColor?: string
buttonSize?: 'small' | 'normal' | 'large'
lines?: number
skeletonColor?: string
skeletonHighlight?: string
animationDuration?: number
showButton?: boolean
tipText?: string
tipColor?: string
tipSize?: number
}>(), {
loading: true,
hover: false,
buttonText: '刷新',
buttonColor: '#07c160',
buttonSize: 'normal',
lines: 4,
skeletonColor: '#f5f5f5',
skeletonHighlight: '#e8e8e8',
animationDuration: 1.5,
showButton: true,
tipText: '',
tipColor: '#666666',
tipSize: 24,
})
const emit = defineEmits<{
(e: 'refresh'): void
(e: 'touchstart'): void
(e: 'touchend'): void
}>()
function handleRefresh() {
emit('refresh')
}
function onTouchStart() {
emit('touchstart')
}
function onTouchEnd() {
emit('touchend')
}
</script>
<template>
<view class="container relative min-h-[200rpx] w-full overflow-hidden rounded-2xl bg-white" style="box-shadow: 0 4rpx 12rpx rgb(0 0 0 / 5%);">
<view v-if="loading" class="skeleton box-border w-full p-3">
<view class="skeleton-body my-5">
<view
v-for="(item, index) in Array(lines).fill(0)"
:key="index"
class="skeleton-line mb-5 h-[32rpx] rounded-lg"
:class="{ short: index === lines - 2, shorter: index === lines - 1 }"
:style="{
background: `linear-gradient(90deg, ${skeletonColor} 25%, ${skeletonHighlight} 50%, ${skeletonColor} 75%)`,
backgroundSize: '400% 100%',
animationDuration: `${animationDuration}s`,
}"
/>
</view>
</view>
<view v-else>
<slot />
</view>
<view v-if="showButton" class="button-container absolute left-1/2 top-1/2 z-2 flex flex-col items-center -translate-x-1/2 -translate-y-1/2">
<text
v-if="tipText"
class="tip-text mb-5 text-center leading-[1.4]"
:style="{ color: tipColor, fontSize: `${tipSize}rpx` }"
>
{{ tipText }}
</text>
<button
class="overlay-button relative flex items-center justify-center text-white"
:class="[buttonSize, { 'button-hover': hover }]"
hover-class="none"
:style="{ backgroundColor: buttonColor }"
@touchstart="onTouchStart"
@touchend="onTouchEnd"
@click="handleRefresh"
>
{{ buttonText }}
</button>
</view>
</view>
</template>
<style scoped lang="scss">
.skeleton {
&-line {
width: 100%;
animation: skeleton-loading 1.5s ease infinite;
&.short {
width: 70%;
}
&.shorter {
width: 50%;
}
}
}
.overlay-button {
border-radius: 50rpx;
padding: 0 40rpx;
height: 80rpx;
line-height: 80rpx;
font-size: 28rpx;
box-shadow: 0 4rpx 12rpx rgb(0 0 0 / 10%);
&:active {
transform: scale(0.95);
}
&.small {
height: 60rpx;
line-height: 60rpx;
font-size: 24rpx;
padding: 0 30rpx;
}
&.large {
height: 100rpx;
line-height: 100rpx;
font-size: 32rpx;
padding: 0 50rpx;
}
}
.button-hover {
transform: translateY(-4rpx);
box-shadow: 0 8rpx 16rpx rgb(0 0 0 / 15%);
}
@keyframes skeleton-loading {
0% {
background-position: 100% 50%;
}
100% {
background-position: 0 50%;
}
}
</style>
+359
View File
@@ -0,0 +1,359 @@
<script lang="ts" setup>
/**
* 轮播组件(源自旧项目 components/e-swiper,新建复刻)
* 支持:图片/视频轮播、今日首推日期指示器(useTop)、标题区域(useTitle)、底部小图指示器(useDot)
*/
import { computed, ref } from 'vue'
export interface IBannerItem {
id: string | number
title?: string
image?: string
src?: string
mp4?: string
type?: string
content?: string
url?: string
[key: string]: unknown
}
const props = withDefaults(defineProps<{
title?: string
height?: string
dotPosition?: string
useTop?: boolean
useDot?: boolean
useTitle?: boolean
useUser?: boolean
/** 轮播图数据列表 */
list: IBannerItem[]
/** 当前选中的项(指示器坐标位置) */
current?: number
/** 是否自动轮播 */
autoplay?: boolean
}>(), {
title: '',
height: '450rpx',
dotPosition: 'bottom',
useTop: true,
useDot: true,
useTitle: true,
useUser: true,
current: 0,
autoplay: false,
})
const emit = defineEmits<{
(e: 'on-click', item: IBannerItem): void
(e: 'on-more'): void
(e: 'change', event: { current: number }): void
}>()
/* ---------------- 状态 ---------------- */
const currentIndex = ref(props.current)
/** 是否禁止用户 touch 操作 */
const disableTouch = ref(false)
/** 日期(今日首推指示器用) */
const date = ref({ year: '-', monthEn: '-', month: '-' })
/* ---------------- 计算属性 ---------------- */
/** 仅渲染前 5 条 */
const displayList = computed(() => props.list.slice(0, 5))
const currentTitle = computed(() => props.list[currentIndex.value]?.title || '')
/* ---------------- 初始化 ---------------- */
function initDate() {
const now = new Date()
const monthArray = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
date.value.year = String(now.getFullYear())
const month = now.getMonth() + 1
date.value.month = month < 10 ? `0${month}` : String(month)
date.value.monthEn = monthArray[now.getMonth()].toUpperCase()
}
initDate()
/* ---------------- 交互 ---------------- */
/** current 改变时会触发 change 事件,event.detail = {current, source} */
function change(e: { detail: { current: number, source: string } }) {
const { current, source } = e.detail
// 只有页面自动切换、手动切换时才轮播,其他不允许
if (source === 'autoplay' || source === 'touch') {
const event = { current }
currentIndex.value = current
emit('change', event)
}
}
/** 手动点击了指示器[小图模式] */
function swiperIndTap(index: number) {
const event = { current: index }
currentIndex.value = index
emit('change', event)
}
function handleOnClick(item: IBannerItem) {
emit('on-click', item)
}
</script>
<template>
<!-- 轮播图 -->
<view class="uh-e-swiper">
<view class="swiper-box" :class="[dotPosition]">
<swiper
class="swiper"
:style="{ height }"
:circular="true"
:indicator-dots="false"
:autoplay="autoplay"
:interval="3000"
:duration="1000"
:current="currentIndex"
:disable-touch="disableTouch"
@change="change"
>
<!-- 只需要前5条数据 -->
<block v-for="(item, index) in list" :key="index">
<swiper-item v-if="index <= 4" class="swiper-mfw-item">
<!-- 如果有视频,则显示视频 -->
<template v-if="item.mp4 && currentIndex === index">
<video
:id="`ImageVideo${index}`"
:src="item.mp4"
class="image-video h-full w-full"
:loop="true"
:muted="false"
:autoplay="true"
:controls="false"
:show-fullscreen-btn="false"
:show-play-btn="false"
:enable-progress-gesture="false"
:poster="item.image || item.src"
/>
</template>
<!-- 否则显示图片 -->
<image
v-else
:src="item.image || item.src"
class="image h-full w-full"
mode="aspectFill"
@click.stop="handleOnClick(item)"
/>
</swiper-item>
</block>
</swiper>
<!-- 指示器 [Top 今日首推] -->
<view v-if="useTop" class="indicator-box indicator-top-box">
<view class="top-date-hot">
<view class="left-date-ri">
<text class="date-ri-text">{{ date.month }}</text>
</view>
<view class="center-date-nianyue">
<view class="left-width-bgcolor" />
<view class="right-date-nianyue">
<text class="top-yue-usa">{{ date.monthEn }}</text>
<text class="bottom-nian">{{ date.year }}</text>
</view>
</view>
<view class="right-hot-ttf">
<text class="hot-text text-overflow-2">{{ title }}</text>
</view>
</view>
</view>
<!-- 指示器 标题区域 -->
<view v-if="useTitle" class="indicator-top" :class="{ 'no-dot': !useDot }">
<block v-for="(item, index) in list" :key="index">
<view v-if="currentIndex === index" class="top-item" :class="currentIndex === index ? 'current' : 'no'">
<!-- 如果存在视频,则显示"视频预览"提示 -->
<view v-if="item.mp4" class="top-image-video">
<view class="icons">
<text class="video-icon">▶</text>
</view>
<text class="image-video-text">视频预览</text>
</view>
<!-- 标题 -->
<view class="top-title">
<text class="title-text text-overflow-2">{{ item.title }}</text>
</view>
</view>
</block>
</view>
<!-- 指示器 [左边图片列表+右边按钮] -->
<view v-if="useDot" class="indicator-bottom">
<!-- 左边 -->
<view class="bottom-left-imagelist">
<block v-for="(item, index) in list" :key="index">
<view
v-if="Number(index) <= 4"
class="bottom-item"
:class="currentIndex === index ? 'current' : 'no'"
@click="swiperIndTap(index)"
>
<image :src="item.image || item.src" class="image h-full w-full" mode="aspectFill" />
</view>
</block>
</view>
</view>
</view>
</view>
</template>
<style scoped lang="scss">
.uh-e-swiper {
position: relative;
width: 100%;
overflow: hidden;
.swiper-box {
position: relative;
width: 100%;
.swiper {
width: 100%;
border-radius: 12rpx;
}
}
/* 今日首推指示器 */
.indicator-top-box {
position: absolute;
top: 0;
left: 0;
right: 0;
z-index: 5;
padding: 16rpx 24rpx;
.top-date-hot {
display: flex;
align-items: center;
.left-date-ri {
.date-ri-text {
font-size: 40rpx;
font-weight: bold;
color: #fff;
text-shadow: 0 2rpx 8rpx rgb(0 0 0 / 40%);
}
}
.center-date-nianyue {
display: flex;
align-items: center;
margin-left: 12rpx;
.left-width-bgcolor {
width: 2rpx;
height: 40rpx;
background-color: rgb(255 255 255 / 50%);
margin-right: 12rpx;
}
.right-date-nianyue {
display: flex;
flex-direction: column;
.top-yue-usa {
font-size: 20rpx;
color: #fff;
text-shadow: 0 2rpx 8rpx rgb(0 0 0 / 40%);
}
.bottom-nian {
font-size: 16rpx;
color: rgb(255 255 255 / 80%);
}
}
}
.right-hot-ttf {
flex: 1;
margin-left: 20rpx;
.hot-text {
display: block;
font-size: 24rpx;
color: #fff;
text-shadow: 0 2rpx 8rpx rgb(0 0 0 / 40%);
}
}
}
}
/* 标题区域 */
.indicator-top {
position: absolute;
left: 0;
right: 0;
bottom: 60rpx;
z-index: 5;
padding: 0 24rpx;
.top-item {
.top-image-video {
display: flex;
align-items: center;
gap: 8rpx;
.icons {
.video-icon {
font-size: 20rpx;
color: #fff;
}
}
.image-video-text {
font-size: 20rpx;
color: #fff;
}
}
.top-title {
margin-top: 8rpx;
.title-text {
display: block;
font-size: 28rpx;
font-weight: bold;
color: #fff;
text-shadow: 0 2rpx 8rpx rgb(0 0 0 / 40%);
}
}
}
}
/* 底部小图指示器 */
.indicator-bottom {
position: absolute;
left: 0;
right: 0;
bottom: 16rpx;
z-index: 5;
padding: 0 24rpx;
.bottom-left-imagelist {
display: flex;
gap: 12rpx;
.bottom-item {
width: 96rpx;
height: 64rpx;
border-radius: 8rpx;
overflow: hidden;
opacity: 0.6;
border: 2rpx solid transparent;
&.current {
opacity: 1;
border-color: #fff;
}
}
}
}
}
</style>
@@ -0,0 +1,145 @@
<script lang="ts" setup>
/**
* 投票卡片(源自旧项目 components/vote-card,新建复刻)
*/
import { computed, ref, watch } from 'vue'
import { getVoteDetail } from '@/api/uni-halo'
import { calcVoteState, VOTE_STATES, VOTE_TYPES } from '@/utils/vote'
import type { IVote, IVoteOption } from '@/api/types/uni-halo'
const props = defineProps<{
voteName: string
}>()
const emit = defineEmits<{
(e: 'on-vote-success'): void
}>()
const loading = ref(true)
const isSubmit = ref(false)
const voteData = ref<IVote | null>(null)
const voteTypes = ref<string[]>([])
const canAnonymously = ref(true)
const voteState = computed(() => calcVoteState(voteData.value || {}, voteTypes.value, canAnonymously.value))
const voteLabel = computed(() => {
if (voteState.value === VOTE_STATES.VOTE_ENDED)
return '投票已结束'
if (voteState.value === VOTE_STATES.VOTED)
return '已参与'
if (voteState.value === VOTE_STATES.VOTING)
return '投票中'
return '开始投票'
})
const voteResultLabel = computed(() => (voteState.value === VOTE_STATES.VOTED ? '查看结果' : ''))
async function handleGetData() {
loading.value = true
try {
const res = await getVoteDetail(props.voteName)
voteData.value = res.data
// 已投票项从缓存恢复(简化:根据 options 计数判断)
voteTypes.value = []
}
catch (err) {
console.error('获取投票失败', err)
}
finally {
loading.value = false
}
}
function handleSelectOption(option: IVoteOption) {
if (voteState.value !== VOTE_STATES.VOTING)
return
const optionName = option.name || ''
if (voteData.value && (voteData.value as { type?: string }).type === VOTE_TYPES.SINGLE) {
voteTypes.value = [optionName]
}
else {
const index = voteTypes.value.indexOf(optionName)
if (index === -1) {
voteTypes.value.push(optionName)
}
else {
voteTypes.value.splice(index, 1)
}
}
}
function handleSubmit() {
if (voteTypes.value.length === 0) {
uni.showToast({ icon: 'none', title: '请先选择选项' })
return
}
isSubmit.value = true
uni.showLoading({ title: '提交中...' })
setTimeout(() => {
uni.hideLoading()
isSubmit.value = false
emit('on-vote-success')
}, 500)
}
watch(() => props.voteName, () => {
handleGetData()
}, { immediate: true })
defineExpose({ refresh: handleGetData })
</script>
<template>
<view class="uh-vote-card box-border w-full rounded-xl bg-white p-3 shadow-sm">
<view v-if="loading" class="loading py-6">
<wd-skeleton :row="2" :animated="true" />
</view>
<view v-else-if="voteData" class="vote-body">
<view class="vote-title text-[30rpx] text-[#303133] font-bold">
{{ voteData.title }}
</view>
<view class="vote-desc mt-1 text-[24rpx] text-[#909399]">
{{ voteData.description }}
</view>
<view class="options mt-5">
<view
v-for="option in voteData.options"
:key="option.name"
class="option mb-4 flex flex-col border-2 border-transparent rounded-xl bg-[#f7f8fa] p-5"
:class="{ active: voteTypes.includes(option.name || '') }"
@click="handleSelectOption(option)"
>
<view class="option-label text-[28rpx] text-[#303133]">
<text>{{ option.label }}</text>
</view>
<view v-if="voteState === VOTE_STATES.VOTED" class="option-bar mt-3 h-4 overflow-hidden rounded-lg bg-[#f0f0f0]">
<view class="option-bar-inner h-full rounded-lg" :style="{ width: `${option.count || 0}%`, background: 'linear-gradient(90deg, #03a9f4, #64b5f6)' }" />
</view>
</view>
</view>
<view v-if="voteState === VOTE_STATES.VOTING" class="submit-btn mt-3">
<wd-button type="primary" size="small" block :loading="isSubmit" @click="handleSubmit">
{{ voteLabel }}
</wd-button>
</view>
<view v-else class="vote-tip mt-4 text-center text-[24rpx] text-[#909399]">
{{ voteLabel }}{{ voteResultLabel }}
</view>
</view>
</view>
</template>
<style scoped lang="scss">
.uh-vote-card {
.option {
&.active {
border-color: #03a9f4;
background-color: rgb(3 169 244 / 8%);
}
}
}
</style>