// ==UserScript== // @name GitHub 输入框添加折叠块 // @namespace https://github.com/ltxhhz/github-auto-add-details/ // @version 0.2 // @description 在 markdown 输入框自动添加添加
标签 // @author ltxhhz // @license MIT // @match https://github.com/* // @icon https://github.githubassets.com/favicons/favicon.png // @grant none // ==/UserScript== (function () { 'use strict'; const matches=[ 'https://github.com/*/*/issues/*', 'https://github.com/*/*/pull/*', 'https://github.com/*/*/compare/*', 'https://github.com/*/*/discussions/*' ] function matchUrl() { return matches.some(e=>(new RegExp(e.replace(/\*/g,'[^/]+'))).test(location.href)) } function insertText(e, content) { let startPos = e.selectionStart; // 获取光标开始的位置 let endPos = e.selectionEnd; // 获取光标结束的位置 if (startPos === undefined || endPos === undefined) return; // 如果没有光标位置 不操作 let oldTxt = e.value; // 获取输入框的文本内容 let result = oldTxt.substring(0, startPos) + content + oldTxt.substring(endPos); // 将文本插入 e.value = result; // 将拼接好的文本设置为输入框的值 e.focus(); // 重新聚焦输入框 e.selectionStart = startPos + content.length; // 设置光标开始的位置 e.selectionEnd = startPos + content.length; // 设置光标结束的位置 } /** * 根据 toolbar 定位,添加功能 * @date 2023-01-28 * @param {Element} e * @returns {any} */ function add(e) { if (e.querySelector('.add-collapse')) return const quote = e.querySelector('md-quote') const a = document.createElement('div') a.id = 'add-collapse-' + Math.random().toString(16).substring(2) a.className = quote.className + ' add-collapse' a.role = 'button' //#region a.innerHTML = `` //#endregion a.onclick = function (e1) { insertText(e.parentElement.parentElement.querySelector('textarea'), `
标题 \`\`\` 被折叠的内容 \`\`\`
`) } for (let i = 0; i < e.children.length; i++) { const e1 = e.children[i]; if (e1.querySelector('md-quote')) { e1.insertBefore(a, e1.firstElementChild) break } } } const _wr = function (type) { let orig = history[type]; return function () { let rv = orig.apply(this, arguments); let e = new Event(type); e.arguments = arguments; window.dispatchEvent(e); return rv; }; }; history.pushState = _wr('pushState'); history.replaceState = _wr('replaceState'); // window.addEventListener('replaceState', function (e) { // console.log('THEY DID IT AGAIN! replaceState 111111'); // }); window.addEventListener('pushState', function (e) { if (matchUrl()) { setTimeout(main, 500); } }); function main(e) { const toolbars = document.querySelectorAll('markdown-toolbar') toolbars.forEach(add) console.log('添加 添加
标签 按钮'); const observer = new MutationObserver((list, obs) => { list.forEach(e => { if (e.type == 'childList') { if (e.addedNodes.length) { e.addedNodes.forEach(e1 => { let a if (e1 instanceof Element && (a = e1.querySelector('markdown-toolbar'))) { add(a) } }) } } }) }); observer.observe(document.querySelector('.js-discussion'), { childList: true, subtree: true }) //issue page } if (matchUrl()) { main() } })();