Greasyfork 快捷編輯收藏

在GF腳本頁直接編輯收藏集

  1. // ==UserScript==
  2. // @name Greasyfork script-set-edit button
  3. // @name:zh-CN Greasyfork 快捷编辑收藏
  4. // @name:zh-TW Greasyfork 快捷編輯收藏
  5. // @name:en Greasyfork script-set-edit button
  6. // @name:en-US Greasyfork script-set-edit button
  7. // @name:fr Greasyfork Set Edit+
  8. // @namespace Greasyfork-Favorite
  9. // @version 0.3.0
  10. // @description Add / Remove script into / from script set directly in GF script info page
  11. // @description:zh-CN 在GF脚本页直接编辑收藏集
  12. // @description:zh-TW 在GF腳本頁直接編輯收藏集
  13. // @description:en Add / Remove script into / from script set directly in GF script info page
  14. // @description:en-US Add / Remove script into / from script set directly in GF script info page
  15. // @description:fr Ajouter un script à un jeu de scripts / supprimer un script d'un jeu de scripts directement sur la page d'informations sur les scripts GF
  16. // @author PY-DNG
  17. // @license GPL-3.0-or-later
  18. // @match http*://*.gf.qytechs.cn/*
  19. // @match http*://*.sleazyfork.org/*
  20. // @match http*://*.gf.qytechs.cn/*
  21. // @require https://update.gf.qytechs.cn/scripts/456034/1532680/Basic%20Functions%20%28For%20userscripts%29.js
  22. // @require https://update.gf.qytechs.cn/scripts/449583/1324274/ConfigManager.js
  23. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAbBJREFUOE+Vk7GKGlEUhr8pAiKKDlqpCDpLUCzWBxCENBa+hBsL9wHsLWxXG4tNtcGH0MIiWopY7JSGEUWsbESwUDMw4Z7siLsZDbnlPff/7n/+e67G38sA6sAXIPVWXgA/gCdgfinRPuhfCoXCw3Q65XA4eLBl6zvw1S2eAZqmvTqOc5/NZhkMBqRSKWzbvgYxgbwquoAX4MGyLHK5HIlEgtFo9C+IOFEAo1gsWsvlUmyPx2MymYxAhsMh6XT6lpM7BXjWdf1xNpuRz+fl8GQywTAMGo0G1WpVnJxOJ692vinADPgcDAaZz+cCOR6PmKZJPB4XUb/fp1wuewF+KoBCf1JVBVE5dDodms3mWdDtdqlUKl6AX+8ALmS9XgtM0/5kvNlspKX9fv8RIgBp4bISCoXo9XqsVitKpRK6rrPb7STQ7XZ7eVRaeAYerz14OBxGOfL7/eIgmUwKzHEcJZEQ1eha1wBqPxqNihufzyeQWCzmtiPPqJYM0jWIyiISibBYLAgEAtTrdVqt1nmQXN0rcH/LicqmVqvRbrdN27bfjbKru+nk7ZD3Z7q4+b++82/YPKIrXsKZ3AAAAABJRU5ErkJggg==
  24. // @grant GM_setValue
  25. // @grant GM_getValue
  26. // @grant GM_listValues
  27. // @grant GM_deleteValue
  28. // @grant GM_registerMenuCommand
  29. // @grant GM_unregisterMenuCommand
  30. // ==/UserScript==
  31.  
  32. /* eslint-disable no-multi-spaces */
  33. /* eslint-disable no-return-assign */
  34.  
  35. /* global LogLevel DoLog Err $ $All $CrE $AEL $$CrE addStyle detectDom destroyEvent copyProp copyProps parseArgs escJsStr replaceText getUrlArgv dl_browser dl_GM AsyncManager queueTask FunctionLoader loadFuncs require isLoaded */
  36. /* global ConfigManager */
  37.  
  38. (function __MAIN__() {
  39. 'use strict';
  40.  
  41. const CONST = {
  42. Text: {
  43. 'zh-CN': {
  44. FavEdit: '收藏集:',
  45. Add: '加入此集',
  46. Remove: '移出此集',
  47. Edit: '手动编辑',
  48. EditIframe: '页内编辑',
  49. CloseIframe: '关闭编辑',
  50. CopySID: '复制脚本ID',
  51. Sync: '同步',
  52. NotLoggedIn: '请先登录(不可用)Greasyfork',
  53. NoSetsYet: '您还没有创建过收藏集',
  54. NewSet: '新建收藏集',
  55. sortByApiDefault: ['默认排序', '默认倒序'],
  56. Working: ['工作中...', '就快好了...'],
  57. InSetStatus: ['[ ]', '[✔]'],
  58. Groups: {
  59. Server: 'GreasyFork收藏集',
  60. Local: '本地收藏集',
  61. New: '新建'
  62. },
  63. Refreshing: {
  64. List: '获取收藏集列表...',
  65. Script: '获取收藏集内容...',
  66. Data: '获取收藏集数据...'
  67. },
  68. UseAPI: ['[ ] 使用GF的收藏集API', '[✔]使用GF的收藏集API'],
  69. Error: {
  70. AlreadyExist: '脚本已经在此收藏集中了',
  71. NotExist: '脚本不在此收藏集中',
  72. NetworkError: '网络错误',
  73. Unknown: '未知错误'
  74. }
  75. },
  76. 'zh-TW': {
  77. FavEdit: '收藏集:',
  78. Add: '加入此集',
  79. Remove: '移出此集',
  80. Edit: '手動編輯',
  81. EditIframe: '頁內編輯',
  82. CloseIframe: '關閉編輯',
  83. CopySID: '複製腳本ID',
  84. Sync: '同步',
  85. NotLoggedIn: '請先登錄Greasyfork',
  86. NoSetsYet: '您還沒有創建過收藏集',
  87. NewSet: '新建收藏集',
  88. sortByApiDefault: ['默認排序', '默認倒序'],
  89. Working: ['工作中...', '就快好了...'],
  90. InSetStatus: ['[ ]', '[✔]'],
  91. Groups: {
  92. Server: 'GreasyFork收藏集',
  93. Local: '本地收藏集',
  94. New: '新建'
  95. },
  96. Refreshing: {
  97. List: '獲取收藏集清單...',
  98. Script: '獲取收藏集內容...',
  99. Data: '獲取收藏集數據...'
  100. },
  101. UseAPI: ['[ ] 使用GF的收藏集API', '[✔]使用GF的收藏集API'],
  102. Error: {
  103. AlreadyExist: '腳本已經在此收藏集中了',
  104. NotExist: '腳本不在此收藏集中',
  105. NetworkError: '網絡錯誤',
  106. Unknown: '未知錯誤'
  107. }
  108. },
  109. 'en': {
  110. FavEdit: 'Script set: ',
  111. Add: 'Add',
  112. Remove: 'Remove',
  113. Edit: 'Edit Manually',
  114. EditIframe: 'In-Page Edit',
  115. CloseIframe: 'Close Editor',
  116. CopySID: 'Copy Script-ID',
  117. Sync: 'Sync',
  118. NotLoggedIn: 'Login to greasyfork to use script sets',
  119. NoSetsYet: 'You haven\'t created a collection yet',
  120. NewSet: 'Create a new set',
  121. sortByApiDefault: ['Default', 'Default reverse'],
  122. Working: ['Working...', 'Just a moment...'],
  123. InSetStatus: ['[ ]', '[✔]'],
  124. Groups: {
  125. Server: 'GreasyFork',
  126. Local: 'Local',
  127. New: 'New'
  128. },
  129. Refreshing: {
  130. List: 'Fetching script sets...',
  131. Script: 'Fetching set content...',
  132. Data: 'Fetching script sets data...'
  133. },
  134. UseAPI: ['[ ] Use GF API', '[✔] Use GF API'],
  135. Error: {
  136. AlreadyExist: 'Script is already in set',
  137. NotExist: 'Script is not in set yet',
  138. NetworkError: 'Network Error',
  139. Unknown: 'Unknown Error'
  140. }
  141. },
  142. 'default': {
  143. FavEdit: 'Script set: ',
  144. Add: 'Add',
  145. Remove: 'Remove',
  146. Edit: 'Edit Manually',
  147. EditIframe: 'In-Page Edit',
  148. CloseIframe: 'Close Editor',
  149. CopySID: 'Copy Script-ID',
  150. Sync: 'Sync',
  151. NotLoggedIn: 'Login to greasyfork to use script sets',
  152. NoSetsYet: 'You haven\'t created a collection yet',
  153. NewSet: 'Create a new set',
  154. sortByApiDefault: ['Default', 'Default reverse'],
  155. Working: ['Working...', 'Just a moment...'],
  156. InSetStatus: ['[ ]', '[✔]'],
  157. Groups: {
  158. Server: 'GreasyFork',
  159. Local: 'Local',
  160. New: 'New'
  161. },
  162. Refreshing: {
  163. List: 'Fetching script sets...',
  164. Script: 'Fetching set content...',
  165. Data: 'Fetching script sets data...'
  166. },
  167. UseAPI: ['[ ] Use GF API', '[✔] Use GF API'],
  168. Error: {
  169. AlreadyExist: 'Script is already in set',
  170. NotExist: 'Script is not in set yet',
  171. NetworkError: 'Network Error',
  172. Unknown: 'Unknown Error'
  173. }
  174. },
  175. },
  176. URL: {
  177. SetLink: `https://${location.host}/scripts?set=$ID`,
  178. SetEdit: `https://${location.host}/users/$UID/sets/$ID/edit`
  179. },
  180. ConfigRule: {
  181. 'version-key': 'config-version',
  182. ignores: ['useAPI'],
  183. defaultValues: {
  184. 'script-sets': {
  185. sets: [],
  186. time: 0,
  187. 'config-version': 2,
  188. },
  189. 'useAPI': true
  190. },
  191. 'updaters': {
  192. /*'config-key': [
  193. function() {
  194. // This function contains updater for config['config-key'] from v0 to v1
  195. },
  196. function() {
  197. // This function contains updater for config['config-key'] from v1 to v2
  198. }
  199. ]*/
  200. 'script-sets': [
  201. config => {
  202. // v0 ==> v1
  203. // Fill set.id
  204. const sets = config.sets;
  205. sets.forEach(set => {
  206. const id = getUrlArgv(set.link, 'set');
  207. set.id = id;
  208. set.scripts = null; // After first refresh, it should be an array of SIDs:string
  209. });
  210.  
  211. // Delete old version identifier
  212. delete config.version;
  213.  
  214. return config;
  215. },
  216. config => {
  217. // v1 ==> v2
  218. return config
  219. }
  220. ]
  221. },
  222. }
  223. };
  224.  
  225. // Get i18n code
  226. let i18n = $('#language-selector-locale') ? $('#language-selector-locale').value : navigator.language;
  227. if (!Object.keys(CONST.Text).includes(i18n)) {i18n = 'default';}
  228.  
  229. const CM = new ConfigManager(CONST.ConfigRule);
  230. const CONFIG = CM.Config;
  231. CM.updateAllConfigs();
  232. CM.setDefaults();
  233.  
  234. loadFuncs([{
  235. id: 'utils',
  236. func() {
  237. function makeBooleanSettings(settings) {
  238. for (const setting of settings) {
  239. makeBooleanMenu(setting.text, setting.key, setting.defaultValue, setting.callback, setting.initCallback);
  240. }
  241.  
  242. function makeBooleanMenu(texts, key, defaultValue=false, callback=null, initCallback=false) {
  243. const initialVal = GM_getValue(key, defaultValue);
  244. const initialText = texts[initialVal + 0];
  245. let id = makeMenu(initialText, onClick);
  246. initCallback && callback(key, initialVal);
  247.  
  248. function onClick() {
  249. const newValue = !GM_getValue(key, defaultValue);
  250. const newText = texts[newValue + 0];
  251. GM_setValue(key, newValue);
  252. id = makeMenu(newText, onClick, id);
  253. typeof callback === 'function' && callback(key, newValue);
  254. }
  255.  
  256. function makeMenu(text, func, id) {
  257. if (GM_info.scriptHandler === 'Tampermonkey' && GM_hasVersion('5.0')) {
  258. return GM_registerMenuCommand(text, func, {
  259. id,
  260. autoClose: false,
  261. });
  262. } else {
  263. GM_unregisterMenuCommand(id);
  264. return GM_registerMenuCommand(text, func);
  265. }
  266. }
  267. }
  268.  
  269. function GM_hasVersion(version) {
  270. return hasVersion(GM_info?.version || '0', version);
  271.  
  272. function hasVersion(ver1, ver2) {
  273. return compareVersions(ver1.toString(), ver2.toString()) >= 0;
  274.  
  275. // https://gf.qytechs.cn/app/javascript/versioncheck.js
  276. // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version/format
  277. function compareVersions(a, b) {
  278. if (a == b) {
  279. return 0;
  280. }
  281. let aParts = a.split('.');
  282. let bParts = b.split('.');
  283. for (let i = 0; i < aParts.length; i++) {
  284. let result = compareVersionPart(aParts[i], bParts[i]);
  285. if (result != 0) {
  286. return result;
  287. }
  288. }
  289. // If all of a's parts are the same as b's parts, but b has additional parts, b is greater.
  290. if (bParts.length > aParts.length) {
  291. return -1;
  292. }
  293. return 0;
  294. }
  295.  
  296. function compareVersionPart(partA, partB) {
  297. let partAParts = parseVersionPart(partA);
  298. let partBParts = parseVersionPart(partB);
  299. for (let i = 0; i < partAParts.length; i++) {
  300. // "A string-part that exists is always less than a string-part that doesn't exist"
  301. if (partAParts[i].length > 0 && partBParts[i].length == 0) {
  302. return -1;
  303. }
  304. if (partAParts[i].length == 0 && partBParts[i].length > 0) {
  305. return 1;
  306. }
  307. if (partAParts[i] > partBParts[i]) {
  308. return 1;
  309. }
  310. if (partAParts[i] < partBParts[i]) {
  311. return -1;
  312. }
  313. }
  314. return 0;
  315. }
  316.  
  317. // It goes number, string, number, string. If it doesn't exist, then
  318. // 0 for numbers, empty string for strings.
  319. function parseVersionPart(part) {
  320. if (!part) {
  321. return [0, "", 0, ""];
  322. }
  323. let partParts = /([0-9]*)([^0-9]*)([0-9]*)([^0-9]*)/.exec(part)
  324. return [
  325. partParts[1] ? parseInt(partParts[1]) : 0,
  326. partParts[2],
  327. partParts[3] ? parseInt(partParts[3]) : 0,
  328. partParts[4]
  329. ];
  330. }
  331. }
  332. }
  333. }
  334.  
  335. // Copy text to clipboard (needs to be called in an user event)
  336. function copyText(text) {
  337. // Create a new textarea for copying
  338. const newInput = document.createElement('textarea');
  339. document.body.appendChild(newInput);
  340. newInput.value = text;
  341. newInput.select();
  342. document.execCommand('copy');
  343. document.body.removeChild(newInput);
  344. }
  345.  
  346. return {
  347. makeBooleanSettings,
  348. copyText
  349. }
  350. }
  351. }, {
  352. id: 'api',
  353. func() {
  354. const API = {
  355. async getScriptSets() {
  356. const userpage = API.getUserpage();
  357. const oDom = await API.getDocument(userpage);
  358. const list = Array.from($(oDom, 'ul#user-script-sets').children);
  359. const NoSets = list.length === 1 && list.every(li => li.children.length === 1);
  360. const script_sets = NoSets ? [] : Array.from($(oDom, 'ul#user-script-sets').children).filter(li => li.children.length === 2).map(li => {
  361. try {
  362. return {
  363. name: li.children[0].innerText,
  364. link: li.children[0].href,
  365. linkedit: li.children[1].href,
  366. id: getUrlArgv(li.children[0].href, 'set')
  367. }
  368. } catch(err) {
  369. DoLog(LogLevel.Error, [li, err, li.children.length, li.children[0]?.innerHTML, li.children[1]?.innerHTML], 'error');
  370. Err(err);
  371. }
  372. });
  373. return script_sets;
  374. },
  375. async getSetScripts(url) {
  376. return [...$All(await API.getDocument(url), '#script-set-scripts>input[name="scripts-included[]"]')].map(input => input.value);
  377. },
  378. /**
  379. * @typedef {Object} SetsDataAPI
  380. * @property {Response} resp - api fetch response object
  381. * @property {boolean} ok - resp.ok (resp.status >= 200 && resp.status <= 299)
  382. * @property {(Object|null)} data - api response json data, or null if not resp.ok
  383. */
  384. /**
  385. * @returns {SetsDataAPI}
  386. */
  387. async getSetsData() {
  388. const userpage = API.getUserpage();
  389. const url = (userpage.endsWith('/') ? userpage : userpage + '/') + 'sets'
  390. const resp = await fetch(url, { credentials: 'same-origin' });
  391. if (resp.ok) {
  392. return {
  393. ok: true,
  394. resp,
  395. data: await resp.json()
  396. };
  397. } else {
  398. return {
  399. ok: false,
  400. resp,
  401. data: null
  402. };
  403. }
  404. },
  405. /**
  406. * @returns {(string|null)} the user's profile page url, from page top-right link <a>.href
  407. */
  408. getUserpage() {
  409. const a = $('#nav-user-info>.user-profile-link>a');
  410. return a ? a.href : null;
  411. },
  412. /**
  413. * @returns {(string|null)} the user's id, in string format
  414. */
  415. getUserID() {
  416. const userpage = API.getUserpage(); //https://gf.qytechs.cn/zh-CN/users/667968-pyudng
  417. return userpage ? userpage.match(/\/users\/(\d+)(-[^\/]*\/*)?/)[1] : null;
  418. },
  419. // editCallback recieves:
  420. // true: edit doc load success
  421. // false: already in set
  422. // finishCallback recieves:
  423. // text: successfully added to set with text tip `text`
  424. // true: successfully loaded document but no text tip found
  425. // false: xhr error
  426. addFav(url, sid, editCallback, finishCallback) {
  427. API.modifyFav(url, oDom => {
  428. const existingInput = [...$All(oDom, '#script-set-scripts>input[name="scripts-included[]"][type="hidden"]')].find(input => input.value === sid);
  429. if (existingInput) {
  430. editCallback(false);
  431. return false;
  432. }
  433. const input = $CrE('input');
  434. input.value = sid;
  435. input.name = 'scripts-included[]';
  436. input.type = 'hidden';
  437. $(oDom, '#script-set-scripts').appendChild(input);
  438. editCallback(true);
  439. }, oDom => {
  440. const status = $(oDom, 'p.notice');
  441. const status_text = status ? status.innerText : true;
  442. finishCallback(status_text);
  443. }, err => finishCallback(false));
  444. },
  445. // editCallback recieves:
  446. // true: edit doc load success
  447. // false: already not in set
  448. // finishCallback recieves:
  449. // text: successfully removed from set with text tip `text`
  450. // true: successfully loaded document but no text tip found
  451. // false: xhr error
  452. removeFav(url, sid, editCallback, finishCallback) {
  453. API.modifyFav(url, oDom => {
  454. const existingInput = [...$All(oDom, '#script-set-scripts>input[name="scripts-included[]"][type="hidden"]')].find(input => input.value === sid);
  455. if (!existingInput) {
  456. editCallback(false);
  457. return false;
  458. }
  459. existingInput.remove();
  460. editCallback(true);
  461. }, oDom => {
  462. const status = $(oDom, 'p.notice');
  463. const status_text = status ? status.innerText : true;
  464. finishCallback(status_text);
  465. }, err => finishCallback(false));
  466. },
  467. async modifyFav(url, editCallback, finishCallback, onerror) {
  468. const oDom = await API.getDocument(url);
  469. if (editCallback(oDom) === false) { return false; }
  470. const form = $(oDom, '.change-script-set');
  471. const data = new FormData(form);
  472. data.append('save', '1');
  473. // Use XMLHttpRequest insteadof GM_xmlhttpRequest because there's unknown issue with GM_xmlhttpRequest
  474. const xhr = new XMLHttpRequest();
  475. xhr.open('POST', API.toAbsoluteURL(form.getAttribute('action')));
  476. xhr.responseType = 'blob';
  477. xhr.onload = async e => finishCallback(await API.parseDocument(xhr.response));
  478. xhr.onerror = onerror;
  479. xhr.send(data);
  480. },
  481. // Download and parse a url page into a html document(dom).
  482. // Returns a promise fulfills with dom
  483. async getDocument(url, retry=5) {
  484. try {
  485. const response = await fetch(url, {
  486. method: 'GET',
  487. cache: 'reload',
  488. });
  489. if (response.status === 200) {
  490. const blob = await response.blob();
  491. const oDom = await API.parseDocument(blob);
  492. return oDom;
  493. } else {
  494. throw new Error(`response.status is not 200 (${response.status})`);
  495. }
  496. } catch(err) {
  497. if (--retry > 0) {
  498. return API.getDocument(url, retry);
  499. } else {
  500. throw err;
  501. }
  502. }
  503. },
  504. // Returns a promise fulfills with dom
  505. parseDocument(htmlblob) {
  506. return new Promise((resolve, reject) => {
  507. const reader = new FileReader();
  508. reader.onload = function(e) {
  509. const htmlText = reader.result;
  510. const dom = new DOMParser().parseFromString(htmlText, 'text/html');
  511. resolve(dom);
  512. }
  513. reader.onerror = err => reject(err);
  514. reader.readAsText(htmlblob, document.characterSet);
  515. });
  516. },
  517. toAbsoluteURL(relativeURL, base=`${location.protocol}//${location.host}/`) {
  518. return new URL(relativeURL, base).href;
  519. },
  520. GM_hasVersion(version) {
  521. return hasVersion(GM_info?.version || '0', version);
  522. function hasVersion(ver1, ver2) {
  523. return compareVersions(ver1.toString(), ver2.toString()) >= 0;
  524. // https://gf.qytechs.cn/app/javascript/versioncheck.js
  525. // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version/format
  526. function compareVersions(a, b) {
  527. if (a == b) {
  528. return 0;
  529. }
  530. let aParts = a.split('.');
  531. let bParts = b.split('.');
  532. for (let i = 0; i < aParts.length; i++) {
  533. let result = compareVersionPart(aParts[i], bParts[i]);
  534. if (result != 0) {
  535. return result;
  536. }
  537. }
  538. // If all of a's parts are the same as b's parts, but b has additional parts, b is greater.
  539. if (bParts.length > aParts.length) {
  540. return -1;
  541. }
  542. return 0;
  543. }
  544. function compareVersionPart(partA, partB) {
  545. let partAParts = parseVersionPart(partA);
  546. let partBParts = parseVersionPart(partB);
  547. for (let i = 0; i < partAParts.length; i++) {
  548. // "A string-part that exists is always less than a string-part that doesn't exist"
  549. if (partAParts[i].length > 0 && partBParts[i].length == 0) {
  550. return -1;
  551. }
  552. if (partAParts[i].length == 0 && partBParts[i].length > 0) {
  553. return 1;
  554. }
  555. if (partAParts[i] > partBParts[i]) {
  556. return 1;
  557. }
  558. if (partAParts[i] < partBParts[i]) {
  559. return -1;
  560. }
  561. }
  562. return 0;
  563. }
  564. // It goes number, string, number, string. If it doesn't exist, then
  565. // 0 for numbers, empty string for strings.
  566. function parseVersionPart(part) {
  567. if (!part) {
  568. return [0, "", 0, ""];
  569. }
  570. let partParts = /([0-9]*)([^0-9]*)([0-9]*)([^0-9]*)/.exec(part)
  571. return [
  572. partParts[1] ? parseInt(partParts[1]) : 0,
  573. partParts[2],
  574. partParts[3] ? parseInt(partParts[3]) : 0,
  575. partParts[4]
  576. ];
  577. }
  578. }
  579. }
  580. };
  581. return API;
  582. }
  583. }, {
  584. id: 'Favorite panel',
  585. checker: {
  586. type: 'func',
  587. value: () => {
  588. const path = location.pathname.split('/').filter(p=>p).map(p => p.toLowerCase());
  589. const index = path.indexOf('scripts');
  590. const scripts_exist = [0,1].includes(index);
  591. const is_scripts_list = path.length-1 === index;
  592. const is_set_page = /[\?&]set=\d+/.test(location.search);
  593. const correct_page = [undefined, 'code', 'feedback'].includes(path[index+2]);
  594. return scripts_exist && !is_scripts_list && !is_set_page && correct_page;
  595. }
  596. },
  597. dependencies: ['utils', 'api'],
  598. func() {
  599. const utils = require('utils');
  600. const GFScriptSetAPI = require('api');
  601. //if (!GFScriptSetAPI.getUserpage()) {return false;}
  602.  
  603. class FavoritePanel {
  604. #CM;
  605. #sid;
  606. #sets;
  607. #elements;
  608. #disabled;
  609.  
  610. constructor(CM) {
  611. this.#CM = CM;
  612. this.#sid = location.pathname.match(/scripts\/(\d+)/)[1];
  613. this.#sets = this.#CM.getConfig('script-sets').sets;
  614. this.#elements = {};
  615. this.disabled = false;
  616.  
  617. // Sort sets by name in alphabetical order
  618. FavoritePanel.#sortSetsdata(this.#sets);
  619.  
  620. const script_after = $('#script-feedback-suggestion+*') || $('#new-script-discussion');
  621. const script_parent = script_after.parentElement;
  622.  
  623. // Container
  624. const script_favorite = this.#elements.container = $$CrE({
  625. tagName: 'div',
  626. props: {
  627. id: 'script-favorite',
  628. innerHTML: CONST.Text[i18n].FavEdit
  629. },
  630. styles: { margin: '0.75em 0' }
  631. });
  632.  
  633. // Selecter
  634. const favorite_groups = this.#elements.select = $$CrE({
  635. tagName: 'select',
  636. props: { id: 'favorite-groups' },
  637. styles: { maxWidth: '40vw' },
  638. listeners: [['change', (() => {
  639. let lastSelected = 0;
  640. const record = () => lastSelected = favorite_groups.selectedIndex;
  641. const recover = () => favorite_groups.selectedIndex = lastSelected;
  642.  
  643. return e => {
  644. const value = favorite_groups.value;
  645. const type = /^\d+$/.test(value) ? 'set-id' : 'command';
  646.  
  647. switch (type) {
  648. case 'set-id': {
  649. const set = this.#sets.find(set => set.id === favorite_groups.value);
  650. favorite_edit.href = set.linkedit;
  651. break;
  652. }
  653. case 'command': {
  654. recover();
  655. this.#execCommand(value);
  656. }
  657. }
  658.  
  659. this.#refreshButtonDisplay();
  660. record();
  661. }
  662. }) ()]]
  663. });
  664. favorite_groups.id = 'favorite-groups';
  665.  
  666. // Buttons
  667. const makeBtn = (id, innerHTML, onClick, isLink=false) => $$CrE({
  668. tagName: 'a',
  669. props: {
  670. id, innerHTML,
  671. [isLink ? 'target' : 'href']: isLink ? '_blank' : 'javascript:void(0);'
  672. },
  673. styles: { margin: '0px 0.5em' },
  674. listeners: [['click', onClick]]
  675. });
  676.  
  677. const favorite_add = this.#elements.btnAdd = makeBtn('favorite-add', CONST.Text[i18n].Add, e => this.#addFav());
  678. const favorite_remove = this.#elements.btnRemove = makeBtn('favorite-remove', CONST.Text[i18n].Remove, e => this.#removeFav());
  679. const favorite_edit = this.#elements.btnEdit = makeBtn('favorite-edit', CONST.Text[i18n].Edit, e => {}, true);
  680. const favorite_iframe = this.#elements.btnIframe = makeBtn('favorite-edit-in-page', CONST.Text[i18n].EditIframe, e => this.#editInPage(e));
  681. const favorite_copy = this.#elements.btnCopy = makeBtn('favorite-add', CONST.Text[i18n].CopySID, e => utils.copyText(this.#sid));
  682. const favorite_sync = this.#elements.btnSync = makeBtn('favorite-sync', CONST.Text[i18n].Sync, e => this.#refresh());
  683.  
  684. script_favorite.appendChild(favorite_groups);
  685. script_after.before(script_favorite);
  686. [favorite_add, favorite_remove, favorite_edit, favorite_iframe, favorite_copy, favorite_sync].forEach(button => script_favorite.appendChild(button));
  687.  
  688. // Text tip
  689. const tip = this.#elements.tip = $CrE('span');
  690. script_favorite.appendChild(tip);
  691.  
  692. // Display cached sets first
  693. this.#displaySets();
  694.  
  695. // Request GF document to update sets
  696. this.#autoRefresh();
  697. }
  698.  
  699. get sid() {
  700. return this.#sid;
  701. }
  702.  
  703. get sets() {
  704. return FavoritePanel.#deepClone(this.#sets);
  705. }
  706.  
  707. get elements() {
  708. return FavoritePanel.#lightClone(this.#elements);
  709. }
  710.  
  711. #refresh() {
  712. const that = this;
  713. const method = CONFIG.useAPI ? 'api' : 'doc';
  714. return {
  715. api: () => this.#refresh_api(),
  716. doc: () => this.#refresh_doc()
  717. }[method]();
  718. }
  719.  
  720. async #refresh_api() {
  721. const CONFIG = this.#CM.Config;
  722.  
  723. this.#disable();
  724. this.#tip(CONST.Text[i18n].Refreshing.Data);
  725.  
  726. // Check login status
  727. if (!GFScriptSetAPI.getUserpage()) {
  728. this.#tip(CONST.Text[i18n].NotLoggedIn);
  729. return;
  730. }
  731.  
  732. // Request sets data api
  733. const api_result = await GFScriptSetAPI.getSetsData();
  734. const sets_data = api_result.data;
  735. const uid = GFScriptSetAPI.getUserID();
  736.  
  737. if (!api_result.ok) {
  738. // When api fails, use doc as fallback
  739. DoLog(LogLevel.Error, 'Sets API failed.');
  740. DoLog(LogLevel.Error, api_result);
  741. return this.#refresh_doc();
  742. }
  743.  
  744. // For forward compatibility, convert all setids and scriptids to string
  745. // and fill property set.link and set.linkedit
  746. for (const set of sets_data) {
  747. // convert set id to string
  748. set.id = set.id.toString();
  749. // https://gf.qytechs.cn/zh-CN/scripts?set=439237
  750. set.link = replaceText(CONST.URL.SetLink, { $ID: set.id });
  751. // https://gf.qytechs.cn/zh-CN/users/667968-pyudng/sets/439237/edit
  752. set.linkedit = replaceText(CONST.URL.SetEdit, { $UID: uid, $ID: set.id });
  753.  
  754. // there's two kind of sets: Favorite and non-favorite
  755. // favorite set's data is an array of object, where each object represents a script, with script's properties
  756. // non-favorite set's data is an array of ints, where each int means a script's id
  757. // For forward compatibility, we only store script ids, in string format
  758. set.scripts.forEach((script, i, scripts) => {
  759. if (typeof script === 'number') {
  760. scripts[i] = script.toString();
  761. } else {
  762. scripts[i] = script.id.toString();
  763. }
  764. });
  765. }
  766.  
  767. // Sort sets by name in alphabetical order
  768. FavoritePanel.#sortSetsdata(sets_data);
  769.  
  770. this.#sets = CONFIG['script-sets'].sets = sets_data;
  771. CONFIG['script-sets'].time = Date.now();
  772.  
  773. this.#tip();
  774. this.#enable();
  775. this.#displaySets();
  776. this.#refreshButtonDisplay();
  777. }
  778.  
  779. // Request document: get sets list and
  780. async #refresh_doc() {
  781. const CONFIG = this.#CM.Config;
  782.  
  783. this.#disable();
  784. this.#tip(CONST.Text[i18n].Refreshing.List);
  785.  
  786. // Check login status
  787. if (!GFScriptSetAPI.getUserpage()) {
  788. this.#tip(CONST.Text[i18n].NotLoggedIn);
  789. return;
  790. }
  791.  
  792. // Refresh sets list
  793. this.#sets = CONFIG['script-sets'].sets = await GFScriptSetAPI.getScriptSets();
  794. CONFIG['script-sets'].time = Date.now();
  795. this.#displaySets();
  796.  
  797. // Refresh each set's script list
  798. this.#tip(CONST.Text[i18n].Refreshing.Script);
  799. await Promise.all(this.#sets.map(async set => {
  800. // Fetch scripts
  801. set.scripts = await GFScriptSetAPI.getSetScripts(set.linkedit);
  802. this.#displaySets();
  803.  
  804. // Save to GM_storage
  805. const setIndex = CONFIG['script-sets'].sets.findIndex(s => s.id === set.id);
  806. CONFIG['script-sets'].sets[setIndex].scripts = set.scripts;
  807. CONFIG['script-sets'].time = Date.now();
  808. }));
  809.  
  810. this.#tip();
  811. this.#enable();
  812. this.#refreshButtonDisplay();
  813. }
  814.  
  815. // Refresh on instance creation.
  816. // This should be running in low-frequecy. Refreshing makes lots of requests which may resul in a 503 error(rate limit) for the user.
  817. #autoRefresh(minTime=1*24*60*60*1000) {
  818. const CONFIG = this.#CM.Config;
  819. const lastRefresh = new Date(CONFIG['script-sets'].time);
  820. if (Date.now() - lastRefresh > minTime) {
  821. this.#refresh();
  822. return true;
  823. } else {
  824. return false;
  825. }
  826. }
  827.  
  828. #addFav() {
  829. const set = this.#getCurrentSet();
  830. const option = set.elmOption;
  831.  
  832. this.#displayNotice(CONST.Text[i18n].Working[0]);
  833. GFScriptSetAPI.addFav(this.#getCurrentSet().linkedit, this.#sid, editStatus => {
  834. if (!editStatus) {
  835. this.#displayNotice(CONST.Text[i18n].Error.AlreadyExist);
  836. option.innerText = `${CONST.Text[i18n].InSetStatus[1]} ${set.name}`;
  837. } else {
  838. this.#displayNotice(CONST.Text[i18n].Working[1]);
  839. }
  840. }, finishStatus => {
  841. if (finishStatus) {
  842. // Save to this.#sets and GM_storage
  843. if (CONFIG['script-sets'].sets.some(set => !set.scripts)) {
  844. // If scripts property is missing, do sync(refresh)
  845. this.#refresh();
  846. } else {
  847. const setIndex = CONFIG['script-sets'].sets.findIndex(s => s.id === set.id);
  848. CONFIG['script-sets'].sets[setIndex].scripts.push(this.#sid);
  849. this.#sets = CM.getConfig('script-sets').sets;
  850. }
  851.  
  852. // Display
  853. this.#displayNotice(typeof finishStatus === 'string' ? finishStatus : CONST.Text[i18n].Error.Unknown);
  854. set.elmOption.innerText = `${CONST.Text[i18n].InSetStatus[1]} ${set.name}`;
  855. this.#displaySets();
  856. } else {
  857. this.#displayNotice(CONST.Text[i18n].Error.NetworkError);
  858. }
  859. });
  860. }
  861.  
  862. #removeFav() {
  863. const set = this.#getCurrentSet();
  864. const option = set.elmOption;
  865.  
  866. this.#displayNotice(CONST.Text[i18n].Working[0]);
  867. GFScriptSetAPI.removeFav(this.#getCurrentSet().linkedit, this.#sid, editStatus => {
  868. if (!editStatus) {
  869. this.#displayNotice(CONST.Text[i18n].Error.NotExist);
  870. option.innerText = `${CONST.Text[i18n].InSetStatus[0]} ${set.name}`;
  871. } else {
  872. this.#displayNotice(CONST.Text[i18n].Working[1]);
  873. }
  874. }, finishStatus => {
  875. if (finishStatus) {
  876. // Save to this.#sets and GM_storage
  877. if (CONFIG['script-sets'].sets.some(set => !set.scripts)) {
  878. // If scripts property is missing, do sync(refresh)
  879. this.#refresh();
  880. } else {
  881. const setIndex = CONFIG['script-sets'].sets.findIndex(s => s.id === set.id);
  882. const scriptIndex = CONFIG['script-sets'].sets[setIndex].scripts.indexOf(this.#sid);
  883. CONFIG['script-sets'].sets[setIndex].scripts.splice(scriptIndex, 1);
  884. this.#sets = CM.getConfig('script-sets').sets;
  885. }
  886.  
  887. // Display
  888. this.#displayNotice(typeof finishStatus === 'string' ? finishStatus : CONST.Text[i18n].Error.Unknown);
  889. set.elmOption.innerText = `${CONST.Text[i18n].InSetStatus[0]} ${set.name}`;
  890. this.#displaySets();
  891. } else {
  892. this.#displayNotice(CONST.Text[i18n].Error.NetworkError);
  893. }
  894. });
  895. }
  896.  
  897. #editInPage(e) {
  898. e.preventDefault();
  899.  
  900. const _iframes = [...$All(this.#elements.container, '.script-edit-page')];
  901. if (_iframes.length) {
  902. // Iframe exists, close iframe
  903. this.#elements.btnIframe.innerText = CONST.Text[i18n].EditIframe;
  904. _iframes.forEach(ifr => ifr.remove());
  905. this.#refresh();
  906. } else {
  907. // Iframe not exist, make iframe
  908. this.#elements.btnIframe.innerText = CONST.Text[i18n].CloseIframe;
  909.  
  910. const iframe = $$CrE({
  911. tagName: 'iframe',
  912. props: {
  913. src: this.#getCurrentSet().linkedit
  914. },
  915. styles: {
  916. width: '100%',
  917. height: '60vh'
  918. },
  919. classes: ['script-edit-page'],
  920. listeners: [['load', e => {
  921. //this.#refresh();
  922. //iframe.style.height = iframe.contentDocument.body.parentElement.offsetHeight + 'px';
  923. }]]
  924. });
  925. this.#elements.container.appendChild(iframe);
  926. }
  927. }
  928.  
  929. #displayNotice(text) {
  930. const notice = $CrE('p');
  931. notice.classList.add('notice');
  932. notice.id = 'fav-notice';
  933. notice.innerText = text;
  934. const old_notice = $('#fav-notice');
  935. old_notice && old_notice.parentElement.removeChild(old_notice);
  936. $('#script-content').insertAdjacentElement('afterbegin', notice);
  937. }
  938.  
  939. #tip(text='', timeout=0) {
  940. this.#elements.tip.innerText = text;
  941. timeout > 0 && setTimeout(() => this.#elements.tip.innerText = '', timeout);
  942. }
  943.  
  944. // Apply this.#sets to gui
  945. #displaySets() {
  946. const elements = this.#elements;
  947.  
  948. // Save selected set
  949. const old_value = elements.select.value;
  950. [...elements.select.children].forEach(child => child.remove());
  951.  
  952. // Make <optgroup>s and <option>s
  953. const serverGroup = elements.serverGroup = $$CrE({ tagName: 'optgroup', attrs: { label: CONST.Text[i18n].Groups.Server } });
  954. this.#sets.forEach(set => {
  955. // Create <option>
  956. set.elmOption = $$CrE({
  957. tagName: 'option',
  958. props: {
  959. innerText: set.name,
  960. value: set.id
  961. }
  962. });
  963. // Display inset status
  964. if (set.scripts) {
  965. const inSet = set.scripts.includes(this.#sid);
  966. set.elmOption.innerText = `${CONST.Text[i18n].InSetStatus[inSet+0]} ${set.name}`;
  967. }
  968. // Append <option> into <select>
  969. serverGroup.appendChild(set.elmOption);
  970. });
  971. if (this.#sets.length === 0) {
  972. const optEmpty = elements.optEmpty = $$CrE({
  973. tagName: 'option',
  974. props: {
  975. innerText: CONST.Text[i18n].NoSetsYet,
  976. value: 'empty',
  977. selected: true
  978. }
  979. });
  980. serverGroup.appendChild(optEmpty);
  981. }
  982.  
  983. const newGroup = elements.newGroup = $$CrE({ tagName: 'optgroup', attrs: { label: CONST.Text[i18n].Groups.New } });
  984. const newSet = elements.newSet = $$CrE({
  985. tagName: 'option',
  986. props: {
  987. innerText: CONST.Text[i18n].NewSet,
  988. value: 'new',
  989. }
  990. });
  991. newGroup.appendChild(newSet);
  992. [serverGroup, newGroup].forEach(optgroup => elements.select.appendChild(optgroup));
  993.  
  994. // Adjust <select> width
  995. elements.select.style.width = Math.max.apply(null, Array.from($All(elements.select, 'option')).map(o => o.innerText.length)).toString() + 'em';
  996.  
  997. // Select previous selected set's <option>
  998. const selected = old_value ? [...$All(elements.select, 'option')].find(option => option.value === old_value) : null;
  999. selected && (selected.selected = true);
  1000.  
  1001. // Set edit-button.href
  1002. if (elements.select.value !== 'empty') {
  1003. const curset = this.#sets.find(set => set.id === elements.select.value);
  1004. elements.btnEdit.href = curset.linkedit;
  1005. }
  1006.  
  1007. // Display correct button
  1008. this.#refreshButtonDisplay();
  1009. }
  1010.  
  1011. // Display only add button when script in current set, otherwise remove button
  1012. // Disable set-related buttons when not selecting options that not represents a set
  1013. #refreshButtonDisplay() {
  1014. const set = this.#getCurrentSet();
  1015. !this.#disabled && ([this.#elements.btnAdd, this.#elements.btnRemove, this.#elements.btnEdit, this.#elements.btnIframe]
  1016. .forEach(element => set ? FavoritePanel.#enableElement(element) : FavoritePanel.#disableElement(element)));
  1017. if (!set || !set.scripts) { return null; }
  1018. if (set.scripts.includes(this.#sid)) {
  1019. this.#elements.btnAdd.style.setProperty('display', 'none');
  1020. this.#elements.btnRemove.style.removeProperty('display');
  1021. return true;
  1022. } else {
  1023. this.#elements.btnRemove.style.setProperty('display', 'none');
  1024. this.#elements.btnAdd.style.removeProperty('display');
  1025. return false;
  1026. }
  1027. }
  1028.  
  1029. #execCommand(command) {
  1030. switch (command) {
  1031. case 'new': {
  1032. const url = GFScriptSetAPI.getUserpage() + (this.#getCurrentSet() ? '/sets/new' : '/sets/new?fav=1');
  1033. window.open(url);
  1034. break;
  1035. }
  1036. case 'empty': {
  1037. // Do nothing
  1038. break;
  1039. }
  1040. }
  1041. }
  1042.  
  1043. // Returns null if no <option>s yet
  1044. #getCurrentSet() {
  1045. return this.#sets.find(set => set.id === this.#elements.select.value) || null;
  1046. }
  1047.  
  1048. #disable() {
  1049. [
  1050. this.#elements.select,
  1051. this.#elements.btnAdd, this.#elements.btnRemove,
  1052. this.#elements.btnEdit, this.#elements.btnIframe,
  1053. this.#elements.btnCopy, this.#elements.btnSync
  1054. ].forEach(element => FavoritePanel.#disableElement(element));
  1055. this.#disabled = true;
  1056. }
  1057.  
  1058. #enable() {
  1059. [
  1060. this.#elements.select,
  1061. this.#elements.btnAdd, this.#elements.btnRemove,
  1062. this.#elements.btnEdit, this.#elements.btnIframe,
  1063. this.#elements.btnCopy, this.#elements.btnSync
  1064. ].forEach(element => FavoritePanel.#enableElement(element));
  1065. this.#disabled = false;
  1066. }
  1067.  
  1068. static #disableElement(element) {
  1069. element.style.filter = 'grayscale(1) brightness(0.95)';
  1070. element.style.opacity = '0.25';
  1071. element.style.pointerEvents = 'none';
  1072. element.tabIndex = -1;
  1073. }
  1074.  
  1075. static #enableElement(element) {
  1076. element.style.removeProperty('filter');
  1077. element.style.removeProperty('opacity');
  1078. element.style.removeProperty('pointer-events');
  1079. element.tabIndex = 0;
  1080. }
  1081.  
  1082. static #deepClone(val) {
  1083. if (typeof structuredClone === 'function') {
  1084. return structuredClone(val);
  1085. } else {
  1086. return JSON.parse(JSON.stringify(val));
  1087. }
  1088. }
  1089.  
  1090. static #lightClone(val) {
  1091. if (['string', 'number', 'boolean', 'undefined', 'bigint', 'symbol', 'function'].includes(val) || val === null) {
  1092. return val;
  1093. }
  1094. if (Array.isArray(val)) {
  1095. return val.slice();
  1096. }
  1097. if (typeof val === 'object') {
  1098. return Object.fromEntries(Object.entries(val));
  1099. }
  1100. }
  1101.  
  1102. static #sortSetsdata(sets_data) {
  1103. // Sort sets by name in alphabetical order
  1104. const sorted_names = sets_data.map(set => set.name).sort();
  1105. if (sorted_names.includes('Favorite')) {
  1106. // Keep set `Favorite` at first place
  1107. sorted_names.splice(0, 0, sorted_names.splice(sorted_names.indexOf('Favorite'), 1)[0]);
  1108. }
  1109. sets_data.sort((setA, setB) => sorted_names.indexOf(setA.name) - sorted_names.indexOf(setB.name));
  1110. }
  1111. }
  1112.  
  1113. const panel = new FavoritePanel(CM);
  1114. }
  1115. }, {
  1116. id: 'api-doc switch',
  1117. checker: {
  1118. type: 'switch',
  1119. value: true
  1120. },
  1121. dependencies: 'utils',
  1122. func: e => {
  1123. const utils = require('utils');
  1124. utils.makeBooleanSettings([{
  1125. text: CONST.Text[i18n].UseAPI,
  1126. key: 'useAPI',
  1127. defaultValue: true
  1128. }]);
  1129. }
  1130. }, {
  1131. id: 'Set scripts sort',
  1132. checker: {
  1133. type: 'func',
  1134. value: () => {
  1135. const scripts_exist = [1, 2].map(index => location.pathname.split('/')[index]?.toLowerCase()).includes('scripts');
  1136. const is_set_page = /[\?&]set=\d+/.test(location.search);
  1137. return scripts_exist && is_set_page;
  1138. }
  1139. },
  1140. detectDom: '#script-list-sort>ul',
  1141. func: e => {
  1142. const search = new URLSearchParams(location.search);
  1143. const set_id = search.get('set');
  1144. const sort = search.get('sort');
  1145. if (!CONFIG['script-sets'].sets.some(set => set.id === set_id)) { return false; }
  1146.  
  1147. const ul = $('#script-list-sort>ul');
  1148. [false, true].forEach(reverse => {
  1149. const li = $$CrE({
  1150. tagName: 'li',
  1151. classes: ['list-option', 'gse-sort'], // gse: (G)resyfork(S)et(E)dit+
  1152. attrs: { reverse: reverse ? '1' : '0' },
  1153. });
  1154. const a = $$CrE({
  1155. tagName: 'a',
  1156. props: { innerText: CONST.Text[i18n].sortByApiDefault[+reverse] },
  1157. attrs: { rel: 'nofollow', href: getSortUrl(reverse) }
  1158. });
  1159. li.appendChild(a);
  1160. ul.appendChild(li);
  1161. });
  1162. $AEL(ul, 'click', e => {
  1163. if (e.target.matches('.gse-sort>a')) {
  1164. e.preventDefault();
  1165. const a = e.target;
  1166. const li = a.parentElement;
  1167. const reverse = !!+li.getAttribute('reverse');
  1168. sortByApiDefault(reverse);
  1169. buttonClicked(a);
  1170. setSortUrl(reverse);
  1171. }
  1172. }, { capture: true });
  1173.  
  1174. switch (sort) {
  1175. case 'gse_default':
  1176. sortByApiDefault(false);
  1177. buttonClicked($('.gse-sort[reverse="0"]>a'));
  1178. break;
  1179. case 'gse_reverse':
  1180. sortByApiDefault(true);
  1181. buttonClicked($('.gse-sort[reverse="1"]>a'));
  1182. break;
  1183. }
  1184.  
  1185. /**
  1186. * Sort <li>s in #browse-script-list by default api order
  1187. * Default api order is by add-to-set time right now (2024-07-21),
  1188. * but this is not a promising feature
  1189. */
  1190. function sortByApiDefault(reverse=false) {
  1191. const ol = $('#browse-script-list');
  1192. const li_scripts = Array.from(ol.children);
  1193. const set = CM.getConfig('script-sets').sets.find(set => set.id === set_id);
  1194. const scripts = set.scripts;
  1195. li_scripts.sort((li1, li2) => {
  1196. const [sid1, sid2] = [li1, li2].map(li => li.getAttribute('data-script-id'));
  1197. const [index1, index2] = [sid1, sid2].map(sid => scripts.indexOf(sid)).map(index => index >= 0 ? index : Infinity);
  1198.  
  1199. return (reverse ? [1, -1] : [-1, 1])[index1 > index2 ? 1 : 0];
  1200. });
  1201. //li_scripts.forEach(li => ol.removeChild(li));
  1202. li_scripts.forEach(li => ol.appendChild(li));
  1203. }
  1204.  
  1205. /**
  1206. * Change the clicked button gui to given one
  1207. */
  1208. function buttonClicked(a) {
  1209. const li = a.parentElement;
  1210. const ul = li.parentElement;
  1211. const old_li_current = Array.from(ul.children).find(li => li.classList.contains('list-current'));
  1212.  
  1213. li.classList.add('list-current');
  1214. a.remove();
  1215. li.innerText = a.innerText;
  1216.  
  1217. old_li_current.classList.remove('list-current');
  1218. const old_li_a = $$CrE({
  1219. tagName: 'a',
  1220. attrs: { href: location.pathname + location.search + location.hash },
  1221. props: { innerText: old_li_current.innerText }
  1222. });
  1223. old_li_current.innerText = '';
  1224. old_li_current.appendChild(old_li_a);
  1225. }
  1226.  
  1227. /**
  1228. * Set url search params when sorting
  1229. */
  1230. function setSortUrl(reverse) {
  1231. history.replaceState({}, '', getSortUrl(reverse));
  1232. }
  1233.  
  1234. /**
  1235. * Make corrent url search params with sorting
  1236. */
  1237. function getSortUrl(reverse) {
  1238. const search = new URLSearchParams(location.search);
  1239. search.set('sort', reverse ? 'gse_reverse' : 'gse_default');
  1240. const url = location.pathname + '?' + search.toString();
  1241. return url;
  1242. }
  1243. }
  1244. }]);
  1245. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址