osu!web enhancement

Some small improvements to osu!web, featuring beatmapset filter and profile page improvement.

当前为 2023-10-10 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name osu!web enhancement
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.6.10
  5. // @description Some small improvements to osu!web, featuring beatmapset filter and profile page improvement.
  6. // @author VoltaXTY
  7. // @match https://osu.ppy.sh/*
  8. // @match https://lazer.ppy.sh/*
  9. // @icon http://ppy.sh/favicon.ico
  10. // @grant none
  11. // @run-at document-end
  12. // ==/UserScript==
  13. // below are source code from http://i18njs.com/js/i18n.js
  14. (function() {
  15. var Translator, i18n, translator,
  16. __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  17. Translator = (function() {
  18. function Translator() {
  19. this.translate = __bind(this.translate, this); this.data = {
  20. values: {},
  21. contexts: []
  22. };
  23. this.globalContext = {};
  24. }
  25. Translator.prototype.translate = function(text, defaultNumOrFormatting, numOrFormattingOrContext, formattingOrContext, context) {
  26. var defaultText, formatting, isObject, num;
  27. if (context == null) {
  28. context = this.globalContext;
  29. }
  30. isObject = function(obj) {
  31. var type;
  32. type = typeof obj;
  33. return type === "function" || type === "object" && !!obj;
  34. };
  35. if (isObject(defaultNumOrFormatting)) {
  36. defaultText = null;
  37. num = null;
  38. formatting = defaultNumOrFormatting;
  39. context = numOrFormattingOrContext || this.globalContext;
  40. } else {
  41. if (typeof defaultNumOrFormatting === "number") {
  42. defaultText = null;
  43. num = defaultNumOrFormatting;
  44. formatting = numOrFormattingOrContext;
  45. context = formattingOrContext || this.globalContext;
  46. } else {
  47. defaultText = defaultNumOrFormatting;
  48. if (typeof numOrFormattingOrContext === "number") {
  49. num = numOrFormattingOrContext;
  50. formatting = formattingOrContext;
  51. context = context;
  52. } else {
  53. num = null;
  54. formatting = numOrFormattingOrContext;
  55. context = formattingOrContext || this.globalContext;
  56. }
  57. }
  58. }
  59. if (isObject(text)) {
  60. if (isObject(text['i18n'])) {
  61. text = text['i18n'];
  62. }
  63. return this.translateHash(text, context);
  64. } else {
  65. return this.translateText(text, num, formatting, context, defaultText);
  66. }
  67. };
  68. Translator.prototype.add = function(d) {
  69. var c, k, v, _i, _len, _ref, _ref1, _results;
  70. if ((d.values != null)) {
  71. _ref = d.values;
  72. for (k in _ref) {
  73. v = _ref[k];
  74. this.data.values[k] = v;
  75. }
  76. }
  77. if ((d.contexts != null)) {
  78. _ref1 = d.contexts;
  79. _results = [];
  80. for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
  81. c = _ref1[_i];
  82. _results.push(this.data.contexts.push(c));
  83. }
  84. return _results;
  85. }
  86. };
  87. Translator.prototype.setContext = function(key, value) {
  88. return this.globalContext[key] = value;
  89. };
  90. Translator.prototype.clearContext = function(key) {
  91. return this.lobalContext[key] = null;
  92. };
  93. Translator.prototype.reset = function() {
  94. this.data = {
  95. values: {},
  96. contexts: []
  97. };
  98. return this.globalContext = {};
  99. };
  100. Translator.prototype.resetData = function() {
  101. return this.data = {
  102. values: {},
  103. contexts: []
  104. };
  105. };
  106. Translator.prototype.resetContext = function() {
  107. return this.globalContext = {};
  108. };
  109. Translator.prototype.translateHash = function(hash, context) {
  110. var k, v;
  111.  
  112. for (k in hash) {
  113. v = hash[k];
  114. if (typeof v === "string") {
  115. hash[k] = this.translateText(v, null, null, context);
  116. }
  117. }
  118. return hash;
  119. };
  120. Translator.prototype.translateText = function(text, num, formatting, context, defaultText) {
  121. var contextData, result;
  122. if (context == null) { context = this.globalContext; }
  123. if (this.data == null) { return this.useOriginalText(defaultText || text, num, formatting); }
  124. contextData = this.getContextData(this.data, context);
  125. if (contextData != null) { result = this.findTranslation(text, num, formatting, contextData.values, defaultText); }
  126. if (result == null) { result = this.findTranslation(text, num, formatting, this.data.values, defaultText); }
  127. if (result == null) { return this.useOriginalText(defaultText || text, num, formatting); }
  128. return result;
  129. };
  130. Translator.prototype.findTranslation = function(text, num, formatting, data) {
  131. var result, triple, value, _i, _len;
  132. value = data[text];
  133. if (value == null) { return null; }
  134. if (num == null) {
  135. if (typeof value === "string") { return this.applyFormatting(value, num, formatting); }
  136. } else {
  137. if (value instanceof Array || value.length) {
  138. for (_i = 0, _len = value.length; _i < _len; _i++) {
  139. triple = value[_i];
  140. if ((num >= triple[0] || triple[0] === null) && (num <= triple[1] || triple[1] === null)) {
  141. result = this.applyFormatting(triple[2].replace("-%n", String(-num)), num, formatting);
  142. return this.applyFormatting(result.replace("%n", String(num)), num, formatting);
  143. }
  144. }
  145. }
  146. }
  147. return null;
  148. };
  149. Translator.prototype.getContextData = function(data, context) {
  150. var c, equal, key, value, _i, _len, _ref, _ref1;
  151. if (data.contexts == null) { return null; }
  152. _ref = data.contexts;
  153. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  154. c = _ref[_i];
  155. equal = true;
  156. _ref1 = c.matches;
  157. for (key in _ref1) {
  158. value = _ref1[key];
  159. equal = equal && value === context[key];
  160. }
  161. if (equal) { return c; }
  162. }
  163. return null;
  164. };
  165. Translator.prototype.useOriginalText = function(text, num, formatting) {
  166. if (num == null) {
  167. return this.applyFormatting(text, num, formatting);
  168. }
  169. return this.applyFormatting(text.replace("%n", String(num)), num, formatting);
  170. };
  171. Translator.prototype.applyFormatting = function(text, num, formatting) {
  172. var ind, regex;
  173. for (ind in formatting) {
  174. regex = new RegExp("%{" + ind + "}", "g");
  175. text = text.replace(regex, formatting[ind]);
  176. }
  177. return text;
  178. };
  179. return Translator;
  180. })();
  181. translator = new Translator();
  182. i18n = translator.translate;
  183. i18n.translator = translator;
  184. i18n.create = function(data) {
  185. var trans;
  186. trans = new Translator();
  187. if (data != null) {
  188. trans.add(data);
  189. }
  190. trans.translate.create = i18n.create;
  191. return trans.translate;
  192. };
  193. (typeof module !== "undefined" && module !== null ? module.exports = i18n : void 0) || (this.i18n = i18n);
  194. }).call(this);
  195. // end of code from http://i18njs.com/js/i18n.js
  196. const ShowPopup = (m, t = "info") => {
  197. window.popup(m, t);
  198. [["info", console.log], ["warning", console.warn], ["danger", console.error]].find(g => g[0] === t)[1](m);
  199. }
  200. const svg_osu_miss = URL.createObjectURL(new Blob(
  201. [`<svg viewBox="0 0 128 128" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" >
  202. <filter id="blur">
  203. <feFlood flood-color="red" flood-opacity="0.5" in="SourceGraphic" />
  204. <feComposite operator="in" in2="SourceGraphic" />
  205. <feGaussianBlur stdDeviation="6" />
  206. <feComponentTransfer result="glow1"> <feFuncA type="linear" slope="10" intercept="0" /> </feComponentTransfer>
  207. <feGaussianBlur in="glow1" stdDeviation="1" result="glow2" />
  208. <feMerge> <feMergeNode in="SourceGraphic" /> <feMergeNode in="glow2" /> </feMerge>
  209. </filter>
  210. <filter id="blur2"> <feGaussianBlur stdDeviation="0.2"/> </filter>
  211. <path id="cross" d="M 26 16 l -10 10 l 38 38 l -38 38 l 10 10 l 38 -38 l 38 38 l 10 -10 l -38 -38 l 38 -38 l -10 -10 l -38 38 Z" />
  212. <use href="#cross" stroke="red" stroke-width="2" fill="transparent" filter="url(#blur)"/>
  213. <use href="#cross" fill="white" stroke="transparent" filter="url(#blur2)"/>
  214. </svg>`], {type: "image/svg+xml"}));
  215. const svg_green_tick = URL.createObjectURL(new Blob([
  216. `<svg viewBox="0 0 18 16" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" >
  217. <polyline points="2,8 7,14 16,2" stroke="#62ee56" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
  218. </svg>`], {type: "image/svg+xml"}));
  219. const inj_style =
  220. `#osu-db-input{
  221. display: none;
  222. }
  223. .osu-db-button{
  224. align-items: center;
  225. padding: 10px;
  226. }
  227. .osu-db-button:hover{
  228. cursor: pointer;
  229. }
  230. .beatmapset-panel[owned-beatmapset] .beatmapset-panel__menu-container{
  231. background-color: #87dda8;
  232. }
  233. .beatmapset-panel[owned-beatmapset] .beatmapset-panel__menu .fa-file-download, .beatmapset-panel[owned-beatmapset] .beatmapset-panel__menu .fa-heart{
  234. color: #5c9170;
  235. }
  236. .owned-beatmap-link{
  237. color: #87dda8;
  238. }
  239. .play-detail__accuracy{
  240. margin: 0px 12px;
  241. }
  242. .play-detail__accuracy.ppAcc{
  243. color: #8ef9f1;
  244. padding: 0;
  245. }
  246. .play-detail__weighted-pp{
  247. margin: 0px;
  248. }
  249. .play-detail__pp{
  250. flex-direction: column;
  251. }
  252. .lost-pp{
  253. font-size: 10px;
  254. position: relative;
  255. right: 7px;
  256. font-weight: 600;
  257. }
  258. .score-detail{
  259. display: inline-block;
  260. }
  261. .score-detail-data-text{
  262. margin-left: 5px;
  263. margin-right: 10px;
  264. width: auto;
  265. display: inline-block;
  266. }
  267. @keyframes rainbow{
  268. 0%{
  269. color: #be19ff;
  270. }
  271. 25%{
  272. color: #0075ff;
  273. }
  274. 50%{
  275. color: #4ddf86;
  276. }
  277. 75%{
  278. color: #e9ea00;
  279. }
  280. 100%{
  281. color: #ff7800;
  282. }
  283. }
  284. .play-detail__accuracy-and-weighted-pp{
  285. display: flex;
  286. flex-direction: row;
  287. }
  288. .play-detail__before{
  289. flex-grow: 1;
  290. }
  291. .mania-max{
  292. animation: 0.16s infinite alternate rainbow;
  293. }
  294. .mania-300{
  295. color: #fbff00;
  296. }
  297. .osu-100, .fruits-100, .taiko-150{
  298. color: #67ff5b;
  299. }
  300. .mania-200{
  301. color: #6cd800;
  302. }
  303. .osu-300, .fruits-300, .taiko-300{
  304. color: #7dfbff;
  305. }
  306. .mania-100{
  307. color: #257aea;
  308. }
  309. .mania-50{
  310. color: #d2d2d2;
  311. }
  312. .osu-50, .fruits-50-miss{
  313. color: #ffbf00;
  314. }
  315. .mania-miss, .taiko-miss, .fruits-miss{
  316. color: #cc2626;
  317. }
  318. .mania-max, .mania-300, .mania-200, .mania-100, .mania-50, .mania-miss, .osu-300, .osu-100, .osu-50, .osu-miss{
  319. font-weight: 600;
  320. }
  321. .score-detail-data-text{
  322. font-weight: 500;
  323. }
  324. .osu-miss{
  325. display: inline-block;
  326. }
  327. .osu-miss > img{
  328. width: 14px;
  329. height: 14px;
  330. bottom: 1px;
  331. position: relative;
  332. }
  333. .play-detail__Accuracy, .play-detail__Accuracy2, .combo, .max-combo, .play-detail__combo{
  334. display: inline-block;
  335. width: auto;
  336. }
  337. .play-detail__Accuracy{
  338. text-align: left;
  339. color: #fc2;
  340. }
  341. .play-detail__Accuracy2{
  342. text-align: left;
  343. color: rgb(142, 249, 241);
  344. }
  345. .play-detail__combo, .play-detail__Accuracy2, .play-detail__Accuracy{
  346. margin-right: 13px;
  347. }
  348. .play-detail__combo{
  349. text-align: right;
  350. }
  351. .combo, .max-combo{
  352. margin: 0px 1px;
  353. }
  354. .max-combo, .legacy-perfect-combo{
  355. color: hsl(var(--hsl-lime-1));
  356. }
  357. div.bar__exp-info{
  358. position: relative;
  359. bottom: 100%;
  360. }
  361. .play-detail__group--background, .beatmap-playcount__background{
  362. position: absolute;
  363. width: 90%;
  364. height: 100%;
  365. left: 0px;
  366. margin: 0px;
  367. pointer-events: none;
  368. z-index: 1;
  369. border-radius: 10px 0px 0px 10px;
  370. background-size: cover;
  371. background-position-y: -100%;
  372. mask-image: linear-gradient(to right, rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0));
  373. -webkit-mask-image: linear-gradient(to right, rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0));
  374. }
  375. @media(max-width: 900px){
  376. .play-detail__group--background, .beatmap-playcount__background{
  377. background-position-y: 0%;
  378. mask-image: linear-gradient(to bottom, #0007, #0004);
  379. -webkit-mask-image: linear-gradient(to bottom, #0007, #0004);
  380. width: 100%;
  381. }
  382. .lost-pp{
  383. left: 3px;
  384. }
  385. .play-detail__group.play-detail__group--bottom{
  386. z-index: 1;
  387. }
  388. .play-detail__before{
  389. flex-grow: 0;
  390. }
  391. }
  392. .play-detail.play-detail--highlightable.play-detail--pin-sortable.js-score-pin-sortable .play-detail__group--background{
  393. left: 20px;
  394. }
  395. .beatmap-playcount__background{
  396. width: 100%;
  397. border-radius: 6px;
  398. mask-image: linear-gradient(to right, rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.3));
  399. -webkit-mask-image: linear-gradient(to right, rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.3));
  400. }
  401. .beatmap-playcount__info, .beatmap-playcount__detail-count, .play-detail__group.play-detail__group--top *{
  402. z-index: 1;
  403. }
  404. div.play-detail-list time.js-timeago, span.beatmap-playcount__mapper, span.beatmap-playcount__mapper > a{
  405. color: #ccc;
  406. }
  407. button.show-more-link{
  408. z-index: 4;
  409. }
  410. a.beatmap-download-link{
  411. margin: 0px 5px;
  412. color: hsl(var(--hsl-l1));
  413. }
  414. a.beatmap-download-link:hover, a.beatmap-pack-item-download-link span:hover{
  415. color: #fff;
  416. }
  417. a.beatmap-pack-item-download-link span{
  418. color: hsl(var(--hsl-l1));
  419. }
  420. .play-detail.play-detail--highlightable.audio-player{
  421. max-width: none;
  422. height: unset;
  423. padding: unset;
  424. align-items: unset;
  425. }
  426. .play-detail.play-detail--highlightable.audio-player__button{
  427. align-items: unset;
  428. padding: unset;
  429. }
  430. .play-detail.play-detail--highlightable.audio-player__button:hover{
  431. color: unset;
  432. }
  433. `;
  434. const scriptContent =
  435. String.raw`console.log("page script injected from osu!web enhancement");
  436. if(window.oldXHROpen === undefined){
  437. window.oldXHROpen = window.XMLHttpRequest.prototype.open;
  438. window.XMLHttpRequest.prototype.open = function() {
  439. this.addEventListener("load", function() {
  440. const url = this.responseURL;
  441. const trreg = /https:\/\/(?<subdomain>osu|lazer)\.ppy\.sh\/users\/(?<id>[0-9]+)\/extra-pages\/(?<type>top_ranks|historical)\?mode=(?<mode>osu|taiko|fruits|mania)/.exec(url);
  442. const adreg = /https:\/\/(?<subdomain>osu|lazer)\.ppy\.sh\/users\/(?<id>[0-9]+)\/scores\/(?<type>firsts|best|recent|pinned)\?mode=(?<mode>osu|taiko|fruits|mania)&limit=[0-9]*&offset=[0-9]*/.exec(url);
  443. let reg = trreg ?? (adreg ?? null);
  444. if(!reg){
  445. const bmsreg = /https:\/\/(?:osu|lazer)\.ppy\.sh\/beatmapsets\/search\?/;
  446. return;
  447. }
  448. let info = {
  449. type: reg.groups.type,
  450. userId: Number(reg.groups.id),
  451. mode: reg.groups.mode,
  452. subdomain: reg.groups.subdomain,
  453. };
  454. const responseBody = this.responseText;
  455. info.data = JSON.parse(responseBody);
  456. info.id = "osu!web enhancement";
  457. window.postMessage(info, "*");
  458. });
  459. return oldXHROpen.apply(this, arguments);
  460. };
  461. }`;
  462. const locales = {
  463. "zh": {
  464. "values": {
  465. "Owned": "已获得",
  466. "Download": "下载",
  467. "pp Accuracy": "pp-准确度",
  468. "V1 Accuracy": "V1-准确度",
  469. "V2 Accuracy": "V2-准确度",
  470. "Lazer Accuracy": "Lazer-准确度",
  471. "Combo": "连击数",
  472. "Combo/Max Combo": "连击数/最大连击数",
  473. "Import osu!.db": "读取 osu!.db",
  474. "Check for update": "检查更新",
  475. "Calculate pp Gini index": "计算 pp 基尼指数",
  476. "Go to GreasyFork page": "前往 GreasyFork 页面",
  477. "Copy Text Details": "复制文本信息",
  478. "Could not find best play data": "无法获取 BP 数据",
  479. "The latest version is already installed!": "已安装最新版本!",
  480. "Script is already busy reading a osu!.db file.": "脚本已经开始读取 osu!.db 文件。",
  481. "There are still remaining unread bytes, something may be wrong.": "部分数据未能读取,可能发生错误。",
  482. "Score details copied to clipboard!": "分数信息已复制到剪贴板!",
  483. "%{pc} of total pp": "占总 pp 的 %{pc}",
  484. "Your pp Gini index of bp%{bp} is %{val}.": "BP%{bp} 的 pp 基尼指数为 %{val}。",
  485. "Finished reading osu!.db in %{time} ms.": "osu!.db 读取完毕,用时 %{time}ms。"
  486. }
  487. },
  488. "zh-tw": {
  489. "values": {
  490. "Owned": "已獲得",
  491. "Download": "下載",
  492. "pp Accuracy": "pp-準確度",
  493. "V1 Accuracy": "V1-準確度",
  494. "V2 Accuracy": "V2-準確度",
  495. "Lazer Accuracy": "Lazer-準確度",
  496. "Combo": "連擊數",
  497. "Combo/Max Combo": "連擊數/最大連擊數",
  498. "Import osu!.db": "讀取 osu!.db",
  499. "Check for update": "檢查更新",
  500. "Calculate pp Gini index": "計算 pp 基尼指數",
  501. "Go to GreasyFork page": "前往 GreasyFork 頁面",
  502. "Copy Text Details": "複製文字訊息",
  503. "Could not find best play data": "无法獲取 BP 數據",
  504. "The latest version is already installed!": "已安裝最新版本!",
  505. "Script is already busy reading a osu!.db file.": "腳本已經開始讀取 osu!.db 文件。",
  506. "There are still remaining unread bytes, something may be wrong.": "部分數據未能讀取,可能發生錯誤。",
  507. "Score details copied to clipboard!": "分數訊息已複製到剪貼簿!",
  508. "%{pc} of total pp": "佔總 pp 的 %{pc}",
  509. "Your pp Gini index of bp%{bp} is %{val}.": "BP%{bp} 的 pp 基尼指數為 %{val}。",
  510. "Finished reading osu!.db in %{time} ms.": "osu!.db 讀取完畢,用時 %{time}ms。"
  511. }
  512. },
  513. "ja": {
  514. "values": {
  515. "Owned": "取得済み",
  516. "Download": "ダウンロード",
  517. "pp Accuracy": "pp-精度",
  518. "V1 Accuracy": "V1-精度",
  519. "V2 Accuracy": "V2-精度",
  520. "Lazer Accuracy": "Lazer-精度",
  521. "Combo": "コンボ数",
  522. "Combo/Max Combo": "コンボ数/最大コンボ数",
  523. "Import osu!.db": "osu!.db を読み取る",
  524. "Check for update": "更新を確認する",
  525. "Calculate pp Gini index": "pp のジニ指数の計算",
  526. "Go to GreasyFork page": "GreasyFork のページへ",
  527. "Copy Text Details": "詳細をテキストにコピー",
  528. "Could not find best play data": "BP データが見つからない",
  529. "The latest version is already installed!": "最新版は既にインストールされている!",
  530. "Script is already busy reading a osu!.db file.": "スクリプトは osu!.db ファイルの読み取りを既に始める。",
  531. "There are still remaining unread bytes, something may be wrong.": "一部のデータを読み取れません、多分何かの間違いだ。",
  532. "Score details copied to clipboard!": "スコア詳細をクリップボードにコピー!",
  533. "%{pc} of total pp": "全 pp の %{pc}",
  534. "Your pp Gini index of bp%{bp} is %{val}.": "BP%{bp} の pp ジニ指数は %{val} です。",
  535. "Finished reading osu!.db in %{time} ms.": "osu!.db の読み取りを %{time}ms で完了しました。"
  536. }
  537. }
  538. };
  539. const scriptId = "osu-web-enhancement-XHR-script";
  540. if(!document.querySelector(`script#${scriptId}`)){
  541. const script = document.createElement("script");
  542. script.textContent = scriptContent;
  543. document.body.appendChild(script);
  544. }
  545. const HTML = (tagname, attrs, ...children) => {
  546. if(attrs === undefined) return document.createTextNode(tagname);
  547. const ele = document.createElement(tagname);
  548. if(attrs) for(const [key, value] of Object.entries(attrs)){
  549. if(key === "eventListener"){
  550. for(const listener of value){
  551. ele.addEventListener(listener.type, listener.listener, listener.options);
  552. }
  553. }
  554. else ele.setAttribute(key, value);
  555. }
  556. for(const child of children) if(child) ele.append(child);
  557. return ele;
  558. };
  559. const html = (html) => {
  560. const t = document.createElement("template");
  561. t.innerHTML = html;
  562. return t.content.firstElementChild;
  563. };
  564. const PostMessage = (msg) => { console.error(msg); };
  565. const OsuMod = {
  566. NoFail: 1 << 0,
  567. Easy: 1 << 1,
  568. TouchDevice: 1 << 2,
  569. NoVideo: 1 << 2,
  570. Hidden: 1 << 3,
  571. HardRock: 1 << 4,
  572. SuddenDeath: 1 << 5,
  573. DoubleTime: 1 << 6,
  574. Relax: 1 << 7,
  575. HalfTime: 1 << 8,
  576. Nightcore: 1 << 9, // always with DT
  577. Flashlight: 1 << 10,
  578. Autoplay: 1 << 11,
  579. SpunOut: 1 << 12,
  580. Autopilot: 1 << 13,
  581. Perfect: 1 << 14,
  582. Key4: 1 << 15,
  583. Key5: 1 << 16,
  584. Key6: 1 << 17,
  585. Key7: 1 << 18,
  586. Key8: 1 << 19,
  587. KeyMod: 1 << 19 | 1 << 18 | 1 << 17 | 1 << 16 | 1 << 15,
  588. FadeIn: 1 << 20,
  589. Random: 1 << 21,
  590. Cinema: 1 << 22,
  591. TargetPractice: 1 << 23,
  592. Key9: 1 << 24,
  593. Coop: 1 << 25,
  594. Key1: 1 << 26,
  595. Key3: 1 << 27,
  596. Key2: 1 << 28,
  597. ScoreV2: 1 << 29,
  598. Mirror: 1 << 30,
  599. };
  600. const Byte = (arr, iter) => {
  601. return arr[iter.nxtpos++];
  602. }
  603. const RankedStatus = (arr, iter) => {
  604. const r = {value: Byte(arr, iter), description: ""};
  605. switch(r.value){
  606. case 1: r.description = "unsubmitted"; break;
  607. case 2: r.description = "pending/wip/graveyard"; break;
  608. case 3: r.description = "unused"; break;
  609. case 4: r.description = "ranked"; break;
  610. case 5: r.description = "approved"; break;
  611. case 6: r.description = "qualified"; break;
  612. case 7: r.description = "loved"; break;
  613. default: r.description = "unknown"; r.value = 0;
  614. }
  615. return r;
  616. };
  617. const OsuMode = (arr, iter) => {
  618. const r = {value: Byte(arr, iter), description: ""};
  619. switch(r.value){
  620. case 1: r.description = "taiko"; break;
  621. case 2: r.description = "catch"; break;
  622. case 3: r.description = "mania"; break;
  623. default: r.value = 0; r.description = "osu";
  624. }
  625. return r;
  626. };
  627. const Grade = (arr, iter) => {
  628. const r = {value: Byte(arr, iter), description: ""};
  629. switch(r.value){
  630. case 0: r.description = "SSH"; break;
  631. case 1: r.description = "SH"; break;
  632. case 2: r.description = "SS"; break;
  633. case 3: r.description = "S"; break;
  634. case 4: r.description = "A"; break;
  635. case 5: r.description = "B"; break;
  636. case 6: r.description = "C"; break;
  637. case 7: r.description = "D"; break;
  638. default: r.description = "not played";
  639. }
  640. return r;
  641. };
  642. const Short = (arr, iter) => (arr[iter.nxtpos++] | arr[iter.nxtpos++] << 8);
  643. const Int = (arr, iter) => { return arr[iter.nxtpos++] | arr[iter.nxtpos++] << 8 | arr[iter.nxtpos++] << 16 | arr[iter.nxtpos++] << 24; };
  644. const Long = (arr, iter) => { const r = new DataView(arr.buffer, iter.nxtpos, 8).getBigUint64(0, true); iter.nxtpos += 8; return r; };
  645. const ULEB128 = (arr, iter) => {
  646. let value = 0n, shift = 0n, peek = 0n;
  647. do{
  648. peek = BigInt(arr[iter.nxtpos++]);
  649. value |= (peek & 0x7Fn) << shift;
  650. shift += 7n;
  651. }while((peek & 0x80n) !== 0n)
  652. return value;
  653. };
  654. const Single = (arr, iter) => { const r = new DataView(arr.buffer, iter.nxtpos, 4).getFloat32(0, true); iter.nxtpos += 4; return r; };
  655. const Double = (arr, iter) => { const r = new DataView(arr.buffer, iter.nxtpos, 8).getFloat64(0, true); iter.nxtpos += 8; return r; };
  656. const Boolean = (arr, iter) => { return arr[iter.nxtpos++] !== 0x00; };
  657. const OString = (arr, iter) => {
  658. let value = "";
  659. switch(arr[iter.nxtpos++]){
  660. case 0: break;
  661. case 0x0b: {
  662. const l = ULEB128(arr, iter);
  663. const bv = new Uint8Array(arr.buffer, iter.nxtpos, Number(l));
  664. value = new TextDecoder().decode(bv);
  665. iter.nxtpos += Number(l);
  666. break;
  667. }
  668. default: console.assert(false, `error occurred while parsing osu string with the first byte.`);
  669. }
  670. return value;
  671. };
  672. const IntDouble = (arr, iter) => {
  673. const r = {int: 0, double: 0};
  674. const m1 = arr[iter.nxtpos++];
  675. console.assert(m1 === 0x08, `error occurred while parsing Int-Double pair at ${iter.nxtpos - 1} with value 0x${m1.toString(16)}: should be 0x8.`);
  676. r.int = Int(arr, iter);
  677. const m2 = arr[iter.nxtpos++];
  678. console.assert(m2 === 0x0d, `error occurred while parsing Int-Double pair at ${iter.nxtpos - 1} with value 0x${m1.toString(16)}: should be 0x8.`);
  679. r.double = Double(arr, iter);
  680. return r;
  681. };
  682. const IntDoubleArray = (arr, iter) => {
  683. const r = new Array(Int(arr, iter));
  684. for(let i = 0; i < r.length; i++) r[i] = IntDouble(arr, iter);
  685. return r;
  686. };
  687. const TimingPoint = (arr, iter) => {
  688. return {
  689. BPM: Double(arr, iter),
  690. offset: Double(arr, iter),
  691. notInherited: Boolean(arr, iter),
  692. };
  693. };
  694. const TimingPointArray = (arr, iter) => {
  695. const r = new Array(Int(arr, iter));
  696. for(let i = 0; i < r.length; i++) r[i] = TimingPoint(arr, iter);
  697. return r;
  698. };
  699. const DateTime = Long;
  700. const Beatmap = (arr, iter) => {
  701. return {
  702. bytes: (iter.osuVersion < 20191106) ? Int(arr, iter) : undefined,
  703. artistName: OString(arr, iter),
  704. artistNameUnicode: OString(arr, iter),
  705. songTitle: OString(arr, iter),
  706. songTitleUnicode: OString(arr, iter),
  707. creatorName: OString(arr, iter),
  708. difficultyName: OString(arr, iter),
  709. audioFilename: OString(arr, iter),
  710. MD5Hash: OString(arr, iter),
  711. beatmapFilename: OString(arr, iter),
  712. rankedStatus: RankedStatus(arr, iter),
  713. hitcircleCount: Short(arr, iter),
  714. sliderCount: Short(arr, iter),
  715. spinnerCount: Short(arr, iter),
  716. lastModified: Long(arr, iter),
  717. AR: iter.osuVersion < 20140609 ? Byte(arr, iter) : Single(arr, iter),
  718. CS: iter.osuVersion < 20140609 ? Byte(arr, iter) : Single(arr, iter),
  719. HP: iter.osuVersion < 20140609 ? Byte(arr, iter) : Single(arr, iter),
  720. OD: iter.osuVersion < 20140609 ? Byte(arr, iter) : Single(arr, iter),
  721. sliderVelocity: Double(arr, iter),
  722. osuSRInfoArr: (iter.osuVersion >= 20140609) ? IntDoubleArray(arr, iter) : undefined,
  723. taikoSRInfoArr: (iter.osuVersion >= 20140609) ? IntDoubleArray(arr, iter) : undefined,
  724. catchSRInfoArr: (iter.osuVersion >= 20140609) ? IntDoubleArray(arr, iter) : undefined,
  725. maniaSRInfoArr: (iter.osuVersion >= 20140609) ? IntDoubleArray(arr, iter) : undefined,
  726. drainTime: Int(arr, iter),
  727. totalTime: Int(arr, iter),
  728. audioPreviewTime: Int(arr, iter),
  729. timingPointArr: TimingPointArray(arr, iter),
  730. difficultyID: Int(arr, iter),
  731. beatmapID: Int(arr, iter),
  732. threadID: Int(arr, iter),
  733. osuGrade: Grade(arr, iter),
  734. taikoGrade: Grade(arr, iter),
  735. catchGrade: Grade(arr, iter),
  736. maniaGrade: Grade(arr, iter),
  737. offsetLocal: Short(arr, iter),
  738. stackLeniency: Single(arr, iter),
  739. mode: OsuMode(arr, iter),
  740. sourceStr: OString(arr, iter),
  741. tagStr: OString(arr, iter),
  742. offsetOnline: Short(arr, iter),
  743. titleFont: OString(arr, iter),
  744. unplayed: Boolean(arr, iter),
  745. lastTimePlayed: Long(arr, iter),
  746. isOsz2: Boolean(arr, iter),
  747. folderName: OString(arr, iter),
  748. lastTimeChecked: Long(arr, iter),
  749. ignoreBeatmapSound: Boolean(arr, iter),
  750. ignoreBeatmapSkin: Boolean(arr, iter),
  751. disableStoryboard: Boolean(arr, iter),
  752. disableVideo: Boolean(arr, iter),
  753. visualOverride: Boolean(arr, iter),
  754. uselessShort: (iter.osuVersion < 20140609) ? Short(arr, iter) : undefined,
  755. lastModified2: Int(arr, iter),
  756. scrollSpeedMania: Byte(arr, iter),
  757. };
  758. };
  759. class _ProgressBar{
  760. barEle = null;
  761. Show(){
  762. if(this.barEle) { this.barEle.style.setProperty("opacity", "1"); return; }
  763. this.barEle = HTML("div", {class: "owenhancement-progress-bar", style: "position: fixed; left: 0px; top: 0px; width: 0%; height: 3px; background-color: #fc2; opacity: 1; z-index: 999;"});
  764. document.body.insertAdjacentElement("beforebegin", this.barEle);
  765. }
  766. Progress(prog){
  767. if(this.barEle) this.barEle.style.setProperty("width", `${prog * 100}%`);
  768. if(prog >= 1) this.Hide();
  769. }
  770. Hide(){ this.barEle.style.setProperty("opacity", "0"); }
  771. };
  772. const ProgressBar = new _ProgressBar();
  773. const BeatmapArray = async (arr, iter) => {
  774. const r = new Array(Int(arr, iter));
  775. for(let i = 0; i < r.length; i++){
  776. r[i] = Beatmap(arr, iter);
  777. if((i + 1) % 1000 === 0){
  778. ProgressBar.Progress((i + 1) / (r.length));
  779. await new Promise((res, rej) => setTimeout(() => res(), 0));
  780. }
  781. }
  782. return r;
  783. };
  784. const OsuDb = async (arr, iter) => {
  785. ProgressBar.Show();
  786. const r = {};
  787. r.version = Int(arr, iter);
  788. iter.osuVersion = r.version;
  789. r.folderCount = Int(arr, iter);
  790. r.accountUnlocked = Boolean(arr, iter);
  791. r.timeTillUnlock = DateTime(arr, iter);
  792. r.playerName = OString(arr, iter);
  793. r.beatmapArray = await BeatmapArray(arr, iter);
  794. r.permission = Int(arr, iter);
  795. ProgressBar.Hide();
  796. return r;
  797. };
  798. class ScoreDb{
  799. constructor(arr, iter){
  800.  
  801. }
  802. }
  803. const beatmapsets = new Set();
  804. const beatmaps = new Set();
  805. const bmsReg = /https:\/\/(?:osu|lazer)\.ppy\.sh\/beatmapsets\/([0-9]+)/;
  806. const bmsdlReg = /https:\/\/(?:osu|lazer)\.ppy\.sh\/beatmapsets\/([0-9]+)\/download/;
  807. const bmReg = /https:\/\/(?:osu|lazer)\.ppy\.sh\/beatmapsets\/(?:[0-9]+)#(?:mania|osu|fruits|taiko)\/([0-9]+)/;
  808. const BeatmapsetRefresh = () => {
  809. for(const bm of window.osudb.beatmapArray){
  810. beatmaps.add(bm.difficultyID);
  811. beatmapsets.add(bm.beatmapID);
  812. }
  813. OnMutation();
  814. };
  815. const NewOsuDb = async (r) => {
  816. const start = performance.now();
  817. const result = new Uint8Array(r.result);
  818. const length = result.length;
  819. console.log(`start reading osu!.db(${length} Bytes).`);
  820. const iter = {
  821. nxtpos: 0,
  822. };
  823. window.osudb = await OsuDb(result, iter);
  824. if(iter.nxtpos !== length) ShowPopup(i18n("There are still remaining unread bytes, something may be wrong."), "danger");
  825. ShowPopup(i18n("Finished reading osu!.db in %{time} ms.", {time: performance.now() - start}));
  826. };
  827. let ReadOsuDbWorking = false;
  828. const ReadOsuDb = async (file) => {
  829. if(ReadOsuDbWorking){
  830. ShowPopup(i18n("Script is already busy reading a osu!.db file."), "warning");
  831. return;
  832. }
  833. ReadOsuDbWorking = true;
  834. if(file.name !== "osu!.db"){ console.assert( false, "filename should be 'osu!.db'."); return; }
  835. const r = new FileReader();
  836. r.onload = async () => {
  837. await NewOsuDb(r);
  838. BeatmapsetRefresh();
  839. ReadOsuDbWorking = false;
  840. };
  841. r.onerror = () => console.assert(false, "error occurred while reading file.");
  842. r.readAsArrayBuffer(file);
  843. };
  844. const SelectOsuDb = (event) => {
  845. const t = event.target;
  846. const l = t.files;
  847. console.assert(l && l.length === 1, "No file or multiple files are selected.");
  848. ReadOsuDb(l[0]);
  849. };
  850. const CheckForUpdate = () => {
  851. const verReg = /<dd class="script-show-version"><span>([0-9\.]+)<\/span><\/dd>/;
  852. fetch("https://greasyfork.org/en/scripts/475417-osu-web-enhancement", {
  853. credentials: "omit"
  854. }).then(response => response.text()).then((html) => {
  855. const ver = verReg.exec(html);
  856. if(ver){
  857. const result = (() => {
  858. const verList = ver[1].split(".");
  859. const thisVer = GM_info.script.version;
  860. console.log(`latest version is: ${ver[1]}, current version is: ${thisVer}`);
  861. const thisVerList = thisVer.split(".");
  862. for(let i = 0; i < verList.length; i++){
  863. if(Number(verList[i]) > Number(thisVerList[i] ?? 0)) return true;
  864. else if(Number(verList[i]) < Number(thisVerList[i] ?? 0)) return false;
  865. }
  866. return false;
  867. })();
  868. if(result){
  869. const a = HTML("a", {href: "https://greasyfork.org/scripts/475417-osu-web-enhancement/code/osu!web%20enhancement.user.js", download: "", style: "display:none;"});
  870. a.click();
  871. }
  872. else{
  873. ShowPopup(i18n("The latest version is already installed!"))
  874. }
  875. }
  876. });
  877. };
  878. const AddMenu = () => {
  879. const menuId = "osu-web-enhancement-toolbar";
  880. if(!window.menuEventListener){
  881. window.addEventListener("click", (ev) => {
  882. const fid = ev.target?.dataset?.functionId;
  883. if(fid) switch(fid){
  884. case "import-osu-db-button": document.getElementById("osu-db-input")?.click(); break;
  885. case "check-for-update-button": CheckForUpdate(); break;
  886. case "pp-gini-index-calculator": PPGiniIndex(); break;
  887. }
  888. });
  889. window.menuEventListener = true;
  890. }
  891. if(document.getElementById(menuId)) return;
  892. const anc = document.querySelector("div.nav2__col.nav2__col--menu.js-react--quick-search-button");
  893. const i = HTML("input", {type: "file", id: "osu-db-input", accept: ".db", eventListener: [{
  894. type: "change",
  895. listener: SelectOsuDb,
  896. options: false,
  897. }]});
  898. const menuClass = "simple-menu simple-menu--nav2 simple-menu--nav2-left-aligned simple-menu--nav2-transparent js-menu";
  899. const menuItemClass = "simple-menu__item u-section-community--before-bg-normal";
  900. const menuTgtId = "osu-web-enhancement";
  901. anc.insertAdjacentElement("beforebegin",
  902. HTML("div", {class: "nav2__col nav2__col--menu", id: menuId},
  903. HTML("div", {class: "nav2__menu-link-main js-menu", "data-menu-target": `nav2-menu-popup-${menuTgtId}`, "data-menu-show-delay":"0", style:"flex-direction: column; cursor: default;"},
  904. HTML("span", {style: "flex-grow: 1;"}),
  905. HTML("span", {style: "font-size: 10px;"}, HTML("osu!web")),
  906. HTML("span", {style: "font-size: 10px;"}, HTML("enhancement")),
  907. HTML("span", {style: "flex-grow: 1;"}),
  908. ),
  909. HTML("div", {class: "nav2__menu-popup"},
  910. HTML("div", {class: `${menuClass}`, "data-menu-id": `nav2-menu-popup-${menuTgtId}`, "data-visibility": "hidden"},
  911. HTML("div", {class: `${menuItemClass}`, style: "cursor: pointer;", "data-function-id": "import-osu-db-button", }, HTML(i18n("Import osu!.db"))),
  912. HTML("div", {class: `${menuItemClass}`, style: "cursor: pointer;", "data-function-id": "check-for-update-button"}, HTML(i18n("Check for update"))),
  913. HTML("div", {class: `${menuItemClass}`, style: "cursor: pointer;", "data-function-id": "pp-gini-index-calculator"}, HTML(i18n("Calculate pp Gini index"))),
  914. HTML("a", {class: `${menuItemClass}`, style: "cursor: pointer;", href: "https://greasyfork.org/en/scripts/475417-osu-web-enhancement", target: "_blank"}, HTML(i18n("Go to GreasyFork page")))
  915. ),
  916. )
  917. )
  918. );
  919. const mobMenuItmCls = "navbar-mobile-item__submenu-item js-click-menu--close";
  920. const mob = document.querySelector(`div.mobile-menu__item.js-click-menu[data-click-menu-id="mobile-nav"]`);
  921. mob.insertAdjacentElement("beforeend",
  922. HTML("div", {class: "navbar-mobile-item"},
  923. HTML("div", {class: "navbar-mobile-item__main js-click-menu", "data-click-menu-target": `nav-mobile-${menuTgtId}`, style: "cursor: pointer;"},
  924. HTML("span", {class: "navbar-mobile-item__icon navbar-mobile-item__icon--closed"},
  925. HTML("i", {class: "fas fa-chevron-right"})
  926. ),
  927. HTML("span", {class: "navbar-mobile-item__icon navbar-mobile-item__icon--opened"},
  928. HTML("i", {class: "fas fa-chevron-down"})
  929. ),
  930. HTML("osu!web enhancement"),
  931. ),
  932. HTML("ul", {class: "navbar-mobile-item__submenu js-click-menu", "data-click-menu-id": `nav-mobile-${menuTgtId}`, "data-visibility": "hidden"},
  933. HTML("li", {}, HTML("div", {class: mobMenuItmCls, style: "cursor: pointer;", "data-function-id": "import-osu-db-button",}, HTML(i18n("Import osu!.db")))),
  934. HTML("li", {}, HTML("div", {class: mobMenuItmCls, style: "cursor: pointer;", "data-function-id": "check-for-update-button"}, HTML(i18n("Check for update")))),
  935. HTML("li", {}, HTML("div", {class: mobMenuItmCls, style: "cursor: pointer;", "data-function-id": "pp-gini-index-calculator"}, HTML(i18n("Calculate pp Gini index")))),
  936. HTML("a", {class: `${mobMenuItmCls}`, style: "cursor: pointer;", href: "https://greasyfork.org/en/scripts/475417-osu-web-enhancement", target: "_blank"}, HTML(i18n("Go to GreasyFork page")))
  937. )
  938. )
  939. );
  940. document.body.appendChild(i);
  941. };
  942. const FilterBeatmapSet = () => {
  943. document.querySelectorAll(".beatmapset-panel").forEach((item) => {
  944. const bmsID = Number(bmsReg.exec(item.innerHTML)?.[1]);
  945. if(bmsID && beatmapsets.has(bmsID)){
  946. item.setAttribute("owned-beatmapset", "");
  947. }
  948. });
  949. document.querySelectorAll("div.bbcode a, a.osu-md__link").forEach(item => {
  950. if(item.classList.contains("owned-beatmap-link") || item.classList.contains("beatmap-download-link")) return;
  951. const e = bmsReg.exec(item.href);
  952. if(e && beatmapsets.has(Number(e[1]))){
  953. item.classList.add("owned-beatmap-link");
  954. if(item.nextElementSibling?.classList?.contains("beatmap-download-link")) item.nextElementSibling.remove();
  955. const box = item.getBoundingClientRect();
  956. const size = Math.round(box.height / 16 * 14);
  957. const vert = Math.round(size * 4 / 14) / 2;
  958. item.after(HTML("img", {src: svg_green_tick, title: i18n("Owned"), alt: "owned beatmap", style: `margin: 0px 5px; width: ${size}px; height: ${size}px; vertical-align: -${vert}px;`}));
  959. }else if(e && !item.nextElementSibling?.classList?.contains("beatmap-download-link")){
  960. item.after(
  961. HTML("a", {class: "beatmap-download-link", href: `https://osu.ppy.sh/beatmapsets/${e[1]}/download`, download: ""},
  962. HTML("span", {class: "fas fa-file-download", title: i18n("Download")})
  963. )
  964. );
  965. }
  966. });
  967. document.querySelectorAll("li.beatmap-pack-items__set").forEach(item => {
  968. if(item.classList.contains("owned-beatmap-pack-item")) return;
  969. const a = item.querySelector("a.beatmap-pack-items__link");
  970. const e = bmsReg.exec(a.href);
  971. if(e && beatmapsets.has(Number(e[1]))){
  972. item.classList.add("owned-beatmap-pack-item");
  973. const span = item.querySelector("span.fal");
  974. span.setAttribute("title", i18n("Owned"));
  975. span.dataset.origTitle = "owned";
  976. span.setAttribute("class", "");
  977. span.append(HTML("img", {src: svg_green_tick, alt: "owned beatmap", style: `width: 16px; height: 16px; vertical-align: -2px;`}));
  978. const parent = item.querySelector(".beatmap-pack-item-download-link");
  979. if(parent){
  980. console.assert(parent.parentElement === item, "unexpected error occurred!");
  981. item.insertBefore(span, parent);
  982. parent.remove();
  983. }
  984. }else if(e){
  985. const icon = item.querySelector(".beatmap-pack-items__icon");
  986. icon.setAttribute("title", i18n("Download"));
  987. icon.setAttribute("class", "fas fa-file-download beatmap-pack-items__icon");
  988. if(icon.parentElement === item){
  989. const dl = HTML("a", {class: "beatmap-pack-item-download-link", href: `https://osu.ppy.sh/beatmapsets/${e[1]}/download`, download: ""});
  990. item.insertBefore(dl, icon);
  991. dl.append(icon);
  992. }
  993. }
  994. })
  995. };
  996. const AdjustStyle = (modestr, sectionName) => {
  997. const styleSheetId = `userscript-generated-stylesheet-${sectionName}`;
  998. let e = document.getElementById(styleSheetId);
  999. if(!e){
  1000. e = document.createElement("style");
  1001. e.id = styleSheetId;
  1002. document.head.appendChild(e);
  1003. }
  1004. const s = e.sheet;
  1005. while(s.cssRules.length) s.deleteRule(0);
  1006. const sectionSelector = `div.js-sortable--page[data-page-id="${sectionName}"]`;
  1007. let ll = [];
  1008. switch(modestr){
  1009. case "mania": ll = [".mania-300", ".mania-200", ".mania-100", ".mania-50", ".mania-miss"]; break;
  1010. case "fruits": ll = [".fruits-300", ".fruits-100", ".fruits-50-miss", ".fruits-miss"]; break;
  1011. case "taiko": ll = [".taiko-300", ".taiko-150", ".taiko-miss"]; break;
  1012. case "osu": ll = [".osu-300", ".osu-100", ".osu-50", ".osu-miss"]; break;
  1013. }
  1014. class FasterCalc{
  1015. _map = new Map();
  1016. Calculate = (ele) => {
  1017. const t = ele.textContent;
  1018. let w = 0, changed = false;
  1019. for(const c of t){
  1020. let wc = this._map.get(c);
  1021. if(!wc){
  1022. if(!changed) changed = ele.cloneNode(true);
  1023. ele.textContent = c;
  1024. wc = ele.clientWidth;
  1025. this._map.set(c, wc);
  1026. }
  1027. w += wc;
  1028. }
  1029. if(changed){
  1030. ele.insertAdjacentElement("afterend", changed);
  1031. ele.remove();
  1032. }
  1033. return w;
  1034. };
  1035. };
  1036. let fc = new FasterCalc();
  1037. ll.forEach((str) =>
  1038. s.insertRule(
  1039. `${sectionSelector} ${str} + .score-detail-data-text {
  1040. width: ${[...document.querySelectorAll(`${sectionSelector} ${str} + .score-detail-data-text`)].reduce((max, ele) => { const w = fc.Calculate(ele); return w > max ? w : max }, 0) + 2}px;
  1041. }` ,0
  1042. )
  1043. );
  1044. fc = new FasterCalc();
  1045. [".play-detail__combo", ".play-detail__Accuracy", ".play-detail__Accuracy2"].forEach((str) =>
  1046. s.insertRule(
  1047. `${sectionSelector} ${str}{
  1048. min-width: ${Math.ceil([...document.querySelectorAll(`${sectionSelector} ${str}`)].reduce((max, ele) => {const w = fc.Calculate(ele); return w > max ? w : max;}, 0)) + 1}px;
  1049. }`
  1050. ,0
  1051. )
  1052. );
  1053. [".play-detail__pp"].forEach((str) =>
  1054. s.insertRule(
  1055. `${sectionSelector} ${str}{
  1056. min-width: ${Math.ceil([...document.querySelectorAll(`${sectionSelector} ${str}`)].reduce((max, ele) => {const w = ele.clientWidth; return w > max ? w : max;}, 0)) + 1}px;
  1057. }`
  1058. ,0
  1059. )
  1060. );
  1061. };
  1062. const PPGiniIndex = () => {
  1063. const vals = [...document.querySelectorAll(`div.js-sortable--page[data-page-id="top_ranks"] div.play-detail-list:nth-child(4) div.play-detail.play-detail--highlightable`)]
  1064. .map((ele) => {const ppele = ele.querySelector("div.play-detail__pp span"); return Number((ppele.title ? ppele.title : ppele.dataset.origTitle).replaceAll(",", ""))})
  1065. .sort((a, b) => b - a);
  1066. if(vals.length === 0) {
  1067. ShowPopup(i18n("Could not find best play data"), "danger");
  1068. return;
  1069. }
  1070. const min = vals[vals.length - 1];
  1071. let _ = 0; for(let i = vals.length - 1; i >= 0; i--) {
  1072. _ += vals[i] - min;
  1073. vals[i] = _;
  1074. }
  1075. const SB = vals.reduce((sum, val) => sum + val, -(vals[0] / 2));
  1076. const SAB = vals[0] / 2 * vals.length;
  1077. ShowPopup(i18n("Your pp Gini index of bp%{bp} is %{val}.", {bp: vals.length, val: (1 - SB/SAB).toPrecision(6)}));
  1078. }
  1079. const TopRanksWorker = (userId, modestr, addedNodes = [document.body]) => {
  1080. const isLazer = window.location.hostname.split(".")[0] === "lazer"; // assume that hostname can only be osu.ppy.sh or lazer.ppy.sh
  1081. const subdomain = isLazer ? "lazer": "osu";
  1082. const sectionNames = new Set();
  1083. const GetSection = (ele) => {
  1084. let count = 0;
  1085. while(ele){
  1086. if(ele.tagName === "DIV" && ele.className === "js-sortable--page") return ele.dataset.pageId;
  1087. ele = ele.parentElement;
  1088. count++;
  1089. if(count > 50) console.log(ele);
  1090. }
  1091. };
  1092. addedNodes.forEach((eles) => {
  1093. if(eles instanceof Element) eles.querySelectorAll(":scope div.play-detail.play-detail--highlightable").forEach((ele) => {
  1094. if(ele.getAttribute("improved") !== null) return;
  1095. const a = ele.querySelector(":scope time.js-timeago");
  1096. const t = a.getAttribute("datetime");
  1097. const data = messageCache.get(`${userId},${modestr},${subdomain},${t}`);
  1098. if(data){
  1099. sectionNames.add(GetSection(ele));
  1100. ListItemWorker(ele, data, isLazer);
  1101. }
  1102. });
  1103. });
  1104. sectionNames.forEach(sectionName => AdjustStyle(modestr, sectionName));
  1105. };
  1106. const DiffToColour = (diff, stops = [0, 0.1, 1.25, 2, 2.5, 3.3, 4.2, 4.9, 5.8, 6.7, 7.7, 9], vals = ['#AAAAAA', '#4290FB', '#4FC0FF', '#4FFFD5', '#7CFF4F', '#F6F05C', '#FF8068', '#FF4E6F', '#C645B8', '#6563DE', '#18158E', '#000000']) => {
  1107. const len = stops.length;
  1108. diff = Math.min(Math.max(diff, stops[0]), stops[len - 1]);
  1109. let r = stops.findIndex(stop => stop > diff);
  1110. if(r === -1) r = len - 1;
  1111. const d = stops[r] - stops[r - 1];
  1112. return `#${[[1, 3], [3, 5], [5, 7]]
  1113. .map(_ => [Number.parseInt(vals[r].slice(..._), 16), Number.parseInt(vals[r-1].slice(..._), 16)])
  1114. .map(_ => Math.round((_[0] ** 2.2 * (diff - stops[r-1]) / d + _[1] ** 2.2 * (stops[r] - diff) / d) ** (1 / 2.2)).toString(16).padStart(2, "0"))
  1115. .join("")
  1116. }`;
  1117. };
  1118. const ListItemWorker = (ele, data, isLazer) => {
  1119. if(ele.getAttribute("improved") !== null) return;
  1120. ele.setAttribute("improved", "");
  1121. ele.setAttribute("data-replay-id", data.id);
  1122. if(data.pp){
  1123. data.pp = Number(data.pp);
  1124. const pptext = ele.querySelector(".play-detail__pp > span").childNodes[0];
  1125. pptext.nodeValue = data.pp >= 1 ? data.pp.toPrecision(5) : (data.pp < 0.00005 ? 0 : data.pp.toFixed(4));
  1126. if(data.weight) pptext.title = i18n("%{pc} of total pp", {pc: data.weight.pp >= 1 ? data.weight.pp.toPrecision(5) : (data.weight.pp < 0.00005 ? 0 : data.weight.pp.toFixed(4))});
  1127. }
  1128. const left = ele.querySelector("div.play-detail__group.play-detail__group--top");
  1129. const leftc = HTML("div", {class: "play-detail__group--background", style: `background-image: url(https://assets.ppy.sh/beatmaps/${data.beatmap.beatmapset_id}/covers/card@2x.jpg);`});
  1130. left.insertAdjacentElement("beforebegin", leftc);
  1131. const detail = ele.querySelector("div.play-detail__score-detail-top-right");
  1132. const du = detail.children[0];
  1133. if(!detail.children[1]) detail.append(HTML("div", {classList: "play-detail__pp-weight"}));
  1134. const db = detail.children[1];
  1135. data.statistics.perfect ??= 0, data.statistics.great ??= 0, data.statistics.good ??= 0, data.statistics.ok ??= 0, data.statistics.meh ??= 0, data.statistics.miss ??= 0;
  1136. const bmName = ele.querySelector("span.play-detail__beatmap");
  1137. const sr = HTML("div", {class: `difficulty-badge ${data.beatmap.difficulty_rating >= 6.5 ? "difficulty-badge--expert-plus" : ""}`, style: `--bg: ${DiffToColour(data.beatmap.difficulty_rating)}`},
  1138. HTML("span", {class: "difficulty-badge__icon"}, HTML("span", {class: "fas fa-star"})),
  1139. HTML("span", {class: "difficulty-badge__rating"}, HTML(`${data.beatmap.difficulty_rating.toFixed(2)}`))
  1140. );
  1141. /*
  1142. const ic = ele;
  1143. ic.classList.add("audio-player", "js-audio--player");
  1144. ic.setAttribute("data-audio-url", `https://b.ppy.sh/preview/${data.beatmap.beatmapset_id}.mp3`)
  1145. ic.setAttribute("data-audio-state", "paused");
  1146. const gr = ele;
  1147. gr.classList.add("audio-player__button", "audio-player__button--play", "js-audio--play");
  1148. */
  1149. bmName.parentElement.insertBefore(sr, bmName);
  1150. const bma = ele.querySelector("a.play-detail__title");
  1151. // const modeName = ["STD", "TAIKO", "CTB", "MANIA"];
  1152. bma.onclick = (e) => {e.stopPropagation();};
  1153. switch(data.ruleset_id){
  1154. case 0:{
  1155. du.replaceChildren(
  1156. HTML("span", {class: "play-detail__before"}),
  1157. HTML("span", {class: "play-detail__Accuracy", title: i18n(`${isLazer ? "Lazer" : "V1"} Accuracy`)}, HTML(`${(data.accuracy * 100).toFixed(2)}%`)),
  1158. HTML("span", {class: "play-detail__combo", title: i18n(`Combo${isLazer ? "/Max Combo" : ""}`)},
  1159. HTML("span", {class: `combo ${isLazer ?(data.max_combo === (data.maximum_statistics.great ?? 0) + (data.maximum_statistics.legacy_combo_increase ?? 0) ? "legacy-perfect-combo" : ""):(data.legacy_perfect ? "legacy-perfect-combo" : "")}`}, HTML(`${data.max_combo}`)),
  1160. isLazer ? HTML("/") : null,
  1161. isLazer ? HTML("span", {class: "max-combo"}, HTML(`${(data.maximum_statistics.great ?? 0) + (data.maximum_statistics.legacy_combo_increase ?? 0)}`)) : null,
  1162. HTML("x"),
  1163. ),
  1164. );
  1165. const m_300 = HTML("span", {class: "score-detail score-detail-osu-300"},
  1166. HTML("span", {class: "osu-300"},
  1167. HTML("300")
  1168. ),
  1169. HTML("span", {class: "score-detail-data-text"},
  1170. HTML(`${data.statistics.great + data.statistics.perfect}`)
  1171. )
  1172. );
  1173. const s100 = HTML("span", {class: "score-detail score-detail-osu-100"},
  1174. HTML("span", {class: "osu-100"},
  1175. HTML("100")
  1176. ),
  1177. HTML("span", {class: "score-detail-data-text"},
  1178. HTML(`${data.statistics.ok + data.statistics.good}`)
  1179. )
  1180. );
  1181. const s50 = HTML("span", {class: "score-detail score-detail-osu-50"},
  1182. HTML("span", {class: "osu-50"},
  1183. HTML("50")
  1184. ),
  1185. HTML("span", {class: "score-detail-data-text"},
  1186. HTML(`${data.statistics.meh}`)
  1187. )
  1188. );
  1189. const s0 = HTML("span", {class: "score-detail score-detail-osu-miss"},
  1190. HTML("span", {class: "osu-miss"},
  1191. HTML("img", {src: svg_osu_miss, alt: "miss"})
  1192. ),
  1193. HTML("span", {class: "score-detail-data-text"},
  1194. HTML(`${data.statistics.miss}`)
  1195. )
  1196. );
  1197. db.replaceChildren(m_300, s100, s50, s0);
  1198. break;
  1199. }
  1200. case 1:{
  1201. const cur = [data.statistics.great ?? 0, data.statistics.ok ?? 0, data.statistics.miss ?? 0];
  1202. const mx = cur[0] + cur[1] + cur[2];
  1203. du.replaceChildren(
  1204. HTML("span", {class: "play-detail__before"}),
  1205. HTML("span", {class: "play-detail__Accuracy", title: i18n(`${isLazer ? "Lazer" : "V1"} Accuracy`)}, HTML(`${(data.accuracy * 100).toFixed(2)}%`)),
  1206. HTML("span", {class: "play-detail__combo", title: i18n(`Combo/Max Combo`)},
  1207. HTML("span", {class: `combo ${(data.max_combo === mx ? "legacy-perfect-combo" : "")}`}, HTML(`${data.max_combo}`)),
  1208. HTML("/"),
  1209. HTML("span", {class: "max-combo"}, HTML(`${mx}`)),
  1210. HTML("x"),
  1211. ),
  1212. );
  1213. db.replaceChildren(
  1214. HTML("span", {class: "score-detail score-detail-taiko-300"},
  1215. HTML("span", {class: "taiko-300"}, HTML("300")),
  1216. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.great ?? 0))
  1217. ),
  1218. HTML("span", {class: "score-detail score-detail-taiko-150"},
  1219. HTML("span", {class: "taiko-150"}, HTML("150")),
  1220. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.ok ?? 0))
  1221. ),
  1222. HTML("span", {class: "score-detail score-detail-fruits-combo"},
  1223. HTML("span", {class: "taiko-miss"}, HTML("miss")),
  1224. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.miss ?? 0))
  1225. ),
  1226. );
  1227. break;
  1228. }
  1229. case 2:{
  1230. if (isLazer) {
  1231. const cur = [data.statistics.great ?? 0, data.statistics.large_tick_hit ?? 0, data.statistics.small_tick_hit ?? 0];
  1232. const mx = [data.maximum_statistics.great ?? 0, data.maximum_statistics.large_tick_hit ?? 0, data.maximum_statistics.small_tick_hit ?? 0];
  1233. du.replaceChildren(
  1234. HTML("span", {class: "play-detail__before"}),
  1235. HTML("span", {class: "play-detail__Accuracy", title: i18n(`Lazer Accuracy`)}, HTML(`${(data.accuracy * 100).toFixed(2)}%`)),
  1236. HTML("span", {class: "play-detail__combo", title: i18n(`Combo/Max Combo`)},
  1237. HTML("span", {class: `combo ${(data.max_combo === mx[0] + mx[1] ? "legacy-perfect-combo" : "")}`}, HTML(`${data.max_combo}`)),
  1238. HTML("/"),
  1239. HTML("span", {class: "max-combo"}, HTML(`${mx[0] + mx[1]}`)),
  1240. HTML("x"),
  1241. ),
  1242. );
  1243. db.replaceChildren(
  1244. HTML("span", {class: "score-detail score-detail-fruits-300"},
  1245. HTML("span", {class: "fruits-300"}, HTML("fruits")),
  1246. HTML("span", {class: "score-detail-data-text"}, HTML(cur[0] + "/" + mx[0]))
  1247. ),
  1248. HTML("span", {class: "score-detail score-detail-fruits-100"},
  1249. HTML("span", {class: "fruits-100"}, HTML("ticks")),
  1250. HTML("span", {class: "score-detail-data-text"}, HTML(cur[1] + "/" + mx[1]))
  1251. ),
  1252. HTML("span", {class: "score-detail score-detail-fruits-50-miss"},
  1253. HTML("span", {class: "fruits-50-miss"}, HTML("drops")),
  1254. HTML("span", {class: "score-detail-data-text"}, HTML(cur[2] + "/" + mx[2]))
  1255. )
  1256. );
  1257. } else {
  1258. du.replaceChildren(
  1259. HTML("span", {class: "play-detail__before"}),
  1260. HTML("span", {class: "play-detail__Accuracy", title: i18n(`V1 Accuracy`)}, HTML(`${(data.accuracy * 100).toFixed(2)}%`)),
  1261. HTML("span", {class: "play-detail__combo", title: i18n(`Combo`)},
  1262. HTML("span", {class: ""}, HTML(`${data.max_combo}`)),
  1263. HTML("x")
  1264. ),
  1265. );
  1266. db.replaceChildren(
  1267. HTML("span", {class: "score-detail score-detail-fruits-300"},
  1268. HTML("span", {class: "fruits-300"}, HTML("FRUIT")),
  1269. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.great ?? 0))
  1270. ),
  1271. HTML("span", {class: "score-detail score-detail-fruits-100"},
  1272. HTML("span", {class: "fruits-100"}, HTML("tick")),
  1273. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.large_tick_hit ?? 0))
  1274. ),
  1275. HTML("span", {class: "score-detail score-detail-fruits-50-miss"},
  1276. HTML("span", {class: "fruits-50-miss"}, HTML("miss")),
  1277. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.small_tick_miss ?? 0))
  1278. ),
  1279. HTML("span", {class: "score-detail score-detail-fruits-miss"},
  1280. HTML("span", {class: "fruits-miss"}, HTML("MISS")),
  1281. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.miss ?? 0))
  1282. )
  1283. );
  1284. }
  1285. break;
  1286. }
  1287. case 3:{
  1288. const v2acc = (320*data.statistics.perfect+300*data.statistics.great+200*data.statistics.good+100*data.statistics.ok+50*data.statistics.meh)/(320*(data.statistics.perfect+data.statistics.great+data.statistics.good+data.statistics.ok+data.statistics.meh+data.statistics.miss));
  1289. const MCombo = (data.maximum_statistics.perfect ?? 0) + (data.maximum_statistics.legacy_combo_increase ?? 0);
  1290. const isMCombo = isLazer ? data.max_combo >= MCombo : data.legacy_perfect;
  1291. du.replaceChildren(
  1292. HTML("span", {class: "play-detail__before"}),
  1293. HTML("span", {class: "play-detail__Accuracy2", title: i18n(`pp Accuracy`)}, HTML(`${(v2acc * 100).toFixed(2)}%`)),
  1294. HTML("span", {class: "play-detail__Accuracy", title: i18n(`${isLazer ? "Lazer" : "V1"} Accuracy`)}, HTML(`${(data.accuracy * 100).toFixed(2)}%`)),
  1295. HTML("span", {class: "play-detail__combo", title: i18n(`Combo${isLazer ? "/Max Combo" : ""}`)},
  1296. HTML("span", {class: `combo ${isMCombo ? "legacy-perfect-combo" : ""}`}, HTML(`${data.max_combo}`)),
  1297. isLazer ? HTML("/") : null,
  1298. isLazer ? HTML("span", {class: "max-combo"}, HTML(MCombo)) : null,
  1299. HTML("x"),
  1300. ),
  1301. );
  1302. if(data.pp){
  1303. const lostpp = data.pp * (0.2 / (Math.min(Math.max(v2acc, 0.8), 1) - 0.8) - 1);
  1304. ele.querySelector(".play-detail__pp").appendChild(HTML("span", {class: "lost-pp"}, HTML(`-${lostpp.toPrecision(4)}`)));
  1305. }
  1306. const M_300 = Number(data.statistics.perfect) / Math.max(Number(data.statistics.great), 1);
  1307. db.replaceChildren(
  1308. HTML("span", {class: "score-detail score-detail-mania-max-300"},
  1309. HTML("span", {class: "mania-max"}, HTML("M")),
  1310. HTML("/"),
  1311. HTML("span", {class: "mania-300"}, HTML("300")),
  1312. HTML("span", {class: "score-detail-data-text"}, HTML(`${M_300 >= 1000 ? Math.round(M_300) : (M_300 < 1 ? M_300.toFixed(2): M_300.toPrecision(3))}`))
  1313. ),
  1314. HTML("span", {class: "score-detail score-detail-mania-max-200"},
  1315. HTML("span", {class: "mania-200"}, HTML("200")),
  1316. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.good))
  1317. ),
  1318. HTML("span", {class: "score-detail score-detail-mania-max-100"},
  1319. HTML("span", {class: "mania-100"}, HTML("100")),
  1320. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.ok))
  1321. ),
  1322. HTML("span", {class: "score-detail score-detail-mania-max-50"},
  1323. HTML("span", {class: "mania-50"}, HTML("50")),
  1324. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.meh))
  1325. ),
  1326. HTML("span", {class: "score-detail score-detail-mania-max-0"},
  1327. HTML("span", {class: "mania-miss"}, HTML("miss")),
  1328. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.miss))
  1329. )
  1330. );
  1331. break;
  1332. }
  1333. default:;
  1334. }
  1335. }
  1336. let lastInitData = null;
  1337. const OsuLevelToExp = (n) => {
  1338. if(n <= 100) return 5000 / 3 * (4 * n ** 3 - 3 * n ** 2 - n) + 1.25 * 1.8 ** (n - 60);
  1339. else return 26_931_190_827 + 99_999_999_999 * (n - 100);
  1340. }
  1341. const OsuExpValToStr = (num) => {
  1342. const exp = Math.log10(num);
  1343. if(exp >= 12){
  1344. return `${(num / 10 ** 12).toPrecision(4)}T`;
  1345. }
  1346. else if(exp >= 9){
  1347. return `${(num / 10 ** 9).toPrecision(4)}B`;
  1348. }
  1349. else if(exp >= 6){
  1350. return `${(num / 10 ** 6).toPrecision(4)}M`;
  1351. }
  1352. else if(exp >= 4){
  1353. return `${(num / 10 ** 3).toPrecision(4)}K`;
  1354. }
  1355. else return `${num}`;
  1356. }
  1357. const messageCache = new Map();
  1358. window.messageCache = messageCache;
  1359. const profUrlReg = /https:\/\/(?:osu|lazer)\.ppy\.sh\/users\/[0-9]+(?:|\/osu|\/taiko|\/fruits|\/mania)/;
  1360. const ImproveProfile = (mulist) => {
  1361. const wloc = window.location.toString();
  1362. if(!profUrlReg.test(wloc)) return;
  1363. const initDataEle = document.querySelector(".js-react--profile-page.osu-layout.osu-layout--full");
  1364. if(!initDataEle) return;
  1365. const initData = JSON.parse(initDataEle.dataset.initialData);
  1366. const userId = initData.user.id, modestr = initData.current_mode;
  1367. if(initData !== lastInitData){
  1368. let ppDiv = null;
  1369. document.querySelectorAll("div.value-display.value-display--plain").forEach((ele) => {
  1370. if(ele.querySelector("div.value-display__label").textContent === "pp") ppDiv = ele;
  1371. });
  1372. if(ppDiv){
  1373. const ttscore = initData.user.statistics.total_score;
  1374. const lvl = initData.user.statistics.level.current;
  1375. const upgradescore = Math.round(OsuLevelToExp(lvl + 1) - OsuLevelToExp(lvl));
  1376. const lvlscore = ttscore - Math.round(OsuLevelToExp(lvl));
  1377. lastInitData = initData;
  1378. document.querySelector("div.bar__text").textContent = `${OsuExpValToStr(lvlscore)}/${OsuExpValToStr(upgradescore)} (${(lvlscore/upgradescore * 100).toPrecision(3)}%)`;
  1379. const _pp = initData.user.statistics.pp;
  1380. ppDiv.querySelector(".value-display__value > div").textContent = _pp >= 1 ? _pp.toPrecision(6) : (_pp < 0.000005 ? 0 : _pp.toFixed(5));
  1381. }
  1382. }
  1383. if(mulist !== undefined) mulist.forEach((record) => {
  1384. if(record.type === "childList" && record.addedNodes) TopRanksWorker(userId, modestr, record.addedNodes);
  1385. });
  1386. }
  1387. let wloc = "";
  1388. const WindowLocationChanged = () => {
  1389. if(window.location !== wloc){
  1390. wloc = window.location;
  1391. return true;
  1392. }
  1393. else return false;
  1394. }
  1395. const InsertStyleSheet = () => {
  1396. //const sheetId = "osu-web-enhancement-general-stylesheet";
  1397. const s = new CSSStyleSheet();
  1398. s.replaceSync(inj_style);
  1399. document.adoptedStyleSheets = [...document.adoptedStyleSheets, s];
  1400. }
  1401. const OnBeatmapsetDownload = (message) => {
  1402. beatmapsets.add(message.beatmapsetId);
  1403. }
  1404. const ImproveBeatmapPlaycountItems = () => {
  1405. for(const item of [...document.querySelectorAll("div.beatmap-playcount")]){
  1406. if(item.getAttribute("improved") !== null) continue;
  1407. item.setAttribute("improved", "");
  1408. const a = item.querySelector("a");
  1409. const bms = bmsReg.exec(a.href);
  1410. if(!bms?.[1]) continue;
  1411. const d = item.querySelector("div.beatmap-playcount__detail");
  1412. const b = HTML("div", {class: "beatmap-playcount__background", style: `background-image: url(https://assets.ppy.sh/beatmaps/${bms[1]}/covers/card@2x.jpg)`});
  1413. if(d.childElementCount > 0) d.insertBefore(b, d.children[0]);
  1414. else d.append(b);
  1415. }
  1416. }
  1417. const CloseScoreCardPopup = () => {
  1418. document.querySelector("div.score-card-popup-window").remove();
  1419. }
  1420. const CopyToClipboard = (txt) => {
  1421. const t = document.createElement('textarea');
  1422. t.value = txt;
  1423. document.body.appendChild(t);
  1424. t.select();
  1425. document.execCommand('copy');
  1426. document.body.removeChild(t);
  1427. }
  1428. const ShowScoreCardPopup = () => {
  1429. const p = document.querySelector("div.js-portal");
  1430. if(!p) return;
  1431. document.body.append(
  1432. HTML("div", {class: "score-card-popup-window"},
  1433. HTML("div", {class: "score-card-popup-menu"},
  1434. HTML("button", {class: "score-card-close-button", eventListener: {type: "click", listener: CloseScoreCardPopup}}),
  1435. HTML("button", {class: "score-card-copy-to-clipboard-button", ev}),
  1436. ),
  1437. HTML("div", {class: "score-card"},
  1438. )
  1439. )
  1440. );
  1441. };
  1442. const MakeTextDetail = (data) => {
  1443. let detail = "";
  1444. const s = data.statistics; const m = data.maximum_statistics; const b = data.beatmap;
  1445. const secToMin = (t) => `${Math.floor(t/60)}:${String(t%60).padStart(2, '0')}`;
  1446. const isLazer = window.location.hostname.split(".")[0] === "lazer"; // assume that hostname can only be osu.ppy.sh or lazer.ppy.sh
  1447. switch(data.ruleset_id){
  1448. case 0: detail =
  1449. `${(s.great ?? 0) + (s.perfect ?? 0)}-${(s.ok ?? 0) + (s.good ?? 0)}-${s.meh ?? 0}-${s.miss ?? 0} ${data.max_combo ?? 0}${isLazer ? `/${(m.great ?? 0) + (m.legacy_combo_increase ?? 0)}` : ""}x
  1450. ${b.count_circles ?? 0} 🌡️ ${b.count_sliders ?? 0} 🔄 ${b.count_spinners ?? 0}
  1451. `; break;
  1452. case 1: detail =
  1453. `${s.great ?? 0}-${s.ok ?? 0}-${s.miss ?? 0} ${data.max_combo ?? 0}/${(s.great ?? 0) + (s.ok ?? 0) + (s.miss ?? 0)}x
  1454. 🥁 ${b.count_circles ?? 0} 🌡️ ${b.count_sliders ?? 0} 🍥 ${b.count_spinners ?? 0}
  1455. `; break;
  1456. case 2: detail = isLazer ?
  1457. `${s.great ?? 0}/${m.great ?? 0}-${s.large_tick_hit ?? 0}/${m.large_tick_hit ?? 0}-${s.small_tick_hit ?? 0}/${m.small_tick_hit ?? 0} ${data.max_combo ?? 0}/${(m.large_tick_hit ?? 0)+(m.great ?? 0)}}x
  1458. 🍎 ${b.count_circles ?? 0} 💧 ${b.count_sliders ?? 0} 🍌 ${b.count_spinners ?? 0}
  1459. ` :
  1460. `${s.great ?? 0}-${s.large_tick_hit ?? 0}-${s.small_tick_miss ?? 0}-${s.miss ?? 0} ${data.max_combo ?? 0}x
  1461. 🍎 ${b.count_circles ?? 0} 💧 ${b.count_sliders ?? 0} 🍌 ${b.count_spinners ?? 0}
  1462. `; break;
  1463. case 3: detail =
  1464. `${s.perfect ?? 0}-${s.great ?? 0}-${s.good ?? 0}-${s.ok ?? 0}-${s.meh ?? 0}-${s.miss ?? 0} ${data.max_combo}${isLazer ? `/${(m.perfect ?? 0) + (m.legacy_combo_increase ?? 0)}` : ""}x
  1465. 🍚 ${b.count_circles ?? 0} 🍜 ${b.count_sliders ?? 0}
  1466. `; break;
  1467. default:;
  1468. }
  1469. const scrMsg =
  1470. `${data.beatmapset.title}
  1471. [${data.beatmap.version}] ${secToMin(data.beatmap.total_length)}
  1472. ${data.total_score} ${data.rank} ${data.pp ? (data.pp >= 1 ? data.pp.toPrecision(5) : (data.pp < 0.00005 ? 0 : data.pp.toFixed(4))) : "-"}pp
  1473. ${detail}
  1474. `;
  1475. return scrMsg;
  1476. }
  1477. const CopyDetailsPopup = () => {
  1478. const ele = document.querySelector("div.play-detail.play-detail--active"); if(!ele) return;
  1479. const id = ele.dataset.replayId;
  1480. const data = messageCache.get(Number(id)); if(!data) return;
  1481. const msg = MakeTextDetail(data);
  1482. console.log(msg);
  1483. CopyToClipboard(msg);
  1484. ShowPopup(i18n("Score details copied to clipboard!"));
  1485. };
  1486. const AddPopupButton = () => {
  1487. const p = document.querySelector("div.js-portal")?.querySelector("div.simple-menu");
  1488. if(!p || p.querySelector("button.score-card-popup-button")) return;
  1489. // p.append(HTML("button", {class: "score-card-popup-button simple-menu__item", type: "button", eventListener: [{type: "click", listener: ShowScoreCardPopup}]}, HTML("Popup")));
  1490. p.append(HTML("button", {class: "score-card-popup-button simple-menu__item", type: "button", eventListener: [{type: "click", listener: CopyDetailsPopup}]}, HTML(i18n("Copy Text Details"))));
  1491. };
  1492. const OnMutation = (mulist) => {
  1493. mut.disconnect();
  1494. AddMenu();
  1495. FilterBeatmapSet();
  1496. ImproveBeatmapPlaycountItems();
  1497. ImproveProfile(mulist);
  1498. AddPopupButton();
  1499. mut.observe(document, {childList: true, subtree: true});
  1500. };
  1501. const MessageFilter = (message) => {
  1502. const info = `${message.userId},${message.mode},${message.subdomain}`;
  1503. switch(message.type){
  1504. case "beatmapset_download_complete": OnBeatmapsetDownload(message); break;
  1505. case "top_ranks":
  1506. [message.data.pinned.items, message.data.best.items, message.data.firsts.items].forEach(items => items.forEach(item => {
  1507. messageCache.set(`${info},${item.ended_at}`, item);
  1508. messageCache.set(item.id, item);
  1509. }));
  1510. TopRanksWorker(message.userId, message.mode);
  1511. break;
  1512. case "firsts": case "pinned": case "best": case "recent":
  1513. message.data.forEach(item => { messageCache.set(`${info},${item.ended_at}`, item); messageCache.set(item.id, item); });
  1514. TopRanksWorker(message.userId, message.mode);
  1515. break;
  1516. case "historical":
  1517. message.data.recent.items.forEach(item => { messageCache.set(`${info},${item.ended_at}`, item); messageCache.set(item.id, item); });
  1518. TopRanksWorker(message.userId, message.mode);
  1519. break;
  1520. default:;
  1521. }
  1522. }
  1523. const WindowMessageFilter = (event) => {
  1524. if(event.source === window && event?.data?.id === "osu!web enhancement"){
  1525. MessageFilter(event.data);
  1526. }
  1527. }
  1528. const OnClick = (event) => {
  1529. let t = event.target;
  1530. while(t){
  1531. if(t.tagName === "A"){
  1532. const e = bmsdlReg.exec(t.href);
  1533. if(!e) continue;
  1534. beatmapsets.add(Number(e[1]));
  1535. FilterBeatmapSet();
  1536. break;
  1537. }
  1538. t = t.parentElement;
  1539. }
  1540. }
  1541. //document.addEventListener("click", OnClick);
  1542. const curLocale = window.currentLocale;
  1543. if (curLocale && locales[curLocale]) {
  1544. console.log("localization available");
  1545. i18n.translator.add(locales[curLocale]);
  1546. }
  1547. window.addEventListener("message", WindowMessageFilter);
  1548. const mut = new MutationObserver(OnMutation);
  1549. mut.observe(document, {childList: true, subtree: true});
  1550. InsertStyleSheet();
  1551. //{id, mode} -> (bmid -> record)
  1552. console.log("osu!web enhancement loaded");
  1553.  
  1554.  
  1555. // below are test code
  1556. /*
  1557. const osusrc = "https://i.ppy.sh/bde5906f8f985126f4ea624d3eb14c8702883aa2/68747470733a2f2f6f73752e7070792e73682f77696b692f696d616765732f536b696e6e696e672f496e746572666163652f696d672f6d6f64652d6f73752e706e67";
  1558. const taikosrc = "https://i.ppy.sh/c1a9502ea05c9fcde03a375ebf528a12ff30cae7/68747470733a2f2f6f73752e7070792e73682f77696b692f696d616765732f536b696e6e696e672f496e746572666163652f696d672f6d6f64652d7461696b6f2e706e67";
  1559. const fruitsrc = "https://i.ppy.sh/e7cad0470810a868df06d597e3441812659c0bfa/68747470733a2f2f6f73752e7070792e73682f77696b692f696d616765732f536b696e6e696e672f496e746572666163652f696d672f6d6f64652d6672756974732e706e67";
  1560. const maniasrc = "https://i.ppy.sh/55d9494fcf7c3ef2d614695a9a951977a21f23f6/68747470733a2f2f6f73752e7070792e73682f77696b692f696d616765732f536b696e6e696e672f496e746572666163652f696d672f6d6f64652d6d616e69612e706e67";
  1561. const pngsrc = [osusrc, taikosrc, fruitsrc, maniasrc];
  1562. const png = [null, null, null, null];
  1563. let canvas, ctx, cw, ch;
  1564. const ToggleSnow = async (modeid) => {
  1565. if(canvas) {canvas.remove(); return;}
  1566. canvas = HTML("canvas", {style: `position: fixed; bottom: 0px; left: 0px;`, width: window.innerWidth, height: window.innerHeight});
  1567. document.body.append(canvas);
  1568. ctx = canvas.getContext("webgl2");
  1569. if(!png[modeid]){
  1570. const response = await fetch(pngsrc[modeid]);
  1571. png[modeid] = await response.blob();
  1572. }
  1573. }
  1574. */