Greasyfork script-set-edit button

Add / Remove script into / from script set directly in GF script info page

As of 2024-02-21. See the latest version.

  1. /* eslint-disable no-multi-spaces */
  2. /* eslint-disable no-return-assign */
  3.  
  4. // ==UserScript==
  5. // @name Greasyfork script-set-edit button
  6. // @name:zh-CN Greasyfork 快捷编辑收藏
  7. // @name:zh-TW Greasyfork 快捷編輯收藏
  8. // @name:en Greasyfork script-set-edit button
  9. // @name:en-US Greasyfork script-set-edit button
  10. // @name:fr Greasyfork Set Edit+
  11. // @namespace Greasyfork-Favorite
  12. // @version 0.2.5.1
  13. // @description Add / Remove script into / from script set directly in GF script info page
  14. // @description:zh-CN 在GF脚本页直接编辑收藏集
  15. // @description:zh-TW 在GF腳本頁直接編輯收藏集
  16. // @description:en Add / Remove script into / from script set directly in GF script info page
  17. // @description:en-US Add / Remove script into / from script set directly in GF script info page
  18. // @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
  19. // @author PY-DNG
  20. // @license GPL-3.0-or-later
  21. // @match http*://*.greatest.deepsurf.us/*
  22. // @match http*://*.sleazyfork.org/*
  23. // @match http*://greatest.deepsurf.us/*
  24. // @match http*://sleazyfork.org/*
  25. // @require https://update.greatest.deepsurf.us/scripts/456034/1303041/Basic%20Functions%20%28For%20userscripts%29.js
  26. // @require https://update.greatest.deepsurf.us/scripts/449583/1324274/ConfigManager.js
  27. // @require https://greatest.deepsurf.us/scripts/460385-gm-web-hooks/code/script.js?version=1221394
  28. // @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==
  29. // @grant GM_xmlhttpRequest
  30. // @grant GM_setValue
  31. // @grant GM_getValue
  32. // @grant GM_listValues
  33. // @grant GM_deleteValue
  34. // ==/UserScript==
  35.  
  36. /* global LogLevel DoLog Err $ $All $CrE $AEL $$CrE addStyle detectDom destroyEvent copyProp copyProps parseArgs escJsStr replaceText getUrlArgv dl_browser dl_GM AsyncManager */
  37. /* global GMXHRHook GMDLHook ConfigManager */
  38.  
  39. const GFScriptSetAPI = (function() {
  40. const API = {
  41. async getScriptSets() {
  42. const userpage = API.getUserpage();
  43. const oDom = await API.getDocument(userpage);
  44.  
  45. const list = Array.from($(oDom, 'ul#user-script-sets').children);
  46. const NoSets = list.length === 1 && list.every(li => li.children.length === 1);
  47. const script_sets = NoSets ? [] : Array.from($(oDom, 'ul#user-script-sets').children).filter(li => li.children.length === 2).map(li => {
  48. try {
  49. return {
  50. name: li.children[0].innerText,
  51. link: li.children[0].href,
  52. linkedit: li.children[1].href,
  53. id: getUrlArgv(li.children[0].href, 'set')
  54. }
  55. } catch(err) {
  56. DoLog(LogLevel.Error, [li, err, li.children.length, li.children[0]?.innerHTML, li.children[1]?.innerHTML], 'error');
  57. Err(err);
  58. }
  59. });
  60.  
  61. return script_sets;
  62. },
  63.  
  64. async getSetScripts(url) {
  65. return [...$All(await API.getDocument(url), '#script-set-scripts>input[name="scripts-included[]"]')].map(input => input.value);
  66. },
  67.  
  68. getUserpage() {
  69. const a = $('#nav-user-info>.user-profile-link>a');
  70. return a ? a.href : null;
  71. },
  72.  
  73. // editCallback recieves:
  74. // true: edit doc load success
  75. // false: already in set
  76. // finishCallback recieves:
  77. // text: successfully added to set with text tip `text`
  78. // true: successfully loaded document but no text tip found
  79. // false: xhr error
  80. addFav(url, sid, editCallback, finishCallback) {
  81. API.modifyFav(url, oDom => {
  82. const existingInput = [...$All(oDom, '#script-set-scripts>input[name="scripts-included[]"][type="hidden"]')].find(input => input.value === sid);
  83. if (existingInput) {
  84. editCallback(false);
  85. return false;
  86. }
  87.  
  88. const input = $CrE('input');
  89. input.value = sid;
  90. input.name = 'scripts-included[]';
  91. input.type = 'hidden';
  92. $(oDom, '#script-set-scripts').appendChild(input);
  93. editCallback(true);
  94. }, oDom => {
  95. const status = $(oDom, 'p.notice');
  96. const status_text = status ? status.innerText : true;
  97. finishCallback(status_text);
  98. }, err => finishCallback(false));
  99. },
  100.  
  101. // editCallback recieves:
  102. // true: edit doc load success
  103. // false: already not in set
  104. // finishCallback recieves:
  105. // text: successfully removed from set with text tip `text`
  106. // true: successfully loaded document but no text tip found
  107. // false: xhr error
  108. removeFav(url, sid, editCallback, finishCallback) {
  109. API.modifyFav(url, oDom => {
  110. const existingInput = [...$All(oDom, '#script-set-scripts>input[name="scripts-included[]"][type="hidden"]')].find(input => input.value === sid);
  111. if (!existingInput) {
  112. editCallback(false);
  113. return false;
  114. }
  115.  
  116. existingInput.remove();
  117. editCallback(true);
  118. }, oDom => {
  119. const status = $(oDom, 'p.notice');
  120. const status_text = status ? status.innerText : true;
  121. finishCallback(status_text);
  122. }, err => finishCallback(false));
  123. },
  124.  
  125. async modifyFav(url, editCallback, finishCallback, onerror) {
  126. const oDom = await API.getDocument(url);
  127. if (editCallback(oDom) === false) { return false; }
  128.  
  129. const form = $(oDom, '.change-script-set');
  130. const data = new FormData(form);
  131. data.append('save', '1');
  132.  
  133. // Use XMLHttpRequest insteadof GM_xmlhttpRequest because there's unknown issue with GM_xmlhttpRequest
  134. // Use XMLHttpRequest insteadof GM_xmlhttpRequest before Tampermonkey 5.0.0 because of FormData posting issues
  135. if (true || GM_info.scriptHandler === 'Tampermonkey' && !API.GM_hasVersion('5.0')) {
  136. const xhr = new XMLHttpRequest();
  137. xhr.open('POST', API.toAbsoluteURL(form.getAttribute('action')));
  138. xhr.responseType = 'blob';
  139. xhr.onload = async e => finishCallback(await API.parseDocument(xhr.response));
  140. xhr.onerror = onerror;
  141. xhr.send(data);
  142. } else {
  143. GM_xmlhttpRequest({
  144. method: 'POST',
  145. url: API.toAbsoluteURL(form.getAttribute('action')),
  146. data,
  147. responseType: 'blob',
  148. onload: async response => finishCallback(await API.parseDocument(response.response)),
  149. onerror
  150. });
  151. }
  152. },
  153.  
  154. // Download and parse a url page into a html document(dom).
  155. // Returns a promise fulfills with dom
  156. getDocument(url, retry=5) {
  157. return new Promise((resolve, reject) => {
  158. GM_xmlhttpRequest({
  159. method : 'GET',
  160. url : url,
  161. responseType : 'blob',
  162. onload : function(response) {
  163. if (response.status === 200) {
  164. const htmlblob = response.response;
  165. API.parseDocument(htmlblob).then(resolve).catch(reject);
  166. } else {
  167. re(response);
  168. }
  169. },
  170. onerror: err => re(err)
  171. });
  172.  
  173. function re(err) {
  174. DoLog(`Get document failed, retrying: (${retry}) ${url}`);
  175. --retry > 0 ? API.getDocument(url, retry).then(resolve).catch(reject) : reject(err);
  176. }
  177. });
  178. },
  179.  
  180. // Returns a promise fulfills with dom
  181. parseDocument(htmlblob) {
  182. return new Promise((resolve, reject) => {
  183. const reader = new FileReader();
  184. reader.onload = function(e) {
  185. const htmlText = reader.result;
  186. const dom = new DOMParser().parseFromString(htmlText, 'text/html');
  187. resolve(dom);
  188. }
  189. reader.onerror = err => reject(err);
  190. reader.readAsText(htmlblob, document.characterSet);
  191. });
  192. },
  193.  
  194. toAbsoluteURL(relativeURL, base=`${location.protocol}//${location.host}/`) {
  195. return new URL(relativeURL, base).href;
  196. },
  197.  
  198. GM_hasVersion(version) {
  199. return hasVersion(GM_info?.version || '0', version);
  200.  
  201. function hasVersion(ver1, ver2) {
  202. return compareVersions(ver1.toString(), ver2.toString()) >= 0;
  203.  
  204. // https://greatest.deepsurf.us/app/javascript/versioncheck.js
  205. // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version/format
  206. function compareVersions(a, b) {
  207. if (a == b) {
  208. return 0;
  209. }
  210. let aParts = a.split('.');
  211. let bParts = b.split('.');
  212. for (let i = 0; i < aParts.length; i++) {
  213. let result = compareVersionPart(aParts[i], bParts[i]);
  214. if (result != 0) {
  215. return result;
  216. }
  217. }
  218. // If all of a's parts are the same as b's parts, but b has additional parts, b is greater.
  219. if (bParts.length > aParts.length) {
  220. return -1;
  221. }
  222. return 0;
  223. }
  224.  
  225. function compareVersionPart(partA, partB) {
  226. let partAParts = parseVersionPart(partA);
  227. let partBParts = parseVersionPart(partB);
  228. for (let i = 0; i < partAParts.length; i++) {
  229. // "A string-part that exists is always less than a string-part that doesn't exist"
  230. if (partAParts[i].length > 0 && partBParts[i].length == 0) {
  231. return -1;
  232. }
  233. if (partAParts[i].length == 0 && partBParts[i].length > 0) {
  234. return 1;
  235. }
  236. if (partAParts[i] > partBParts[i]) {
  237. return 1;
  238. }
  239. if (partAParts[i] < partBParts[i]) {
  240. return -1;
  241. }
  242. }
  243. return 0;
  244. }
  245.  
  246. // It goes number, string, number, string. If it doesn't exist, then
  247. // 0 for numbers, empty string for strings.
  248. function parseVersionPart(part) {
  249. if (!part) {
  250. return [0, "", 0, ""];
  251. }
  252. let partParts = /([0-9]*)([^0-9]*)([0-9]*)([^0-9]*)/.exec(part)
  253. return [
  254. partParts[1] ? parseInt(partParts[1]) : 0,
  255. partParts[2],
  256. partParts[3] ? parseInt(partParts[3]) : 0,
  257. partParts[4]
  258. ];
  259. }
  260. }
  261. }
  262. };
  263.  
  264. return API;
  265. }) ();
  266.  
  267. (function __MAIN__() {
  268. 'use strict';
  269.  
  270. const CONST = {
  271. Text: {
  272. 'zh-CN': {
  273. FavEdit: '收藏集:',
  274. Add: '加入此集',
  275. Remove: '移出此集',
  276. Edit: '手动编辑',
  277. EditIframe: '页内编辑',
  278. CloseIframe: '关闭编辑',
  279. CopySID: '复制脚本ID',
  280. Sync: '同步',
  281. NotLoggedIn: '请先登录Greasyfork',
  282. NoSetsYet: '您还没有创建过收藏集',
  283. NewSet: '新建收藏集',
  284. Working: ['工作中...', '就快好了...'],
  285. InSetStatus: ['[ ]', '[✔]'],
  286. Groups: {
  287. Server: 'GreasyFork收藏集',
  288. Local: '本地收藏集',
  289. New: '新建'
  290. },
  291. Refreshing: {
  292. List: '获取收藏集列表...',
  293. Script: '获取收藏集内容...'
  294. },
  295. Error: {
  296. AlreadyExist: '脚本已经在此收藏集中了',
  297. NotExist: '脚本不在此收藏集中',
  298. NetworkError: '网络错误',
  299. Unknown: '未知错误'
  300. }
  301. },
  302. 'zh-TW': {
  303. FavEdit: '收藏集:',
  304. Add: '加入此集',
  305. Remove: '移出此集',
  306. Edit: '手動編輯',
  307. EditIframe: '頁內編輯',
  308. CloseIframe: '關閉編輯',
  309. CopySID: '複製腳本ID',
  310. Sync: '同步',
  311. NotLoggedIn: '請先登錄Greasyfork',
  312. NoSetsYet: '您還沒有創建過收藏集',
  313. NewSet: '新建收藏集',
  314. Working: ['工作中...', '就快好了...'],
  315. InSetStatus: ['[ ]', '[✔]'],
  316. Groups: {
  317. Server: 'GreasyFork收藏集',
  318. Local: '本地收藏集',
  319. New: '新建'
  320. },
  321. Refreshing: {
  322. List: '獲取收藏集清單...',
  323. Script: '獲取收藏集內容...'
  324. },
  325. Error: {
  326. AlreadyExist: '腳本已經在此收藏集中了',
  327. NotExist: '腳本不在此收藏集中',
  328. NetworkError: '網絡錯誤',
  329. Unknown: '未知錯誤'
  330. }
  331. },
  332. 'en': {
  333. FavEdit: 'Script set: ',
  334. Add: 'Add',
  335. Remove: 'Remove',
  336. Edit: 'Edit Manually',
  337. EditIframe: 'In-Page Edit',
  338. CloseIframe: 'Close Editor',
  339. CopySID: 'Copy Script-ID',
  340. Sync: 'Sync',
  341. NotLoggedIn: 'Login to greasyfork to use script sets',
  342. NoSetsYet: 'You haven\'t created a collection yet',
  343. NewSet: 'Create a new set',
  344. Working: ['Working...', 'Just a moment...'],
  345. InSetStatus: ['[ ]', '[✔]'],
  346. Groups: {
  347. Server: 'GreasyFork',
  348. Local: 'Local',
  349. New: 'New'
  350. },
  351. Refreshing: {
  352. List: 'Fetching script sets...',
  353. Script: 'Fetching set content...'
  354. },
  355. Error: {
  356. AlreadyExist: 'Script is already in set',
  357. NotExist: 'Script is not in set yet',
  358. NetworkError: 'Network Error',
  359. Unknown: 'Unknown Error'
  360. }
  361. },
  362. 'default': {
  363. FavEdit: 'Script set: ',
  364. Add: 'Add',
  365. Remove: 'Remove',
  366. Edit: 'Edit Manually',
  367. EditIframe: 'In-Page Edit',
  368. CloseIframe: 'Close Editor',
  369. CopySID: 'Copy Script-ID',
  370. Sync: 'Sync',
  371. NotLoggedIn: 'Login to greasyfork to use script sets',
  372. NoSetsYet: 'You haven\'t created a collection yet',
  373. NewSet: 'Create a new set',
  374. Working: ['Working...', 'Just a moment...'],
  375. InSetStatus: ['[ ]', '[✔]'],
  376. Groups: {
  377. Server: 'GreasyFork',
  378. Local: 'Local',
  379. New: 'New'
  380. },
  381. Refreshing: {
  382. List: 'Fetching script sets...',
  383. Script: 'Fetching set content...'
  384. },
  385. Error: {
  386. AlreadyExist: 'Script is already in set',
  387. NotExist: 'Script is not in set yet',
  388. NetworkError: 'Network Error',
  389. Unknown: 'Unknown Error'
  390. }
  391. },
  392. },
  393. ConfigRule: {
  394. 'version-key': 'config-version',
  395. ignores: [],
  396. defaultValues: {
  397. 'script-sets': {
  398. sets: [],
  399. time: 0,
  400. 'config-version': 1,
  401. },
  402. },
  403. 'updaters': {
  404. /*'config-key': [
  405. function() {
  406. // This function contains updater for config['config-key'] from v0 to v1
  407. },
  408. function() {
  409. // This function contains updater for config['config-key'] from v1 to v2
  410. }
  411. ]*/
  412. 'script-sets': [
  413. config => {
  414. // Fill set.id
  415. const sets = config.sets;
  416. sets.forEach(set => {
  417. const id = getUrlArgv(set.link, 'set');
  418. set.id = id;
  419. set.scripts = null; // After first refresh, it should be an array of SIDs:string
  420. });
  421.  
  422. // Delete old version identifier
  423. delete config.version;
  424.  
  425. return config;
  426. }
  427. ]
  428. },
  429. }
  430. };
  431.  
  432. // Get i18n code
  433. let i18n = $('#language-selector-locale') ? $('#language-selector-locale').value : navigator.language;
  434. if (!Object.keys(CONST.Text).includes(i18n)) {i18n = 'default';}
  435.  
  436. const CM = new ConfigManager(CONST.ConfigRule);
  437. const CONFIG = CM.Config;
  438. CM.updateAllConfigs();
  439.  
  440. loadFuncs([{
  441. name: 'Hook GM_xmlhttpRequest',
  442. checker: {
  443. type: 'switch',
  444. value: true
  445. },
  446. func: () => GMXHRHook(5)
  447. }, {
  448. name: 'Favorite panel',
  449. checker: {
  450. type: 'func',
  451. value: () => {
  452. const path = location.pathname.split('/').filter(p=>p);
  453. const index = path.indexOf('scripts');
  454. return [0,1].includes(index) && [undefined, 'code', 'feedback'].includes(path[index+2])
  455. }
  456. },
  457. func: addFavPanel
  458. }]);
  459.  
  460. function addFavPanel() {
  461. //if (!GFScriptSetAPI.getUserpage()) {return false;}
  462.  
  463. class FavoritePanel {
  464. #CM;
  465. #sid;
  466. #sets;
  467. #elements;
  468. #disabled;
  469.  
  470. constructor(CM) {
  471. this.#CM = CM;
  472. this.#sid = location.pathname.match(/scripts\/(\d+)/)[1];
  473. this.#sets = this.#CM.getConfig('script-sets').sets;
  474. this.#elements = {};
  475. this.disabled = false;
  476.  
  477. const script_after = $('#script-feedback-suggestion+*') || $('#new-script-discussion');
  478. const script_parent = script_after.parentElement;
  479.  
  480. // Container
  481. const script_favorite = this.#elements.container = $$CrE({
  482. tagName: 'div',
  483. props: {
  484. id: 'script-favorite',
  485. innerHTML: CONST.Text[i18n].FavEdit
  486. },
  487. styles: { margin: '0.75em 0' }
  488. });
  489.  
  490. // Selecter
  491. const favorite_groups = this.#elements.select = $$CrE({
  492. tagName: 'select',
  493. props: { id: 'favorite-groups' },
  494. styles: { maxWidth: '40vw' },
  495. listeners: [['change', (() => {
  496. let lastSelected = 0;
  497. const record = () => lastSelected = favorite_groups.selectedIndex;
  498. const recover = () => favorite_groups.selectedIndex = lastSelected;
  499.  
  500. return e => {
  501. const value = favorite_groups.value;
  502. const type = /^\d+$/.test(value) ? 'set-id' : 'command';
  503.  
  504. switch (type) {
  505. case 'set-id': {
  506. const set = this.#sets.find(set => set.id === favorite_groups.value);
  507. favorite_edit.href = set.linkedit;
  508. break;
  509. }
  510. case 'command': {
  511. recover();
  512. this.#execCommand(value);
  513. }
  514. }
  515.  
  516. this.#refreshButtonDisplay();
  517. record();
  518. }
  519. }) ()]]
  520. });
  521. favorite_groups.id = 'favorite-groups';
  522.  
  523. // Buttons
  524. const makeBtn = (id, innerHTML, onClick, isLink=false) => $$CrE({
  525. tagName: 'a',
  526. props: {
  527. id, innerHTML,
  528. [isLink ? 'target' : 'href']: isLink ? '_blank' : 'javascript:void(0);'
  529. },
  530. styles: { margin: '0px 0.5em' },
  531. listeners: [['click', onClick]]
  532. });
  533.  
  534. const favorite_add = this.#elements.btnAdd = makeBtn('favorite-add', CONST.Text[i18n].Add, e => this.#addFav());
  535. const favorite_remove = this.#elements.btnRemove = makeBtn('favorite-remove', CONST.Text[i18n].Remove, e => this.#removeFav());
  536. const favorite_edit = this.#elements.btnEdit = makeBtn('favorite-edit', CONST.Text[i18n].Edit, e => {}, true);
  537. const favorite_iframe = this.#elements.btnIframe = makeBtn('favorite-edit-in-page', CONST.Text[i18n].EditIframe, e => this.#editInPage(e));
  538. const favorite_copy = this.#elements.btnCopy = makeBtn('favorite-add', CONST.Text[i18n].CopySID, e => copyText(this.#sid));
  539. const favorite_sync = this.#elements.btnSync = makeBtn('favorite-sync', CONST.Text[i18n].Sync, e => this.#refresh());
  540.  
  541. script_favorite.appendChild(favorite_groups);
  542. script_after.before(script_favorite);
  543. [favorite_add, favorite_remove, favorite_edit, favorite_iframe, favorite_copy, favorite_sync].forEach(button => script_favorite.appendChild(button));
  544.  
  545. // Text tip
  546. const tip = this.#elements.tip = $CrE('span');
  547. script_favorite.appendChild(tip);
  548.  
  549. // Display cached sets first
  550. this.#displaySets();
  551.  
  552. // Request GF document to update sets
  553. this.#refresh();
  554. }
  555.  
  556. get sid() {
  557. return this.#sid;
  558. }
  559.  
  560. get sets() {
  561. return FavoritePanel.#deepClone(this.#sets);
  562. }
  563.  
  564. get elements() {
  565. return FavoritePanel.#lightClone(this.#elements);
  566. }
  567.  
  568. // Request document: get sets list and
  569. async #refresh() {
  570. this.#disable();
  571. this.#tip(CONST.Text[i18n].Refreshing.List);
  572.  
  573. // Check login status
  574. if (!GFScriptSetAPI.getUserpage()) {
  575. this.#tip(CONST.Text[i18n].NotLoggedIn);
  576. return;
  577. }
  578.  
  579. // Refresh sets list
  580. this.#sets = CONFIG['script-sets'].sets = await GFScriptSetAPI.getScriptSets();
  581. this.#displaySets();
  582.  
  583. // Refresh each set's script list
  584. this.#tip(CONST.Text[i18n].Refreshing.Script);
  585. await Promise.all(this.#sets.map(async set => {
  586. // Fetch scripts
  587. set.scripts = await GFScriptSetAPI.getSetScripts(set.linkedit);
  588. this.#displaySets();
  589.  
  590. // Save to GM_storage
  591. const setIndex = CONFIG['script-sets'].sets.findIndex(s => s.id === set.id);
  592. CONFIG['script-sets'].sets[setIndex].scripts = set.scripts;
  593. }));
  594.  
  595. this.#tip();
  596. this.#enable();
  597. this.#refreshButtonDisplay();
  598. }
  599.  
  600. #addFav() {
  601. const set = this.#getCurrentSet();
  602. const option = set.elmOption;
  603.  
  604. this.#displayNotice(CONST.Text[i18n].Working[0]);
  605. GFScriptSetAPI.addFav(this.#getCurrentSet().linkedit, this.#sid, editStatus => {
  606. if (!editStatus) {
  607. this.#displayNotice(CONST.Text[i18n].Error.AlreadyExist);
  608. option.innerText = `${CONST.Text[i18n].InSetStatus[1]} ${set.name}`;
  609. } else {
  610. this.#displayNotice(CONST.Text[i18n].Working[1]);
  611. }
  612. }, finishStatus => {
  613. if (finishStatus) {
  614. // Save to this.#sets and GM_storage
  615. const setIndex = CONFIG['script-sets'].sets.findIndex(s => s.id === set.id);
  616. CONFIG['script-sets'].sets[setIndex].scripts.push(this.#sid);
  617. this.#sets = CM.getConfig('script-sets').sets;
  618.  
  619. // Display
  620. this.#displayNotice(typeof finishStatus === 'string' ? finishStatus : CONST.Text[i18n].Error.Unknown);
  621. set.elmOption.innerText = `${CONST.Text[i18n].InSetStatus[1]} ${set.name}`;
  622. this.#displaySets();
  623. } else {
  624. this.#displayNotice(CONST.Text[i18n].Error.NetworkError);
  625. }
  626. });
  627. }
  628.  
  629. #removeFav() {
  630. const set = this.#getCurrentSet();
  631. const option = set.elmOption;
  632.  
  633. this.#displayNotice(CONST.Text[i18n].Working[0]);
  634. GFScriptSetAPI.removeFav(this.#getCurrentSet().linkedit, this.#sid, editStatus => {
  635. if (!editStatus) {
  636. this.#displayNotice(CONST.Text[i18n].Error.NotExist);
  637. option.innerText = `${CONST.Text[i18n].InSetStatus[0]} ${set.name}`;
  638. } else {
  639. this.#displayNotice(CONST.Text[i18n].Working[1]);
  640. }
  641. }, finishStatus => {
  642. if (finishStatus) {
  643. // Save to this.#sets and GM_storage
  644. const setIndex = CONFIG['script-sets'].sets.findIndex(s => s.id === set.id);
  645. const scriptIndex = CONFIG['script-sets'].sets[setIndex].scripts.indexOf(this.#sid);
  646. CONFIG['script-sets'].sets[setIndex].scripts.splice(scriptIndex, 1);
  647. this.#sets = CM.getConfig('script-sets').sets;
  648.  
  649. // Display
  650. this.#displayNotice(typeof finishStatus === 'string' ? finishStatus : CONST.Text[i18n].Error.Unknown);
  651. set.elmOption.innerText = `${CONST.Text[i18n].InSetStatus[0]} ${set.name}`;
  652. this.#displaySets();
  653. } else {
  654. this.#displayNotice(CONST.Text[i18n].Error.NetworkError);
  655. }
  656. });
  657. }
  658.  
  659. #editInPage(e) {
  660. e.preventDefault();
  661.  
  662. const _iframes = [...$All(this.#elements.container, '.script-edit-page')];
  663. if (_iframes.length) {
  664. // Iframe exists, close iframe
  665. this.#elements.btnIframe.innerText = CONST.Text[i18n].EditIframe;
  666. _iframes.forEach(ifr => ifr.remove());
  667. this.#refresh();
  668. } else {
  669. // Iframe not exist, make iframe
  670. this.#elements.btnIframe.innerText = CONST.Text[i18n].CloseIframe;
  671.  
  672. const iframe = $$CrE({
  673. tagName: 'iframe',
  674. props: {
  675. src: this.#getCurrentSet().linkedit
  676. },
  677. styles: {
  678. width: '100%',
  679. height: '60vh'
  680. },
  681. classes: ['script-edit-page'],
  682. listeners: [['load', e => {
  683. //this.#refresh();
  684. //iframe.style.height = iframe.contentDocument.body.parentElement.offsetHeight + 'px';
  685. }]]
  686. });
  687. this.#elements.container.appendChild(iframe);
  688. }
  689. }
  690.  
  691. #displayNotice(text) {
  692. const notice = $CrE('p');
  693. notice.classList.add('notice');
  694. notice.id = 'fav-notice';
  695. notice.innerText = text;
  696. const old_notice = $('#fav-notice');
  697. old_notice && old_notice.parentElement.removeChild(old_notice);
  698. $('#script-content').insertAdjacentElement('afterbegin', notice);
  699. }
  700.  
  701. #tip(text='', timeout=0) {
  702. this.#elements.tip.innerText = text;
  703. timeout > 0 && setTimeout(() => this.#elements.tip.innerText = '', timeout);
  704. }
  705.  
  706. // Apply this.#sets to gui
  707. #displaySets() {
  708. const elements = this.#elements;
  709.  
  710. // Save selected set
  711. const old_value = elements.select.value;
  712. [...elements.select.children].forEach(child => child.remove());
  713.  
  714. // Make <optgroup>s and <option>s
  715. const serverGroup = elements.serverGroup = $$CrE({ tagName: 'optgroup', attrs: { label: CONST.Text[i18n].Groups.Server } });
  716. this.#sets.forEach(set => {
  717. // Create <option>
  718. set.elmOption = $$CrE({
  719. tagName: 'option',
  720. props: {
  721. innerText: set.name,
  722. value: set.id
  723. }
  724. });
  725. // Display inset status
  726. if (set.scripts) {
  727. const inSet = set.scripts.includes(this.#sid);
  728. set.elmOption.innerText = `${CONST.Text[i18n].InSetStatus[inSet+0]} ${set.name}`;
  729. }
  730. // Append <option> into <select>
  731. serverGroup.appendChild(set.elmOption);
  732. });
  733. if (this.#sets.length === 0) {
  734. const optEmpty = elements.optEmpty = $$CrE({
  735. tagName: 'option',
  736. props: {
  737. innerText: CONST.Text[i18n].NoSetsYet,
  738. value: 'empty',
  739. selected: true
  740. }
  741. });
  742. serverGroup.appendChild(optEmpty);
  743. }
  744.  
  745. const newGroup = elements.newGroup = $$CrE({ tagName: 'optgroup', attrs: { label: CONST.Text[i18n].Groups.New } });
  746. const newSet = elements.newSet = $$CrE({
  747. tagName: 'option',
  748. props: {
  749. innerText: CONST.Text[i18n].NewSet,
  750. value: 'new',
  751. }
  752. });
  753. newGroup.appendChild(newSet);
  754. [serverGroup, newGroup].forEach(optgroup => elements.select.appendChild(optgroup));
  755.  
  756. // Adjust <select> width
  757. elements.select.style.width = Math.max.apply(null, Array.from($All(elements.select, 'option')).map(o => o.innerText.length)).toString() + 'em';
  758.  
  759. // Select previous selected set's <option>
  760. const selected = old_value ? [...$All(elements.select, 'option')].find(option => option.value === old_value) : null;
  761. selected && (selected.selected = true);
  762.  
  763. // Set edit-button.href
  764. if (elements.select.value !== 'empty') {
  765. const curset = this.#sets.find(set => set.id === elements.select.value);
  766. elements.btnEdit.href = curset.linkedit;
  767. }
  768.  
  769. // Display correct button
  770. this.#refreshButtonDisplay();
  771. }
  772.  
  773. // Display only add button when script in current set, otherwise remove button
  774. // Disable set-related buttons when not selecting options that not represents a set
  775. #refreshButtonDisplay() {
  776. const set = this.#getCurrentSet();
  777. !this.#disabled && ([this.#elements.btnAdd, this.#elements.btnRemove, this.#elements.btnEdit, this.#elements.btnIframe]
  778. .forEach(element => set ? FavoritePanel.#enableElement(element) : FavoritePanel.#disableElement(element)));
  779. if (!set || !set.scripts) { return null; }
  780. if (set.scripts.includes(this.#sid)) {
  781. this.#elements.btnAdd.style.setProperty('display', 'none');
  782. this.#elements.btnRemove.style.removeProperty('display');
  783. return true;
  784. } else {
  785. this.#elements.btnRemove.style.setProperty('display', 'none');
  786. this.#elements.btnAdd.style.removeProperty('display');
  787. return false;
  788. }
  789. }
  790.  
  791. #execCommand(command) {
  792. switch (command) {
  793. case 'new': {
  794. const url = GFScriptSetAPI.getUserpage() + (this.#getCurrentSet() ? '/sets/new' : '/sets/new?fav=1');
  795. window.open(url);
  796. break;
  797. }
  798. case 'empty': {
  799. // Do nothing
  800. break;
  801. }
  802. }
  803. }
  804.  
  805. // Returns null if no <option>s yet
  806. #getCurrentSet() {
  807. return this.#sets.find(set => set.id === this.#elements.select.value) || null;
  808. }
  809.  
  810. #disable() {
  811. [
  812. this.#elements.select,
  813. this.#elements.btnAdd, this.#elements.btnRemove,
  814. this.#elements.btnEdit, this.#elements.btnIframe,
  815. this.#elements.btnCopy, this.#elements.btnSync
  816. ].forEach(element => FavoritePanel.#disableElement(element));
  817. this.#disabled = true;
  818. }
  819.  
  820. #enable() {
  821. [
  822. this.#elements.select,
  823. this.#elements.btnAdd, this.#elements.btnRemove,
  824. this.#elements.btnEdit, this.#elements.btnIframe,
  825. this.#elements.btnCopy, this.#elements.btnSync
  826. ].forEach(element => FavoritePanel.#enableElement(element));
  827. this.#disabled = false;
  828. }
  829.  
  830. static #disableElement(element) {
  831. element.style.filter = 'grayscale(1) brightness(0.95)';
  832. element.style.opacity = '0.25';
  833. element.style.pointerEvents = 'none';
  834. element.tabIndex = -1;
  835. }
  836.  
  837. static #enableElement(element) {
  838. element.style.removeProperty('filter');
  839. element.style.removeProperty('opacity');
  840. element.style.removeProperty('pointer-events');
  841. element.tabIndex = 0;
  842. }
  843.  
  844. static #deepClone(val) {
  845. if (typeof structuredClone === 'function') {
  846. return structuredClone(val);
  847. } else {
  848. return JSON.parse(JSON.stringify(val));
  849. }
  850. }
  851.  
  852. static #lightClone(val) {
  853. if (['string', 'number', 'boolean', 'undefined', 'bigint', 'symbol', 'function'].includes(val) || val === null) {
  854. return val;
  855. }
  856. if (Array.isArray(val)) {
  857. return val.slice();
  858. }
  859. if (typeof val === 'object') {
  860. return Object.fromEntries(Object.entries(val));
  861. }
  862. }
  863. }
  864.  
  865. const panel = new FavoritePanel(CM);
  866. }
  867.  
  868. // Basic functions
  869.  
  870. // Copy text to clipboard (needs to be called in an user event)
  871. function copyText(text) {
  872. // Create a new textarea for copying
  873. const newInput = document.createElement('textarea');
  874. document.body.appendChild(newInput);
  875. newInput.value = text;
  876. newInput.select();
  877. document.execCommand('copy');
  878. document.body.removeChild(newInput);
  879. }
  880.  
  881. // Check whether current page url matches FuncInfo.checker rule
  882. // This code is copy and modified from FunctionLoader.check
  883. function testChecker(checker) {
  884. if (!checker) {return true;}
  885. const values = Array.isArray(checker.value) ? checker.value : [checker.value]
  886. return values.some(value => {
  887. switch (checker.type) {
  888. case 'regurl': {
  889. return !!location.href.match(value);
  890. }
  891. case 'func': {
  892. try {
  893. return value();
  894. } catch (err) {
  895. DoLog(LogLevel.Error, CONST.Text.Loader.CheckerError);
  896. DoLog(LogLevel.Error, err);
  897. return false;
  898. }
  899. }
  900. case 'switch': {
  901. return value;
  902. }
  903. case 'starturl': {
  904. return location.href.startsWith(value);
  905. }
  906. case 'startpath': {
  907. return location.pathname.startsWith(value);
  908. }
  909. default: {
  910. DoLog(LogLevel.Error, CONST.Text.Loader.CheckerInvalid);
  911. return false;
  912. }
  913. }
  914. });
  915. }
  916.  
  917. // Load all function-objs provided in funcs asynchronously, and merge return values into one return obj
  918. // funcobj: {[checker], [detectDom], func}
  919. function loadFuncs(oFuncs) {
  920. const returnObj = {};
  921.  
  922. oFuncs.forEach(oFunc => {
  923. if (!oFunc.checker || testChecker(oFunc.checker)) {
  924. if (oFunc.detectDom) {
  925. detectDom(oFunc.detectDom, e => execute(oFunc));
  926. } else {
  927. setTimeout(e => execute(oFunc), 0);
  928. }
  929. }
  930. });
  931.  
  932. return returnObj;
  933.  
  934. function execute(oFunc) {
  935. setTimeout(e => {
  936. const rval = oFunc.func(returnObj) || {};
  937. copyProps(rval, returnObj);
  938. }, 0);
  939. }
  940. }
  941.  
  942. function randint(min, max) {
  943. return Math.floor(Math.random() * (max - min + 1)) + min;
  944. }
  945. })();