osu!web enhancement

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

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

  1. // ==UserScript==
  2. // @name osu!web enhancement
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.6.11
  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. "en": {
  464. "values": {
  465. "Owned": "Owned",
  466. "Download": "Download",
  467. "pp Accuracy": "pp Accuracy",
  468. "V1 Accuracy": "V1 Accuracy",
  469. "V2 Accuracy": "V2 Accuracy",
  470. "Lazer Accuracy": "Lazer Accuracy",
  471. "Combo": "Combo",
  472. "Combo/Max Combo": "Combo/Max Combo",
  473. "Import osu!.db": "Import osu!.db",
  474. "Check for update": "Check for update",
  475. "Calculate pp Gini index": "Calculate pp Gini index",
  476. "Go to GreasyFork page": "Go to GreasyFork page",
  477. "Copy Text Details": "Copy Text Details",
  478. "Could not find best play data": "Could not find best play data",
  479. "The latest version is already installed!": "The latest version is already installed!",
  480. "Script is already busy reading a osu!.db file.": "Script is already busy reading a osu!.db file.",
  481. "There are still remaining unread bytes, something may be wrong.": "There are still remaining unread bytes, something may be wrong.",
  482. "Score details copied to clipboard!": "Score details copied to clipboard!",
  483. "%{pc} of total pp": "%{pc} of total pp",
  484. "Your pp Gini index of bp%{bp} is %{val}.": "Your pp Gini index of bp%{bp} is %{val}.",
  485. "Finished reading osu!.db in %{time} ms.": "Finished reading osu!.db in %{time} ms.",
  486. "MAX: %{MAX} 300: %{MAX}": "MAX: %{MAX} 300: %{MAX}",
  487. }
  488. },
  489. "zh": {
  490. "values": {
  491. "Owned": "已获得",
  492. "Download": "下载",
  493. "pp Accuracy": "pp-准确度",
  494. "V1 Accuracy": "V1-准确度",
  495. "V2 Accuracy": "V2-准确度",
  496. "Lazer Accuracy": "Lazer-准确度",
  497. "Combo": "连击数",
  498. "Combo/Max Combo": "连击数/最大连击数",
  499. "Import osu!.db": "读取 osu!.db",
  500. "Check for update": "检查更新",
  501. "Calculate pp Gini index": "计算 pp 基尼指数",
  502. "Go to GreasyFork page": "前往 GreasyFork 页面",
  503. "Copy Text Details": "复制文本信息",
  504. "Could not find best play data": "无法获取 BP 数据",
  505. "The latest version is already installed!": "已安装最新版本!",
  506. "Script is already busy reading a osu!.db file.": "脚本已经开始读取 osu!.db 文件。",
  507. "There are still remaining unread bytes, something may be wrong.": "部分数据未能读取,可能发生错误。",
  508. "Score details copied to clipboard!": "分数信息已复制到剪贴板!",
  509. "%{pc} of total pp": "占总 pp 的 %{pc}",
  510. "Your pp Gini index of bp%{bp} is %{val}.": "BP%{bp} 的 pp 基尼指数为 %{val}。",
  511. "Finished reading osu!.db in %{time} ms.": "osu!.db 读取完毕,用时 %{time}ms。",
  512. "MAX: %{MAX} 300: %{MAX}": "MAX: %{MAX} 300: %{MAX}",
  513. }
  514. },
  515. "zh-tw": {
  516. "values": {
  517. "Owned": "已獲得",
  518. "Download": "下載",
  519. "pp Accuracy": "pp-準確度",
  520. "V1 Accuracy": "V1-準確度",
  521. "V2 Accuracy": "V2-準確度",
  522. "Lazer Accuracy": "Lazer-準確度",
  523. "Combo": "連擊數",
  524. "Combo/Max Combo": "連擊數/最大連擊數",
  525. "Import osu!.db": "讀取 osu!.db",
  526. "Check for update": "檢查更新",
  527. "Calculate pp Gini index": "計算 pp 基尼指數",
  528. "Go to GreasyFork page": "前往 GreasyFork 頁面",
  529. "Copy Text Details": "複製文字訊息",
  530. "Could not find best play data": "无法獲取 BP 數據",
  531. "The latest version is already installed!": "已安裝最新版本!",
  532. "Script is already busy reading a osu!.db file.": "腳本已經開始讀取 osu!.db 文件。",
  533. "There are still remaining unread bytes, something may be wrong.": "部分數據未能讀取,可能發生錯誤。",
  534. "Score details copied to clipboard!": "分數訊息已複製到剪貼簿!",
  535. "%{pc} of total pp": "佔總 pp 的 %{pc}",
  536. "Your pp Gini index of bp%{bp} is %{val}.": "BP%{bp} 的 pp 基尼指數為 %{val}。",
  537. "Finished reading osu!.db in %{time} ms.": "osu!.db 讀取完畢,用時 %{time}ms。",
  538. "MAX: %{MAX} 300: %{MAX}": "MAX: %{MAX} 300: %{MAX}",
  539. }
  540. },
  541. "ja": {
  542. "values": {
  543. "Owned": "取得済み",
  544. "Download": "ダウンロード",
  545. "pp Accuracy": "pp-精度",
  546. "V1 Accuracy": "V1-精度",
  547. "V2 Accuracy": "V2-精度",
  548. "Lazer Accuracy": "Lazer-精度",
  549. "Combo": "コンボ数",
  550. "Combo/Max Combo": "コンボ数/最大コンボ数",
  551. "Import osu!.db": "osu!.db を読み取る",
  552. "Check for update": "更新を確認する",
  553. "Calculate pp Gini index": "pp のジニ指数の計算",
  554. "Go to GreasyFork page": "GreasyFork のページへ",
  555. "Copy Text Details": "詳細をテキストにコピー",
  556. "Could not find best play data": "BP データが見つからない",
  557. "The latest version is already installed!": "最新版は既にインストールされている!",
  558. "Script is already busy reading a osu!.db file.": "スクリプトは osu!.db ファイルの読み取りを既に始める。",
  559. "There are still remaining unread bytes, something may be wrong.": "一部のデータを読み取れません、多分何かの間違いだ。",
  560. "Score details copied to clipboard!": "スコア詳細をクリップボードにコピー!",
  561. "%{pc} of total pp": "全 pp の %{pc}",
  562. "Your pp Gini index of bp%{bp} is %{val}.": "BP%{bp} の pp ジニ指数は %{val} です。",
  563. "Finished reading osu!.db in %{time} ms.": "osu!.db の読み取りを %{time}ms で完了しました。",
  564. "MAX: %{MAX} 300: %{MAX}": "MAX: %{MAX} 300: %{MAX}",
  565. }
  566. }
  567. };
  568. const scriptId = "osu-web-enhancement-XHR-script";
  569. if(!document.querySelector(`script#${scriptId}`)){
  570. const script = document.createElement("script");
  571. script.textContent = scriptContent;
  572. document.body.appendChild(script);
  573. }
  574. const HTML = (tagname, attrs, ...children) => {
  575. if(attrs === undefined) return document.createTextNode(tagname);
  576. const ele = document.createElement(tagname);
  577. if(attrs) for(const [key, value] of Object.entries(attrs)){
  578. if(value === null || value === undefined) continue;
  579. if(key === "eventListener"){
  580. for(const listener of value){
  581. ele.addEventListener(listener.type, listener.listener, listener.options);
  582. }
  583. }
  584. else ele.setAttribute(key, value);
  585. }
  586. for(const child of children) if(child) ele.append(child);
  587. return ele;
  588. };
  589. const html = (html) => {
  590. const t = document.createElement("template");
  591. t.innerHTML = html;
  592. return t.content.firstElementChild;
  593. };
  594. const OsuMod = {
  595. NoFail: 1 << 0,
  596. Easy: 1 << 1,
  597. TouchDevice: 1 << 2,
  598. NoVideo: 1 << 2,
  599. Hidden: 1 << 3,
  600. HardRock: 1 << 4,
  601. SuddenDeath: 1 << 5,
  602. DoubleTime: 1 << 6,
  603. Relax: 1 << 7,
  604. HalfTime: 1 << 8,
  605. Nightcore: 1 << 9, // always with DT
  606. Flashlight: 1 << 10,
  607. Autoplay: 1 << 11,
  608. SpunOut: 1 << 12,
  609. Autopilot: 1 << 13,
  610. Perfect: 1 << 14,
  611. Key4: 1 << 15,
  612. Key5: 1 << 16,
  613. Key6: 1 << 17,
  614. Key7: 1 << 18,
  615. Key8: 1 << 19,
  616. KeyMod: 1 << 19 | 1 << 18 | 1 << 17 | 1 << 16 | 1 << 15,
  617. FadeIn: 1 << 20,
  618. Random: 1 << 21,
  619. Cinema: 1 << 22,
  620. TargetPractice: 1 << 23,
  621. Key9: 1 << 24,
  622. Coop: 1 << 25,
  623. Key1: 1 << 26,
  624. Key3: 1 << 27,
  625. Key2: 1 << 28,
  626. ScoreV2: 1 << 29,
  627. Mirror: 1 << 30,
  628. };
  629. const Byte = (arr, iter) => {
  630. return arr[iter.nxtpos++];
  631. }
  632. const RankedStatus = (arr, iter) => {
  633. const r = {value: Byte(arr, iter), description: ""};
  634. switch(r.value){
  635. case 1: r.description = "unsubmitted"; break;
  636. case 2: r.description = "pending/wip/graveyard"; break;
  637. case 3: r.description = "unused"; break;
  638. case 4: r.description = "ranked"; break;
  639. case 5: r.description = "approved"; break;
  640. case 6: r.description = "qualified"; break;
  641. case 7: r.description = "loved"; break;
  642. default: r.description = "unknown"; r.value = 0;
  643. }
  644. return r;
  645. };
  646. const OsuMode = (arr, iter) => {
  647. const r = {value: Byte(arr, iter), description: ""};
  648. switch(r.value){
  649. case 1: r.description = "taiko"; break;
  650. case 2: r.description = "catch"; break;
  651. case 3: r.description = "mania"; break;
  652. default: r.value = 0; r.description = "osu";
  653. }
  654. return r;
  655. };
  656. const Grade = (arr, iter) => {
  657. const r = {value: Byte(arr, iter), description: ""};
  658. switch(r.value){
  659. case 0: r.description = "SSH"; break;
  660. case 1: r.description = "SH"; break;
  661. case 2: r.description = "SS"; break;
  662. case 3: r.description = "S"; break;
  663. case 4: r.description = "A"; break;
  664. case 5: r.description = "B"; break;
  665. case 6: r.description = "C"; break;
  666. case 7: r.description = "D"; break;
  667. default: r.description = "not played";
  668. }
  669. return r;
  670. };
  671. const Short = (arr, iter) => (arr[iter.nxtpos++] | arr[iter.nxtpos++] << 8);
  672. const Int = (arr, iter) => { return arr[iter.nxtpos++] | arr[iter.nxtpos++] << 8 | arr[iter.nxtpos++] << 16 | arr[iter.nxtpos++] << 24; };
  673. const Long = (arr, iter) => { const r = new DataView(arr.buffer, iter.nxtpos, 8).getBigUint64(0, true); iter.nxtpos += 8; return r; };
  674. const ULEB128 = (arr, iter) => {
  675. let value = 0n, shift = 0n, peek = 0n;
  676. do{
  677. peek = BigInt(arr[iter.nxtpos++]);
  678. value |= (peek & 0x7Fn) << shift;
  679. shift += 7n;
  680. }while((peek & 0x80n) !== 0n)
  681. return value;
  682. };
  683. const Single = (arr, iter) => { const r = new DataView(arr.buffer, iter.nxtpos, 4).getFloat32(0, true); iter.nxtpos += 4; return r; };
  684. const Double = (arr, iter) => { const r = new DataView(arr.buffer, iter.nxtpos, 8).getFloat64(0, true); iter.nxtpos += 8; return r; };
  685. const Boolean = (arr, iter) => { return arr[iter.nxtpos++] !== 0x00; };
  686. const OString = (arr, iter) => {
  687. let value = "";
  688. switch(arr[iter.nxtpos++]){
  689. case 0: break;
  690. case 0x0b: {
  691. const l = ULEB128(arr, iter);
  692. const bv = new Uint8Array(arr.buffer, iter.nxtpos, Number(l));
  693. value = new TextDecoder().decode(bv);
  694. iter.nxtpos += Number(l);
  695. break;
  696. }
  697. default: console.assert(false, `error occurred while parsing osu string with the first byte.`);
  698. }
  699. return value;
  700. };
  701. const IntDouble = (arr, iter) => {
  702. const r = {int: 0, double: 0};
  703. const m1 = arr[iter.nxtpos++];
  704. console.assert(m1 === 0x08, `error occurred while parsing Int-Double pair at ${iter.nxtpos - 1} with value 0x${m1.toString(16)}: should be 0x8.`);
  705. r.int = Int(arr, iter);
  706. const m2 = arr[iter.nxtpos++];
  707. console.assert(m2 === 0x0d, `error occurred while parsing Int-Double pair at ${iter.nxtpos - 1} with value 0x${m1.toString(16)}: should be 0x8.`);
  708. r.double = Double(arr, iter);
  709. return r;
  710. };
  711. const IntDoubleArray = (arr, iter) => {
  712. const r = new Array(Int(arr, iter));
  713. for(let i = 0; i < r.length; i++) r[i] = IntDouble(arr, iter);
  714. return r;
  715. };
  716. const TimingPoint = (arr, iter) => {
  717. return {
  718. BPM: Double(arr, iter),
  719. offset: Double(arr, iter),
  720. notInherited: Boolean(arr, iter),
  721. };
  722. };
  723. const TimingPointArray = (arr, iter) => {
  724. const r = new Array(Int(arr, iter));
  725. for(let i = 0; i < r.length; i++) r[i] = TimingPoint(arr, iter);
  726. return r;
  727. };
  728. const DateTime = Long;
  729. const Beatmap = (arr, iter) => {
  730. return {
  731. bytes: (iter.osuVersion < 20191106) ? Int(arr, iter) : undefined,
  732. artistName: OString(arr, iter),
  733. artistNameUnicode: OString(arr, iter),
  734. songTitle: OString(arr, iter),
  735. songTitleUnicode: OString(arr, iter),
  736. creatorName: OString(arr, iter),
  737. difficultyName: OString(arr, iter),
  738. audioFilename: OString(arr, iter),
  739. MD5Hash: OString(arr, iter),
  740. beatmapFilename: OString(arr, iter),
  741. rankedStatus: RankedStatus(arr, iter),
  742. hitcircleCount: Short(arr, iter),
  743. sliderCount: Short(arr, iter),
  744. spinnerCount: Short(arr, iter),
  745. lastModified: Long(arr, iter),
  746. AR: iter.osuVersion < 20140609 ? Byte(arr, iter) : Single(arr, iter),
  747. CS: iter.osuVersion < 20140609 ? Byte(arr, iter) : Single(arr, iter),
  748. HP: iter.osuVersion < 20140609 ? Byte(arr, iter) : Single(arr, iter),
  749. OD: iter.osuVersion < 20140609 ? Byte(arr, iter) : Single(arr, iter),
  750. sliderVelocity: Double(arr, iter),
  751. osuSRInfoArr: (iter.osuVersion >= 20140609) ? IntDoubleArray(arr, iter) : undefined,
  752. taikoSRInfoArr: (iter.osuVersion >= 20140609) ? IntDoubleArray(arr, iter) : undefined,
  753. catchSRInfoArr: (iter.osuVersion >= 20140609) ? IntDoubleArray(arr, iter) : undefined,
  754. maniaSRInfoArr: (iter.osuVersion >= 20140609) ? IntDoubleArray(arr, iter) : undefined,
  755. drainTime: Int(arr, iter),
  756. totalTime: Int(arr, iter),
  757. audioPreviewTime: Int(arr, iter),
  758. timingPointArr: TimingPointArray(arr, iter),
  759. difficultyID: Int(arr, iter),
  760. beatmapID: Int(arr, iter),
  761. threadID: Int(arr, iter),
  762. osuGrade: Grade(arr, iter),
  763. taikoGrade: Grade(arr, iter),
  764. catchGrade: Grade(arr, iter),
  765. maniaGrade: Grade(arr, iter),
  766. offsetLocal: Short(arr, iter),
  767. stackLeniency: Single(arr, iter),
  768. mode: OsuMode(arr, iter),
  769. sourceStr: OString(arr, iter),
  770. tagStr: OString(arr, iter),
  771. offsetOnline: Short(arr, iter),
  772. titleFont: OString(arr, iter),
  773. unplayed: Boolean(arr, iter),
  774. lastTimePlayed: Long(arr, iter),
  775. isOsz2: Boolean(arr, iter),
  776. folderName: OString(arr, iter),
  777. lastTimeChecked: Long(arr, iter),
  778. ignoreBeatmapSound: Boolean(arr, iter),
  779. ignoreBeatmapSkin: Boolean(arr, iter),
  780. disableStoryboard: Boolean(arr, iter),
  781. disableVideo: Boolean(arr, iter),
  782. visualOverride: Boolean(arr, iter),
  783. uselessShort: (iter.osuVersion < 20140609) ? Short(arr, iter) : undefined,
  784. lastModified2: Int(arr, iter),
  785. scrollSpeedMania: Byte(arr, iter),
  786. };
  787. };
  788. class _ProgressBar{
  789. barEle = null;
  790. Show(){
  791. if(this.barEle) { this.barEle.style.setProperty("opacity", "1"); return; }
  792. 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;"});
  793. document.body.insertAdjacentElement("beforebegin", this.barEle);
  794. }
  795. Progress(prog){
  796. if(this.barEle) this.barEle.style.setProperty("width", `${prog * 100}%`);
  797. if(prog >= 1) this.Hide();
  798. }
  799. Hide(){ this.barEle.style.setProperty("opacity", "0"); }
  800. };
  801. const ProgressBar = new _ProgressBar();
  802. const BeatmapArray = async (arr, iter) => {
  803. const t = 200;
  804. const r = new Array(Int(arr, iter));
  805. let l = performance.now();
  806. for(let i = 0; i < r.length; i++){
  807. r[i] = Beatmap(arr, iter);
  808. if(performance.now() - l > t){
  809. l = performance.now();
  810. ProgressBar.Progress((i + 1) / (r.length));
  811. await new Promise((res, rej) => setTimeout(() => res(), 0));
  812. }
  813. }
  814. return r;
  815. };
  816. const OsuDb = async (arr, iter) => {
  817. ProgressBar.Show();
  818. const r = {};
  819. r.version = Int(arr, iter);
  820. iter.osuVersion = r.version;
  821. r.folderCount = Int(arr, iter);
  822. r.accountUnlocked = Boolean(arr, iter);
  823. r.timeTillUnlock = DateTime(arr, iter);
  824. r.playerName = OString(arr, iter);
  825. r.beatmapArray = await BeatmapArray(arr, iter);
  826. r.permission = Int(arr, iter);
  827. ProgressBar.Hide();
  828. return r;
  829. };
  830. class ScoreDb{
  831. constructor(arr, iter){
  832.  
  833. }
  834. }
  835. const beatmapsets = new Set();
  836. const beatmaps = new Set();
  837. const bmsReg = /https:\/\/(?:osu|lazer)\.ppy\.sh\/beatmapsets\/([0-9]+)/;
  838. const bmsdlReg = /https:\/\/(?:osu|lazer)\.ppy\.sh\/beatmapsets\/([0-9]+)\/download/;
  839. const bmReg = /https:\/\/(?:osu|lazer)\.ppy\.sh\/beatmapsets\/(?:[0-9]+)#(?:mania|osu|fruits|taiko)\/([0-9]+)/;
  840. const BeatmapsetRefresh = () => {
  841. for(const bm of window.osudb.beatmapArray){
  842. beatmaps.add(bm.difficultyID);
  843. beatmapsets.add(bm.beatmapID);
  844. }
  845. OnMutation();
  846. };
  847. const NewOsuDb = async (r) => {
  848. const start = performance.now();
  849. const result = new Uint8Array(r.result);
  850. const length = result.length;
  851. console.log(`start reading osu!.db(${length} Bytes).`);
  852. const iter = {
  853. nxtpos: 0,
  854. };
  855. window.osudb = await OsuDb(result, iter);
  856. if(iter.nxtpos !== length) ShowPopup(i18n("There are still remaining unread bytes, something may be wrong."), "danger");
  857. ShowPopup(i18n("Finished reading osu!.db in %{time} ms.", {time: performance.now() - start}));
  858. };
  859. let ReadOsuDbWorking = false;
  860. const ReadOsuDb = async (file) => {
  861. if(ReadOsuDbWorking){
  862. ShowPopup(i18n("Script is already busy reading a osu!.db file."), "warning");
  863. return;
  864. }
  865. ReadOsuDbWorking = true;
  866. if(file.name !== "osu!.db"){ console.assert( false, "filename should be 'osu!.db'."); return; }
  867. const r = new FileReader();
  868. r.onload = async () => {
  869. await NewOsuDb(r);
  870. BeatmapsetRefresh();
  871. ReadOsuDbWorking = false;
  872. };
  873. r.onerror = () => console.assert(false, "error occurred while reading file.");
  874. r.readAsArrayBuffer(file);
  875. };
  876. const SelectOsuDb = (event) => {
  877. const t = event.target;
  878. const l = t.files;
  879. console.assert(l && l.length === 1, "No file or multiple files are selected.");
  880. ReadOsuDb(l[0]);
  881. };
  882. const CheckForUpdate = () => {
  883. const verReg = /<dd class="script-show-version"><span>([0-9\.]+)<\/span><\/dd>/;
  884. fetch("https://greasyfork.org/en/scripts/475417-osu-web-enhancement", {
  885. credentials: "omit"
  886. }).then(response => response.text()).then((html) => {
  887. const ver = verReg.exec(html);
  888. if(ver){
  889. const result = (() => {
  890. const verList = ver[1].split(".");
  891. const thisVer = GM_info.script.version;
  892. console.log(`latest version is: ${ver[1]}, current version is: ${thisVer}`);
  893. const thisVerList = thisVer.split(".");
  894. for(let i = 0; i < verList.length; i++){
  895. if(Number(verList[i]) > Number(thisVerList[i] ?? 0)) return true;
  896. else if(Number(verList[i]) < Number(thisVerList[i] ?? 0)) return false;
  897. }
  898. return false;
  899. })();
  900. if(result){
  901. const a = HTML("a", {href: "https://greasyfork.org/scripts/475417-osu-web-enhancement/code/osu!web%20enhancement.user.js", download: "", style: "display:none;"});
  902. a.click();
  903. }
  904. else{
  905. ShowPopup(i18n("The latest version is already installed!"))
  906. }
  907. }
  908. });
  909. };
  910. const AddMenu = () => {
  911. const menuId = "osu-web-enhancement-toolbar";
  912. if(!window.menuEventListener){
  913. window.addEventListener("click", (ev) => {
  914. const fid = ev.target?.dataset?.functionId;
  915. if(fid) switch(fid){
  916. case "import-osu-db-button": document.getElementById("osu-db-input")?.click(); break;
  917. case "check-for-update-button": CheckForUpdate(); break;
  918. case "pp-gini-index-calculator": PPGiniIndex(); break;
  919. }
  920. });
  921. window.menuEventListener = true;
  922. }
  923. if(document.getElementById(menuId)) return;
  924. const anc = document.querySelector("div.nav2__col.nav2__col--menu.js-react--quick-search-button");
  925. const i = HTML("input", {type: "file", id: "osu-db-input", accept: ".db", eventListener: [{
  926. type: "change",
  927. listener: SelectOsuDb,
  928. options: false,
  929. }]});
  930. const menuClass = "simple-menu simple-menu--nav2 simple-menu--nav2-left-aligned simple-menu--nav2-transparent js-menu";
  931. const menuItemClass = "simple-menu__item u-section-community--before-bg-normal";
  932. const menuTgtId = "osu-web-enhancement";
  933. anc.insertAdjacentElement("beforebegin",
  934. HTML("div", {class: "nav2__col nav2__col--menu", id: menuId},
  935. 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;"},
  936. HTML("span", {style: "flex-grow: 1;"}),
  937. HTML("span", {style: "font-size: 10px;"}, HTML("osu!web")),
  938. HTML("span", {style: "font-size: 10px;"}, HTML("enhancement")),
  939. HTML("span", {style: "flex-grow: 1;"}),
  940. ),
  941. HTML("div", {class: "nav2__menu-popup"},
  942. HTML("div", {class: `${menuClass}`, "data-menu-id": `nav2-menu-popup-${menuTgtId}`, "data-visibility": "hidden"},
  943. HTML("div", {class: `${menuItemClass}`, style: "cursor: pointer;", "data-function-id": "import-osu-db-button", }, HTML(i18n("Import osu!.db"))),
  944. HTML("div", {class: `${menuItemClass}`, style: "cursor: pointer;", "data-function-id": "check-for-update-button"}, HTML(i18n("Check for update"))),
  945. HTML("div", {class: `${menuItemClass}`, style: "cursor: pointer;", "data-function-id": "pp-gini-index-calculator"}, HTML(i18n("Calculate pp Gini index"))),
  946. 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")))
  947. ),
  948. )
  949. )
  950. );
  951. const mobMenuItmCls = "navbar-mobile-item__submenu-item js-click-menu--close";
  952. const mob = document.querySelector(`div.mobile-menu__item.js-click-menu[data-click-menu-id="mobile-nav"]`);
  953. mob.insertAdjacentElement("beforeend",
  954. HTML("div", {class: "navbar-mobile-item"},
  955. HTML("div", {class: "navbar-mobile-item__main js-click-menu", "data-click-menu-target": `nav-mobile-${menuTgtId}`, style: "cursor: pointer;"},
  956. HTML("span", {class: "navbar-mobile-item__icon navbar-mobile-item__icon--closed"},
  957. HTML("i", {class: "fas fa-chevron-right"})
  958. ),
  959. HTML("span", {class: "navbar-mobile-item__icon navbar-mobile-item__icon--opened"},
  960. HTML("i", {class: "fas fa-chevron-down"})
  961. ),
  962. HTML("osu!web enhancement"),
  963. ),
  964. HTML("ul", {class: "navbar-mobile-item__submenu js-click-menu", "data-click-menu-id": `nav-mobile-${menuTgtId}`, "data-visibility": "hidden"},
  965. HTML("li", {}, HTML("div", {class: mobMenuItmCls, style: "cursor: pointer;", "data-function-id": "import-osu-db-button",}, HTML(i18n("Import osu!.db")))),
  966. HTML("li", {}, HTML("div", {class: mobMenuItmCls, style: "cursor: pointer;", "data-function-id": "check-for-update-button"}, HTML(i18n("Check for update")))),
  967. HTML("li", {}, HTML("div", {class: mobMenuItmCls, style: "cursor: pointer;", "data-function-id": "pp-gini-index-calculator"}, HTML(i18n("Calculate pp Gini index")))),
  968. 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")))
  969. )
  970. )
  971. );
  972. document.body.appendChild(i);
  973. };
  974. const FilterBeatmapSet = () => {
  975. document.querySelectorAll(".beatmapset-panel").forEach((item) => {
  976. const bmsID = Number(bmsReg.exec(item.innerHTML)?.[1]);
  977. if(bmsID && beatmapsets.has(bmsID)){
  978. item.setAttribute("owned-beatmapset", "");
  979. }
  980. });
  981. document.querySelectorAll("div.bbcode a, a.osu-md__link").forEach(item => {
  982. if(item.classList.contains("owned-beatmap-link") || item.classList.contains("beatmap-download-link")) return;
  983. const e = bmsReg.exec(item.href);
  984. if(e && beatmapsets.has(Number(e[1]))){
  985. item.classList.add("owned-beatmap-link");
  986. if(item.nextElementSibling?.classList?.contains("beatmap-download-link")) item.nextElementSibling.remove();
  987. const box = item.getBoundingClientRect();
  988. const size = Math.round(box.height / 16 * 14);
  989. const vert = Math.round(size * 4 / 14) / 2;
  990. 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;`}));
  991. }else if(e && !item.nextElementSibling?.classList?.contains("beatmap-download-link")){
  992. item.after(
  993. HTML("a", {class: "beatmap-download-link", href: `https://osu.ppy.sh/beatmapsets/${e[1]}/download`, download: ""},
  994. HTML("span", {class: "fas fa-file-download", title: i18n("Download")})
  995. )
  996. );
  997. }
  998. });
  999. document.querySelectorAll("li.beatmap-pack-items__set").forEach(item => {
  1000. if(item.classList.contains("owned-beatmap-pack-item")) return;
  1001. const a = item.querySelector("a.beatmap-pack-items__link");
  1002. const e = bmsReg.exec(a.href);
  1003. if(e && beatmapsets.has(Number(e[1]))){
  1004. item.classList.add("owned-beatmap-pack-item");
  1005. const span = item.querySelector("span.fal");
  1006. span.setAttribute("title", i18n("Owned"));
  1007. span.dataset.origTitle = "owned";
  1008. span.setAttribute("class", "");
  1009. span.append(HTML("img", {src: svg_green_tick, alt: "owned beatmap", style: `width: 16px; height: 16px; vertical-align: -2px;`}));
  1010. const parent = item.querySelector(".beatmap-pack-item-download-link");
  1011. if(parent){
  1012. console.assert(parent.parentElement === item, "unexpected error occurred!");
  1013. item.insertBefore(span, parent);
  1014. parent.remove();
  1015. }
  1016. }else if(e){
  1017. const icon = item.querySelector(".beatmap-pack-items__icon");
  1018. icon.setAttribute("title", i18n("Download"));
  1019. icon.setAttribute("class", "fas fa-file-download beatmap-pack-items__icon");
  1020. if(icon.parentElement === item){
  1021. const dl = HTML("a", {class: "beatmap-pack-item-download-link", href: `https://osu.ppy.sh/beatmapsets/${e[1]}/download`, download: ""});
  1022. item.insertBefore(dl, icon);
  1023. dl.append(icon);
  1024. }
  1025. }
  1026. })
  1027. };
  1028. const AdjustStyle = (modestr, sectionName) => {
  1029. const styleSheetId = `userscript-generated-stylesheet-${sectionName}`;
  1030. let e = document.getElementById(styleSheetId);
  1031. if(!e){
  1032. e = document.createElement("style");
  1033. e.id = styleSheetId;
  1034. document.head.appendChild(e);
  1035. }
  1036. const s = e.sheet;
  1037. while(s.cssRules.length) s.deleteRule(0);
  1038. const sectionSelector = `div.js-sortable--page[data-page-id="${sectionName}"]`;
  1039. let ll = [];
  1040. switch(modestr){
  1041. case "mania": ll = [".mania-300", ".mania-200", ".mania-100", ".mania-50", ".mania-miss"]; break;
  1042. case "fruits": ll = [".fruits-300", ".fruits-100", ".fruits-50-miss", ".fruits-miss"]; break;
  1043. case "taiko": ll = [".taiko-300", ".taiko-150", ".taiko-miss"]; break;
  1044. case "osu": ll = [".osu-300", ".osu-100", ".osu-50", ".osu-miss"]; break;
  1045. }
  1046. class FasterCalc{
  1047. _map = new Map();
  1048. Calculate = (ele) => {
  1049. const t = ele.textContent;
  1050. let w = 0, changed = false;
  1051. for(const c of t){
  1052. let wc = this._map.get(c);
  1053. if(!wc){
  1054. if(!changed) changed = ele.cloneNode(true);
  1055. ele.textContent = c;
  1056. wc = ele.clientWidth;
  1057. this._map.set(c, wc);
  1058. }
  1059. w += wc;
  1060. }
  1061. if(changed){
  1062. ele.insertAdjacentElement("afterend", changed);
  1063. ele.remove();
  1064. }
  1065. return w;
  1066. };
  1067. };
  1068. let fc = new FasterCalc();
  1069. ll.forEach((str) =>
  1070. s.insertRule(
  1071. `${sectionSelector} ${str} + .score-detail-data-text {
  1072. 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;
  1073. }` ,0
  1074. )
  1075. );
  1076. fc = new FasterCalc();
  1077. [".play-detail__combo", ".play-detail__Accuracy", ".play-detail__Accuracy2"].forEach((str) =>
  1078. s.insertRule(
  1079. `${sectionSelector} ${str}{
  1080. min-width: ${Math.ceil([...document.querySelectorAll(`${sectionSelector} ${str}`)].reduce((max, ele) => {const w = fc.Calculate(ele); return w > max ? w : max;}, 0)) + 1}px;
  1081. }`
  1082. ,0
  1083. )
  1084. );
  1085. [".play-detail__pp"].forEach((str) =>
  1086. s.insertRule(
  1087. `${sectionSelector} ${str}{
  1088. min-width: ${Math.ceil([...document.querySelectorAll(`${sectionSelector} ${str}`)].reduce((max, ele) => {const w = ele.clientWidth; return w > max ? w : max;}, 0)) + 1}px;
  1089. }`
  1090. ,0
  1091. )
  1092. );
  1093. };
  1094. const PPGiniIndex = () => {
  1095. 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`)]
  1096. .map((ele) => {const ppele = ele.querySelector("div.play-detail__pp span"); return Number((ppele.title ? ppele.title : ppele.dataset.origTitle).replaceAll(",", ""))})
  1097. .sort((a, b) => b - a);
  1098. if(vals.length === 0) {
  1099. ShowPopup(i18n("Could not find best play data"), "danger");
  1100. return;
  1101. }
  1102. const min = vals[vals.length - 1];
  1103. let _ = 0; for(let i = vals.length - 1; i >= 0; i--) {
  1104. _ += vals[i] - min;
  1105. vals[i] = _;
  1106. }
  1107. const SB = vals.reduce((sum, val) => sum + val, -(vals[0] / 2));
  1108. const SAB = vals[0] / 2 * vals.length;
  1109. ShowPopup(i18n("Your pp Gini index of bp%{bp} is %{val}.", {bp: vals.length, val: (1 - SB/SAB).toPrecision(6)}));
  1110. }
  1111. const TopRanksWorker = (userId, modestr, addedNodes = [document.body]) => {
  1112. const isLazer = window.location.hostname.split(".")[0] === "lazer"; // assume that hostname can only be osu.ppy.sh or lazer.ppy.sh
  1113. const subdomain = isLazer ? "lazer": "osu";
  1114. const sectionNames = new Set();
  1115. const GetSection = (ele) => {
  1116. let count = 0;
  1117. while(ele){
  1118. if(ele.tagName === "DIV" && ele.className === "js-sortable--page") return ele.dataset.pageId;
  1119. ele = ele.parentElement;
  1120. count++;
  1121. if(count > 50) console.log(ele);
  1122. }
  1123. };
  1124. addedNodes.forEach((eles) => {
  1125. if(eles instanceof Element) eles.querySelectorAll(":scope div.play-detail.play-detail--highlightable").forEach((ele) => {
  1126. if(ele.getAttribute("improved") !== null) return;
  1127. const a = ele.querySelector(":scope time.js-timeago");
  1128. const t = a.getAttribute("datetime");
  1129. const data = messageCache.get(`${userId},${modestr},${subdomain},${t}`);
  1130. if(data){
  1131. sectionNames.add(GetSection(ele));
  1132. ListItemWorker(ele, data, isLazer);
  1133. }
  1134. });
  1135. });
  1136. sectionNames.forEach(sectionName => AdjustStyle(modestr, sectionName));
  1137. };
  1138. 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']) => {
  1139. const len = stops.length;
  1140. diff = Math.min(Math.max(diff, stops[0]), stops[len - 1]);
  1141. let r = stops.findIndex(stop => stop > diff);
  1142. if(r === -1) r = len - 1;
  1143. const d = stops[r] - stops[r - 1];
  1144. return `#${[[1, 3], [3, 5], [5, 7]]
  1145. .map(_ => [Number.parseInt(vals[r].slice(..._), 16), Number.parseInt(vals[r-1].slice(..._), 16)])
  1146. .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"))
  1147. .join("")
  1148. }`;
  1149. };
  1150. const CustomToPrecision = (number, precision) => {
  1151. return number >= 1 ? number.toPrecision(precision) : (number < (10 ** (-precision + 1) / 2) ? 0 : number.toFixed(precision - 1));
  1152. }
  1153. const ListItemWorker = (ele, data, isLazer) => {
  1154. if(ele.getAttribute("improved") !== null) return;
  1155. ele.setAttribute("improved", "");
  1156. ele.setAttribute("data-replay-id", data.id);
  1157. if(data.pp){
  1158. data.pp = Number(data.pp);
  1159. const pptext = ele.querySelector(".play-detail__pp > span").childNodes[0];
  1160. pptext.nodeValue = CustomToPrecision(data.pp, 5);
  1161. if(data.weight) pptext.title = i18n("%{pc} of total pp", {pc: CustomToPrecision(data.weight.pp, 5)});
  1162. }
  1163. const left = ele.querySelector("div.play-detail__group.play-detail__group--top");
  1164. 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);`});
  1165. left.insertAdjacentElement("beforebegin", leftc);
  1166. const detail = ele.querySelector("div.play-detail__score-detail-top-right");
  1167. const du = detail.children[0];
  1168. if(!detail.children[1]) detail.append(HTML("div", {classList: "play-detail__pp-weight"}));
  1169. const db = detail.children[1];
  1170. data.statistics.perfect ??= 0, data.statistics.great ??= 0, data.statistics.good ??= 0, data.statistics.ok ??= 0, data.statistics.meh ??= 0, data.statistics.miss ??= 0;
  1171. const bmName = ele.querySelector("span.play-detail__beatmap");
  1172. const sr = HTML("div", {class: `difficulty-badge ${data.beatmap.difficulty_rating >= 6.5 ? "difficulty-badge--expert-plus" : ""}`, style: `--bg: ${DiffToColour(data.beatmap.difficulty_rating)}`},
  1173. HTML("span", {class: "difficulty-badge__icon"}, HTML("span", {class: "fas fa-star"})),
  1174. HTML("span", {class: "difficulty-badge__rating"}, HTML(`${data.beatmap.difficulty_rating.toFixed(2)}`))
  1175. );
  1176. /*
  1177. const ic = ele;
  1178. ic.classList.add("audio-player", "js-audio--player");
  1179. ic.setAttribute("data-audio-url", `https://b.ppy.sh/preview/${data.beatmap.beatmapset_id}.mp3`)
  1180. ic.setAttribute("data-audio-state", "paused");
  1181. const gr = ele;
  1182. gr.classList.add("audio-player__button", "audio-player__button--play", "js-audio--play");
  1183. */
  1184. bmName.parentElement.insertBefore(sr, bmName);
  1185. const bma = ele.querySelector("a.play-detail__title");
  1186. // const modeName = ["STD", "TAIKO", "CTB", "MANIA"];
  1187. bma.onclick = (e) => {e.stopPropagation();};
  1188. switch(data.ruleset_id){
  1189. case 0:{
  1190. du.replaceChildren(
  1191. HTML("span", {class: "play-detail__before"}),
  1192. HTML("span", {class: "play-detail__Accuracy", title: i18n(`${isLazer ? "Lazer" : "V1"} Accuracy`)}, HTML(`${(data.accuracy * 100).toFixed(2)}%`)),
  1193. HTML("span", {class: "play-detail__combo", title: i18n(`Combo${isLazer ? "/Max Combo" : ""}`)},
  1194. 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}`)),
  1195. isLazer ? HTML("/") : null,
  1196. isLazer ? HTML("span", {class: "max-combo"}, HTML(`${(data.maximum_statistics.great ?? 0) + (data.maximum_statistics.legacy_combo_increase ?? 0)}`)) : null,
  1197. HTML("x"),
  1198. ),
  1199. );
  1200. const m_300 = HTML("span", {class: "score-detail score-detail-osu-300"},
  1201. HTML("span", {class: "osu-300"},
  1202. HTML("300")
  1203. ),
  1204. HTML("span", {class: "score-detail-data-text"},
  1205. HTML(`${data.statistics.great + data.statistics.perfect}`)
  1206. )
  1207. );
  1208. const s100 = HTML("span", {class: "score-detail score-detail-osu-100"},
  1209. HTML("span", {class: "osu-100"},
  1210. HTML("100")
  1211. ),
  1212. HTML("span", {class: "score-detail-data-text"},
  1213. HTML(`${data.statistics.ok + data.statistics.good}`)
  1214. )
  1215. );
  1216. const s50 = HTML("span", {class: "score-detail score-detail-osu-50"},
  1217. HTML("span", {class: "osu-50"},
  1218. HTML("50")
  1219. ),
  1220. HTML("span", {class: "score-detail-data-text"},
  1221. HTML(`${data.statistics.meh}`)
  1222. )
  1223. );
  1224. const s0 = HTML("span", {class: "score-detail score-detail-osu-miss"},
  1225. HTML("span", {class: "osu-miss"},
  1226. HTML("img", {src: svg_osu_miss, alt: "miss"})
  1227. ),
  1228. HTML("span", {class: "score-detail-data-text"},
  1229. HTML(`${data.statistics.miss}`)
  1230. )
  1231. );
  1232. db.replaceChildren(m_300, s100, s50, s0);
  1233. break;
  1234. }
  1235. case 1:{
  1236. const cur = [data.statistics.great ?? 0, data.statistics.ok ?? 0, data.statistics.miss ?? 0];
  1237. const mx = cur[0] + cur[1] + cur[2];
  1238. du.replaceChildren(
  1239. HTML("span", {class: "play-detail__before"}),
  1240. HTML("span", {class: "play-detail__Accuracy", title: i18n(`${isLazer ? "Lazer" : "V1"} Accuracy`)}, HTML(`${(data.accuracy * 100).toFixed(2)}%`)),
  1241. HTML("span", {class: "play-detail__combo", title: i18n(`Combo/Max Combo`)},
  1242. HTML("span", {class: `combo ${(data.max_combo === mx ? "legacy-perfect-combo" : "")}`}, HTML(`${data.max_combo}`)),
  1243. HTML("/"),
  1244. HTML("span", {class: "max-combo"}, HTML(`${mx}`)),
  1245. HTML("x"),
  1246. ),
  1247. );
  1248. db.replaceChildren(
  1249. HTML("span", {class: "score-detail score-detail-taiko-300"},
  1250. HTML("span", {class: "taiko-300"}, HTML("300")),
  1251. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.great ?? 0))
  1252. ),
  1253. HTML("span", {class: "score-detail score-detail-taiko-150"},
  1254. HTML("span", {class: "taiko-150"}, HTML("150")),
  1255. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.ok ?? 0))
  1256. ),
  1257. HTML("span", {class: "score-detail score-detail-fruits-combo"},
  1258. HTML("span", {class: "taiko-miss"}, HTML("miss")),
  1259. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.miss ?? 0))
  1260. ),
  1261. );
  1262. break;
  1263. }
  1264. case 2:{
  1265. if (isLazer) {
  1266. const cur = [data.statistics.great ?? 0, data.statistics.large_tick_hit ?? 0, data.statistics.small_tick_hit ?? 0];
  1267. const mx = [data.maximum_statistics.great ?? 0, data.maximum_statistics.large_tick_hit ?? 0, data.maximum_statistics.small_tick_hit ?? 0];
  1268. du.replaceChildren(
  1269. HTML("span", {class: "play-detail__before"}),
  1270. HTML("span", {class: "play-detail__Accuracy", title: i18n(`Lazer Accuracy`)}, HTML(`${(data.accuracy * 100).toFixed(2)}%`)),
  1271. HTML("span", {class: "play-detail__combo", title: i18n(`Combo/Max Combo`)},
  1272. HTML("span", {class: `combo ${(data.max_combo === mx[0] + mx[1] ? "legacy-perfect-combo" : "")}`}, HTML(`${data.max_combo}`)),
  1273. HTML("/"),
  1274. HTML("span", {class: "max-combo"}, HTML(`${mx[0] + mx[1]}`)),
  1275. HTML("x"),
  1276. ),
  1277. );
  1278. db.replaceChildren(
  1279. HTML("span", {class: "score-detail score-detail-fruits-300"},
  1280. HTML("span", {class: "fruits-300"}, HTML("fruits")),
  1281. HTML("span", {class: "score-detail-data-text"}, HTML(cur[0] + "/" + mx[0]))
  1282. ),
  1283. HTML("span", {class: "score-detail score-detail-fruits-100"},
  1284. HTML("span", {class: "fruits-100"}, HTML("ticks")),
  1285. HTML("span", {class: "score-detail-data-text"}, HTML(cur[1] + "/" + mx[1]))
  1286. ),
  1287. HTML("span", {class: "score-detail score-detail-fruits-50-miss"},
  1288. HTML("span", {class: "fruits-50-miss"}, HTML("drops")),
  1289. HTML("span", {class: "score-detail-data-text"}, HTML(cur[2] + "/" + mx[2]))
  1290. )
  1291. );
  1292. } else {
  1293. du.replaceChildren(
  1294. HTML("span", {class: "play-detail__before"}),
  1295. HTML("span", {class: "play-detail__Accuracy", title: i18n(`V1 Accuracy`)}, HTML(`${(data.accuracy * 100).toFixed(2)}%`)),
  1296. HTML("span", {class: "play-detail__combo", title: i18n(`Combo`)},
  1297. HTML("span", {class: ""}, HTML(`${data.max_combo}`)),
  1298. HTML("x")
  1299. ),
  1300. );
  1301. db.replaceChildren(
  1302. HTML("span", {class: "score-detail score-detail-fruits-300"},
  1303. HTML("span", {class: "fruits-300"}, HTML("FRUIT")),
  1304. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.great ?? 0))
  1305. ),
  1306. HTML("span", {class: "score-detail score-detail-fruits-100"},
  1307. HTML("span", {class: "fruits-100"}, HTML("tick")),
  1308. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.large_tick_hit ?? 0))
  1309. ),
  1310. HTML("span", {class: "score-detail score-detail-fruits-50-miss"},
  1311. HTML("span", {class: "fruits-50-miss"}, HTML("miss")),
  1312. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.small_tick_miss ?? 0))
  1313. ),
  1314. HTML("span", {class: "score-detail score-detail-fruits-miss"},
  1315. HTML("span", {class: "fruits-miss"}, HTML("MISS")),
  1316. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.miss ?? 0))
  1317. )
  1318. );
  1319. }
  1320. break;
  1321. }
  1322. case 3:{
  1323. 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));
  1324. const MCombo = (data.maximum_statistics.perfect ?? 0) + (data.maximum_statistics.legacy_combo_increase ?? 0);
  1325. const isMCombo = isLazer ? data.max_combo >= MCombo : data.legacy_perfect;
  1326. du.replaceChildren(
  1327. HTML("span", {class: "play-detail__before"}),
  1328. HTML("span", {class: "play-detail__Accuracy2", title: i18n(`pp Accuracy`)}, HTML(`${(v2acc * 100).toFixed(2)}%`)),
  1329. HTML("span", {class: "play-detail__Accuracy", title: i18n(`${isLazer ? "Lazer" : "V1"} Accuracy`)}, HTML(`${(data.accuracy * 100).toFixed(2)}%`)),
  1330. HTML("span", {class: "play-detail__combo", title: i18n(`Combo${isLazer ? "/Max Combo" : ""}`)},
  1331. HTML("span", {class: `combo ${isMCombo ? "legacy-perfect-combo" : ""}`}, HTML(`${data.max_combo}`)),
  1332. isLazer ? HTML("/") : null,
  1333. isLazer ? HTML("span", {class: "max-combo"}, HTML(MCombo)) : null,
  1334. HTML("x"),
  1335. ),
  1336. );
  1337. if(data.pp){
  1338. const lostpp = CustomToPrecision(data.pp * (0.2 / (Math.min(Math.max(v2acc, 0.8), 1) - 0.8) - 1), 4);
  1339. ele.querySelector(".play-detail__pp").appendChild(HTML("span", {class: "lost-pp"}, HTML(lostpp === 0 ? "MAX" : `-${lostpp}`)));
  1340. }
  1341. const M_300 = Number(data.statistics.perfect) / Math.max(Number(data.statistics.great), 1);
  1342. db.replaceChildren(
  1343. HTML("span", {class: "score-detail score-detail-mania-max-300", title: i18n("MAX: %{perfect}, 300: %{great}", data.statistics)},
  1344. HTML("span", {class: "mania-max"}, HTML("M")),
  1345. HTML("/"),
  1346. HTML("span", {class: "mania-300"}, HTML("300")),
  1347. 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))}`))
  1348. ),
  1349. HTML("span", {class: "score-detail score-detail-mania-max-200"},
  1350. HTML("span", {class: "mania-200"}, HTML("200")),
  1351. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.good))
  1352. ),
  1353. HTML("span", {class: "score-detail score-detail-mania-max-100"},
  1354. HTML("span", {class: "mania-100"}, HTML("100")),
  1355. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.ok))
  1356. ),
  1357. HTML("span", {class: "score-detail score-detail-mania-max-50"},
  1358. HTML("span", {class: "mania-50"}, HTML("50")),
  1359. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.meh))
  1360. ),
  1361. HTML("span", {class: "score-detail score-detail-mania-max-0"},
  1362. HTML("span", {class: "mania-miss"}, HTML("miss")),
  1363. HTML("span", {class: "score-detail-data-text"}, HTML(data.statistics.miss))
  1364. )
  1365. );
  1366. break;
  1367. }
  1368. default:;
  1369. }
  1370. }
  1371. let lastInitData = null;
  1372. const OsuLevelToExp = (n) => {
  1373. if(n <= 100) return 5000 / 3 * (4 * n ** 3 - 3 * n ** 2 - n) + 1.25 * 1.8 ** (n - 60);
  1374. else return 26_931_190_827 + 99_999_999_999 * (n - 100);
  1375. }
  1376. const OsuExpValToStr = (num) => {
  1377. const exp = Math.log10(num);
  1378. if(exp >= 12){
  1379. return `${(num / 10 ** 12).toPrecision(4)}T`;
  1380. }
  1381. else if(exp >= 9){
  1382. return `${(num / 10 ** 9).toPrecision(4)}B`;
  1383. }
  1384. else if(exp >= 6){
  1385. return `${(num / 10 ** 6).toPrecision(4)}M`;
  1386. }
  1387. else if(exp >= 4){
  1388. return `${(num / 10 ** 3).toPrecision(4)}K`;
  1389. }
  1390. else return `${num}`;
  1391. }
  1392. const messageCache = new Map();
  1393. window.messageCache = messageCache;
  1394. const profUrlReg = /https:\/\/(?:osu|lazer)\.ppy\.sh\/users\/[0-9]+(?:|\/osu|\/taiko|\/fruits|\/mania)/;
  1395. const AddBPAnalyzeSection = () => {
  1396. if(document.getElementById("bp-analyze-section")) return;
  1397. const h3 = document.querySelector('div.js-sortable--page[data-page-id="top_ranks"] h3.title.title--page-extra-small:nth-child(3)');
  1398. if(!h3) return;
  1399. h3.insertAdjacentElement("beforeend",
  1400. HTML("span", {class: "title__count", id: "bp-analyze-section"}, i18n("Show bp analytic"))
  1401. );
  1402. };
  1403. const ImproveProfile = (mulist) => {
  1404. const wloc = window.location.toString();
  1405. if(!profUrlReg.test(wloc)) return;
  1406. //AddBPAnalyzeSection();
  1407. const initDataEle = document.querySelector(".js-react--profile-page.osu-layout.osu-layout--full");
  1408. if(!initDataEle) return;
  1409. const initData = JSON.parse(initDataEle.dataset.initialData);
  1410. const userId = initData.user.id, modestr = initData.current_mode;
  1411. if(initData !== lastInitData){
  1412. let ppDiv = null;
  1413. document.querySelectorAll("div.value-display.value-display--plain").forEach((ele) => {
  1414. if(ele.querySelector("div.value-display__label").textContent === "pp") ppDiv = ele;
  1415. });
  1416. if(ppDiv){
  1417. const ttscore = initData.user.statistics.total_score;
  1418. const lvl = initData.user.statistics.level.current;
  1419. const upgradescore = Math.round(OsuLevelToExp(lvl + 1) - OsuLevelToExp(lvl));
  1420. const lvlscore = ttscore - Math.round(OsuLevelToExp(lvl));
  1421. lastInitData = initData;
  1422. document.querySelector("div.bar__text").textContent = `${OsuExpValToStr(lvlscore)}/${OsuExpValToStr(upgradescore)} (${(lvlscore/upgradescore * 100).toPrecision(3)}%)`;
  1423. const _pp = initData.user.statistics.pp;
  1424. ppDiv.querySelector(".value-display__value > div").textContent = _pp >= 1 ? _pp.toPrecision(6) : (_pp < 0.000005 ? 0 : _pp.toFixed(5));
  1425. }
  1426. }
  1427. if(mulist !== undefined) mulist.forEach((record) => {
  1428. if(record.type === "childList" && record.addedNodes) TopRanksWorker(userId, modestr, record.addedNodes);
  1429. });
  1430. }
  1431. let wloc = "";
  1432. const WindowLocationChanged = () => {
  1433. if(window.location !== wloc){
  1434. wloc = window.location;
  1435. return true;
  1436. }
  1437. else return false;
  1438. }
  1439. const InsertStyleSheet = () => {
  1440. //const sheetId = "osu-web-enhancement-general-stylesheet";
  1441. const s = new CSSStyleSheet();
  1442. s.replaceSync(inj_style);
  1443. document.adoptedStyleSheets = [...document.adoptedStyleSheets, s];
  1444. }
  1445. const OnBeatmapsetDownload = (message) => {
  1446. beatmapsets.add(message.beatmapsetId);
  1447. }
  1448. const ImproveBeatmapPlaycountItems = () => {
  1449. for(const item of [...document.querySelectorAll("div.beatmap-playcount")]){
  1450. if(item.getAttribute("improved") !== null) continue;
  1451. item.setAttribute("improved", "");
  1452. const a = item.querySelector("a");
  1453. const bms = bmsReg.exec(a.href);
  1454. if(!bms?.[1]) continue;
  1455. const d = item.querySelector("div.beatmap-playcount__detail");
  1456. const b = HTML("div", {class: "beatmap-playcount__background", style: `background-image: url(https://assets.ppy.sh/beatmaps/${bms[1]}/covers/card@2x.jpg)`});
  1457. if(d.childElementCount > 0) d.insertBefore(b, d.children[0]);
  1458. else d.append(b);
  1459. }
  1460. }
  1461. const CloseScoreCardPopup = () => {
  1462. document.querySelector("div.score-card-popup-window").remove();
  1463. }
  1464. const CopyToClipboard = (txt) => {
  1465. const t = document.createElement('textarea');
  1466. t.value = txt;
  1467. document.body.appendChild(t);
  1468. t.select();
  1469. document.execCommand('copy');
  1470. document.body.removeChild(t);
  1471. }
  1472. const ShowScoreCardPopup = () => {
  1473. const p = document.querySelector("div.js-portal");
  1474. if(!p) return;
  1475. document.body.append(
  1476. HTML("div", {class: "score-card-popup-window"},
  1477. HTML("div", {class: "score-card-popup-menu"},
  1478. HTML("button", {class: "score-card-close-button", eventListener: {type: "click", listener: CloseScoreCardPopup}}),
  1479. HTML("button", {class: "score-card-copy-to-clipboard-button", ev}),
  1480. ),
  1481. HTML("div", {class: "score-card"},
  1482. )
  1483. )
  1484. );
  1485. };
  1486. const MakeTextDetail = (data) => {
  1487. let detail = "";
  1488. const s = data.statistics; const m = data.maximum_statistics; const b = data.beatmap;
  1489. const secToMin = (t) => `${Math.floor(t/60)}:${String(t%60).padStart(2, '0')}`;
  1490. const isLazer = window.location.hostname.split(".")[0] === "lazer"; // assume that hostname can only be osu.ppy.sh or lazer.ppy.sh
  1491. switch(data.ruleset_id){
  1492. case 0: detail =
  1493. `${(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
  1494. ${b.count_circles ?? 0} 🌡️ ${b.count_sliders ?? 0} 🔄 ${b.count_spinners ?? 0}
  1495. `; break;
  1496. case 1: detail =
  1497. `${s.great ?? 0}-${s.ok ?? 0}-${s.miss ?? 0} ${data.max_combo ?? 0}/${(s.great ?? 0) + (s.ok ?? 0) + (s.miss ?? 0)}x
  1498. 🥁 ${b.count_circles ?? 0} 🌡️ ${b.count_sliders ?? 0} 🍥 ${b.count_spinners ?? 0}
  1499. `; break;
  1500. case 2: detail = isLazer ?
  1501. `${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
  1502. 🍎 ${b.count_circles ?? 0} 💧 ${b.count_sliders ?? 0} 🍌 ${b.count_spinners ?? 0}
  1503. ` :
  1504. `${s.great ?? 0}-${s.large_tick_hit ?? 0}-${s.small_tick_miss ?? 0}-${s.miss ?? 0} ${data.max_combo ?? 0}x
  1505. 🍎 ${b.count_circles ?? 0} 💧 ${b.count_sliders ?? 0} 🍌 ${b.count_spinners ?? 0}
  1506. `; break;
  1507. case 3: detail =
  1508. `${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
  1509. 🍚 ${b.count_circles ?? 0} 🍜 ${b.count_sliders ?? 0}
  1510. `; break;
  1511. default:;
  1512. }
  1513. const scrMsg =
  1514. `${data.beatmapset.title}
  1515. [${data.beatmap.version}] ${secToMin(data.beatmap.total_length)}
  1516. ${data.total_score} ${data.rank} ${data.pp ? (data.pp >= 1 ? data.pp.toPrecision(5) : (data.pp < 0.00005 ? 0 : data.pp.toFixed(4))) : "-"}pp
  1517. ${detail}
  1518. `;
  1519. return scrMsg;
  1520. }
  1521. const CopyDetailsPopup = () => {
  1522. const ele = document.querySelector("div.play-detail.play-detail--active"); if(!ele) return;
  1523. const id = ele.dataset.replayId;
  1524. const data = messageCache.get(Number(id)); if(!data) return;
  1525. const msg = MakeTextDetail(data);
  1526. console.log(msg);
  1527. CopyToClipboard(msg);
  1528. ShowPopup(i18n("Score details copied to clipboard!"));
  1529. };
  1530. const AddPopupButton = () => {
  1531. const p = document.querySelector("div.js-portal")?.querySelector("div.simple-menu");
  1532. if(!p || p.querySelector("button.score-card-popup-button")) return;
  1533. // p.append(HTML("button", {class: "score-card-popup-button simple-menu__item", type: "button", eventListener: [{type: "click", listener: ShowScoreCardPopup}]}, HTML("Popup")));
  1534. p.append(HTML("button", {class: "score-card-popup-button simple-menu__item", type: "button", eventListener: [{type: "click", listener: CopyDetailsPopup}]}, HTML(i18n("Copy Text Details"))));
  1535. };
  1536. const OnMutation = (mulist) => {
  1537. mut.disconnect();
  1538. AddMenu();
  1539. FilterBeatmapSet();
  1540. ImproveBeatmapPlaycountItems();
  1541. ImproveProfile(mulist);
  1542. AddPopupButton();
  1543. mut.observe(document, {childList: true, subtree: true});
  1544. };
  1545. const MessageFilter = (message) => {
  1546. const info = `${message.userId},${message.mode},${message.subdomain}`;
  1547. switch(message.type){
  1548. case "beatmapset_download_complete": OnBeatmapsetDownload(message); break;
  1549. case "top_ranks":
  1550. [message.data.pinned.items, message.data.best.items, message.data.firsts.items].forEach(items => items.forEach(item => {
  1551. messageCache.set(`${info},${item.ended_at}`, item);
  1552. messageCache.set(item.id, item);
  1553. }));
  1554. TopRanksWorker(message.userId, message.mode);
  1555. break;
  1556. case "firsts": case "pinned": case "best": case "recent":
  1557. message.data.forEach(item => { messageCache.set(`${info},${item.ended_at}`, item); messageCache.set(item.id, item); });
  1558. TopRanksWorker(message.userId, message.mode);
  1559. break;
  1560. case "historical":
  1561. message.data.recent.items.forEach(item => { messageCache.set(`${info},${item.ended_at}`, item); messageCache.set(item.id, item); });
  1562. TopRanksWorker(message.userId, message.mode);
  1563. break;
  1564. default:;
  1565. }
  1566. }
  1567. const WindowMessageFilter = (event) => {
  1568. if(event.source === window && event?.data?.id === "osu!web enhancement"){
  1569. MessageFilter(event.data);
  1570. }
  1571. }
  1572. const OnClick = (event) => {
  1573. let t = event.target;
  1574. while(t){
  1575. if(t.tagName === "A"){
  1576. const e = bmsdlReg.exec(t.href);
  1577. if(!e) continue;
  1578. beatmapsets.add(Number(e[1]));
  1579. FilterBeatmapSet();
  1580. break;
  1581. }
  1582. t = t.parentElement;
  1583. }
  1584. }
  1585. //document.addEventListener("click", OnClick);
  1586. const curLocale = window.currentLocale;
  1587. if (curLocale && locales[curLocale]) {
  1588. console.log("localization available");
  1589. i18n.translator.add(locales[curLocale]);
  1590. }
  1591. window.addEventListener("message", WindowMessageFilter);
  1592. const mut = new MutationObserver(OnMutation);
  1593. mut.observe(document, {childList: true, subtree: true});
  1594. InsertStyleSheet();
  1595. console.log("osu!web enhancement loaded");
  1596. // below are test code
  1597. /*
  1598. const osusrc = "https://i.ppy.sh/bde5906f8f985126f4ea624d3eb14c8702883aa2/68747470733a2f2f6f73752e7070792e73682f77696b692f696d616765732f536b696e6e696e672f496e746572666163652f696d672f6d6f64652d6f73752e706e67";
  1599. const taikosrc = "https://i.ppy.sh/c1a9502ea05c9fcde03a375ebf528a12ff30cae7/68747470733a2f2f6f73752e7070792e73682f77696b692f696d616765732f536b696e6e696e672f496e746572666163652f696d672f6d6f64652d7461696b6f2e706e67";
  1600. const fruitsrc = "https://i.ppy.sh/e7cad0470810a868df06d597e3441812659c0bfa/68747470733a2f2f6f73752e7070792e73682f77696b692f696d616765732f536b696e6e696e672f496e746572666163652f696d672f6d6f64652d6672756974732e706e67";
  1601. const maniasrc = "https://i.ppy.sh/55d9494fcf7c3ef2d614695a9a951977a21f23f6/68747470733a2f2f6f73752e7070792e73682f77696b692f696d616765732f536b696e6e696e672f496e746572666163652f696d672f6d6f64652d6d616e69612e706e67";
  1602. const pngsrc = [osusrc, taikosrc, fruitsrc, maniasrc];
  1603. const png = [null, null, null, null];
  1604. let canvas, ctx, cw, ch;
  1605. const ToggleSnow = async (modeid) => {
  1606. if(canvas) {canvas.remove(); return;}
  1607. canvas = HTML("canvas", {style: `position: fixed; bottom: 0px; left: 0px;`, width: window.innerWidth, height: window.innerHeight});
  1608. document.body.append(canvas);
  1609. ctx = canvas.getContext("webgl2");
  1610. if(!png[modeid]){
  1611. const response = await fetch(pngsrc[modeid]);
  1612. png[modeid] = await response.blob();
  1613. }
  1614. }
  1615. */