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.2
  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*://*.greatest.deepsurf.us/*
  19. // @match http*://*.sleazyfork.org/*
  20. // @match http*://*.cn-greatest.deepsurf.us/*
  21. // @require https://update.greatest.deepsurf.us/scripts/456034/1597683/Basic%20Functions%20%28For%20userscripts%29.js
  22. // @require https://update.greatest.deepsurf.us/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. TextAllLang: {
  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. get Text() {
  224. const i18n = Object.keys(CONST.TextAllLang).includes(navigator.language) ? navigator.language : CONST.TextAllLang.DEFAULT;
  225. return CONST.TextAllLang[i18n];
  226. },
  227. };
  228.  
  229. const CM = new ConfigManager(CONST.ConfigRule);
  230. const CONFIG = CM.Config;
  231. CM.updateAllConfigs();
  232. CM.setDefaults();
  233.  
  234. const functions = {
  235. utils: {
  236. /** @typedef {Awaited<ReturnType<typeof functions.utils.func>>} utils */
  237. func() {
  238. function makeBooleanSettings(settings) {
  239. for (const setting of settings) {
  240. makeBooleanMenu(setting.text, setting.key, setting.defaultValue, setting.callback, setting.initCallback);
  241. }
  242.  
  243. function makeBooleanMenu(texts, key, defaultValue=false, callback=null, initCallback=false) {
  244. const initialVal = GM_getValue(key, defaultValue);
  245. const initialText = texts[initialVal + 0];
  246. let id = makeMenu(initialText, onClick);
  247. initCallback && callback(key, initialVal);
  248.  
  249. function onClick() {
  250. const newValue = !GM_getValue(key, defaultValue);
  251. const newText = texts[newValue + 0];
  252. GM_setValue(key, newValue);
  253. id = makeMenu(newText, onClick, id);
  254. typeof callback === 'function' && callback(key, newValue);
  255. }
  256.  
  257. function makeMenu(text, func, id) {
  258. if (GM_info.scriptHandler === 'Tampermonkey' && GM_hasVersion('5.0')) {
  259. return GM_registerMenuCommand(text, func, {
  260. id,
  261. autoClose: false,
  262. });
  263. } else {
  264. GM_unregisterMenuCommand(id);
  265. return GM_registerMenuCommand(text, func);
  266. }
  267. }
  268. }
  269.  
  270. function GM_hasVersion(version) {
  271. return hasVersion(GM_info?.version || '0', version);
  272.  
  273. function hasVersion(ver1, ver2) {
  274. return compareVersions(ver1.toString(), ver2.toString()) >= 0;
  275.  
  276. // https://greatest.deepsurf.us/app/javascript/versioncheck.js
  277. // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version/format
  278. function compareVersions(a, b) {
  279. if (a == b) {
  280. return 0;
  281. }
  282. let aParts = a.split('.');
  283. let bParts = b.split('.');
  284. for (let i = 0; i < aParts.length; i++) {
  285. let result = compareVersionPart(aParts[i], bParts[i]);
  286. if (result != 0) {
  287. return result;
  288. }
  289. }
  290. // If all of a's parts are the same as b's parts, but b has additional parts, b is greater.
  291. if (bParts.length > aParts.length) {
  292. return -1;
  293. }
  294. return 0;
  295. }
  296.  
  297. function compareVersionPart(partA, partB) {
  298. let partAParts = parseVersionPart(partA);
  299. let partBParts = parseVersionPart(partB);
  300. for (let i = 0; i < partAParts.length; i++) {
  301. // "A string-part that exists is always less than a string-part that doesn't exist"
  302. if (partAParts[i].length > 0 && partBParts[i].length == 0) {
  303. return -1;
  304. }
  305. if (partAParts[i].length == 0 && partBParts[i].length > 0) {
  306. return 1;
  307. }
  308. if (partAParts[i] > partBParts[i]) {
  309. return 1;
  310. }
  311. if (partAParts[i] < partBParts[i]) {
  312. return -1;
  313. }
  314. }
  315. return 0;
  316. }
  317.  
  318. // It goes number, string, number, string. If it doesn't exist, then
  319. // 0 for numbers, empty string for strings.
  320. function parseVersionPart(part) {
  321. if (!part) {
  322. return [0, "", 0, ""];
  323. }
  324. let partParts = /([0-9]*)([^0-9]*)([0-9]*)([^0-9]*)/.exec(part)
  325. return [
  326. partParts[1] ? parseInt(partParts[1]) : 0,
  327. partParts[2],
  328. partParts[3] ? parseInt(partParts[3]) : 0,
  329. partParts[4]
  330. ];
  331. }
  332. }
  333. }
  334. }
  335.  
  336. // Copy text to clipboard (needs to be called in an user event)
  337. function copyText(text) {
  338. // Create a new textarea for copying
  339. const newInput = document.createElement('textarea');
  340. document.body.appendChild(newInput);
  341. newInput.value = text;
  342. newInput.select();
  343. document.execCommand('copy');
  344. document.body.removeChild(newInput);
  345. }
  346.  
  347. return {
  348. makeBooleanSettings,
  349. copyText
  350. }
  351. }
  352. },
  353. api: {
  354. /** @typedef {Awaited<ReturnType<typeof functions.api.func>>} api */
  355. func() {
  356. const API = {
  357. async getScriptSets() {
  358. const userpage = API.getUserpage();
  359. const oDom = await API.getDocument(userpage);
  360. const list = Array.from($(oDom, 'ul#user-script-sets').children);
  361. const NoSets = list.length === 1 && list.every(li => li.children.length === 1);
  362. const script_sets = NoSets ? [] : Array.from($(oDom, 'ul#user-script-sets').children).filter(li => li.children.length === 2).map(li => {
  363. try {
  364. return {
  365. name: li.children[0].innerText,
  366. link: li.children[0].href,
  367. linkedit: li.children[1].href,
  368. id: getUrlArgv(li.children[0].href, 'set')
  369. }
  370. } catch(err) {
  371. DoLog(LogLevel.Error, [li, err, li.children.length, li.children[0]?.innerHTML, li.children[1]?.innerHTML], 'error');
  372. Err(err);
  373. }
  374. });
  375. return script_sets;
  376. },
  377. async getSetScripts(url) {
  378. return [...$All(await API.getDocument(url), '#script-set-scripts>input[name="scripts-included[]"]')].map(input => input.value);
  379. },
  380. /**
  381. * @typedef {Object} SetsDataAPI
  382. * @property {Response} resp - api fetch response object
  383. * @property {boolean} ok - resp.ok (resp.status >= 200 && resp.status <= 299)
  384. * @property {(Object|null)} data - api response json data, or null if not resp.ok
  385. */
  386. /**
  387. * @returns {SetsDataAPI}
  388. */
  389. async getSetsData() {
  390. const userpage = API.getUserpage();
  391. const url = (userpage.endsWith('/') ? userpage : userpage + '/') + 'sets'
  392. const resp = await fetch(url, { credentials: 'same-origin' });
  393. if (resp.ok) {
  394. return {
  395. ok: true,
  396. resp,
  397. data: await resp.json()
  398. };
  399. } else {
  400. return {
  401. ok: false,
  402. resp,
  403. data: null
  404. };
  405. }
  406. },
  407. /**
  408. * @returns {(string|null)} the user's profile page url, from page top-right link <a>.href
  409. */
  410. getUserpage() {
  411. const a = $('#nav-user-info>.user-profile-link>a');
  412. return a ? a.href : null;
  413. },
  414. /**
  415. * @returns {(string|null)} the user's id, in string format
  416. */
  417. getUserID() {
  418. const userpage = API.getUserpage(); //https://greatest.deepsurf.us/zh-CN/users/667968-pyudng
  419. return userpage ? userpage.match(/\/users\/(\d+)(-[^\/]*\/*)?/)[1] : null;
  420. },
  421. // editCallback recieves:
  422. // true: edit doc load success
  423. // false: already in set
  424. // finishCallback recieves:
  425. // text: successfully added to set with text tip `text`
  426. // true: successfully loaded document but no text tip found
  427. // false: xhr error
  428. addFav(url, sid, editCallback, finishCallback) {
  429. API.modifyFav(url, oDom => {
  430. const existingInput = [...$All(oDom, '#script-set-scripts>input[name="scripts-included[]"][type="hidden"]')].find(input => input.value === sid);
  431. if (existingInput) {
  432. editCallback(false);
  433. return false;
  434. }
  435. const input = $CrE('input');
  436. input.value = sid;
  437. input.name = 'scripts-included[]';
  438. input.type = 'hidden';
  439. $(oDom, '#script-set-scripts').appendChild(input);
  440. editCallback(true);
  441. }, oDom => {
  442. const status = $(oDom, 'p.notice');
  443. const status_text = status ? status.innerText : true;
  444. finishCallback(status_text);
  445. }, err => finishCallback(false));
  446. },
  447. // editCallback recieves:
  448. // true: edit doc load success
  449. // false: already not in set
  450. // finishCallback recieves:
  451. // text: successfully removed from set with text tip `text`
  452. // true: successfully loaded document but no text tip found
  453. // false: xhr error
  454. removeFav(url, sid, editCallback, finishCallback) {
  455. API.modifyFav(url, oDom => {
  456. const existingInput = [...$All(oDom, '#script-set-scripts>input[name="scripts-included[]"][type="hidden"]')].find(input => input.value === sid);
  457. if (!existingInput) {
  458. editCallback(false);
  459. return false;
  460. }
  461. existingInput.remove();
  462. editCallback(true);
  463. }, oDom => {
  464. const status = $(oDom, 'p.notice');
  465. const status_text = status ? status.innerText : true;
  466. finishCallback(status_text);
  467. }, err => finishCallback(false));
  468. },
  469. async modifyFav(url, editCallback, finishCallback, onerror) {
  470. const oDom = await API.getDocument(url);
  471. if (editCallback(oDom) === false) { return false; }
  472. const form = $(oDom, '.change-script-set');
  473. const data = new FormData(form);
  474. data.append('save', '1');
  475. // Use XMLHttpRequest insteadof GM_xmlhttpRequest because there's unknown issue with GM_xmlhttpRequest
  476. const xhr = new XMLHttpRequest();
  477. xhr.open('POST', API.toAbsoluteURL(form.getAttribute('action')));
  478. xhr.responseType = 'blob';
  479. xhr.onload = async e => finishCallback(await API.parseDocument(xhr.response));
  480. xhr.onerror = onerror;
  481. xhr.send(data);
  482. },
  483. // Download and parse a url page into a html document(dom).
  484. // Returns a promise fulfills with dom
  485. async getDocument(url, retry=5) {
  486. try {
  487. const response = await fetch(url, {
  488. method: 'GET',
  489. cache: 'reload',
  490. });
  491. if (response.status === 200) {
  492. const blob = await response.blob();
  493. const oDom = await API.parseDocument(blob);
  494. return oDom;
  495. } else {
  496. throw new Error(`response.status is not 200 (${response.status})`);
  497. }
  498. } catch(err) {
  499. if (--retry > 0) {
  500. return API.getDocument(url, retry);
  501. } else {
  502. throw err;
  503. }
  504. }
  505. },
  506. // Returns a promise fulfills with dom
  507. parseDocument(htmlblob) {
  508. return new Promise((resolve, reject) => {
  509. const reader = new FileReader();
  510. reader.onload = function(e) {
  511. const htmlText = reader.result;
  512. const dom = new DOMParser().parseFromString(htmlText, 'text/html');
  513. resolve(dom);
  514. }
  515. reader.onerror = err => reject(err);
  516. reader.readAsText(htmlblob, document.characterSet);
  517. });
  518. },
  519. toAbsoluteURL(relativeURL, base=`${location.protocol}//${location.host}/`) {
  520. return new URL(relativeURL, base).href;
  521. },
  522. GM_hasVersion(version) {
  523. return hasVersion(GM_info?.version || '0', version);
  524. function hasVersion(ver1, ver2) {
  525. return compareVersions(ver1.toString(), ver2.toString()) >= 0;
  526. // https://greatest.deepsurf.us/app/javascript/versioncheck.js
  527. // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version/format
  528. function compareVersions(a, b) {
  529. if (a == b) {
  530. return 0;
  531. }
  532. let aParts = a.split('.');
  533. let bParts = b.split('.');
  534. for (let i = 0; i < aParts.length; i++) {
  535. let result = compareVersionPart(aParts[i], bParts[i]);
  536. if (result != 0) {
  537. return result;
  538. }
  539. }
  540. // If all of a's parts are the same as b's parts, but b has additional parts, b is greater.
  541. if (bParts.length > aParts.length) {
  542. return -1;
  543. }
  544. return 0;
  545. }
  546. function compareVersionPart(partA, partB) {
  547. let partAParts = parseVersionPart(partA);
  548. let partBParts = parseVersionPart(partB);
  549. for (let i = 0; i < partAParts.length; i++) {
  550. // "A string-part that exists is always less than a string-part that doesn't exist"
  551. if (partAParts[i].length > 0 && partBParts[i].length == 0) {
  552. return -1;
  553. }
  554. if (partAParts[i].length == 0 && partBParts[i].length > 0) {
  555. return 1;
  556. }
  557. if (partAParts[i] > partBParts[i]) {
  558. return 1;
  559. }
  560. if (partAParts[i] < partBParts[i]) {
  561. return -1;
  562. }
  563. }
  564. return 0;
  565. }
  566. // It goes number, string, number, string. If it doesn't exist, then
  567. // 0 for numbers, empty string for strings.
  568. function parseVersionPart(part) {
  569. if (!part) {
  570. return [0, "", 0, ""];
  571. }
  572. let partParts = /([0-9]*)([^0-9]*)([0-9]*)([^0-9]*)/.exec(part)
  573. return [
  574. partParts[1] ? parseInt(partParts[1]) : 0,
  575. partParts[2],
  576. partParts[3] ? parseInt(partParts[3]) : 0,
  577. partParts[4]
  578. ];
  579. }
  580. }
  581. }
  582. };
  583. return API;
  584. }
  585. },
  586. 'Favorite panel': {
  587. checkers: {
  588. type: 'func',
  589. value: () => {
  590. const path = location.pathname.split('/').filter(p=>p).map(p => p.toLowerCase());
  591. const index = path.indexOf('scripts');
  592. const scripts_exist = [0,1].includes(index);
  593. const is_scripts_list = path.length-1 === index;
  594. const is_set_page = /[\?&]set=\d+/.test(location.search);
  595. const correct_page = [undefined, 'code', 'feedback'].includes(path[index+2]);
  596. return scripts_exist && !is_scripts_list && !is_set_page && correct_page;
  597. }
  598. },
  599. dependencies: ['utils', 'api'],
  600. func() {
  601. /** @type {utils} */
  602. const utils = require('utils');
  603. /** @type {api} */
  604. const GFScriptSetAPI = require('api');
  605. //if (!GFScriptSetAPI.getUserpage()) {return false;}
  606.  
  607. class FavoritePanel {
  608. #CM;
  609. #sid;
  610. #sets;
  611. #elements;
  612. #disabled;
  613.  
  614. constructor(CM) {
  615. this.#CM = CM;
  616. this.#sid = location.pathname.match(/scripts\/(\d+)/)[1];
  617. this.#sets = this.#CM.getConfig('script-sets').sets;
  618. this.#elements = {};
  619. this.disabled = false;
  620.  
  621. // Sort sets by name in alphabetical order
  622. FavoritePanel.#sortSetsdata(this.#sets);
  623.  
  624. const script_after = $('#script-feedback-suggestion+*') || $('#new-script-discussion');
  625. const script_parent = script_after.parentElement;
  626.  
  627. // Container
  628. const script_favorite = this.#elements.container = $$CrE({
  629. tagName: 'div',
  630. props: {
  631. id: 'script-favorite',
  632. innerHTML: CONST.Text.FavEdit
  633. },
  634. styles: { margin: '0.75em 0' }
  635. });
  636.  
  637. // Selecter
  638. const favorite_groups = this.#elements.select = $$CrE({
  639. tagName: 'select',
  640. props: { id: 'favorite-groups' },
  641. styles: { maxWidth: '40vw' },
  642. listeners: [['change', (() => {
  643. let lastSelected = 0;
  644. const record = () => lastSelected = favorite_groups.selectedIndex;
  645. const recover = () => favorite_groups.selectedIndex = lastSelected;
  646.  
  647. return e => {
  648. const value = favorite_groups.value;
  649. const type = /^\d+$/.test(value) ? 'set-id' : 'command';
  650.  
  651. switch (type) {
  652. case 'set-id': {
  653. const set = this.#sets.find(set => set.id === favorite_groups.value);
  654. favorite_edit.href = set.linkedit;
  655. break;
  656. }
  657. case 'command': {
  658. recover();
  659. this.#execCommand(value);
  660. }
  661. }
  662.  
  663. this.#refreshButtonDisplay();
  664. record();
  665. }
  666. }) ()]]
  667. });
  668. favorite_groups.id = 'favorite-groups';
  669.  
  670. // Buttons
  671. const makeBtn = (id, innerHTML, onClick, isLink=false) => $$CrE({
  672. tagName: 'a',
  673. props: {
  674. id, innerHTML,
  675. [isLink ? 'target' : 'href']: isLink ? '_blank' : 'javascript:void(0);'
  676. },
  677. styles: { margin: '0px 0.5em' },
  678. listeners: [['click', onClick]]
  679. });
  680.  
  681. const favorite_add = this.#elements.btnAdd = makeBtn('favorite-add', CONST.Text.Add, e => this.#addFav());
  682. const favorite_remove = this.#elements.btnRemove = makeBtn('favorite-remove', CONST.Text.Remove, e => this.#removeFav());
  683. const favorite_edit = this.#elements.btnEdit = makeBtn('favorite-edit', CONST.Text.Edit, e => {}, true);
  684. const favorite_iframe = this.#elements.btnIframe = makeBtn('favorite-edit-in-page', CONST.Text.EditIframe, e => this.#editInPage(e));
  685. const favorite_copy = this.#elements.btnCopy = makeBtn('favorite-add', CONST.Text.CopySID, e => utils.copyText(this.#sid));
  686. const favorite_sync = this.#elements.btnSync = makeBtn('favorite-sync', CONST.Text.Sync, e => this.#refresh());
  687.  
  688. script_favorite.appendChild(favorite_groups);
  689. script_after.before(script_favorite);
  690. [favorite_add, favorite_remove, favorite_edit, favorite_iframe, favorite_copy, favorite_sync].forEach(button => script_favorite.appendChild(button));
  691.  
  692. // Text tip
  693. const tip = this.#elements.tip = $CrE('span');
  694. script_favorite.appendChild(tip);
  695.  
  696. // Display cached sets first
  697. this.#displaySets();
  698.  
  699. // Request GF document to update sets
  700. this.#autoRefresh();
  701. }
  702.  
  703. get sid() {
  704. return this.#sid;
  705. }
  706.  
  707. get sets() {
  708. return FavoritePanel.#deepClone(this.#sets);
  709. }
  710.  
  711. get elements() {
  712. return FavoritePanel.#lightClone(this.#elements);
  713. }
  714.  
  715. #refresh() {
  716. const that = this;
  717. const method = CONFIG.useAPI ? 'api' : 'doc';
  718. return {
  719. api: () => this.#refresh_api(),
  720. doc: () => this.#refresh_doc()
  721. }[method]();
  722. }
  723.  
  724. async #refresh_api() {
  725. const CONFIG = this.#CM.Config;
  726.  
  727. this.#disable();
  728. this.#tip(CONST.Text.Refreshing.Data);
  729.  
  730. // Check login status
  731. if (!GFScriptSetAPI.getUserpage()) {
  732. this.#tip(CONST.Text.NotLoggedIn);
  733. return;
  734. }
  735.  
  736. // Request sets data api
  737. const api_result = await GFScriptSetAPI.getSetsData();
  738. const sets_data = api_result.data;
  739. const uid = GFScriptSetAPI.getUserID();
  740.  
  741. if (!api_result.ok) {
  742. // When api fails, use doc as fallback
  743. DoLog(LogLevel.Error, 'Sets API failed.');
  744. DoLog(LogLevel.Error, api_result);
  745. return this.#refresh_doc();
  746. }
  747.  
  748. // For forward compatibility, convert all setids and scriptids to string
  749. // and fill property set.link and set.linkedit
  750. for (const set of sets_data) {
  751. // convert set id to string
  752. set.id = set.id.toString();
  753. // https://greatest.deepsurf.us/zh-CN/scripts?set=439237
  754. set.link = replaceText(CONST.URL.SetLink, { $ID: set.id });
  755. // https://greatest.deepsurf.us/zh-CN/users/667968-pyudng/sets/439237/edit
  756. set.linkedit = replaceText(CONST.URL.SetEdit, { $UID: uid, $ID: set.id });
  757.  
  758. // there's two kind of sets: Favorite and non-favorite
  759. // favorite set's data is an array of object, where each object represents a script, with script's properties
  760. // non-favorite set's data is an array of ints, where each int means a script's id
  761. // For forward compatibility, we only store script ids, in string format
  762. set.scripts.forEach((script, i, scripts) => {
  763. if (typeof script === 'number') {
  764. scripts[i] = script.toString();
  765. } else {
  766. scripts[i] = script.id.toString();
  767. }
  768. });
  769. }
  770.  
  771. // Sort sets by name in alphabetical order
  772. FavoritePanel.#sortSetsdata(sets_data);
  773.  
  774. this.#sets = CONFIG['script-sets'].sets = sets_data;
  775. CONFIG['script-sets'].time = Date.now();
  776.  
  777. this.#tip();
  778. this.#enable();
  779. this.#displaySets();
  780. this.#refreshButtonDisplay();
  781. }
  782.  
  783. // Request document: get sets list and
  784. async #refresh_doc() {
  785. const CONFIG = this.#CM.Config;
  786.  
  787. this.#disable();
  788. this.#tip(CONST.Text.Refreshing.List);
  789.  
  790. // Check login status
  791. if (!GFScriptSetAPI.getUserpage()) {
  792. this.#tip(CONST.Text.NotLoggedIn);
  793. return;
  794. }
  795.  
  796. // Refresh sets list
  797. this.#sets = CONFIG['script-sets'].sets = await GFScriptSetAPI.getScriptSets();
  798. CONFIG['script-sets'].time = Date.now();
  799. this.#displaySets();
  800.  
  801. // Refresh each set's script list
  802. this.#tip(CONST.Text.Refreshing.Script);
  803. await Promise.all(this.#sets.map(async set => {
  804. // Fetch scripts
  805. set.scripts = await GFScriptSetAPI.getSetScripts(set.linkedit);
  806. this.#displaySets();
  807.  
  808. // Save to GM_storage
  809. const setIndex = CONFIG['script-sets'].sets.findIndex(s => s.id === set.id);
  810. CONFIG['script-sets'].sets[setIndex].scripts = set.scripts;
  811. CONFIG['script-sets'].time = Date.now();
  812. }));
  813.  
  814. this.#tip();
  815. this.#enable();
  816. this.#refreshButtonDisplay();
  817. }
  818.  
  819. // Refresh on instance creation.
  820. // This should be running in low-frequecy. Refreshing makes lots of requests which may resul in a 503 error(rate limit) for the user.
  821. #autoRefresh(minTime=1*24*60*60*1000) {
  822. const CONFIG = this.#CM.Config;
  823. const lastRefresh = new Date(CONFIG['script-sets'].time);
  824. if (Date.now() - lastRefresh > minTime) {
  825. this.#refresh();
  826. return true;
  827. } else {
  828. return false;
  829. }
  830. }
  831.  
  832. #addFav() {
  833. const set = this.#getCurrentSet();
  834. const option = set.elmOption;
  835.  
  836. this.#displayNotice(CONST.Text.Working[0]);
  837. GFScriptSetAPI.addFav(this.#getCurrentSet().linkedit, this.#sid, editStatus => {
  838. if (!editStatus) {
  839. this.#displayNotice(CONST.Text.Error.AlreadyExist);
  840. option.innerText = `${CONST.Text.InSetStatus[1]} ${set.name}`;
  841. } else {
  842. this.#displayNotice(CONST.Text.Working[1]);
  843. }
  844. }, finishStatus => {
  845. if (finishStatus) {
  846. // Save to this.#sets and GM_storage
  847. if (CONFIG['script-sets'].sets.some(set => !set.scripts)) {
  848. // If scripts property is missing, do sync(refresh)
  849. this.#refresh();
  850. } else {
  851. const setIndex = CONFIG['script-sets'].sets.findIndex(s => s.id === set.id);
  852. CONFIG['script-sets'].sets[setIndex].scripts.push(this.#sid);
  853. this.#sets = CM.getConfig('script-sets').sets;
  854. }
  855.  
  856. // Display
  857. this.#displayNotice(typeof finishStatus === 'string' ? finishStatus : CONST.Text.Error.Unknown);
  858. set.elmOption.innerText = `${CONST.Text.InSetStatus[1]} ${set.name}`;
  859. this.#displaySets();
  860. } else {
  861. this.#displayNotice(CONST.Text.Error.NetworkError);
  862. }
  863. });
  864. }
  865.  
  866. #removeFav() {
  867. const set = this.#getCurrentSet();
  868. const option = set.elmOption;
  869.  
  870. this.#displayNotice(CONST.Text.Working[0]);
  871. GFScriptSetAPI.removeFav(this.#getCurrentSet().linkedit, this.#sid, editStatus => {
  872. if (!editStatus) {
  873. this.#displayNotice(CONST.Text.Error.NotExist);
  874. option.innerText = `${CONST.Text.InSetStatus[0]} ${set.name}`;
  875. } else {
  876. this.#displayNotice(CONST.Text.Working[1]);
  877. }
  878. }, finishStatus => {
  879. if (finishStatus) {
  880. // Save to this.#sets and GM_storage
  881. if (CONFIG['script-sets'].sets.some(set => !set.scripts)) {
  882. // If scripts property is missing, do sync(refresh)
  883. this.#refresh();
  884. } else {
  885. const setIndex = CONFIG['script-sets'].sets.findIndex(s => s.id === set.id);
  886. const scriptIndex = CONFIG['script-sets'].sets[setIndex].scripts.indexOf(this.#sid);
  887. CONFIG['script-sets'].sets[setIndex].scripts.splice(scriptIndex, 1);
  888. this.#sets = CM.getConfig('script-sets').sets;
  889. }
  890.  
  891. // Display
  892. this.#displayNotice(typeof finishStatus === 'string' ? finishStatus : CONST.Text.Error.Unknown);
  893. set.elmOption.innerText = `${CONST.Text.InSetStatus[0]} ${set.name}`;
  894. this.#displaySets();
  895. } else {
  896. this.#displayNotice(CONST.Text.Error.NetworkError);
  897. }
  898. });
  899. }
  900.  
  901. #editInPage(e) {
  902. e.preventDefault();
  903.  
  904. const _iframes = [...$All(this.#elements.container, '.script-edit-page')];
  905. if (_iframes.length) {
  906. // Iframe exists, close iframe
  907. this.#elements.btnIframe.innerText = CONST.Text.EditIframe;
  908. _iframes.forEach(ifr => ifr.remove());
  909. this.#refresh();
  910. } else {
  911. // Iframe not exist, make iframe
  912. this.#elements.btnIframe.innerText = CONST.Text.CloseIframe;
  913.  
  914. const iframe = $$CrE({
  915. tagName: 'iframe',
  916. props: {
  917. src: this.#getCurrentSet().linkedit
  918. },
  919. styles: {
  920. width: '100%',
  921. height: '60vh'
  922. },
  923. classes: ['script-edit-page'],
  924. listeners: [['load', e => {
  925. //this.#refresh();
  926. //iframe.style.height = iframe.contentDocument.body.parentElement.offsetHeight + 'px';
  927. }]]
  928. });
  929. this.#elements.container.appendChild(iframe);
  930. }
  931. }
  932.  
  933. #displayNotice(text) {
  934. const notice = $CrE('p');
  935. notice.classList.add('notice');
  936. notice.id = 'fav-notice';
  937. notice.innerText = text;
  938. const old_notice = $('#fav-notice');
  939. old_notice && old_notice.parentElement.removeChild(old_notice);
  940. $('#script-content').insertAdjacentElement('afterbegin', notice);
  941. }
  942.  
  943. #tip(text='', timeout=0) {
  944. this.#elements.tip.innerText = text;
  945. timeout > 0 && setTimeout(() => this.#elements.tip.innerText = '', timeout);
  946. }
  947.  
  948. // Apply this.#sets to gui
  949. #displaySets() {
  950. const elements = this.#elements;
  951.  
  952. // Save selected set
  953. const old_value = elements.select.value;
  954. [...elements.select.children].forEach(child => child.remove());
  955.  
  956. // Make <optgroup>s and <option>s
  957. const serverGroup = elements.serverGroup = $$CrE({ tagName: 'optgroup', attrs: { label: CONST.Text.Groups.Server } });
  958. this.#sets.forEach(set => {
  959. // Create <option>
  960. set.elmOption = $$CrE({
  961. tagName: 'option',
  962. props: {
  963. innerText: set.name,
  964. value: set.id
  965. }
  966. });
  967. // Display inset status
  968. if (set.scripts) {
  969. const inSet = set.scripts.includes(this.#sid);
  970. set.elmOption.innerText = `${CONST.Text.InSetStatus[inSet+0]} ${set.name}`;
  971. }
  972. // Append <option> into <select>
  973. serverGroup.appendChild(set.elmOption);
  974. });
  975. if (this.#sets.length === 0) {
  976. const optEmpty = elements.optEmpty = $$CrE({
  977. tagName: 'option',
  978. props: {
  979. innerText: CONST.Text.NoSetsYet,
  980. value: 'empty',
  981. selected: true
  982. }
  983. });
  984. serverGroup.appendChild(optEmpty);
  985. }
  986.  
  987. const newGroup = elements.newGroup = $$CrE({ tagName: 'optgroup', attrs: { label: CONST.Text.Groups.New } });
  988. const newSet = elements.newSet = $$CrE({
  989. tagName: 'option',
  990. props: {
  991. innerText: CONST.Text.NewSet,
  992. value: 'new',
  993. }
  994. });
  995. newGroup.appendChild(newSet);
  996. [serverGroup, newGroup].forEach(optgroup => elements.select.appendChild(optgroup));
  997.  
  998. // Adjust <select> width
  999. elements.select.style.width = Math.max.apply(null, Array.from($All(elements.select, 'option')).map(o => o.innerText.length)).toString() + 'em';
  1000.  
  1001. // Select previous selected set's <option>
  1002. const selected = old_value ? [...$All(elements.select, 'option')].find(option => option.value === old_value) : null;
  1003. selected && (selected.selected = true);
  1004.  
  1005. // Set edit-button.href
  1006. if (elements.select.value !== 'empty') {
  1007. const curset = this.#sets.find(set => set.id === elements.select.value);
  1008. elements.btnEdit.href = curset.linkedit;
  1009. }
  1010.  
  1011. // Display correct button
  1012. this.#refreshButtonDisplay();
  1013. }
  1014.  
  1015. // Display only add button when script in current set, otherwise remove button
  1016. // Disable set-related buttons when not selecting options that not represents a set
  1017. #refreshButtonDisplay() {
  1018. const set = this.#getCurrentSet();
  1019. !this.#disabled && ([this.#elements.btnAdd, this.#elements.btnRemove, this.#elements.btnEdit, this.#elements.btnIframe]
  1020. .forEach(element => set ? FavoritePanel.#enableElement(element) : FavoritePanel.#disableElement(element)));
  1021. if (!set || !set.scripts) { return null; }
  1022. if (set.scripts.includes(this.#sid)) {
  1023. this.#elements.btnAdd.style.setProperty('display', 'none');
  1024. this.#elements.btnRemove.style.removeProperty('display');
  1025. return true;
  1026. } else {
  1027. this.#elements.btnRemove.style.setProperty('display', 'none');
  1028. this.#elements.btnAdd.style.removeProperty('display');
  1029. return false;
  1030. }
  1031. }
  1032.  
  1033. #execCommand(command) {
  1034. switch (command) {
  1035. case 'new': {
  1036. const url = GFScriptSetAPI.getUserpage() + (this.#getCurrentSet() ? '/sets/new' : '/sets/new?fav=1');
  1037. window.open(url);
  1038. break;
  1039. }
  1040. case 'empty': {
  1041. // Do nothing
  1042. break;
  1043. }
  1044. }
  1045. }
  1046.  
  1047. // Returns null if no <option>s yet
  1048. #getCurrentSet() {
  1049. return this.#sets.find(set => set.id === this.#elements.select.value) || null;
  1050. }
  1051.  
  1052. #disable() {
  1053. [
  1054. this.#elements.select,
  1055. this.#elements.btnAdd, this.#elements.btnRemove,
  1056. this.#elements.btnEdit, this.#elements.btnIframe,
  1057. this.#elements.btnCopy, this.#elements.btnSync
  1058. ].forEach(element => FavoritePanel.#disableElement(element));
  1059. this.#disabled = true;
  1060. }
  1061.  
  1062. #enable() {
  1063. [
  1064. this.#elements.select,
  1065. this.#elements.btnAdd, this.#elements.btnRemove,
  1066. this.#elements.btnEdit, this.#elements.btnIframe,
  1067. this.#elements.btnCopy, this.#elements.btnSync
  1068. ].forEach(element => FavoritePanel.#enableElement(element));
  1069. this.#disabled = false;
  1070. }
  1071.  
  1072. static #disableElement(element) {
  1073. element.style.filter = 'grayscale(1) brightness(0.95)';
  1074. element.style.opacity = '0.25';
  1075. element.style.pointerEvents = 'none';
  1076. element.tabIndex = -1;
  1077. }
  1078.  
  1079. static #enableElement(element) {
  1080. element.style.removeProperty('filter');
  1081. element.style.removeProperty('opacity');
  1082. element.style.removeProperty('pointer-events');
  1083. element.tabIndex = 0;
  1084. }
  1085.  
  1086. static #deepClone(val) {
  1087. if (typeof structuredClone === 'function') {
  1088. return structuredClone(val);
  1089. } else {
  1090. return JSON.parse(JSON.stringify(val));
  1091. }
  1092. }
  1093.  
  1094. static #lightClone(val) {
  1095. if (['string', 'number', 'boolean', 'undefined', 'bigint', 'symbol', 'function'].includes(val) || val === null) {
  1096. return val;
  1097. }
  1098. if (Array.isArray(val)) {
  1099. return val.slice();
  1100. }
  1101. if (typeof val === 'object') {
  1102. return Object.fromEntries(Object.entries(val));
  1103. }
  1104. }
  1105.  
  1106. static #sortSetsdata(sets_data) {
  1107. // Sort sets by name in alphabetical order
  1108. const sorted_names = sets_data.map(set => set.name).sort();
  1109. if (sorted_names.includes('Favorite')) {
  1110. // Keep set `Favorite` at first place
  1111. sorted_names.splice(0, 0, sorted_names.splice(sorted_names.indexOf('Favorite'), 1)[0]);
  1112. }
  1113. sets_data.sort((setA, setB) => sorted_names.indexOf(setA.name) - sorted_names.indexOf(setB.name));
  1114. }
  1115. }
  1116.  
  1117. const panel = new FavoritePanel(CM);
  1118. }
  1119. },
  1120. 'api-doc switch': {
  1121. checkers: {
  1122. type: 'switch',
  1123. value: true
  1124. },
  1125. dependencies: 'utils',
  1126. func: e => {
  1127. /** @type {utils} */
  1128. const utils = require('utils');
  1129. utils.makeBooleanSettings([{
  1130. text: CONST.Text.UseAPI,
  1131. key: 'useAPI',
  1132. defaultValue: true
  1133. }]);
  1134. }
  1135. },
  1136. 'Set scripts sort': {
  1137. checkers: {
  1138. type: 'func',
  1139. value: () => {
  1140. const scripts_exist = [1, 2].map(index => location.pathname.split('/')[index]?.toLowerCase()).includes('scripts');
  1141. const is_set_page = /[\?&]set=\d+/.test(location.search);
  1142. return scripts_exist && is_set_page;
  1143. }
  1144. },
  1145. detectDom: '#script-list-sort>ul',
  1146. func: e => {
  1147. const search = new URLSearchParams(location.search);
  1148. const set_id = search.get('set');
  1149. const sort = search.get('sort');
  1150. if (!CONFIG['script-sets'].sets.some(set => set.id === set_id)) { return false; }
  1151.  
  1152. const ul = $('#script-list-sort>ul');
  1153. [false, true].forEach(reverse => {
  1154. const li = $$CrE({
  1155. tagName: 'li',
  1156. classes: ['list-option', 'gse-sort'], // gse: (G)resyfork(S)et(E)dit+
  1157. attrs: { reverse: reverse ? '1' : '0' },
  1158. });
  1159. const a = $$CrE({
  1160. tagName: 'a',
  1161. props: { innerText: CONST.Text.sortByApiDefault[+reverse] },
  1162. attrs: { rel: 'nofollow', href: getSortUrl(reverse) }
  1163. });
  1164. li.appendChild(a);
  1165. ul.appendChild(li);
  1166. });
  1167. $AEL(ul, 'click', e => {
  1168. if (e.target.matches('.gse-sort>a')) {
  1169. e.preventDefault();
  1170. const a = e.target;
  1171. const li = a.parentElement;
  1172. const reverse = !!+li.getAttribute('reverse');
  1173. sortByApiDefault(reverse);
  1174. buttonClicked(a);
  1175. setSortUrl(reverse);
  1176. }
  1177. }, { capture: true });
  1178.  
  1179. switch (sort) {
  1180. case 'gse_default':
  1181. sortByApiDefault(false);
  1182. buttonClicked($('.gse-sort[reverse="0"]>a'));
  1183. break;
  1184. case 'gse_reverse':
  1185. sortByApiDefault(true);
  1186. buttonClicked($('.gse-sort[reverse="1"]>a'));
  1187. break;
  1188. }
  1189.  
  1190. /**
  1191. * Sort <li>s in #browse-script-list by default api order
  1192. * Default api order is by add-to-set time right now (2024-07-21),
  1193. * but this is not a promising feature
  1194. */
  1195. function sortByApiDefault(reverse=false) {
  1196. const ol = $('#browse-script-list');
  1197. const li_scripts = Array.from(ol.children);
  1198. const set = CM.getConfig('script-sets').sets.find(set => set.id === set_id);
  1199. const scripts = set.scripts;
  1200. li_scripts.sort((li1, li2) => {
  1201. const [sid1, sid2] = [li1, li2].map(li => li.getAttribute('data-script-id'));
  1202. const [index1, index2] = [sid1, sid2].map(sid => scripts.indexOf(sid)).map(index => index >= 0 ? index : Infinity);
  1203.  
  1204. return (reverse ? [1, -1] : [-1, 1])[index1 > index2 ? 1 : 0];
  1205. });
  1206. //li_scripts.forEach(li => ol.removeChild(li));
  1207. li_scripts.forEach(li => ol.appendChild(li));
  1208. }
  1209.  
  1210. /**
  1211. * Change the clicked button gui to given one
  1212. */
  1213. function buttonClicked(a) {
  1214. const li = a.parentElement;
  1215. const ul = li.parentElement;
  1216. const old_li_current = Array.from(ul.children).find(li => li.classList.contains('list-current'));
  1217.  
  1218. li.classList.add('list-current');
  1219. a.remove();
  1220. li.innerText = a.innerText;
  1221.  
  1222. old_li_current.classList.remove('list-current');
  1223. const old_li_a = $$CrE({
  1224. tagName: 'a',
  1225. attrs: { href: location.pathname + location.search + location.hash },
  1226. props: { innerText: old_li_current.innerText }
  1227. });
  1228. old_li_current.innerText = '';
  1229. old_li_current.appendChild(old_li_a);
  1230. }
  1231.  
  1232. /**
  1233. * Set url search params when sorting
  1234. */
  1235. function setSortUrl(reverse) {
  1236. history.replaceState({}, '', getSortUrl(reverse));
  1237. }
  1238.  
  1239. /**
  1240. * Make corrent url search params with sorting
  1241. */
  1242. function getSortUrl(reverse) {
  1243. const search = new URLSearchParams(location.search);
  1244. search.set('sort', reverse ? 'gse_reverse' : 'gse_default');
  1245. const url = location.pathname + '?' + search.toString();
  1246. return url;
  1247. }
  1248. }
  1249. }
  1250. };
  1251.  
  1252. const oFuncs = Object.entries(functions).reduce((arr, [id, oFunc]) => {
  1253. oFunc.id = id;
  1254. arr.push(oFunc);
  1255. return arr;
  1256. }, []);
  1257. loadFuncs(oFuncs);
  1258. })();