This commit is contained in:
2026-09-14 22:30:09 +02:00
parent 22ffc3b51a
commit 912deeb28e
42 changed files with 2998 additions and 618 deletions
+346 -88
View File
@@ -12,11 +12,42 @@
const PILL_MIN_MS = 6000; // Fastest a pill can cross the screen
const PILL_MAX_MS = 12000; // Slowest a pill can cross the screen
const LANE_COUNT = 10; // Vertical lane slots
const LOOKAHEAD_SEC = 0.25; // How far ahead of currentTime we look when scanning
const MIN_RANDOM_SECS = 2; // Random timecode lower bound (avoid very start)
const RANDOM_SPREAD = 0.85; // Use 85% of duration for random spread
const DEFAULT_DANMAKU_TUNING = {
fontSize: 35,
opacity: 1.0,
speedMultiplier: 1.0,
laneCount: 10,
laneCoverage: 100,
fontWeight: 700,
outlineStyle: 2, // 0=None, 1=Subtle, 2=Default Outline, 3=Neon Glow
useCustomColor: 0,
customColor: '#ffffff',
pillBackground: 0, // 0=None, 1=Glass Card, 2=Solid Capsule
allowMediaEmbeds: 1,
mediaMaxHeight: 80,
showGreentext: 1,
densityLimit: 35,
flashInterval: 2.5,
showLaneGuides: 0,
showDebugHUD: 0
};
const loadDanmakuTuning = () => {
try {
const raw = localStorage.getItem('f0ck_danmaku_tuning');
return raw ? Object.assign({}, DEFAULT_DANMAKU_TUNING, JSON.parse(raw)) : Object.assign({}, DEFAULT_DANMAKU_TUNING);
} catch (e) {
return Object.assign({}, DEFAULT_DANMAKU_TUNING);
}
};
window.DEFAULT_DANMAKU_TUNING = DEFAULT_DANMAKU_TUNING;
window.danmakuTuning = window.danmakuTuning || loadDanmakuTuning();
/**
* SyntheticClock — emulates a <video> element's time API for non-video items
* (Flash/Ruffle). Ticks at 4 Hz so Danmaku's timeupdate handler fires normally.
@@ -74,7 +105,10 @@ class Danmaku {
this.items = [];
this._lastTime = -1;
this._paused = false;
this._laneUntil = new Array(LANE_COUNT).fill(0);
const initialLanes = Math.max(2, Math.min(30, Number(window.danmakuTuning?.laneCount) || 10));
this._laneUntil = new Array(initialLanes).fill(0);
// Site-wide config default
const configDefault = (window.f0ckSession && window.f0ckSession.enable_danmaku !== undefined)
? !!window.f0ckSession.enable_danmaku
@@ -100,12 +134,15 @@ class Danmaku {
this._initEmojiCache();
this._createOverlay();
this._applyTuning();
this._bound_onTuningChange = () => this._applyTuning();
window.addEventListener('f0ck:danmaku_tuning_changed', this._bound_onTuningChange);
this.media.addEventListener('timeupdate', this._bound_onTime, { passive: true });
this.media.addEventListener('seeked', this._bound_onSeek, { passive: true });
this.media.addEventListener('pause', this._bound_onPause, { passive: true });
this.media.addEventListener('play', this._bound_onPlay, { passive: true });
// For Ruffle/SyntheticClock: no poller needed — clock runs freely
}
/**
@@ -135,14 +172,12 @@ class Danmaku {
window.addEventListener('f0ck:emojis_ready', this._bound_onEmojis);
// Aggressive retry: try every 500 ms for up to 30 attempts.
// Each attempt checks CommentSystem first (free), then falls back to a fetch.
let attempts = 0;
let fetched = false;
const retry = () => {
if (this._emojiCache && Object.keys(this._emojiCache).length > 0) return; // already got them
if (this._emojiCache && Object.keys(this._emojiCache).length > 0) return;
if (++attempts > 30) return;
// 1. CommentSystem populated by now?
const cs = tryCs();
if (cs) {
this._emojiCache = cs;
@@ -150,7 +185,6 @@ class Danmaku {
return;
}
// 2. Kick off the HTTP fetch once; then just wait for it / the event
if (!fetched) {
fetched = true;
fetch('/api/v2/emojis')
@@ -169,14 +203,13 @@ class Danmaku {
})
.catch(err => {
console.warn('[Danmaku] emoji fetch failed:', err.message);
fetched = false; // allow retry
fetched = false;
});
}
// Schedule next check
if (!this._destroyed) setTimeout(retry, 500);
};
setTimeout(retry, 200); // first attempt after a short grace window
setTimeout(retry, 200);
}
// ── Public API ────────────────────────────────────────────────────────────
@@ -205,14 +238,11 @@ class Danmaku {
}));
if (this._synthClock) {
// Flash/Ruffle mode: bypass the timeline entirely.
// Store pool and start the random continuous loop.
this._flashPool = mapped;
this._startFlashLoop();
return; // don't touch this.items / _lastTime
return;
}
// Normal video mode: use video_time, random spread for nulls
this.items = mapped.map(item => {
if (item.raw_time !== null) {
item.video_time = item.raw_time;
@@ -231,16 +261,13 @@ class Danmaku {
/**
* Random continuous loop for Flash/Ruffle.
* Fires one comment every 2-5 s (random), reshuffles pool on exhaustion.
*/
_startFlashLoop() {
// Cancel any previous loop
if (this._flashTimer) clearTimeout(this._flashTimer);
this._flashTimer = null;
if (!this._flashPool || this._flashPool.length === 0) return;
// Shuffle helper
const shuffle = arr => {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
@@ -249,14 +276,12 @@ class Danmaku {
return arr;
};
// Working queue — randomised copy of pool
let queue = shuffle([...this._flashPool]);
let idx = 0;
const tick = () => {
if (this._destroyed || !this._enabled) return;
// Refill and reshuffle when queue exhausted
if (idx >= queue.length) {
queue = shuffle([...this._flashPool]);
idx = 0;
@@ -265,12 +290,12 @@ class Danmaku {
const item = queue[idx++];
this._spawnPill(item.text, item.username, item.color);
// Random delay 2 5 seconds between pills
const delay = 2000 + Math.random() * 3000;
const cfg = window.danmakuTuning || DEFAULT_DANMAKU_TUNING;
const baseInterval = Math.max(0.4, Number(cfg.flashInterval) || 2.5);
const delay = (baseInterval * 1000) + Math.random() * (baseInterval * 1200);
this._flashTimer = setTimeout(tick, delay);
};
// Small initial delay so page finishes loading before first pill
this._flashTimer = setTimeout(tick, 800);
}
@@ -284,8 +309,6 @@ class Danmaku {
/**
* Add a new comment to the timeline so it loops back in future playback.
* Also fires it immediately as a one-shot pill.
* @param {Object} comment — raw comment object from API
*/
addItem(comment) {
if (!comment || !comment.content) return;
@@ -314,7 +337,7 @@ class Danmaku {
text: this._prepareText(comment.content),
username: comment.display_name || comment.username || '?',
color: comment.username_color || null,
fired: true // mark as already fired — caller handles any immediate one-shot
fired: true
};
if (this._synthClock && this._flashPool) {
@@ -324,7 +347,6 @@ class Danmaku {
return;
}
// Insert in sorted order
const idx = this.items.findIndex(i => i.video_time > t);
if (idx === -1) this.items.push(item);
else this.items.splice(idx, 0, item);
@@ -334,9 +356,8 @@ class Danmaku {
toggle() {
this._enabled = !this._enabled;
localStorage.setItem('danmaku', this._enabled ? 'true' : 'false');
this.overlay.style.display = this._enabled ? '' : 'none';
if (this.overlay) this.overlay.style.display = this._enabled ? '' : 'none';
// Update the switch if it exists in the player
const sw = this.player.querySelector('#toggledanmaku');
if (sw) sw.classList.toggle('active', this._enabled);
}
@@ -348,13 +369,123 @@ class Danmaku {
isEnabled() { return this._enabled; }
toggleLoop(forcedVal, options = {}) {
this._loopMode = (forcedVal !== undefined) ? !!forcedVal : !this._loopMode;
if (this._loopMode) {
this.items.forEach(i => { i.fired = false; });
this._startDebugContinuousLoop(options.interval || 220, options.customText, options.username, options.color);
} else {
this._stopDebugContinuousLoop();
}
return this._loopMode;
}
isLooping() {
return !!this._loopMode;
}
_getSampleComments() {
return [
{ text: 'Danmaku burst test! :kreygasm:', username: 'BurstUser', color: '#ffcc00' },
{ text: '>be me\n>browsing f0ck\n>feels good man', username: 'Anon', color: '#78b87a' },
{ text: '[spoiler]Secret Classified Spoiler[/spoiler]', username: 'Agent007', color: '#ff5577' },
{ text: '[blur]Sensitive content blur reveal[/blur]', username: 'ModUser', color: '#bb77ff' },
{ text: 'Testing flight speed & collision avoidance 🚀', username: 'DevTester', color: '#00e5ff' },
{ text: '弾幕 Nico Nico style flying comment', username: 'Otaku', color: '#ff88aa' },
{ text: 'Super high density bullet stream! ⚡⚡', username: 'HyperUser', color: '#99ff00' },
{ text: 'FeelsGoodMan :feelsgood:', username: 'Pepe', color: '#55cc55' },
{ text: 'Nice visualizer and danmaku sync! 🔥', username: 'Vibes', color: '#ff6600' },
{ text: '>mfw danmaku is running infinitely :dance_fart:', username: 'F0cker', color: '#78b87a' }
];
}
_startDebugContinuousLoop(interval = 220, customText = null, username = null, color = null) {
if (this._debugLoopTimer) clearInterval(this._debugLoopTimer);
let idx = 0;
const tick = () => {
if (this._destroyed || !this._enabled || !this._loopMode) {
this._stopDebugContinuousLoop();
return;
}
if (customText) {
this._spawnPill(customText, username || 'LoopTester', color || '#00ffcc');
} else {
let pool = (this.items && this.items.length > 0) ? this.items : (this._flashPool || []);
if (!pool || pool.length === 0) {
pool = this._getSampleComments();
}
if (idx >= pool.length) {
idx = 0;
pool.forEach(i => { i.fired = false; });
}
const item = pool[idx++];
if (item) {
this._spawnPill(item.text, item.username || 'Tester', item.color || null);
}
}
};
tick();
this._debugLoopTimer = setInterval(tick, Math.max(40, interval));
}
_stopDebugContinuousLoop() {
if (this._debugLoopTimer) {
clearInterval(this._debugLoopTimer);
this._debugLoopTimer = null;
}
}
clearActivePills() {
if (!this.overlay) return;
this.overlay.querySelectorAll('.danmaku-pill').forEach(p => p.remove());
}
resetTimeline() {
if (this._synthClock) {
this._loopSynth();
} else {
this._resetFiredState(this.media ? this.media.currentTime : 0);
this._lastTime = this.media ? this.media.currentTime : 0;
}
}
fireBurst(count = 10, options = {}) {
const isFlood = count > 15;
const interval = isFlood ? 100 : 160;
if (this._loopMode) {
this._startDebugContinuousLoop(interval, options.text, options.username, options.color);
return;
}
const samples = this._getSampleComments();
for (let i = 0; i < count; i++) {
setTimeout(() => {
if (this._destroyed || !this._enabled) return;
const sample = samples[i % samples.length];
const text = options.text ? `${options.text} #${i + 1}` : `${sample.text} #${i + 1}`;
const user = options.username || sample.username;
const col = options.color || sample.color;
this.fire(text, user, col);
}, i * interval);
}
}
destroy() {
this._destroyed = true;
this._stopDebugContinuousLoop();
this.media.removeEventListener('timeupdate', this._bound_onTime);
this.media.removeEventListener('seeked', this._bound_onSeek);
this.media.removeEventListener('pause', this._bound_onPause);
this.media.removeEventListener('play', this._bound_onPlay);
if (this._bound_onEmojis) window.removeEventListener('f0ck:emojis_ready', this._bound_onEmojis);
if (this._bound_onTuningChange) window.removeEventListener('f0ck:danmaku_tuning_changed', this._bound_onTuningChange);
if (this._laneGuidesTimer) clearInterval(this._laneGuidesTimer);
if (this._hudTimer) clearInterval(this._hudTimer);
if (this._rufflePoller) clearInterval(this._rufflePoller);
if (this._flashTimer) clearTimeout(this._flashTimer);
if (this._synthClock) this._synthClock.destroy();
@@ -371,22 +502,150 @@ class Danmaku {
this.player.appendChild(this.overlay);
}
_applyTuning() {
if (!this.overlay) return;
const cfg = window.danmakuTuning || DEFAULT_DANMAKU_TUNING;
this.overlay.style.setProperty('--danmaku-font-size', (cfg.fontSize || 35) + 'px');
this.overlay.style.setProperty('--danmaku-opacity', cfg.opacity !== undefined ? cfg.opacity : 1);
this.overlay.style.setProperty('--danmaku-font-weight', cfg.fontWeight || 700);
this.overlay.style.setProperty('--danmaku-color', Number(cfg.useCustomColor) === 1 ? (cfg.customColor || '#ffffff') : '#ffffff');
this.overlay.style.setProperty('--danmaku-media-max-h', (cfg.mediaMaxHeight || 80) + 'px');
this.overlay.classList.toggle('danmaku-bg-glass', Number(cfg.pillBackground) === 1);
this.overlay.classList.toggle('danmaku-bg-capsule', Number(cfg.pillBackground) === 2);
this.overlay.classList.toggle('danmaku-glow-none', Number(cfg.outlineStyle) === 0);
this.overlay.classList.toggle('danmaku-glow-subtle', Number(cfg.outlineStyle) === 1);
this.overlay.classList.toggle('danmaku-glow-neon', Number(cfg.outlineStyle) === 3);
this.overlay.classList.toggle('danmaku-no-greentext', Number(cfg.showGreentext) === 0);
const targetLanes = Math.max(2, Math.min(30, Number(cfg.laneCount) || 10));
if (this._laneUntil.length !== targetLanes) {
const old = this._laneUntil;
this._laneUntil = new Array(targetLanes).fill(0);
for (let i = 0; i < Math.min(old.length, targetLanes); i++) {
this._laneUntil[i] = old[i];
}
}
this._updateLaneGuides();
this._updateDebugHUD();
}
_updateLaneGuides() {
if (!this.overlay) return;
const cfg = window.danmakuTuning || DEFAULT_DANMAKU_TUNING;
let guides = this.overlay.querySelector('.danmaku-lane-guides-container');
if (!cfg.showLaneGuides) {
if (guides) guides.remove();
if (this._laneGuidesTimer) {
clearInterval(this._laneGuidesTimer);
this._laneGuidesTimer = null;
}
return;
}
if (!guides) {
guides = document.createElement('div');
guides.className = 'danmaku-lane-guides-container';
this.overlay.appendChild(guides);
}
const laneCount = this._laneUntil.length || 10;
const coverage = Math.min(100, Math.max(10, Number(cfg.laneCoverage) || 100)) / 100;
const laneH = (100 * coverage) / laneCount;
let html = '';
const now = Date.now();
for (let i = 0; i < laneCount; i++) {
const topPct = i * laneH;
const isOccupied = (this._laneUntil[i] || 0) > now;
const remainingSec = isOccupied ? (((this._laneUntil[i] - now) / 1000).toFixed(1) + 's') : 'FREE';
html += `
<div class="danmaku-lane-guide ${isOccupied ? 'occupied' : ''}" style="top: ${topPct}%; height: ${laneH}%;">
<span class="danmaku-lane-badge">L${i} (${topPct.toFixed(0)}%)</span>
<span class="danmaku-lane-status">${remainingSec}</span>
</div>
`;
}
guides.innerHTML = html;
if (!this._laneGuidesTimer) {
this._laneGuidesTimer = setInterval(() => {
if (this._destroyed || !this.overlay || !window.danmakuTuning?.showLaneGuides) {
if (this._laneGuidesTimer) clearInterval(this._laneGuidesTimer);
this._laneGuidesTimer = null;
return;
}
this._updateLaneGuides();
}, 300);
}
}
_updateDebugHUD() {
if (!this.overlay) return;
const cfg = window.danmakuTuning || DEFAULT_DANMAKU_TUNING;
let hud = this.overlay.querySelector('.danmaku-debug-hud');
if (!cfg.showDebugHUD) {
if (hud) hud.remove();
if (this._hudTimer) {
clearInterval(this._hudTimer);
this._hudTimer = null;
}
return;
}
if (!hud) {
hud = document.createElement('div');
hud.className = 'danmaku-debug-hud';
this.overlay.appendChild(hud);
}
const activePills = this.overlay.querySelectorAll('.danmaku-pill').length;
const totalItems = this.items.length || (this._flashPool ? this._flashPool.length : 0);
const firedItems = this.items.filter(i => i.fired).length;
const curTime = (this.media ? this.media.currentTime : 0).toFixed(1);
const emojiCount = Object.keys(this._emojiCache || {}).length;
hud.innerHTML = `
<div class="hud-title"><i class="fa-solid fa-bolt"></i> Danmaku Debug HUD</div>
<div class="hud-row"><span>Active Pills:</span><span class="hud-val accent">${activePills} / ${cfg.densityLimit || 35}</span></div>
<div class="hud-row"><span>Loaded Comments:</span><span class="hud-val">${totalItems} (fired: ${firedItems})</span></div>
<div class="hud-row"><span>Clock Time:</span><span class="hud-val">${curTime}s ${this._synthClock ? '(Synth)' : ''}</span></div>
<div class="hud-row"><span>Lanes:</span><span class="hud-val">${this._laneUntil.length} (${cfg.laneCoverage || 100}%)</span></div>
<div class="hud-row"><span>Speed Multiplier:</span><span class="hud-val">${cfg.speedMultiplier || 1.0}x</span></div>
<div class="hud-row"><span>Emoji Cache:</span><span class="hud-val">${emojiCount} emojis</span></div>
`;
if (!this._hudTimer) {
this._hudTimer = setInterval(() => {
if (this._destroyed || !this.overlay || !window.danmakuTuning?.showDebugHUD) {
if (this._hudTimer) clearInterval(this._hudTimer);
this._hudTimer = null;
return;
}
this._updateDebugHUD();
}, 250);
}
}
_onPause() {
this._paused = true;
if (this._synthClock) this._synthClock.pause();
// Do NOT pause pill animations — pills already in flight always complete.
}
_onPlay() {
this._paused = false;
if (this._synthClock) this._synthClock.resume();
// Nothing to do for in-flight pills — they were never paused.
}
_checkRuffleState() {
const rp = document.querySelector('ruffle-player, ruffle-object');
if (!rp) return;
// Ruffle exposes is_playing on the element
const isPlaying = rp.is_playing !== undefined ? !!rp.is_playing : true;
if (isPlaying && this._paused) this._onPlay();
if (!isPlaying && !this._paused) this._onPause();
@@ -400,7 +659,6 @@ class Danmaku {
const prev = this._lastTime;
this._lastTime = now;
// Detect video loop (time jumped backwards) — reset so comments fire again
if (now < prev - 0.5) {
this._resetFiredState(now);
return;
@@ -411,22 +669,20 @@ class Danmaku {
for (const item of this.items) {
if (item.fired) continue;
if (item.video_time < from) { item.fired = true; continue; } // already passed
if (item.video_time > to) break; // sorted, nothing further in range
if (item.video_time < from) { item.fired = true; continue; }
if (item.video_time > to) break;
item.fired = true;
this._spawnPill(item.text, item.username, item.color);
}
// Loop for SyntheticClock (Flash/Ruffle): once all items have fired, restart
if (this._synthClock && this.items.length > 0 && this.items.every(i => i.fired)) {
this._loopSynth();
}
}
/** Reset all fired flags and the synthetic clock for looping. */
_loopSynth() {
this.items.forEach(i => { i.fired = false; });
this._synthClock.reset(); // back to t=0
this._synthClock.reset();
this._lastTime = 0;
}
@@ -443,38 +699,50 @@ class Danmaku {
_pickLane() {
const now = Date.now();
// Find the lane that will be free soonest
const laneCount = this._laneUntil.length || 10;
let best = 0;
let bestFree = this._laneUntil[0];
for (let i = 1; i < LANE_COUNT; i++) {
if (this._laneUntil[i] < bestFree) {
let bestFree = this._laneUntil[0] || 0;
for (let i = 1; i < laneCount; i++) {
if ((this._laneUntil[i] || 0) < bestFree) {
bestFree = this._laneUntil[i];
best = i;
}
}
// Occupy the lane — use the max duration so slower pills don't get overwritten
this._laneUntil[best] = now + PILL_MAX_MS;
const cfg = window.danmakuTuning || DEFAULT_DANMAKU_TUNING;
const speedMult = Math.max(0.2, Number(cfg.speedMultiplier) || 1.0);
const maxMs = PILL_MAX_MS / speedMult;
this._laneUntil[best] = now + maxMs;
return best;
}
_spawnPill(text, username, color) {
if (!this.overlay || !this._enabled || this._paused) return;
const cfg = window.danmakuTuning || DEFAULT_DANMAKU_TUNING;
const limit = Number(cfg.densityLimit) || 35;
const currentPills = this.overlay.querySelectorAll('.danmaku-pill');
if (currentPills.length >= limit) {
if (currentPills[0]) currentPills[0].remove();
}
const pill = document.createElement('div');
pill.className = 'danmaku-pill';
// Lane assignment — distribute vertically to avoid full overlap
const lane = this._pickLane();
const laneH = 100 / LANE_COUNT;
const topPct = lane * laneH + (laneH * 0.1); // slight inset
const laneCount = this._laneUntil.length || 10;
const coverage = Math.min(100, Math.max(10, Number(cfg.laneCoverage) || 100)) / 100;
const laneH = (100 * coverage) / laneCount;
const topPct = lane * laneH + (laneH * 0.1);
pill.style.top = topPct + '%';
// Message content — store raw text for deferred emoji re-render
if (Number(cfg.useCustomColor) === 1 && cfg.customColor) {
pill.style.color = cfg.customColor;
}
const msg = document.createElement('span');
msg.className = 'dpill-text';
msg.dataset.rawText = text;
// Read the freshest emoji source available at spawn time
const liveCache = (this._emojiCache && Object.keys(this._emojiCache).length > 0)
? this._emojiCache
: ((typeof CommentSystem !== 'undefined' && CommentSystem.emojiCache) || null);
@@ -482,29 +750,23 @@ class Danmaku {
msg.appendChild(this._renderContent(text));
// Track pill for deferred re-render if emojis weren't ready yet
if (!this._emojiCache || Object.keys(this._emojiCache).length === 0) {
if (!this._pendingPills) this._pendingPills = new Set();
this._pendingPills.add(msg);
}
pill.appendChild(msg);
// Insert paused so we can measure before animation fires
this.overlay.appendChild(pill);
// Duration scales with text length so long comments get enough time to cross.
// Formula: 5s base + 25ms per character, clamped to [6s, 45s].
const charCount = text.length;
const duration = Math.min(Math.max(5000 + charCount * 25, PILL_MIN_MS), 45_000);
const speedMult = Math.max(0.2, Number(cfg.speedMultiplier) || 1.0);
const baseDuration = Math.min(Math.max(5000 + charCount * 25, PILL_MIN_MS), 45_000);
const duration = baseDuration / speedMult;
// Use actual scroll (content) width — wider than offsetWidth for very long lines.
// This ensures the animation pixel travel is enough for ALL content to exit left,
// not just the max-width-capped pill box.
const overlayW = this.overlay.offsetWidth || window.innerWidth || 1920;
const contentW = pill.scrollWidth || pill.offsetWidth || 200;
const startX = overlayW + contentW; // off-screen right
const endX = -(contentW + 200); // fully off-screen left, overflow included
const startX = overlayW + contentW;
const endX = -(contentW + 200);
const anim = pill.animate(
[
@@ -514,23 +776,20 @@ class Danmaku {
{ duration, easing: 'linear', fill: 'none' }
);
// Remove pill once animation completes
anim.addEventListener('finish', () => {
if (pill.parentNode) pill.parentNode.removeChild(pill);
}, { once: true });
// Failsafe in case the Animations API finish event doesn't fire
pill._timeoutId = setTimeout(() => { if (pill.parentNode) pill.parentNode.removeChild(pill); }, duration + 1000);
}
/** Re-render pending pills once emojis are available. */
_reRenderEmojis() {
if (!this.overlay) return;
// Prefer direct element tracking (fast, no DOM query needed)
const pending = this._pendingPills;
if (pending && pending.size > 0) {
pending.forEach(msg => {
if (!msg.parentNode) { pending.delete(msg); return; } // already removed
if (!msg.parentNode) { pending.delete(msg); return; }
const raw = msg.dataset.rawText;
if (!raw) return;
msg.textContent = '';
@@ -538,11 +797,9 @@ class Danmaku {
});
pending.clear();
}
// Also sweep any pills that slipped through (belt-and-suspenders)
this.overlay.querySelectorAll('.dpill-text[data-raw-text]').forEach(msg => {
const raw = msg.dataset.rawText;
if (!raw) return;
// Only re-render if the content is still plain text (no img children)
if (!msg.querySelector('.dpill-emoji')) {
msg.textContent = '';
msg.appendChild(this._renderContent(raw));
@@ -559,10 +816,8 @@ class Danmaku {
const prepared = this._prepareText(rawText);
const frag = document.createDocumentFragment();
const cache = this._emojiCache; // always use full cache in danmaku
const cache = this._emojiCache;
// Process line by line — leading > lines become greentext
// Filter empty lines to avoid ghost rows from trailing newlines
const lines = prepared.split('\n').filter(l => l.trim() !== '');
lines.forEach((line) => {
const isQuote = /^>\s?/.test(line);
@@ -579,10 +834,8 @@ class Danmaku {
/**
* Renders inline content (spoiler/blur/emoji) into a parent node.
* Prepends a space before the first text chunk for visual separation.
*/
_renderInline(text, parent, emojiCache) {
// match[1]=spoiler, match[2]=blur, match[3]=emoji, match[4]=inline-img-url
const combined = /\[spoiler\]([\s\S]*?)\[\/spoiler\]|\[blur\]([\s\S]*?)\[\/blur\]|:([a-z0-9_+\-]+):|\x04([^\x05]+)\x05/gi;
let lastIndex = 0;
let match;
@@ -597,14 +850,14 @@ class Danmaku {
span.className = 'dpill-spoiler';
span.title = 'Click to reveal spoiler';
span.addEventListener('click', (e) => { e.stopPropagation(); span.classList.toggle('revealed'); });
this._renderInline(match[1], span, emojiCache); // recursive so emojis inside spoilers work
this._renderInline(match[1], span, emojiCache);
parent.appendChild(span);
} else if (match[2] !== undefined) {
const span = document.createElement('span');
span.className = 'dpill-blur';
span.title = 'Click to reveal';
span.addEventListener('click', (e) => { e.stopPropagation(); span.classList.toggle('revealed'); });
this._renderInline(match[2], span, emojiCache); // recursive so emojis inside blur work
this._renderInline(match[2], span, emojiCache);
parent.appendChild(span);
} else if (match[3]) {
const code = match[3];
@@ -634,12 +887,17 @@ class Danmaku {
}
} else if (match[4]) {
const mediaUrl = match[4];
const isConvertedGif = mediaUrl.endsWith('#gif');
const cleanUrl = mediaUrl.replace(/#gif$/, '');
const videoExts = /\.(?:mp4|webm|ogv|mov)$/i;
const audioExts = /\.(?:mp3|ogg|wav|flac|aac|opus|m4a)$/i;
const cfg = window.danmakuTuning || DEFAULT_DANMAKU_TUNING;
if (videoExts.test(cleanUrl)) {
if (Number(cfg.allowMediaEmbeds) === 0) {
const span = document.createElement('span');
span.className = 'dpill-media-placeholder';
span.textContent = ' [attachment] ';
parent.appendChild(span);
} else if (videoExts.test(cleanUrl)) {
const vid = document.createElement('video');
vid.src = cleanUrl;
vid.className = 'dpill-video';
@@ -674,17 +932,12 @@ class Danmaku {
_prepareText(text) {
if (!text) return '';
// Protect emoji codes from the bold/italic underscore regex.
// e.g. `:dance_fart: :dance_fart:` would have its underscores eaten
// when the regex pairs the _ from the first code with the _ in the second.
const emojiTokens = [];
let protected_ = text.replace(/:([a-z0-9_+\-]+):/gi, (match) => {
emojiTokens.push(match);
return `\x02${emojiTokens.length - 1}\x03`; // private-use delimiters
return `\x02${emojiTokens.length - 1}\x03`;
});
// Tokenize image URLs with \x04URL\x05 so they survive all regexes and reach _renderInline
// Only embed images from the allowed-images allowlist (window.f0ckAllowedImages) or same site
const allowedHosts = Array.isArray(window.f0ckAllowedImages) ? window.f0ckAllowedImages : [];
const siteHost = window.location.hostname;
const isAllowedImg = (url) => {
@@ -695,16 +948,14 @@ class Danmaku {
};
const imgTokenUrls = [];
protected_ = protected_
// Tokenize relative /c/ media URLs (comment attachments)
.replace(/\/c\/[a-f0-9]+\.(?:png|jpg|jpeg|gif|webp|svg|avif|mp4|webm|ogv|mov|mp3|ogg|wav|flac|aac|opus|m4a)(?:#gif)?/gi, (url) => {
imgTokenUrls.push(url);
return `\x04${imgTokenUrls.length - 1}\x05`;
})
// Stop at protocol boundaries so concatenated URLs aren't merged into one broken src.
.replace(/https?:\/\/(?:(?!https?:\/\/)\S)+\.(?:png|jpg|jpeg|gif|webp|svg|avif)(\?(?:(?!https?:\/\/)\S)*)?/gi, (url) => {
if (!isAllowedImg(url)) return url; // disallowed image URLs stay as plain text
if (!isAllowedImg(url)) return url;
imgTokenUrls.push(url);
return `\x04${imgTokenUrls.length - 1}\x05`; // numeric index placeholder
return `\x04${imgTokenUrls.length - 1}\x05`;
})
.replace(/```[\s\S]*?```/g, '[code]')
.replace(/`[^`]+`/g, match => match.slice(1, -1))
@@ -712,19 +963,26 @@ class Danmaku {
.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
.replace(/^#{1,6}\s+/gm, '')
.replace(/[*_]{1,3}([^*_]+)[*_]{1,3}/g, '$1')
// Normalize \r\n → \n but keep line breaks for greentext
.replace(/\r\n?/g, '\n')
// Collapse 3+ blank lines to 2
.replace(/\n{3,}/g, '\n\n')
.trim();
// Restore emoji codes, then image URL tokens
return protected_
.replace(/\x02(\d+)\x03/g, (_, i) => emojiTokens[+i] || '')
.replace(/\x04(\d+)\x05/g, (_, i) => imgTokenUrls[+i] ? `\x04${imgTokenUrls[+i]}\x05` : '');
}
}
Danmaku.applyGlobalTuning = function(newCfg) {
if (newCfg) {
Object.assign(window.danmakuTuning, newCfg);
try {
localStorage.setItem('f0ck_danmaku_tuning', JSON.stringify(window.danmakuTuning));
} catch (e) {}
}
window.dispatchEvent(new CustomEvent('f0ck:danmaku_tuning_changed', { detail: window.danmakuTuning }));
};
window.Danmaku = Danmaku;
window.SyntheticClock = SyntheticClock;