build all

Refactor utility functions for improved readability and consistency

- Updated compatibility.js to use consistent line endings and formatting.
- Refactored component.js for better readability and structure, including consistent use of arrow functions and binding.
- Simplified dom.js functions with consistent formatting and improved readability.
- Enhanced emitter.js with consistent formatting and arrow function usage.
- Streamlined error.js for improved readability and consistency.
- Refactored file.js to use consistent formatting and improved readability.
- Improved format.js functions for better readability and consistency.
- Updated index.js to maintain consistent export formatting.
- Refactored property.js for improved readability and consistency.
- Enhanced subtitle.js with consistent formatting and improved readability.
- Refactored time.js for better readability and consistent formatting.

fix: update lint script to target only source files for consistency

Revert "fix: restore export statements for various plugins and update type definitions for better clarity"

This reverts commit b5e969d81ec765cd8a34b06e6ef4f232ef25087f.

fix: restore export statements for various plugins and update type definitions for better clarity

Refactor type definitions to use interfaces instead of type aliases for better extensibility and clarity across i18n, icons, option, player, quality, setting, subtitle, template, and utils modules.
This commit is contained in:
Harvey Zack committed 2025-08-03 13:17:33 +08:00
1 parent 532dd67cfd
commit 35ad9883af
447 files changed
+18248 -17946

No files matched your search

@@ -1,88 +1,93 @@
function getMode(key) {
switch (key) {
case 1:
case 2:
case 3:
return 0;
case 4:
return 2;
case 5:
return 1;
default:
return 0;
}
switch (key) {
case 1:
case 2:
case 3:
return 0
case 4:
return 2
case 5:
return 1
default:
return 0
}
}
function bilibiliDanmuParseFromXml(xmlString) {
if (typeof xmlString !== 'string') return [];
const reg = new RegExp(/<d (?:.*? )??p="(?<p>.+?)"(?: .*?)?>(?<text>.+?)<\/d>/gs);
const matches = xmlString.matchAll(reg);
return Array.from(matches)
.map((match) => {
const attr = match.groups.p.split(',');
if (attr.length >= 8) {
const text = match.groups.text
.trim()
.replaceAll('&quot;', '"')
.replaceAll('&apos;', "'")
.replaceAll('&lt;', '<')
.replaceAll('&gt;', '>')
.replaceAll('&amp;', '&');
if (typeof xmlString !== 'string')
return []
const reg = /<d[^>]*?p="(?<p>[^"]+)"[^>]*>(?<text>.*?)<\/d>/gs
const matches = xmlString.matchAll(reg)
return Array.from(matches)
.map((match) => {
const attr = match.groups.p.split(',')
if (attr.length >= 8) {
const text = match.groups.text
.trim()
.replaceAll('&quot;', '"')
.replaceAll('&apos;', '\'')
.replaceAll('&lt;', '<')
.replaceAll('&gt;', '>')
.replaceAll('&amp;', '&')
return {
text,
time: Number(attr[0]),
mode: getMode(Number(attr[1])),
fontSize: Number(attr[2]),
color: `#${Number(attr[3]).toString(16)}`,
timestamp: Number(attr[4]),
pool: Number(attr[5]),
userID: attr[6],
rowID: Number(attr[7]),
};
} else {
return null;
}
})
.filter(Boolean);
return {
text,
time: Number(attr[0]),
mode: getMode(Number(attr[1])),
fontSize: Number(attr[2]),
color: `#${Number(attr[3]).toString(16)}`,
timestamp: Number(attr[4]),
pool: Number(attr[5]),
userID: attr[6],
rowID: Number(attr[7]),
}
}
else {
return null
}
})
.filter(Boolean)
}
function onmessage({ data }) {
const { xml, id } = data;
if (!id || !xml) return;
const danmus = bilibiliDanmuParseFromXml(xml);
self.postMessage({ danmus, id });
const { xml, id } = data
if (!id || !xml)
return
const danmus = bilibiliDanmuParseFromXml(xml)
globalThis.postMessage({ danmus, id })
}
function createWorker() {
const workerText = `
const workerText = `
${getMode.toString()}
${bilibiliDanmuParseFromXml.toString()}
onmessage = ${onmessage.toString()}
`;
const blob = new Blob([workerText], { type: 'application/javascript' });
return new Worker(URL.createObjectURL(blob));
`
const blob = new Blob([workerText], { type: 'application/javascript' })
return new Worker(URL.createObjectURL(blob))
}
export function bilibiliDanmuParseFromUrl(url) {
// eslint-disable-next-line no-async-promise-executor
return new Promise(async (resolve) => {
const res = await fetch(url);
const xml = await res.text();
// eslint-disable-next-line no-async-promise-executor
return new Promise(async (resolve) => {
const res = await fetch(url)
const xml = await res.text()
try {
const worker = createWorker();
worker.onmessage = (event) => {
const { danmus, id } = event.data;
if (!id || !danmus) return;
resolve(danmus);
worker.terminate();
};
worker.postMessage({ xml, id: Date.now() });
// eslint-disable-next-line no-unused-vars
} catch (error) {
const danmus = bilibiliDanmuParseFromXml(xml);
resolve(danmus);
}
});
try {
const worker = createWorker()
worker.onmessage = (event) => {
const { danmus, id } = event.data
if (!id || !danmus)
return
resolve(danmus)
worker.terminate()
}
worker.postMessage({ xml, id: Date.now() })
}
catch (error) {
console.error('Error parsing Bilibili Danmu:', error)
const danmus = bilibiliDanmuParseFromXml(xml)
resolve(danmus)
}
})
}
File diff suppressed because it is too large. Load diff
+149 -146
View File
@@ -1,146 +1,149 @@
const lib = {
map(value, inMin, inMax, outMin, outMax) {
return ((value - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;
},
range(start, end, tick) {
const s = Math.round(start / tick) * tick;
return Array.from(
{
length: Math.floor((end - start) / tick),
},
(v, k) => {
return k * tick + s;
},
);
},
};
map(value, inMin, inMax, outMin, outMax) {
return ((value - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin
},
range(start, end, tick) {
const s = Math.round(start / tick) * tick
return Array.from(
{
length: Math.floor((end - start) / tick),
},
(v, k) => {
return k * tick + s
},
)
},
}
const line = (pointA, pointB) => {
const lengthX = pointB[0] - pointA[0];
const lengthY = pointB[1] - pointA[1];
return {
length: Math.sqrt(Math.pow(lengthX, 2) + Math.pow(lengthY, 2)),
angle: Math.atan2(lengthY, lengthX),
};
};
function line(pointA, pointB) {
const lengthX = pointB[0] - pointA[0]
const lengthY = pointB[1] - pointA[1]
return {
length: Math.sqrt(lengthX ** 2 + lengthY ** 2),
angle: Math.atan2(lengthY, lengthX),
}
}
export default function heatmap(art, danmuku, option) {
const { query } = art.constructor.utils;
const { query } = art.constructor.utils
art.controls.add({
name: 'heatmap',
position: 'top',
html: '',
style: {
position: 'absolute',
top: '-100px',
left: '0px',
right: '0px',
height: '100px',
width: '100%',
pointerEvents: 'none',
},
mounted($heatmap) {
let $start = null;
let $stop = null;
art.controls.add({
name: 'heatmap',
position: 'top',
html: '',
style: {
position: 'absolute',
top: '-100px',
left: '0px',
right: '0px',
height: '100px',
width: '100%',
pointerEvents: 'none',
},
mounted($heatmap) {
let $start = null
let $stop = null
function update(arg = []) {
$start = null;
$stop = null;
$heatmap.innerHTML = '';
function update(arg = []) {
$start = null
$stop = null
$heatmap.innerHTML = ''
if (!art.duration || art.option.isLive) return;
if (!art.duration || art.option.isLive)
return
const svg = {
w: $heatmap.offsetWidth,
h: $heatmap.offsetHeight,
};
const svg = {
w: $heatmap.offsetWidth,
h: $heatmap.offsetHeight,
}
const options = {
xMin: 0,
xMax: svg.w,
yMin: 0,
yMax: 128,
scale: 0.25,
opacity: 0.2,
minHeight: Math.floor(svg.h * 0.05),
sampling: Math.floor(svg.w / 100),
smoothing: 0.2,
flattening: 0.2,
};
const options = {
xMin: 0,
xMax: svg.w,
yMin: 0,
yMax: 128,
scale: 0.25,
opacity: 0.2,
minHeight: Math.floor(svg.h * 0.05),
sampling: Math.floor(svg.w / 100),
smoothing: 0.2,
flattening: 0.2,
}
if (typeof option === 'object') {
Object.assign(options, option);
}
if (typeof option === 'object') {
Object.assign(options, option)
}
let points = [];
let points = []
if (Array.isArray(arg) && arg.length) {
points = [...arg];
} else {
const gap = art.duration / svg.w;
for (let x = 0; x <= svg.w; x += options.sampling) {
const y = danmuku.queue.filter(
({ time }) => time > x * gap && time <= (x + options.sampling) * gap,
).length;
points.push([x, y]);
}
}
if (Array.isArray(arg) && arg.length) {
points = [...arg]
}
else {
const gap = art.duration / svg.w
for (let x = 0; x <= svg.w; x += options.sampling) {
const y = danmuku.queue.filter(
({ time }) => time > x * gap && time <= (x + options.sampling) * gap,
).length
points.push([x, y])
}
}
if (points.length === 0) return;
if (points.length === 0)
return
const lastPoint = points[points.length - 1];
const lastX = lastPoint[0];
const lastY = lastPoint[1];
if (lastX !== svg.w) {
points.push([svg.w, lastY]);
}
const lastPoint = points[points.length - 1]
const lastX = lastPoint[0]
const lastY = lastPoint[1]
if (lastX !== svg.w) {
points.push([svg.w, lastY])
}
const yPoints = points.map((point) => point[1]);
const yMin = Math.min(...yPoints);
const yMax = Math.max(...yPoints);
const yMid = (yMin + yMax) / 2;
const yPoints = points.map(point => point[1])
const yMin = Math.min(...yPoints)
const yMax = Math.max(...yPoints)
const yMid = (yMin + yMax) / 2
for (let i = 0; i < points.length; i++) {
const point = points[i];
const y = point[1];
point[1] = y * (y > yMid ? 1 + options.scale : 1 - options.scale) + options.minHeight;
}
for (let i = 0; i < points.length; i++) {
const point = points[i]
const y = point[1]
point[1] = y * (y > yMid ? 1 + options.scale : 1 - options.scale) + options.minHeight
}
const controlPoint = (current, previous, next, reverse) => {
const p = previous || current;
const n = next || current;
const o = line(p, n);
const flat = lib.map(Math.cos(o.angle) * options.flattening, 0, 1, 1, 0);
const angle = o.angle * flat + (reverse ? Math.PI : 0);
const length = o.length * options.smoothing;
const x = current[0] + Math.cos(angle) * length;
const y = current[1] + Math.sin(angle) * length;
return [x, y];
};
const controlPoint = (current, previous, next, reverse) => {
const p = previous || current
const n = next || current
const o = line(p, n)
const flat = lib.map(Math.cos(o.angle) * options.flattening, 0, 1, 1, 0)
const angle = o.angle * flat + (reverse ? Math.PI : 0)
const length = o.length * options.smoothing
const x = current[0] + Math.cos(angle) * length
const y = current[1] + Math.sin(angle) * length
return [x, y]
}
const bezierCommand = (point, i, a) => {
const cps = controlPoint(a[i - 1], a[i - 2], point);
const cpe = controlPoint(point, a[i - 1], a[i + 1], true);
const close = i === a.length - 1 ? ' z' : '';
return `C ${cps[0]},${cps[1]} ${cpe[0]},${cpe[1]} ${point[0]},${point[1]}${close}`;
};
const bezierCommand = (point, i, a) => {
const cps = controlPoint(a[i - 1], a[i - 2], point)
const cpe = controlPoint(point, a[i - 1], a[i + 1], true)
const close = i === a.length - 1 ? ' z' : ''
return `C ${cps[0]},${cps[1]} ${cpe[0]},${cpe[1]} ${point[0]},${point[1]}${close}`
}
const pointsPositions = points.map((e) => {
const x = lib.map(e[0], options.xMin, options.xMax, 0, svg.w);
const y = lib.map(e[1], options.yMin, options.yMax, svg.h, 0);
return [x, y];
});
const pointsPositions = points.map((e) => {
const x = lib.map(e[0], options.xMin, options.xMax, 0, svg.w)
const y = lib.map(e[1], options.yMin, options.yMax, svg.h, 0)
return [x, y]
})
const pathD = pointsPositions.reduce(
(acc, e, i, a) =>
i === 0
? `M ${a[a.length - 1][0]},${svg.h} L ${e[0]},${svg.h} L ${e[0]},${e[1]}`
: `${acc} ${bezierCommand(e, i, a)}`,
'',
);
const pathD = pointsPositions.reduce(
(acc, e, i, a) =>
i === 0
? `M ${a[a.length - 1][0]},${svg.h} L ${e[0]},${svg.h} L ${e[0]},${e[1]}`
: `${acc} ${bezierCommand(e, i, a)}`,
'',
)
$heatmap.innerHTML = `
$heatmap.innerHTML = `
<svg viewBox="0 0 ${svg.w} ${svg.h}">
<defs>
<linearGradient id="heatmap-solids" x1="0%" y1="0%" x2="100%" y2="0%">
@@ -152,32 +155,32 @@ export default function heatmap(art, danmuku, option) {
</defs>
<path fill="url(#heatmap-solids)" d="${pathD}"></path>
</svg>
`;
`
$start = query('#heatmap-start', $heatmap);
$stop = query('#heatmap-stop', $heatmap);
$start.setAttribute('offset', `${art.played * 100}%`);
$stop.setAttribute('offset', `${art.played * 100}%`);
}
$start = query('#heatmap-start', $heatmap)
$stop = query('#heatmap-stop', $heatmap)
$start.setAttribute('offset', `${art.played * 100}%`)
$stop.setAttribute('offset', `${art.played * 100}%`)
}
art.on('video:timeupdate', () => {
if ($start && $stop) {
$start.setAttribute('offset', `${art.played * 100}%`);
$stop.setAttribute('offset', `${art.played * 100}%`);
}
});
art.on('video:timeupdate', () => {
if ($start && $stop) {
$start.setAttribute('offset', `${art.played * 100}%`)
$stop.setAttribute('offset', `${art.played * 100}%`)
}
})
art.on('setBar', (type, percentage) => {
if ($start && $stop && type === 'played') {
$start.setAttribute('offset', `${percentage * 100}%`);
$stop.setAttribute('offset', `${percentage * 100}%`);
}
});
art.on('setBar', (type, percentage) => {
if ($start && $stop && type === 'played') {
$start.setAttribute('offset', `${percentage * 100}%`)
$stop.setAttribute('offset', `${percentage * 100}%`)
}
})
art.on('ready', () => update());
art.on('resize', () => update());
art.on('artplayerPluginDanmuku:loaded', () => update());
art.on('artplayerPluginDanmuku:points', (points) => update(points));
},
});
art.on('ready', () => update())
art.on('resize', () => update())
art.on('artplayerPluginDanmuku:loaded', () => update())
art.on('artplayerPluginDanmuku:points', points => update(points))
},
})
}
+31 -31
View File
@@ -1,40 +1,40 @@
import Danmuku from './danmuku';
import Setting from './setting';
import heatmap from './heatmap';
import Danmuku from './danmuku'
import heatmap from './heatmap'
import Setting from './setting'
export default function artplayerPluginDanmuku(option) {
return (art) => {
const danmuku = new Danmuku(art, option);
const setting = new Setting(art, danmuku);
return (art) => {
const danmuku = new Danmuku(art, option)
const setting = new Setting(art, danmuku)
if (danmuku.option.heatmap) {
heatmap(art, danmuku, danmuku.option.heatmap);
}
if (danmuku.option.heatmap) {
heatmap(art, danmuku, danmuku.option.heatmap)
}
return {
name: 'artplayerPluginDanmuku',
emit: danmuku.emit.bind(danmuku),
load: danmuku.load.bind(danmuku),
config: danmuku.config.bind(danmuku),
hide: danmuku.hide.bind(danmuku),
show: danmuku.show.bind(danmuku),
reset: danmuku.reset.bind(danmuku),
mount: setting.mount.bind(setting),
get option() {
return danmuku.option;
},
get isHide() {
return danmuku.isHide;
},
get isStop() {
return danmuku.isStop;
},
};
};
return {
name: 'artplayerPluginDanmuku',
emit: danmuku.emit.bind(danmuku),
load: danmuku.load.bind(danmuku),
config: danmuku.config.bind(danmuku),
hide: danmuku.hide.bind(danmuku),
show: danmuku.show.bind(danmuku),
reset: danmuku.reset.bind(danmuku),
mount: setting.mount.bind(setting),
get option() {
return danmuku.option
},
get isHide() {
return danmuku.isHide
},
get isStop() {
return danmuku.isStop
},
}
}
}
artplayerPluginDanmuku.icons = Setting.icons;
artplayerPluginDanmuku.icons = Setting.icons
if (typeof window !== 'undefined') {
window['artplayerPluginDanmuku'] = artplayerPluginDanmuku;
window.artplayerPluginDanmuku = artplayerPluginDanmuku
}
File diff suppressed because it is too large. Load diff
+140 -131
View File
@@ -1,142 +1,151 @@
function getDanmuTop({ target, visibles, clientWidth, clientHeight, marginBottom, marginTop, antiOverlap }) {
// 弹幕最大高度
const maxTop = clientHeight - marginBottom;
// 弹幕最大高度
const maxTop = clientHeight - marginBottom
// 过滤同模式的弹幕,即每种模式各不影响
const danmus = visibles
.filter((item) => item.mode === target.mode && item.top <= maxTop)
.sort((prev, next) => prev.top - next.top);
// 过滤同模式的弹幕,即每种模式各不影响
const danmus = visibles
.filter(item => item.mode === target.mode && item.top <= maxTop)
.sort((prev, next) => prev.top - next.top)
// 如果没有同模式的弹幕,直接返回
if (danmus.length === 0) {
if (target.mode === 2) {
return maxTop - target.height;
} else {
return marginTop;
}
}
// 上下各加一个虚拟弹幕,方便计算
danmus.unshift({
type: 'top',
top: 0,
left: 0,
right: 0,
height: marginTop,
width: clientWidth,
speed: 0,
distance: clientWidth,
});
danmus.push({
type: 'bottom',
top: maxTop,
left: 0,
right: 0,
height: marginBottom,
width: clientWidth,
speed: 0,
distance: clientWidth,
});
// 查找是否有多余的缝隙足以容纳当前弹幕
// 如果没有同模式的弹幕,直接返回
if (danmus.length === 0) {
if (target.mode === 2) {
// 倒序查找
for (let index = danmus.length - 2; index >= 0; index -= 1) {
const item = danmus[index];
const prev = danmus[index + 1];
const itemBottom = item.top + item.height;
const diff = prev.top - itemBottom;
if (diff >= target.height) {
return prev.top - target.height;
}
}
} else {
// 顺序查找
for (let index = 1; index < danmus.length; index += 1) {
const item = danmus[index];
const prev = danmus[index - 1];
const prevBottom = prev.top + prev.height;
const diff = item.top - prevBottom;
if (diff >= target.height) {
return prevBottom;
}
}
return maxTop - target.height
}
else {
return marginTop
}
}
// 上下各加一个虚拟弹幕,方便计算
danmus.unshift({
type: 'top',
top: 0,
left: 0,
right: 0,
height: marginTop,
width: clientWidth,
speed: 0,
distance: clientWidth,
})
danmus.push({
type: 'bottom',
top: maxTop,
left: 0,
right: 0,
height: marginBottom,
width: clientWidth,
speed: 0,
distance: clientWidth,
})
// 查找是否有多余的缝隙足以容纳当前弹幕
if (target.mode === 2) {
// 倒序查找
for (let index = danmus.length - 2; index >= 0; index -= 1) {
const item = danmus[index]
const prev = danmus[index + 1]
const itemBottom = item.top + item.height
const diff = prev.top - itemBottom
if (diff >= target.height) {
return prev.top - target.height
}
}
}
else {
// 顺序查找
for (let index = 1; index < danmus.length; index += 1) {
const item = danmus[index]
const prev = danmus[index - 1]
const prevBottom = prev.top + prev.height
const diff = item.top - prevBottom
if (diff >= target.height) {
return prevBottom
}
}
}
const topMap = []
for (let index = 1; index < danmus.length - 1; index += 1) {
const item = danmus[index]
if (topMap.length) {
const last = topMap[topMap.length - 1]
if (last[0].top === item.top) {
last.push(item)
}
else {
topMap.push([item])
}
}
else {
topMap.push([item])
}
}
if (antiOverlap) {
switch (target.mode) {
case 0: {
const result = topMap.find((list) => {
return list.every((danmu) => {
if (clientWidth < danmu.distance)
return false
if (target.speed < danmu.speed)
return true
const overlapTime = danmu.right / (target.speed - danmu.speed)
if (overlapTime > danmu.time)
return true
return false
})
})
return result && result[0] ? result[0].top : undefined
}
// 静止弹幕没有重叠问题
case 1:
case 2:
return undefined
default:
break
}
}
else {
switch (target.mode) {
case 0:
topMap.sort((prev, next) => {
const nextMinRight = Math.min(...next.map(item => item.right))
const prevMinRight = Math.min(...prev.map(item => item.right))
return nextMinRight * next.length - prevMinRight * prev.length
})
break
case 1:
case 2:
topMap.sort((prev, next) => {
const nextMaxWidth = Math.max(...next.map(item => item.width))
const prevMaxWidth = Math.max(...prev.map(item => item.width))
return prevMaxWidth * prev.length - nextMaxWidth * next.length
})
break
default:
break
}
const topMap = [];
for (let index = 1; index < danmus.length - 1; index += 1) {
const item = danmus[index];
if (topMap.length) {
const last = topMap[topMap.length - 1];
if (last[0].top === item.top) {
last.push(item);
} else {
topMap.push([item]);
}
} else {
topMap.push([item]);
}
}
if (antiOverlap) {
switch (target.mode) {
case 0: {
const result = topMap.find((list) => {
return list.every((danmu) => {
if (clientWidth < danmu.distance) return false;
if (target.speed < danmu.speed) return true;
const overlapTime = danmu.right / (target.speed - danmu.speed);
if (overlapTime > danmu.time) return true;
return false;
});
});
return result && result[0] ? result[0].top : undefined;
}
// 静止弹幕没有重叠问题
case 1:
case 2:
return undefined;
default:
break;
}
} else {
switch (target.mode) {
case 0:
topMap.sort((prev, next) => {
const nextMinRight = Math.min(...next.map((item) => item.right));
const prevMinRight = Math.min(...prev.map((item) => item.right));
return nextMinRight * next.length - prevMinRight * prev.length;
});
break;
case 1:
case 2:
topMap.sort((prev, next) => {
const nextMaxWidth = Math.max(...next.map((item) => item.width));
const prevMaxWidth = Math.max(...prev.map((item) => item.width));
return prevMaxWidth * prev.length - nextMaxWidth * next.length;
});
break;
default:
break;
}
return topMap[0][0].top;
}
return topMap[0][0].top
}
}
onmessage = (event) => {
const { data } = event;
if (!data.id || !data.type) return;
const { data } = event
if (!data.id || !data.type)
return
const fns = { getDanmuTop };
const fn = fns[data.type];
const result = fn(data);
const fns = { getDanmuTop }
const fn = fns[data.type]
const result = fn(data)
self.postMessage({
result,
id: data.id,
});
};
globalThis.postMessage({
result,
id: data.id,
})
}