diff --git a/README.md b/README.md index 667fc16..331387c 100644 --- a/README.md +++ b/README.md @@ -141,6 +141,7 @@ html page (`index.html`) where you can: * See the damage, crowd control, boon uptime, resurrects, mechanic fails, downs and deaths of every player * See the health of the boss when you wiped * See the statistics over all days (kill rate and time per encounter, downs and deaths) on the Statistics tab +* Copy the statistics of a boss as a Discord-formatted message (summary, an aligned table of the tries and links to the logs) with the "Copy for Discord" button on the boss page, and the boss health left per try as a picture with "Copy image" * Look at one boss in detail on the Boss tab (or with "Stats →" on a boss card): all tries of a day or of all days, boss health left per try, fastest kill, best wipe, and per player average/best DPS, mechanic fails, downs and deaths * Click on the try to go to the log (the html log of Elite Insights, or the dps.report page) diff --git a/raidTimeline.Logic/template.html b/raidTimeline.Logic/template.html index 7ee130d..adeca08 100644 --- a/raidTimeline.Logic/template.html +++ b/raidTimeline.Logic/template.html @@ -524,13 +524,25 @@ const bossNames = Object.keys(bossStats).sort((a, b) => bossStats[b].tries - bossStats[a].tries || a.localeCompare(b)); const hp0 = e => e.log.hpLeft.length ? e.log.hpLeft[0] : null; const dash = '–'; -function bossBody(name, dayKey) { +function bossData(name, dayKey) { const tries = allEnc.filter(e => e.boss === name && (dayKey === 'all' || e.day === dayKey)); const kills = tries.filter(e => e.kill), wipes = tries.filter(e => !e.kill); const fastest = kills.length ? Math.min(...kills.map(e => e.sec)) : null; const hps = wipes.map(hp0).filter(v => v !== null); const bestWipe = hps.length ? Math.min(...hps) : null; const avgDps = tries.reduce((s, e) => s + gdps(e), 0) / (tries.length || 1); + const pl = {}; + tries.forEach(e => e.log.players.filter(p => !p.isNpc).forEach(p => { + const a = pl[p.account] ??= { p, n: 0, dps: 0, best: 0, downed: 0, died: 0, mech: 0 }; + a.n++; a.dps += p.dps; a.best = Math.max(a.best, p.dps); a.downed += p.downed; a.died += p.died; + a.mech += e.log.columns.filter(c => c.rank).reduce((s, c) => s + (p.mechanics[c.key] ?? 0), 0); + a.p = p; + })); + const players = Object.values(pl).sort((a, b) => b.dps / b.n - a.dps / a.n); + return { tries, kills, wipes, fastest, bestWipe, avgDps, players }; +} +function bossBody(name, dayKey) { + const { tries, kills, fastest, bestWipe, avgDps, players: plist } = bossData(name, dayKey); const cards = `
${tries.length}
Tries
${kills.length}
Kills · ${Math.round(kills.length / (tries.length || 1) * 100)}% kill rate
@@ -558,30 +570,122 @@ }).join(''); const triesTbl = `

All tries

${tbl(`#${showDay ? 'Day' : ''}StartResultTimeHP leftGroup DPSDeathsDowns`, rows)}
`; - const pl = {}; - tries.forEach(e => e.log.players.filter(p => !p.isNpc).forEach(p => { - const a = pl[p.account] ??= { p, n: 0, dps: 0, best: 0, downed: 0, died: 0, mech: 0 }; - a.n++; a.dps += p.dps; a.best = Math.max(a.best, p.dps); a.downed += p.downed; a.died += p.died; - a.mech += e.log.columns.filter(c => c.rank).reduce((s, c) => s + (p.mechanics[c.key] ?? 0), 0); - a.p = p; - })); - const plRows = Object.values(pl).sort((a, b) => b.dps / b.n - a.dps / a.n).map(a => `${who(a.p)}${a.n} + const plRows = plist.map(a => `${who(a.p)}${a.n} ${fmt(a.dps / a.n)}${fmt(a.best)} ${a.mech ? `${a.mech}` : dash} ${a.downed || dash}${a.died || dash}`).join(''); const players = `

Players

${tbl('PlayerTriesAvg DPSBest DPSMech failsDownedDied', plRows)}
`; return cards + trend + triesTbl + players; } +/* ---------- copy the boss statistics as Discord markdown ---------- */ +const DISCORD_LIMIT = 2000; +function bossDiscord(name, dayKey) { + const { tries, kills, fastest, bestWipe, avgDps, players } = bossData(name, dayKey); + const all = dayKey === 'all'; + const day = all ? 'All days' : (days.find(d => d.key === dayKey)?.date ?? dayKey); + const safe = t => String(t).replace(/`/g, "'"); + const header = [`## ${safe(name)} · ${safe(day)}`, + `**${tries.length}** ${tries.length === 1 ? 'try' : 'tries'} · **${kills.length}** ${kills.length === 1 ? 'kill' : 'kills'} (${Math.round(kills.length / (tries.length || 1) * 100)}%)`, + `Fastest kill **${fastest === null ? '–' : mmss(fastest)}** · Best wipe **${bestWipe === null ? '–' : bestWipe.toFixed(1) + '% left'}** · Ø group DPS **${(avgDps / 1000).toFixed(1)}k**`].join('\n'); + /* Discord has no tables: the tries are aligned in a code block, which cannot hold links, so the links to the logs follow below it (only real http(s) links work in Discord) */ + const head = all ? ['#', 'Day', 'Start', 'Result', 'Time', 'HP left'] : ['#', 'Start', 'Result', 'Time', 'HP left']; + const table = rows => { + const cells = [head, ...rows.map(({ e, i }) => { const h = hp0(e); return [String(i + 1).padStart(2, '0'), ...(all ? [e.day] : []), clock(e.s0), e.kill ? 'Kill' : 'Wipe', e.dur, e.kill ? '–' : h === null ? '?' : h.toFixed(1) + '%']; })]; + const w = head.map((_, c) => Math.max(...cells.map(r => String(r[c]).length))); + const left = c => ['#', 'Day', 'Start', 'Result'].includes(head[c]); + const line = r => r.map((v, c) => String(v)[left(c) ? 'padEnd' : 'padStart'](w[c])).join(' ').trimEnd(); + return '```\n' + cells.map(line).join('\n') + '\n```'; + }; + const links = rows => { + const l = rows.filter(({ e }) => /^https?:\/\//i.test(e.log.url)).map(({ e, i }) => `[${String(i + 1).padStart(2, '0')}](<${e.log.url.replace(/>/g, '%3E')}>)`); + return l.length ? '**Logs:** ' + l.join(' ') : ''; + }; + const build = rows => [header, rows.length ? table(rows) : '', links(rows)].filter(Boolean).join('\n'); + const indexed = tries.map((e, i) => ({ e, i })); + /* Discord cuts messages at 2000 characters: drop the oldest tries instead of sending a cut-off message */ + for (let n = indexed.length; n >= 0; n--) { const text = build(indexed.slice(indexed.length - n)); if (text.length <= DISCORD_LIMIT) return text; } + return header.slice(0, DISCORD_LIMIT); +} +/* ---------- image: boss health left per try (a kill is the small green bar) ---------- */ +function bossImage(name, dayKey) { + const { tries } = bossData(name, dayKey); + const day = dayKey === 'all' ? 'All days' : (days.find(d => d.key === dayKey)?.date ?? dayKey); + const colW = 34, left = 56, right = 24, top = 78, plotH = 280, bottom = 44; + const W = Math.max(640, left + right + tries.length * colW), H = top + plotH + bottom; + const cv = document.createElement('canvas'); cv.width = W; cv.height = H; + const g = cv.getContext('2d'); + const font = (px, w = '') => `${w} ${px}px "Segoe UI", system-ui, sans-serif`.trim(); + g.fillStyle = '#171a22'; g.fillRect(0, 0, W, H); + g.fillStyle = '#e8eaf0'; g.font = font(22, '700'); g.textAlign = 'left'; g.textBaseline = 'alphabetic'; + g.fillText(`${name} · ${day}`, left, 34); + const kills = tries.filter(e => e.kill).length; + g.fillStyle = '#9aa1b2'; g.font = font(14); + g.fillText(`Boss health left per try · ${tries.length} ${tries.length === 1 ? 'try' : 'tries'} · ${kills} ${kills === 1 ? 'kill' : 'kills'} (${Math.round(kills / (tries.length || 1) * 100)}%)`, left, 58); + g.textAlign = 'right'; g.textBaseline = 'middle'; g.font = font(12); + for (const v of [0, 25, 50, 75, 100]) { + const y = top + plotH - plotH * v / 100; + g.strokeStyle = v === 0 ? '#4a5064' : '#2a2f3d'; g.lineWidth = 1; + g.beginPath(); g.moveTo(left, y + .5); g.lineTo(W - right, y + .5); g.stroke(); + g.fillStyle = '#9aa1b2'; g.fillText(v + '%', left - 8, y); + } + g.textAlign = 'center'; + tries.forEach((e, i) => { + const h = e.kill ? null : hp0(e), x = left + i * colW + 4, w = colW - 8; + const hh = e.kill ? 6 : h === null ? 10 : Math.max(h, 1.5); + const bh = Math.max(plotH * hh / 100, 4), y = top + plotH - bh; + g.fillStyle = e.kill ? '#3fcf9b' : h === null ? '#6b7285' : h <= 25 ? '#e5b455' : '#f2677a'; + g.fillRect(x, y, w, bh); + g.fillStyle = '#e8eaf0'; g.textBaseline = 'bottom'; g.font = font(11, '600'); + g.fillText(e.kill ? '✓' : h === null ? '?' : Math.round(h) + '', x + w / 2, y - 3); + g.fillStyle = '#9aa1b2'; g.textBaseline = 'top'; g.font = font(11); + g.fillText(String(i + 1), x + w / 2, top + plotH + 8); + }); + g.fillStyle = '#6b7285'; g.textAlign = 'left'; g.textBaseline = 'top'; g.font = font(11); + g.fillText('Try number · bar = % boss health left · green ✓ = kill · orange = wipe under 25%', left, top + plotH + 26); + return cv; +} +async function copyImage(cv, fileName) { + const blob = await new Promise(r => cv.toBlob(r, 'image/png')); + if (!blob) return false; + try { await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]); return 'copied'; } catch (e) { } + const a = document.createElement('a'); /* no clipboard access (e.g. a local file): save the png instead */ + a.href = URL.createObjectURL(blob); a.download = fileName; document.body.appendChild(a); a.click(); a.remove(); + setTimeout(() => URL.revokeObjectURL(a.href), 4000); + return 'saved'; +} +async function copyText(text) { + try { await navigator.clipboard.writeText(text); return true; } catch (e) { } + const ta = document.createElement('textarea'); + ta.value = text; ta.style.cssText = 'position:fixed;opacity:0'; document.body.appendChild(ta); ta.select(); + let ok = false; + try { ok = document.execCommand('copy'); } catch (e) { } + ta.remove(); + return ok; +} function renderBoss(i, dayKey) { const name = bossNames[i]; const dayKeys = [...new Set(allEnc.filter(e => e.boss === name).map(e => e.day))]; if (dayKey !== 'all' && !dayKeys.includes(dayKey)) dayKey = 'all'; $('#boss').innerHTML = `
-
+ + +
${bossBody(name, dayKey)}
`; $('#boss-pick').onchange = ev => renderBoss(+ev.target.value, 'all'); $('#boss-day').onchange = ev => renderBoss(i, ev.target.value); + $('#boss-copy').onclick = async ev => { + const btn = ev.currentTarget; + btn.textContent = (await copyText(bossDiscord(name, dayKey))) ? 'Copied ✓' : 'Copy failed'; + setTimeout(() => { btn.textContent = 'Copy for Discord'; }, 1800); + }; + $('#boss-img').onclick = async ev => { + const btn = ev.currentTarget; + let r = false; + try { r = await copyImage(bossImage(name, dayKey), `${name.replace(/[^\w.-]+/g, '_')}_${dayKey}.png`); } catch (e) { } + btn.textContent = r === 'copied' ? 'Copied ✓' : r === 'saved' ? 'Saved as file ✓' : 'Image failed'; + setTimeout(() => { btn.textContent = 'Copy image'; }, 1800); + }; } function openBoss(name, dayKey) { const i = bossNames.indexOf(name); diff --git a/tests-js/timeline.test.js b/tests-js/timeline.test.js index ea267d5..f12146e 100644 --- a/tests-js/timeline.test.js +++ b/tests-js/timeline.test.js @@ -431,3 +431,94 @@ test('boss page: no logs says so', () => { const w = load({ newestFirst: false, logs: [] }); assert.match(text(boss(w)), /No logs found yet/); }); + +/* ---------- copy for discord ---------- */ + +async function copied(w, dayKey) { + let out = null; + Object.defineProperty(w.navigator, 'clipboard', { value: { writeText: async t => { out = t; } }, configurable: true }); + if (dayKey) { const d = w.document.querySelector('#boss-day'); d.value = dayKey; d.dispatchEvent(new w.Event('change')); } + click(w.document.querySelector('#boss-copy')); + await new Promise(r => setTimeout(r, 10)); + return out; +} + +test('boss page: copy for discord puts the summary and every try with a link to its log on the clipboard', async () => { + const w = load(tonight()); + const md = await copied(w); + assert.match(md, /^## Sabetha · /); + assert.match(md, /\*\*4\*\* tries · \*\*1\*\* kill \(25%\)/); + assert.match(md, /Fastest kill \*\*3:00\*\*/); + assert.match(md, /Best wipe \*\*15\.0% left\*\*/); + assert.doesNotMatch(md, /\p{Extended_Pictographic}/u); + assert.match(md, /```\n# {3}Start {2}Result {2}Time {2}HP left\n01 {2}20:10 {2}Wipe {4}4:00 {4}60\.0%\n/); + assert.match(md, /\n04 {2}20:50 {2}Kill {4}3:00 {8}–\n```/); + assert.match(md, /\*\*Logs:\*\* \[01\]\(\) \[02\]\(<[^>]+>\) \[03\]\(<[^>]+>\) \[04\]\(<[^>]+>\)$/); + assert.doesNotMatch(md, /Players|A\.1111/); + assert.equal(w.document.querySelector('#boss-copy').textContent, 'Copied ✓'); +}); + +test('boss page: a try without a web link gets no link in the discord text', async () => { + const w = load({ newestFirst: false, logs: [log('Sabetha', '2026-03-02T20:00:00', '2026-03-02T20:03:00', { url: 'logs/a.html' })] }); + const md = await copied(w); + assert.match(md, /Kill {4}3:00 {8}–\n```$/); + assert.doesNotMatch(md, /Logs/); +}); + +test('boss page: the discord text stays under the 2000 character limit', async () => { + const many = Array.from({ length: 60 }, (_, i) => log('Sabetha', `2026-03-02T20:${String(i).padStart(2, '0')}:00`, `2026-03-02T20:${String(i).padStart(2, '0')}:30`, + { killed: false, hpLeft: [50], players: Array.from({ length: 10 }, (_, k) => player(`Player${k}.${1000 + k}`)) })); + const w = load({ newestFirst: false, logs: many }); + const md = await copied(w); + assert.equal(md.length <= 2000, true); + assert.match(md, /^## Sabetha/); +}); + +test('boss page: copying falls back to the old copy command without clipboard access', async () => { + const w = load(tonight()); + Object.defineProperty(w.navigator, 'clipboard', { value: { writeText: async () => { throw new Error('denied'); } }, configurable: true }); + w.document.execCommand = () => true; + click(w.document.querySelector('#boss-copy')); + await new Promise(r => setTimeout(r, 10)); + assert.equal(w.document.querySelector('#boss-copy').textContent, 'Copied ✓'); +}); + +/* ---------- image of the health left per try ---------- */ + +/* jsdom has no canvas: record what is drawn */ +function fakeCanvas(w) { + const drawn = { texts: [], rects: [], fills: [], size: null }; + const ctx = new Proxy({}, { get: (t, k) => k === 'fillText' ? (s) => drawn.texts.push(s) + : k === 'fillRect' ? (...a) => drawn.rects.push(a) + : k === 'measureText' ? () => ({ width: 10 }) : () => { }, set: (t, k, v) => { if (k === 'fillStyle') drawn.fills.push(v); return true; } }); + w.HTMLCanvasElement.prototype.getContext = function () { drawn.size = [this.width, this.height]; return ctx; }; + w.HTMLCanvasElement.prototype.toBlob = function (cb) { cb(new w.Blob(['png'], { type: 'image/png' })); }; + return drawn; +} + +test('boss page: copy image draws a bar per try and puts the png on the clipboard', async () => { + const w = load(tonight()); + const drawn = fakeCanvas(w); + let item = null; + w.ClipboardItem = class { constructor(o) { this.o = o; } }; + Object.defineProperty(w.navigator, 'clipboard', { value: { write: async i => { item = i[0]; } }, configurable: true }); + click(w.document.querySelector('#boss-img')); + await new Promise(r => setTimeout(r, 10)); + assert.deepEqual(Object.keys(item.o), ['image/png']); + assert.ok(drawn.texts.includes('Sabetha · ' + w.document.querySelector('#boss-day').selectedOptions[0].text) || drawn.texts.some(t => t.startsWith('Sabetha · '))); + assert.deepEqual(['60', '40', '15', '✓'].filter(t => !drawn.texts.includes(t)), []); + assert.equal(drawn.rects.length, 1 + 4); + assert.equal(w.document.querySelector('#boss-img').textContent, 'Copied ✓'); +}); + +test('boss page: copy image saves the png when the clipboard cannot take images', async () => { + const w = load(tonight()); + fakeCanvas(w); + let saved = null; + w.URL.createObjectURL = () => 'blob:x'; w.URL.revokeObjectURL = () => { }; + w.HTMLAnchorElement.prototype.click = function () { saved = this.download; }; + click(w.document.querySelector('#boss-img')); + await new Promise(r => setTimeout(r, 10)); + assert.match(saved, /^Sabetha_.*\.png$/); + assert.equal(w.document.querySelector('#boss-img').textContent, 'Saved as file ✓'); +});