Skip to content

Instantly share code, notes, and snippets.

@muro3r
Last active November 6, 2022 03:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muro3r/577afa2605064af998960a0012c458d5 to your computer and use it in GitHub Desktop.
Save muro3r/577afa2605064af998960a0012c458d5 to your computer and use it in GitHub Desktop.
ユーザーリンクのマウスオーバー時に勝敗結果を表示する
// ==UserScript==
// @name Tooltip on Rival
// @description ユーザーリンクのマウスオーバー時に勝敗結果を表示する
// @namespace https://gist.github.com/muro3r/577afa2605064af998960a0012c458d5
// @version 0.4.0
// @author muro3r
// @match https://p.eagate.573.jp/game/2dx/*
// @icon https://www.google.com/s2/favicons?domain=573.jp
// @run-at document-end
// @require data:text/javascript;base64,dGhpcy5nbG9iYWxUaGlzID0gdGhpczs=
// @require https://unpkg.com/@popperjs/core@2
// @require https://unpkg.com/tippy.js@6
// @updateURL https://gist.githubusercontent.com/muro3r/577afa2605064af998960a0012c458d5/raw/tooltipOnRival.user.js
// @downloadURL https://gist.githubusercontent.com/muro3r/577afa2605064af998960a0012c458d5/raw/tooltipOnRival.user.js
// @grant none
// ==/UserScript==
(function () {
'use strict';
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function createTippyBodyElement(comparison) {
return `<div style="display: table;">
${Object.entries(comparison)
.map(([key, value]) => tableRow(key, value))
.join('')}
</div>`;
}
const tableRow = (playStyle, { win, lose }) => {
const playStyleFormat = playStyle.toUpperCase() + ':';
const percentage = win / (win + lose);
const percentageFormat = !isNaN(percentage)
? Number(percentage).toLocaleString(undefined, {
style: 'percent',
minimumFractionDigits: 1
})
: '0.0%';
return `<div style="display: table-row">
<div style="display: table-cell; text-align: end;"> ${playStyleFormat} </div>
<div style="display: table-cell; text-align: end; padding-left: 8px;"> ${win}勝 </div>
<div style="display: table-cell; text-align: end; padding-left: 8px;"> ${lose}敗 </div>
<div style="display: table-cell; text-align: end; padding-left: 8px;"> (${percentageFormat})</div>
</div>`;
};
class InvalidWinLoseTextException extends Error {
}
const extractWinLoseText = (str) => {
const reg = /(\d+)勝(\d+)敗/;
const matches = str.match(reg);
if (!matches || matches.length != 3) {
throw InvalidWinLoseTextException;
}
const result = {
win: 0,
lose: 0
};
result.win = Number.parseInt(matches[1]);
result.lose = Number.parseInt(matches[2]);
return result;
};
function aggregateComparison(HTMLString) {
const result = {
single: { win: 0, lose: 0 },
double: { win: 0, lose: 0 },
all: { win: 0, lose: 0 }
};
const element = document.createElement('html');
element.innerHTML = HTMLString;
const compareGame = Array.from(element.querySelectorAll('.compare-game td'), (td) => td.textContent);
if (compareGame.length != 2) {
// 'DJ DATA が公開されていません。'
return null;
}
result.all = extractWinLoseText(compareGame[1]);
const compareResult = element.querySelectorAll('.compare-result tr');
compareResult.forEach((tr) => {
var _a, _b;
if ((_a = tr.textContent) === null || _a === void 0 ? void 0 : _a.includes('SP')) {
const comp = extractWinLoseText(tr.textContent);
result.single.win += comp.win;
result.single.lose += comp.lose;
}
if ((_b = tr.textContent) === null || _b === void 0 ? void 0 : _b.includes('DP')) {
const comp = extractWinLoseText(tr.textContent);
result.double.win += comp.win;
result.double.lose += comp.lose;
}
});
return result;
}
const versionId = location.pathname.match(/\/game\/2dx\/(\d{2})/)[1];
const basePath = `/game/2dx/${versionId}`;
function main() {
const htmlAnchors = document.querySelectorAll('td > a');
const links = Array.from(htmlAnchors).filter((anchor) => anchor.href.includes('rival_status.html'));
// リンク毎に状態を管理する必要があるため
links.forEach((elem) => {
function setupTippyInstance(instance) {
instance._onFetch = false;
instance._context = null;
const url = new URL(elem.href);
if (url.pathname === `${basePath}/rival/robo/robo_status.html`) {
instance._onFetch = true;
instance._context = '🤖';
instance.setContent(instance._context);
}
const rival = url.searchParams.get('rival');
if (!rival) {
throw new Error('should have rival param');
}
instance._target = `${basePath}/djdata/rival/score_compare.html?rival=${encodeURIComponent(rival)}`;
instance._target += '&type=c';
}
function fetchRivalComparison(instance) {
return __awaiter(this, void 0, void 0, function* () {
try {
const resp = yield fetch(instance._target);
const html = yield resp.text();
instance._context = createTippyBodyElement(aggregateComparison(html));
instance.setContent(instance._context);
}
catch (e) {
console.error(`Error: ${e}`);
}
});
}
tippy(elem, {
content: 'Loading...',
allowHTML: true,
onCreate(instance) {
setupTippyInstance(instance);
},
onShow(instance) {
if (!!instance._context || instance._onFetch)
return;
instance._onFetch = true;
fetchRivalComparison(instance);
instance._onFetch = false;
}
});
});
}
if ([
`${basePath}/ranking/arena/top_ranking.html`,
`${basePath}/ranking/dani.html`
].includes(document.location.pathname)) {
const target = document.querySelector('div.play-tab');
if (target) {
const observer = new MutationObserver(main);
observer.observe(target, { subtree: true, childList: true });
}
}
else {
main();
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment