Greasyfork 快捷编辑收藏

在GF脚本页直接编辑收藏集

目前为 2024-02-21 提交的版本。查看 最新版本

  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
  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*://*.greasyfork.org/*
  22. // @match http*://*.sleazyfork.org/*
  23. // @match http*://greasyfork.org/*
  24. // @match http*://sleazyfork.org/*
  25. // @require https://update.greasyfork.org/scripts/456034/1303041/Basic%20Functions%20%28For%20userscripts%29.js
  26. // @require https://update.greasyfork.org/scripts/449583/1324274/ConfigManager.js
  27. // @require https://greasyfork.org/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://greasyfork.org/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.  
  469. constructor(CM) {
  470. this.#CM = CM;
  471. this.#sid = location.pathname.match(/scripts\/(\d+)/)[1];
  472. this.#sets = this.#CM.getConfig('script-sets').sets;
  473. this.#elements = {};
  474.  
  475. const script_after = $('#script-feedback-suggestion+*') || $('#new-script-discussion');
  476. const script_parent = script_after.parentElement;
  477.  
  478. // Container
  479. const script_favorite = this.#elements.container = $$CrE({
  480. tagName: 'div',
  481. props: {
  482. id: 'script-favorite',
  483. innerHTML: CONST.Text[i18n].FavEdit
  484. },
  485. styles: { margin: '0.75em 0' }
  486. });
  487.  
  488. // Selecter
  489. const favorite_groups = this.#elements.select = $$CrE({
  490. tagName: 'select',
  491. props: { id: 'favorite-groups' },
  492. styles: { maxWidth: '40vw' },
  493. listeners: [['change', (() => {
  494. let lastSelected = 0;
  495. const record = () => lastSelected = favorite_groups.selectedIndex;
  496. const recover = () => favorite_groups.selectedIndex = lastSelected;
  497.  
  498. return e => {
  499. const value = favorite_groups.value;
  500. const type = /^\d+$/.test(value) ? 'set-id' : 'command';
  501.  
  502. switch (type) {
  503. case 'set-id': {
  504. const set = this.#sets.find(set => set.id === favorite_groups.value);
  505. favorite_edit.href = set.linkedit;
  506. break;
  507. }
  508. case 'command': {
  509. recover();
  510. this.#execCommand(value);
  511. }
  512. }
  513.  
  514. this.#refreshButtonDisplay();
  515. record();
  516. }
  517. }) ()]]
  518. });
  519. favorite_groups.id = 'favorite-groups';
  520.  
  521. // Buttons
  522. const makeBtn = (id, innerHTML, onClick, isLink=false) => $$CrE({
  523. tagName: 'a',
  524. props: {
  525. id, innerHTML,
  526. [isLink ? 'target' : 'href']: isLink ? '_blank' : 'javascript:void(0);'
  527. },
  528. styles: { margin: '0px 0.5em' },
  529. listeners: [['click', onClick]]
  530. });
  531.  
  532. const favorite_add = this.#elements.btnAdd = makeBtn('favorite-add', CONST.Text[i18n].Add, e => this.#addFav());
  533. const favorite_remove = this.#elements.btnRemove = makeBtn('favorite-remove', CONST.Text[i18n].Remove, e => this.#removeFav());
  534. const favorite_edit = this.#elements.btnEdit = makeBtn('favorite-edit', CONST.Text[i18n].Edit, e => {}, true);
  535. const favorite_iframe = this.#elements.btnIframe = makeBtn('favorite-edit-in-page', CONST.Text[i18n].EditIframe, e => this.#editInPage(e));
  536. const favorite_copy = this.#elements.btnCopy = makeBtn('favorite-add', CONST.Text[i18n].CopySID, e => copyText(this.#sid));
  537. const favorite_sync = this.#elements.btnSync = makeBtn('favorite-sync', CONST.Text[i18n].Sync, e => this.#refresh());
  538.  
  539. script_favorite.appendChild(favorite_groups);
  540. script_after.before(script_favorite);
  541. [favorite_add, favorite_remove, favorite_edit, favorite_iframe, favorite_copy, favorite_sync].forEach(button => script_favorite.appendChild(button));
  542.  
  543. // Text tip
  544. const tip = this.#elements.tip = $CrE('span');
  545. script_favorite.appendChild(tip);
  546.  
  547. // Display cached sets first
  548. this.#displaySets();
  549.  
  550. // Request GF document to update sets
  551. this.#refresh();
  552. }
  553.  
  554. get sid() {
  555. return this.#sid;
  556. }
  557.  
  558. get sets() {
  559. return FavoritePanel.#deepClone(this.#sets);
  560. }
  561.  
  562. get elements() {
  563. return FavoritePanel.#lightClone(this.#elements);
  564. }
  565.  
  566. // Request document: get sets list and
  567. async #refresh() {
  568. this.#disable();
  569. this.#tip(CONST.Text[i18n].Refreshing.List);
  570.  
  571. // Check login status
  572. if (!GFScriptSetAPI.getUserpage()) {
  573. this.#tip(CONST.Text[i18n].NotLoggedIn);
  574. return;
  575. }
  576.  
  577. // Refresh sets list
  578. this.#sets = CONFIG['script-sets'].sets = await GFScriptSetAPI.getScriptSets();
  579. this.#displaySets();
  580.  
  581. // Refresh each set's script list
  582. this.#tip(CONST.Text[i18n].Refreshing.Script);
  583. await Promise.all(this.#sets.map(async set => {
  584. // Fetch scripts
  585. set.scripts = await GFScriptSetAPI.getSetScripts(set.linkedit);
  586. this.#displaySets();
  587.  
  588. // Save to GM_storage
  589. const setIndex = CONFIG['script-sets'].sets.findIndex(s => s.id === set.id);
  590. CONFIG['script-sets'].sets[setIndex].scripts = set.scripts;
  591. }));
  592.  
  593. this.#tip();
  594. this.#enable();
  595. this.#refreshButtonDisplay();
  596. }
  597.  
  598. #addFav() {
  599. const set = this.#getCurrentSet();
  600. const option = set.elmOption;
  601.  
  602. this.#displayNotice(CONST.Text[i18n].Working[0]);
  603. GFScriptSetAPI.addFav(this.#getCurrentSet().linkedit, this.#sid, editStatus => {
  604. if (!editStatus) {
  605. this.#displayNotice(CONST.Text[i18n].Error.AlreadyExist);
  606. option.innerText = `${CONST.Text[i18n].InSetStatus[1]} ${set.name}`;
  607. } else {
  608. this.#displayNotice(CONST.Text[i18n].Working[1]);
  609. }
  610. }, finishStatus => {
  611. if (finishStatus) {
  612. // Save to this.#sets and GM_storage
  613. const setIndex = CONFIG['script-sets'].sets.findIndex(s => s.id === set.id);
  614. CONFIG['script-sets'].sets[setIndex].scripts.push(this.#sid);
  615. this.#sets = CM.getConfig('script-sets').sets;
  616.  
  617. // Display
  618. this.#displayNotice(typeof finishStatus === 'string' ? finishStatus : CONST.Text[i18n].Error.Unknown);
  619. set.elmOption.innerText = `${CONST.Text[i18n].InSetStatus[1]} ${set.name}`;
  620. this.#displaySets();
  621. } else {
  622. this.#displayNotice(CONST.Text[i18n].Error.NetworkError);
  623. }
  624. });
  625. }
  626.  
  627. #removeFav() {
  628. const set = this.#getCurrentSet();
  629. const option = set.elmOption;
  630.  
  631. this.#displayNotice(CONST.Text[i18n].Working[0]);
  632. GFScriptSetAPI.removeFav(this.#getCurrentSet().linkedit, this.#sid, editStatus => {
  633. if (!editStatus) {
  634. this.#displayNotice(CONST.Text[i18n].Error.NotExist);
  635. option.innerText = `${CONST.Text[i18n].InSetStatus[0]} ${set.name}`;
  636. } else {
  637. this.#displayNotice(CONST.Text[i18n].Working[1]);
  638. }
  639. }, finishStatus => {
  640. if (finishStatus) {
  641. // Save to this.#sets and GM_storage
  642. const setIndex = CONFIG['script-sets'].sets.findIndex(s => s.id === set.id);
  643. const scriptIndex = CONFIG['script-sets'].sets[setIndex].scripts.indexOf(this.#sid);
  644. CONFIG['script-sets'].sets[setIndex].scripts.splice(scriptIndex, 1);
  645. this.#sets = CM.getConfig('script-sets').sets;
  646.  
  647. // Display
  648. this.#displayNotice(typeof finishStatus === 'string' ? finishStatus : CONST.Text[i18n].Error.Unknown);
  649. set.elmOption.innerText = `${CONST.Text[i18n].InSetStatus[0]} ${set.name}`;
  650. this.#displaySets();
  651. } else {
  652. this.#displayNotice(CONST.Text[i18n].Error.NetworkError);
  653. }
  654. });
  655. }
  656.  
  657. #editInPage(e) {
  658. e.preventDefault();
  659.  
  660. const _iframes = [...$All(this.#elements.container, '.script-edit-page')];
  661. if (_iframes.length) {
  662. // Iframe exists, close iframe
  663. this.#elements.btnIframe.innerText = CONST.Text[i18n].EditIframe;
  664. _iframes.forEach(ifr => ifr.remove());
  665. this.#refresh();
  666. } else {
  667. // Iframe not exist, make iframe
  668. this.#elements.btnIframe.innerText = CONST.Text[i18n].CloseIframe;
  669.  
  670. const iframe = $$CrE({
  671. tagName: 'iframe',
  672. props: {
  673. src: this.#getCurrentSet().linkedit
  674. },
  675. styles: {
  676. width: '100%',
  677. height: '60vh'
  678. },
  679. classes: ['script-edit-page'],
  680. listeners: [['load', e => {
  681. //this.#refresh();
  682. //iframe.style.height = iframe.contentDocument.body.parentElement.offsetHeight + 'px';
  683. }]]
  684. });
  685. this.#elements.container.appendChild(iframe);
  686. }
  687. }
  688.  
  689. #displayNotice(text) {
  690. const notice = $CrE('p');
  691. notice.classList.add('notice');
  692. notice.id = 'fav-notice';
  693. notice.innerText = text;
  694. const old_notice = $('#fav-notice');
  695. old_notice && old_notice.parentElement.removeChild(old_notice);
  696. $('#script-content').insertAdjacentElement('afterbegin', notice);
  697. }
  698.  
  699. #tip(text='', timeout=0) {
  700. this.#elements.tip.innerText = text;
  701. timeout > 0 && setTimeout(() => this.#elements.tip.innerText = '', timeout);
  702. }
  703.  
  704. // Apply this.#sets to gui
  705. #displaySets() {
  706. const elements = this.#elements;
  707.  
  708. // Save selected set
  709. const old_value = elements.select.value;
  710. [...elements.select.children].forEach(child => child.remove());
  711.  
  712. // Make <optgroup>s and <option>s
  713. const serverGroup = elements.serverGroup = $$CrE({ tagName: 'optgroup', attrs: { label: CONST.Text[i18n].Groups.Server } });
  714. this.#sets.forEach(set => {
  715. // Create <option>
  716. set.elmOption = $$CrE({
  717. tagName: 'option',
  718. props: {
  719. innerText: set.name,
  720. value: set.id
  721. }
  722. });
  723. // Display inset status
  724. if (set.scripts) {
  725. const inSet = set.scripts.includes(this.#sid);
  726. set.elmOption.innerText = `${CONST.Text[i18n].InSetStatus[inSet+0]} ${set.name}`;
  727. }
  728. // Append <option> into <select>
  729. serverGroup.appendChild(set.elmOption);
  730. });
  731. if (this.#sets.length === 0) {
  732. const optEmpty = elements.optEmpty = $$CrE({
  733. tagName: 'option',
  734. props: {
  735. innerText: CONST.Text[i18n].NoSetsYet,
  736. value: 'empty',
  737. selected: true
  738. }
  739. });
  740. serverGroup.appendChild(optEmpty);
  741. }
  742.  
  743. const newGroup = elements.newGroup = $$CrE({ tagName: 'optgroup', attrs: { label: CONST.Text[i18n].Groups.New } });
  744. const newSet = elements.newSet = $$CrE({
  745. tagName: 'option',
  746. props: {
  747. innerText: CONST.Text[i18n].NewSet,
  748. value: 'new',
  749. }
  750. });
  751. newGroup.appendChild(newSet);
  752. [serverGroup, newGroup].forEach(optgroup => elements.select.appendChild(optgroup));
  753.  
  754. // Adjust <select> width
  755. elements.select.style.width = Math.max.apply(null, Array.from($All(elements.select, 'option')).map(o => o.innerText.length)).toString() + 'em';
  756.  
  757. // Select previous selected set's <option>
  758. const selected = old_value ? [...$All(elements.select, 'option')].find(option => option.value === old_value) : null;
  759. selected && (selected.selected = true);
  760.  
  761. // Set edit-button.href
  762. if (elements.select.value !== 'empty') {
  763. const curset = this.#sets.find(set => set.id === elements.select.value);
  764. elements.btnEdit.href = curset.linkedit;
  765. }
  766.  
  767. // Display correct button
  768. this.#refreshButtonDisplay();
  769. }
  770.  
  771. // Display only add button when script in current set, otherwise remove button
  772. // Disable set-related buttons when not selecting options that not represents a set
  773. #refreshButtonDisplay() {
  774. const set = this.#getCurrentSet();
  775. if (!set) {
  776. [this.#elements.btnAdd, this.#elements.btnRemove, this.#elements.btnEdit, this.#elements.btnIframe]
  777. .forEach(element => FavoritePanel.#disableElement(element));
  778. return null;
  779. } else {
  780. [this.#elements.btnAdd, this.#elements.btnRemove, this.#elements.btnEdit, this.#elements.btnIframe]
  781. .forEach(element => FavoritePanel.#enableElement(element));
  782. }
  783. if (!set?.scripts) { return null; }
  784. if (set.scripts.includes(this.#sid)) {
  785. this.#elements.btnAdd.style.setProperty('display', 'none');
  786. this.#elements.btnRemove.style.removeProperty('display');
  787. return true;
  788. } else {
  789. this.#elements.btnRemove.style.setProperty('display', 'none');
  790. this.#elements.btnAdd.style.removeProperty('display');
  791. return false;
  792. }
  793. }
  794.  
  795. #execCommand(command) {
  796. switch (command) {
  797. case 'new': {
  798. const url = GFScriptSetAPI.getUserpage() + (this.#getCurrentSet() ? '/sets/new' : '/sets/new?fav=1');
  799. window.open(url);
  800. break;
  801. }
  802. case 'empty': {
  803. // Do nothing
  804. break;
  805. }
  806. }
  807. }
  808.  
  809. // Returns null if no <option>s yet
  810. #getCurrentSet() {
  811. return this.#sets.find(set => set.id === this.#elements.select.value) || null;
  812. }
  813.  
  814. #disable() {
  815. [
  816. this.#elements.select,
  817. this.#elements.btnAdd, this.#elements.btnRemove,
  818. this.#elements.btnEdit, this.#elements.btnIframe,
  819. this.#elements.btnCopy, this.#elements.btnSync
  820. ].forEach(element => FavoritePanel.#disableElement(element));
  821. }
  822.  
  823. #enable() {
  824. [
  825. this.#elements.select,
  826. this.#elements.btnAdd, this.#elements.btnRemove,
  827. this.#elements.btnEdit, this.#elements.btnIframe,
  828. this.#elements.btnCopy, this.#elements.btnSync
  829. ].forEach(element => FavoritePanel.#enableElement(element));
  830. }
  831.  
  832. static #disableElement(element) {
  833. element.style.filter = 'grayscale(1) brightness(0.95)';
  834. element.style.opacity = '0.25';
  835. element.style.pointerEvents = 'none';
  836. element.tabIndex = -1;
  837. }
  838.  
  839. static #enableElement(element) {
  840. element.style.removeProperty('filter');
  841. element.style.removeProperty('opacity');
  842. element.style.removeProperty('pointer-events');
  843. element.tabIndex = 0;
  844. }
  845.  
  846. static #deepClone(val) {
  847. if (typeof structuredClone === 'function') {
  848. return structuredClone(val);
  849. } else {
  850. return JSON.parse(JSON.stringify(val));
  851. }
  852. }
  853.  
  854. static #lightClone(val) {
  855. if (['string', 'number', 'boolean', 'undefined', 'bigint', 'symbol', 'function'].includes(val) || val === null) {
  856. return val;
  857. }
  858. if (Array.isArray(val)) {
  859. return val.slice();
  860. }
  861. if (typeof val === 'object') {
  862. return Object.fromEntries(Object.entries(val));
  863. }
  864. }
  865. }
  866.  
  867. const panel = new FavoritePanel(CM);
  868. }
  869.  
  870. // Basic functions
  871.  
  872. // Copy text to clipboard (needs to be called in an user event)
  873. function copyText(text) {
  874. // Create a new textarea for copying
  875. const newInput = document.createElement('textarea');
  876. document.body.appendChild(newInput);
  877. newInput.value = text;
  878. newInput.select();
  879. document.execCommand('copy');
  880. document.body.removeChild(newInput);
  881. }
  882.  
  883. // Check whether current page url matches FuncInfo.checker rule
  884. // This code is copy and modified from FunctionLoader.check
  885. function testChecker(checker) {
  886. if (!checker) {return true;}
  887. const values = Array.isArray(checker.value) ? checker.value : [checker.value]
  888. return values.some(value => {
  889. switch (checker.type) {
  890. case 'regurl': {
  891. return !!location.href.match(value);
  892. }
  893. case 'func': {
  894. try {
  895. return value();
  896. } catch (err) {
  897. DoLog(LogLevel.Error, CONST.Text.Loader.CheckerError);
  898. DoLog(LogLevel.Error, err);
  899. return false;
  900. }
  901. }
  902. case 'switch': {
  903. return value;
  904. }
  905. case 'starturl': {
  906. return location.href.startsWith(value);
  907. }
  908. case 'startpath': {
  909. return location.pathname.startsWith(value);
  910. }
  911. default: {
  912. DoLog(LogLevel.Error, CONST.Text.Loader.CheckerInvalid);
  913. return false;
  914. }
  915. }
  916. });
  917. }
  918.  
  919. // Load all function-objs provided in funcs asynchronously, and merge return values into one return obj
  920. // funcobj: {[checker], [detectDom], func}
  921. function loadFuncs(oFuncs) {
  922. const returnObj = {};
  923.  
  924. oFuncs.forEach(oFunc => {
  925. if (!oFunc.checker || testChecker(oFunc.checker)) {
  926. if (oFunc.detectDom) {
  927. detectDom(oFunc.detectDom, e => execute(oFunc));
  928. } else {
  929. setTimeout(e => execute(oFunc), 0);
  930. }
  931. }
  932. });
  933.  
  934. return returnObj;
  935.  
  936. function execute(oFunc) {
  937. setTimeout(e => {
  938. const rval = oFunc.func(returnObj) || {};
  939. copyProps(rval, returnObj);
  940. }, 0);
  941. }
  942. }
  943.  
  944. function randint(min, max) {
  945. return Math.floor(Math.random() * (max - min + 1)) + min;
  946. }
  947. })();