调整整体样式

This commit is contained in:
Harvey Zack committed 2019-04-30 15:10:30 +08:00
1 parent 487e865017
commit fa585e536a
49 files changed
+984 -322

No files matched your search

@@ -0,0 +1,9 @@
node_modules
.DS_Store
yarn.lock
package-lock.json
test
coverage
.nyc_output
.cache
docs
+1
View File
@@ -0,0 +1 @@
package-lock=false
@@ -0,0 +1,80 @@
# artplayer-plugin-danmuku
Danmuku plugin for ArtPlayer
## Demo
[Checkout the demo](https://artplayer.org/?libs=.%2Funcompiled%2Fartplayer-plugin-danmuku.js&example=danmuku) from Github Pages
## Install
Install with `npm`
```
$ npm install artplayer-plugin-danmuku
```
Or install with `yarn`
```
$ yarn add artplayer-plugin-danmuku
```
```js
import artplayerPluginBacklight from 'artplayer-plugin-danmuku';
```
Or umd builds are also available
```html
<script src="artplayer-plugin-danmuku.js"></script>
```
Will expose the global variable to `window.artplayerPluginDanmuku`.
## Usage
```js
var art = new Artplayer({
container: '.artplayer-app',
url: 'path/to/video.mp4',
plugins: [artplayerPluginDanmuku({
danmuku: [], // Can be an array or return the promised function or danmuku xml url
speed: 5, // Animation time
opacity: 1, // Opacity
color: '#fff', // Font color
size: 25, // Font size
maxlength: 50, // The maximum number of words in the danmu
margin: [10, 20], // Margin top and margin bottom
})],
});
// Send danmu
art.plugins.artplayerPluginDanmuku.emit({
text: '666', // Danmu text
time: 5, // Video time
color: '#fff', // Danmu color
size: 25, // Danmu size
border: '#fff' // Danmu border color
});
// Start danmu
art.plugins.artplayerPluginDanmuku.start();
// Stop danmu
art.plugins.artplayerPluginDanmuku.stop();
// Hide danmu
art.plugins.artplayerPluginDanmuku.hide();
// Show danmu
art.plugins.artplayerPluginDanmuku.show();
// Config danmu
art.plugins.artplayerPluginDanmuku.config({
// option
});
```
## License
MIT © [Harvey Zack](https://sleepy.im/)
@@ -0,0 +1 @@
.artplayerPluginDanmu{display:-webkit-box;display:-ms-flexbox;display:flex}
@@ -0,0 +1,8 @@
/*!
* artplayer-plugin-danmu.js v3.1.7
* Github: https://github.com/zhw2590582/ArtPlayer#readme
* (c) 2017-2019 Harvey Zack
* Released under the MIT License.
*/
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self)["artplayer-plugin-danmu"]=e()}(this,function(){"use strict";var n=function(t){if(Array.isArray(t))return t};var i=function(t,e){var n=[],i=!0,r=!1,o=void 0;try{for(var a,s=t[Symbol.iterator]();!(i=(a=s.next()).done)&&(n.push(a.value),!e||n.length!==e);i=!0);}catch(t){r=!0,o=t}finally{try{i||null==s.return||s.return()}finally{if(r)throw o}}return n};var r=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")};var p=function(t,e){return n(t)||i(t,e)||r()};function e(t){if("string"!=typeof t)return[];var e=t.match(/<d([\S ]*?>[\S ]*?)<\/d>/gi);return e.length?e.map(function(t){var e=t.match(/<d p="(.+)">(.+)<\/d>/),n=p(e,3),i=n[1],r=n[2],o=i.split(",");return 8===o.length&&r.trim()?{text:r,time:Number(o[0]),mode:Number(o[1]),size:Number(o[2]),color:"#".concat(Number(o[3]).toString(16)),timestamp:Number(o[4]),pool:Number(o[5]),userID:o[6],rowID:Number(o[7])}:null}):[]}function o(t){return fetch(t).then(function(t){return t.text()}).then(function(t){return e(t)})}var a=function(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t};var s=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},i=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(i=i.concat(Object.getOwnPropertySymbols(n).filter(function(t){return Object.getOwnPropertyDescriptor(n,t).enumerable}))),i.forEach(function(t){a(e,t,n[t])})}return e};var u=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")};function l(t,e){for(var n=0;n<e.length;n++){var i=e[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}var t=function(t,e,n){return e&&l(t.prototype,e),n&&l(t,n),t};function c(t){var e=function(t){for(var e=0,n=0,i=1;i<t.length;i+=1){var r=t[i],o=t[i-1],a=o.top+o.height,s=r.top-a;n<s&&(e=a,n=s)}return e}(t);return 0===e&&(e=function(t){for(var e={},n=0;n<t.length;n+=1){var i=t[n];e[i.top]?e[i.top].push(i):e[i.top]=[i]}for(var r=0,o=0,a=Object.keys(e),s=0;s<a.length;s+=1){for(var u=t[0].width,l=e[a[s]],h=0;h<l.length;h+=1){var c=l[h];c.right<u&&(u=c.right)}r<u&&(r=u,o=p(l,1)[0].top)}return 0===o&&(o=a[Math.floor(Math.random()*(2-a.length)+a.length-1)]),o}(t)),e}var h=function(){function h(e,t){var n=this;u(this,h),this.art=e,this.queue=[],this.layer=null,this.isStop=!1,this.animationFrameTimer=null,e.on("video:play",this.start.bind(this)),e.on("video:playing",this.start.bind(this)),e.on("video:pause",this.stop.bind(this)),e.on("video:waiting",this.stop.bind(this)),e.on("destroy",this.stop.bind(this)),this.config(t),"function"==typeof this.option.danmus?this.option.danmus().then(function(t){t.forEach(n.addToQueue.bind(n)),n.init(),e.emit("artplayerPluginDanmu:loaded",t)}):"string"==typeof this.option.danmus?o(this.option.danmus).then(function(t){t.forEach(n.addToQueue.bind(n)),n.init(),e.emit("artplayerPluginDanmu:loaded",t)}):(this.option.danmus.forEach(this.addToQueue.bind(this)),this.init())}return t(h,[{key:"config",value:function(t){var e=this.art.constructor,n=e.utils.clamp,i=e.validator;this.option=Object.assign({},h.option,t),i(this.option,h.scheme),this.option.speed=n(this.option.speed,1,10),this.option.opacity=n(this.option.opacity,0,1),this.option.size=n(this.option.size,12,30),this.option.maxlength=n(this.option.maxlength,10,100),this.option.margin[0]=n(this.option.margin[0],0,100),this.option.margin[1]=n(this.option.margin[1],0,100)}},{key:"init",value:function(){this.layer=this.art.layers.add({name:"danmu",style:{position:"absolute",left:0,top:0,right:0,bottom:0,width:"100%",height:"100%",overflow:"hidden",pointerEvents:"none",opacity:this.option.opacity}})}},{key:"emit",value:function(t){var e=this.art.template.$player;t.$ref=this.getDanmuRef(),t.$ref.innerText=t.text,t.$ref.style.fontSize="".concat(t.size||this.option.size,"px");var n=h.getRect(e,"width"),i=h.getRect(t.$ref,"width");t.$restWidth=n+i+5,t.$restTime=this.option.speed,t.$lastStartTime=Date.now(),t.$ref.style.color=t.color||this.option.color,t.$ref.style.left="".concat(n,"px"),t.$ref.style.top="".concat(this.getDanmuTop(),"px"),t.$ref.style.transform="translateX(".concat(-t.$restWidth,"px) translateY(0px) translateZ(0px)"),t.$ref.style.transition="-webkit-transform ".concat(t.$restTime,"s linear 0s"),t.border&&(t.$ref.style.border="1px solid ".concat(t.border)),t.$state="emit"}},{key:"suspend",value:function(t){var e=this.art.template.$player,n=h.getRect(e),i=n.left,r=n.width,o=h.getRect(t.$ref).left;t.$restTime-=(Date.now()-t.$lastStartTime)/1e3;var a=r-(o-i)+5;t.$ref.style.transform="translateX(".concat(-a,"px) translateY(0px) translateZ(0px)"),t.$ref.style.transition="-webkit-transform 0s linear 0s",t.$state="stop"}},{key:"addToQueue",value:function(t){var e=this.art,n=e.notice,i=e.player;t.teLine truncated
@@ -0,0 +1,23 @@
{
"name": "artplayer-plugin-danmuku",
"version": "3.1.7",
"description": "Danmuku plugin for ArtPlayer",
"main": "dist/artplayer-plugin-danmuku.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/zhw2590582/ArtPlayer.git"
},
"keywords": [
"video",
"player"
],
"author": "Harvey Zack <laozhaochaguan@gmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/zhw2590582/ArtPlayer/issues"
},
"homepage": "https://github.com/zhw2590582/ArtPlayer#readme"
}
@@ -0,0 +1,43 @@
export function bilibiliDanmuParseFromXml(xmlString) {
if (typeof xmlString !== 'string') return [];
const srtList = xmlString.match(/<d([\S ]*?>[\S ]*?)<\/d>/gi);
return srtList.length
? srtList.map(item => {
const [, attrStr, text] = item.match(/<d p="(.+)">(.+)<\/d>/);
const attr = attrStr.split(',');
return attr.length === 8 && text.trim()
? {
text,
time: Number(attr[0]),
mode: Number(attr[1]),
size: Number(attr[2]),
color: `#${Number(attr[3]).toString(16)}`,
timestamp: Number(attr[4]),
pool: Number(attr[5]),
userID: attr[6],
rowID: Number(attr[7]),
}
: null;
})
: [];
}
export function bilibiliDanmuParseFromUrl(url) {
return fetch(url)
.then(res => res.text())
.then(xmlString => {
return bilibiliDanmuParseFromXml(xmlString);
});
}
export function bilibiliDanmuParseFromAv(av) {
const corsUrl = 'https://cors-anywhere.herokuapp.com/';
return fetch(`${corsUrl}https://api.bilibili.com/x/web-interface/view?aid=${av}`)
.then(res => res.json())
.then(res => {
if (res.code === 0 && res.data && res.data.cid) {
return bilibiliDanmuParseFromUrl(`${corsUrl}https://api.bilibili.com/x/v1/dm/list.so?oid=${res.data.cid}`);
}
throw new Error(`Unable to get data: ${JSON.stringify(res)}`);
});
}
@@ -0,0 +1,317 @@
import { bilibiliDanmuParseFromUrl } from './bilibiliDanmuParse';
import getDanmuTop from './getDanmuTop';
export default class Danmuku {
constructor(art, option) {
this.art = art;
this.queue = [];
this.isStop = false;
this.refs = [];
this.animationFrameTimer = null;
this.$danmuku = art.template.$danmuku;
art.i18n.update(Danmuku.i18n);
art.on('video:play', this.start.bind(this));
art.on('video:playing', this.start.bind(this));
art.on('video:pause', this.stop.bind(this));
art.on('video:waiting', this.stop.bind(this));
art.on('resize', this.resize.bind(this));
art.on('destroy', this.stop.bind(this));
this.config(option);
if (typeof this.option.danmuku === 'function') {
this.option.danmuku().then(danmus => {
danmus.forEach(this.addToQueue.bind(this));
art.emit('artplayerPluginDanmuku:loaded');
});
} else if (typeof this.option.danmuku === 'string') {
bilibiliDanmuParseFromUrl(this.option.danmuku).then(danmus => {
danmus.forEach(this.addToQueue.bind(this));
art.emit('artplayerPluginDanmuku:loaded');
});
} else {
this.option.danmuku.forEach(this.addToQueue.bind(this));
art.emit('artplayerPluginDanmuku:loaded');
}
}
static get i18n() {
return {
'zh-cn': {
'Danmu text cannot be empty': '弹幕文本不能为空',
'The length of the danmu does not exceed': '弹幕文本字数不能超过',
},
'zh-tw': {
'Danmu text cannot be empty': '彈幕文本不能為空',
'The length of the danmu does not exceed': '彈幕文本字數不能超過',
},
};
}
static get option() {
return {
danmuku: [],
speed: 5,
opacity: 1,
color: '#fff',
size: 25,
maxlength: 50,
margin: [10, 20],
};
}
static get scheme() {
return {
danmuku: 'array|function|string',
speed: 'number',
opacity: 'number',
color: 'string',
size: 'number',
maxlength: 'number',
margin: 'array',
};
}
static getRect(ref, key) {
const result = ref.getBoundingClientRect();
return key ? result[key] : result;
}
config(option) {
const {
utils: { clamp },
validator,
} = this.art.constructor;
this.option = Object.assign({}, Danmuku.option, option);
validator(this.option, Danmuku.scheme);
this.option.speed = clamp(this.option.speed, 1, 10);
this.option.opacity = clamp(this.option.opacity, 0, 1);
this.option.size = clamp(this.option.size, 12, 30);
this.option.maxlength = clamp(this.option.maxlength, 10, 100);
this.option.margin[0] = clamp(this.option.margin[0], 0, 100);
this.option.margin[1] = clamp(this.option.margin[1], 0, 100);
}
emit(danmu) {
const { $player } = this.art.template;
danmu.$ref = this.getDanmuRef();
danmu.$ref.innerText = danmu.text;
danmu.$ref.style.fontSize = `${danmu.size || this.option.size}px`;
const playerWidth = Danmuku.getRect($player, 'width');
const danmuWidth = Danmuku.getRect(danmu.$ref, 'width');
danmu.$restWidth = playerWidth + danmuWidth + 5;
danmu.$restTime = this.option.speed;
danmu.$lastStartTime = Date.now();
danmu.$ref.style.color = danmu.color || this.option.color;
danmu.$ref.style.left = `${playerWidth}px`;
danmu.$ref.style.top = `${this.getDanmuTop()}px`;
danmu.$ref.style.transform = `translateX(${-danmu.$restWidth}px) translateY(0px) translateZ(0px)`;
danmu.$ref.style.transition = `transform ${danmu.$restTime}s linear 0s`;
if (danmu.border) {
danmu.$ref.style.border = `1px solid ${danmu.border}`;
}
danmu.$state = 'emit';
}
static continue(danmu) {
danmu.$lastStartTime = Date.now();
danmu.$ref.style.transform = `translateX(${-danmu.$restWidth}px) translateY(0px) translateZ(0px)`;
danmu.$ref.style.transition = `transform ${danmu.$restTime}s linear 0s`;
danmu.$state = 'emit';
}
resize() {
const { $player } = this.art.template;
const { width: playerWidth } = Danmuku.getRect($player);
this.queue.forEach(danmu => {
danmu.$state = 'wait';
});
this.refs.forEach($ref => {
$ref.style.left = `${playerWidth}px`;
$ref.style.border = 'none';
$ref.style.transform = 'translateX(0px) translateY(0px) translateZ(0px)';
$ref.style.transition = 'transform 0s linear 0s';
});
}
suspend(danmu) {
const { $player } = this.art.template;
const { left: playerLeft, width: playerWidth } = Danmuku.getRect($player);
const { left: danmuLeft } = Danmuku.getRect(danmu.$ref);
danmu.$restTime -= (Date.now() - danmu.$lastStartTime) / 1000;
const translateX = playerWidth - (danmuLeft - playerLeft) + 5;
danmu.$ref.style.transform = `translateX(${-translateX}px) translateY(0px) translateZ(0px)`;
danmu.$ref.style.transition = 'transform 0s linear 0s';
danmu.$state = 'stop';
}
addToQueue(danmu) {
const { notice, player, i18n } = this.art;
if (!danmu.text.trim()) {
notice.show(i18n.get('Danmu text cannot be empty'));
return;
}
if (danmu.text.length > this.option.maxlength) {
notice.show(`${i18n.get('The length of the danmu does not exceed')} ${this.option.maxlength}`);
return;
}
if (typeof danmu.time !== 'number') {
danmu.time = player.currentTime;
}
this.queue.push({
...danmu,
$state: 'wait',
$ref: null,
$restTime: 0,
$lastStartTime: 0,
});
}
getDanmuRef() {
const { $player } = this.art.template;
const { setStyles, append } = this.art.constructor.utils;
const playerLeft = Danmuku.getRect($player, 'left');
const waitDanmu = this.queue.find(danmu => {
if (danmu.$ref) {
const { left: danmuLeft, width: danmuWidth } = Danmuku.getRect(danmu.$ref);
return danmu.$state === 'emit' && playerLeft > danmuLeft + danmuWidth;
}
return false;
});
if (waitDanmu) {
waitDanmu.$state = 'wait';
waitDanmu.$ref.style.border = 'none';
waitDanmu.$ref.style.transform = 'translateX(0px) translateY(0px) translateZ(0px)';
waitDanmu.$ref.style.transition = 'transform 0s linear 0s';
this.$danmuku.appendChild(waitDanmu.$ref);
return waitDanmu.$ref;
}
const $ref = document.createElement('div');
setStyles($ref, {
userSelect: 'none',
position: 'absolute',
whiteSpace: 'pre',
pointerEvents: 'none',
perspective: '500px',
display: 'inline-block',
willChange: 'transform',
fontFamily: 'SimHei, "Microsoft JhengHei", Arial, Helvetica, sans-serif',
fontWeight: 'normal',
lineHeight: '1.125',
textShadow:
'rgb(0, 0, 0) 1px 0px 1px, rgb(0, 0, 0) 0px 1px 1px, rgb(0, 0, 0) 0px -1px 1px, rgb(0, 0, 0) -1px 0px 1px',
});
append(this.$danmuku, $ref);
this.refs.push($ref);
return $ref;
}
getDanmuTop() {
const { $player } = this.art.template;
const { left: playerLeft, top: playerTop, height: playerHeight, width: playerWidth } = Danmuku.getRect($player);
const danmus = this.queue.filter(danmu => danmu.$state === 'emit');
if (danmus.length === 0) {
return this.option.margin[0];
}
const danmusBySort = danmus
.map(danmu => {
const { left: danmuLeft, top: danmuTop, width: danmuWidth, height: danmuHeight } = Danmuku.getRect(
danmu.$ref,
);
const top = danmuTop - playerTop;
const left = danmuLeft - playerLeft;
const right = playerWidth - left - danmuWidth;
return {
top,
left,
right,
height: danmuHeight,
width: danmuWidth,
};
})
.sort((prev, next) => {
return prev.top - next.top;
});
danmusBySort.unshift({
top: 0,
left: 0,
right: 0,
height: this.option.margin[0],
width: playerWidth,
});
danmusBySort.push({
top: playerHeight - this.option.margin[1],
left: 0,
right: 0,
height: this.option.margin[1],
width: playerWidth,
});
return getDanmuTop(danmusBySort);
}
update() {
const { player } = this.art;
this.animationFrameTimer = window.requestAnimationFrame(() => {
if (player.playing) {
this.queue
.filter(danmu => {
return (
player.currentTime + 0.1 >= danmu.time &&
danmu.time >= player.currentTime - 0.1 &&
danmu.$state === 'wait'
);
})
.forEach(danmu => {
this.emit(danmu);
});
}
if (!this.isStop) {
this.update();
}
});
}
stop() {
this.isStop = true;
this.queue
.filter(danmu => danmu.$state === 'emit')
.forEach(danmu => {
this.suspend(danmu);
});
window.cancelAnimationFrame(this.animationFrameTimer);
this.art.emit('artplayerPluginDanmu:stop');
}
start() {
this.isStop = false;
this.queue
.filter(danmu => danmu.$state === 'stop')
.forEach(danmu => {
Danmuku.continue(danmu);
});
this.update();
this.art.emit('artplayerPluginDanmu:start');
}
show() {
this.$danmuku.style = 'none';
this.art.emit('artplayerPluginDanmu:show');
}
hide() {
this.$danmuku.style = 'block';
this.art.emit('artplayerPluginDanmu:hide');
}
}
@@ -0,0 +1,62 @@
function getDanmuTopByDiff(danmus) {
let top = 0;
let maxDiff = 0;
for (let index = 1; index < danmus.length; index += 1) {
const item = danmus[index];
const prev = danmus[index - 1];
const prevTop = prev.top + prev.height;
const diff = item.top - prevTop;
if (diff > maxDiff) {
top = prevTop;
maxDiff = diff;
}
}
return top;
}
function getDanmuTopBySparse(danmus) {
const topMap = {};
for (let index = 0; index < danmus.length; index += 1) {
const item = danmus[index];
if (topMap[item.top]) {
topMap[item.top].push(item);
} else {
topMap[item.top] = [item];
}
}
let maxRight = 0;
let top = 0;
const topMapKeys = Object.keys(topMap);
for (let index = 0; index < topMapKeys.length; index += 1) {
let minRight = danmus[0].width;
const topKey = topMapKeys[index];
const danmuArr = topMap[topKey];
for (let index = 0; index < danmuArr.length; index += 1) {
const danmu = danmuArr[index];
if (danmu.right < minRight) {
minRight = danmu.right;
}
}
if (minRight > maxRight) {
maxRight = minRight;
[{ top }] = danmuArr;
}
}
if (top === 0) {
const randomKey = Math.floor(Math.random() * (2 - topMapKeys.length) + topMapKeys.length - 1);
top = topMapKeys[randomKey];
}
return top;
}
export default function getDanmuTop(danmus) {
let top = getDanmuTopByDiff(danmus);
if (top === 0) {
top = getDanmuTopBySparse(danmus);
}
return top;
}
@@ -0,0 +1,23 @@
import { bilibiliDanmuParseFromXml, bilibiliDanmuParseFromAv, bilibiliDanmuParseFromUrl } from './bilibiliDanmuParse';
import Danmuku from './danmuku';
function artplayerPluginDanmuku(option) {
return art => {
const danmuku = new Danmuku(art, option);
return {
name: 'artplayerPluginDanmuku',
emit: danmuku.addToQueue.bind(danmuku),
config: danmuku.config.bind(danmuku),
start: danmuku.start.bind(danmuku),
stop: danmuku.stop.bind(danmuku),
hide: danmuku.hide.bind(danmuku),
show: danmuku.show.bind(danmuku),
};
};
}
artplayerPluginDanmuku.bilibiliDanmuParseFromXml = bilibiliDanmuParseFromXml;
artplayerPluginDanmuku.bilibiliDanmuParseFromAv = bilibiliDanmuParseFromAv;
artplayerPluginDanmuku.bilibiliDanmuParseFromUrl = bilibiliDanmuParseFromUrl;
window.artplayerPluginDanmuku = artplayerPluginDanmuku;
export default artplayerPluginDanmuku;