lc-to-markdown-txt-html

力扣题目描述,讨论发布内容复制 复制为 markdown、txt、html 等格式

2024-05-24 يوللانغان نەشرى. ئەڭ يېڭى نەشرىنى كۆرۈش.

  1. // ==UserScript==
  2. // @name lc-to-markdown-txt-html
  3. // @author wuxin0011
  4. // @version 0.0.4
  5. // @namespace https://github.com/wuxin0011/tampermonkey-script/tree/main/lc-to-markdown-txt-html
  6. // @description 力扣题目描述,讨论发布内容复制 复制为 markdown、txt、html 等格式
  7. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAAAXNSR0IArs4c6QAABsxJREFUeF7tnVvoZVMcxz9TkkQawoQUEYXECKHcybg+uBUevXibvBC55IXyIG/ePbglwwxyl0suo5FRbjVvNJFMkSTF/tU+Op32Oeu69z5rr+96UWat3/r9vr/P+e21z9n799+ARtUKbKg6egWPAKgcAgEgACpXoPLwVQEEQOUKVB6+KoAAqFyBysNXBRAAlStQefiqAAKgcgUqD18VQABUrkDl4asCCIDKFag8fFUAAVC5ApWHrwogACpXoPLwc1WAQ4GLgc3AccAm0ONmmdn6F9gL7AF2Au8C+1L3SAXgMOAR4E5gv1RntD5IgX+Ap4AHgV+DVs5NTgHgNOAt4IjYzbUuiwI/A5cBu2OsxQJwNvA2cFDMplqTXYE/gEuBz0ItxwBgn/hdwFGhm2l+rwr8CJweejmIAWA7cHWvoch4rALbgBtCFocCcCHwXsgGmju4Ape0dwheG4cCsKO5zmzxsqxJYykQVAVCANgf+B2w/2qsrwJ/AhuBv31cDAHAvuSxLyA01l8BOwx+5eNmCAB28LMDoMb6K3Al8IaPmyEA3Aw862NUc0ZXwHL1vI8XAsBHpfLmCIDycpbVYwGQVc7yjAmA8nKW1WMBkFXO8owJgPJyltVjAZBVzvKMCYDycpbVYwGQVc7yjAmA8nKW1WMBkFXO8owJgPJyltVjAZBVzvKMCYDycpbVYwGQVc7yjBUFwJPAa83LDR8C9nx7n+Os5qHWi5pH2+5uX1/LtddNwAsrjD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ndoApYWxvrbeQcrpcm5g1sBnY6LWrCOihwBvCljyMhANgfWfgNsD77GuurgLW12djR2KrT4xAAzMArTRW4Zn1jl2dN+7qX27Z2XmKEAnAdsM3LsiaNpYD9GZ7tvpuHAmDzdzfNok7x3UDzBlVgV0cX05UOhAJgxk5tW5umdLEaVJVKNtvXdhj7PiTeGADM/nltmbHDhsb4Ctjh3G7Trb1d0IgFwDY5GrB+fhcE7ajJuRWwzqLWP/GnGMMpAMz2sxbu1vXa/gCTxnAKfAPcD7yYsmUOAGb7n9+WoePbv8qZ03ZKjFNZa13N9wJ7gFfbFrXJsSlJyRKWbUAAlJ2/ZO8FQLKEZRsQAGXnL9l7AZAsYdkGBEDZ+Uv2XgAkS1i2AQFQdv6SvRcAyRKWbUAAlJ2/ZO8FQLKEZRsQAGXnL9l7AZAsYdkGBEDZ+Uv2XgAkS1i2AQFQdv6SvRcAyRKWbUAAlJ2/ZO8FQLKEZRsQAGXnL9l7AZAsYdkG/gORYKWQd56JTQAAAABJRU5ErkJggg==
  8. // @match https://leetcode.cn/circle/discuss/*
  9. // @match https://leetcode.cn/problems/*
  10. // @match https://leetcode.cn/contest/weekly-contest-*/problems/*
  11. // @match https://leetcode.cn/contest/biweekly-contest-*/problems/*
  12. // @require https://cdn.bootcdn.net/ajax/libs/clipboard.js/2.0.11/clipboard.min.js
  13. // @require https://cdn.bootcdn.net/ajax/libs/turndown/7.1.2/turndown.min.js
  14. // @grant GM_registerMenuCommand
  15. // @grant GM_setValue
  16. // @grant GM_getValue
  17. // @license MIT
  18. // ==/UserScript==
  19.  
  20. (function () {
  21. 'use strict';
  22. const url = window.location.href
  23. const HTML_CONVERT = '__HTML_CONVERT__'
  24. const TXT_CONVERT = '__TXT_CONVERT__'
  25. const MARKDOWN_CONVERT = '__MARKDOWN_CONVERT__'
  26. const markdownURL = "https://stonehank.github.io/html-to-md/"
  27.  
  28.  
  29.  
  30. const isDiscuss = () => url.indexOf('https://leetcode.cn/circle/discuss') != -1
  31. const isProblem = () => url.indexOf('https://leetcode.cn/problems') != -1
  32. const isContest = () => url.indexOf('https://leetcode.cn/contest/weekly-contest') != -1 || url.indexOf('https://leetcode.cn/contest/biweekly-contest') != -1
  33.  
  34. const isAutoKey = '__auto_pluging_key' + (isDiscuss() ? '__Discuss__' : isProblem() ? '__Problem__' : '__Contest__')
  35. //
  36. const use = (key) => typeof GM_getValue(key) == 'undefined' ? true : GM_getValue(key)
  37. const isUseMarkDown = () => use(MARKDOWN_CONVERT)
  38. const isUseTxt = () => use(TXT_CONVERT)
  39. const isUseHTML = () => use(HTML_CONVERT)
  40. let timerId = null
  41. let loadOk = false
  42. console.log('markdown', isUseMarkDown(), 'txt', isUseTxt(), 'html', isUseHTML())
  43. const isUsePlugins = () => isUseHTML() || isUseMarkDown() || isUseTxt()
  44. const isUsePluginInThis = () => use(isAutoKey) // 当前页面是否使用该插件
  45. let isFindButtonContainer = false
  46.  
  47.  
  48.  
  49. const SUPPORT_TYPE = {
  50. 'md': 'md',
  51. 'txt': 'txt',
  52. 'html': 'html'
  53. }
  54.  
  55.  
  56.  
  57. const buttons = []
  58. const targetClass = 'my-button-target'
  59. const BUTTON_ID = `#${targetClass}`
  60. for (let i = 0; i < 3; i++) {
  61. const temp = document.createElement('button')
  62. temp.style.marginLeft = '10px'
  63. const type = i == 0 ? SUPPORT_TYPE['md'] : i == 1 ? SUPPORT_TYPE['txt'] : SUPPORT_TYPE['html']
  64. temp.title = `复制为 ${type == 'md' ? 'markdown' : type} 格式`
  65. temp.id = `${BUTTON_ID}-${type}`
  66. temp.textContent = type
  67. temp.copytype = type
  68. buttons.push(temp)
  69. }
  70.  
  71.  
  72. const updateDisplay = (element, u) => element && element instanceof HTMLElement ? (element.style.display = u ? 'inline-block' : 'none') : ''
  73. // markdown button
  74. const markdownButton = buttons[0]
  75. updateDisplay(markdownButton, isUseMarkDown())
  76.  
  77. // txt button
  78. const txtButton = buttons[1]
  79. updateDisplay(txtButton, isUseTxt())
  80.  
  81. // html button
  82. const htmlButton = buttons[2]
  83. updateDisplay(htmlButton, isUseHTML())
  84.  
  85. function getHtmlContent(className) {
  86. const htmlContent = document.querySelector(className)
  87. return htmlContent ? htmlContent.innerHTML : ''
  88. }
  89.  
  90. function updateElementShow(element) {
  91. if (!element instanceof HTMLElement) {
  92. return
  93. }
  94. element.style.display = element.style.display == 'none' ? 'inline-block' : 'none'
  95. }
  96.  
  97.  
  98. function runQuestionActionsContainer() {
  99. const className = '[class$=MarkdownContent]';
  100. const questionActionsContainer = document.querySelector('[class*=QuestionActionsContainer]')
  101. markdownButton.className = 'e11vgnte0 css-yf7o-BaseButtonComponent-ThemedButton ery7n2v0'
  102. htmlButton.className = 'e11vgnte0 css-yf7o-BaseButtonComponent-ThemedButton ery7n2v0'
  103. txtButton.className = 'e11vgnte0 css-yf7o-BaseButtonComponent-ThemedButton ery7n2v0'
  104. const htmlContent = getHtmlContent(className)
  105. runCopy(questionActionsContainer, markdownButton, htmlContent, SUPPORT_TYPE['md'])
  106. runCopy(questionActionsContainer, htmlButton, htmlContent, SUPPORT_TYPE['html'])
  107. }
  108.  
  109.  
  110.  
  111. const toMarkdown = (htmlContent) => {
  112. try {
  113. var turndownService = new TurndownService()
  114. var markdown = turndownService.turndown(htmlContent)
  115. return markdown
  116. } catch (e) {
  117. if (confirm('markdown转换失败,跳转到网站转换?')) {
  118. if (window?.navigator?.clipboard?.writeText) {
  119. window.navigator.clipboard.writeText(htmlContent).then(() => {
  120. window.open(markdownURL, '_blank')
  121. }, () => {
  122.  
  123. })
  124. }
  125. } else {
  126. console.error('convert markdown error default convert txt !', e)
  127. const d = document.createElement('div')
  128. d.innerHTML = content
  129. const txt = handlerText(d.textContent)
  130. return txt
  131. }
  132. }
  133. }
  134.  
  135.  
  136.  
  137. function runProblems() {
  138. console.log('~~~ run problem ~~~~', url)
  139. let buttonClassName = 'relative inline-flex items-center justify-center text-caption px-2 py-1 gap-1 rounded-full bg-fill-secondary text-difficulty-easy dark:text-difficulty-easy'
  140. let className = "[data-track-load=description_content]"
  141. let titleClassName = '#qd-content [class*=text-title]'
  142. const isFlexMode = !!document.querySelector('#__next')
  143. console.log('is find', !!document.querySelector(className))
  144. if (isContest()) {
  145. // console.log('isFlexMode', isFlexMode)
  146. if (isFlexMode) {
  147. className = ".FN9Jv"
  148. titleClassName = '#qd-content a'
  149. } else {
  150. className = '#base_content .question-content'
  151. titleClassName = '#base_content .question-title h3'
  152. }
  153.  
  154. } else {
  155.  
  156. // LCP 老版本的 容器 https://leetcode.cn/problems/1ybDKD/description/
  157. if (!document.querySelector(className)) {
  158. className = ".FN9Jv"
  159. titleClassName = '#qd-content a'
  160. }
  161. }
  162.  
  163. let title = document.querySelector(titleClassName)
  164. const titleTxt = title?.textContent
  165. title = title ? '<h2>' + (title?.textContent) + '</h2>' : ''
  166. let u = window.location.href
  167. let orginUrl = title ? `<a href="${u}">` + (u) + '</a>' : ''
  168. let htmlContent = title + getHtmlContent(className) + orginUrl
  169. let container = null
  170.  
  171. // https://leetcode.cn/contest/weekly-contest-312
  172. if (isContest() && !isFlexMode) {
  173. if (!isFindButtonContainer) {
  174. const c = document.querySelector('.contest-question-info')
  175. if (c && !c.querySelector('#lx-markdown-plugins')) {
  176. const str = `<li class="list-group-item lx-markdown-plugins" id="lx-markdown-plugins">
  177. <span>插件</span>
  178. </li>`
  179. c.innerHTML = c.innerHTML + str
  180. container = c.querySelector('.lx-markdown-plugins')
  181. if (container) {
  182. isFindButtonContainer = true
  183. }
  184. }
  185.  
  186. }
  187.  
  188. } else {
  189. container = document.querySelector(className)
  190. if (container) {
  191. container = container.previousElementSibling
  192. }
  193. }
  194. if (!container) {
  195. console.warn('找不到 容器!', url)
  196. urlChangeLoadOk = false
  197. return;
  198. }
  199. markdownButton.className = buttonClassName
  200. txtButton.className = buttonClassName
  201. htmlButton.className = buttonClassName
  202. runCopy(container, txtButton, htmlContent, SUPPORT_TYPE['txt'], titleTxt)
  203. runCopy(container, htmlButton, htmlContent, SUPPORT_TYPE['html'])
  204. runCopy(container, markdownButton, htmlContent, SUPPORT_TYPE['md'])
  205. urlChangeLoadOk = true
  206. }
  207.  
  208.  
  209. function copy(w, element) {
  210. if (!element || !(element instanceof HTMLElement)) {
  211. return
  212. }
  213.  
  214. try {
  215. let clipboard = element?.clipboardObject
  216. if (clipboard) {
  217. //console.log('clipboard destroy')
  218. clipboard.destroy();
  219. }
  220. clipboard = new ClipboardJS(element, {
  221. text: function () {
  222. return w;
  223. }
  224. })
  225. // console.log('update txt >>>>>>>>>')
  226. element.clipboardObject = clipboard
  227. clipboard.on('success', function (e) {
  228. updateButtonStatus(element)
  229. })
  230. clipboard.on('error', function (e) {
  231. updateButtonStatus(element, 'copy error!')
  232. })
  233.  
  234.  
  235. } catch (error) {
  236. // 如果 clipboardjs 引入失败 使用原生的
  237. // use navigator writeText
  238. element.onclick = () => {
  239. navigator.clipboard.writeText(w).then(() => {
  240. //updateButtonStatus(element)
  241. }, () => {
  242. updateButtonStatus(element, 'copy error!')
  243. })
  244. }
  245.  
  246. }
  247.  
  248. }
  249.  
  250.  
  251.  
  252.  
  253. function runCopy(container, ele, htmlContent, type = SUPPORT_TYPE['md'], title = '') {
  254.  
  255. if (!ele || !container || !htmlContent || !type) {
  256. return
  257. }
  258. if (!(container instanceof HTMLElement && ele instanceof HTMLElement)) {
  259. return;
  260. }
  261. // append
  262. if (!document.getElementById(ele.id)) {
  263. ele.originClass = ele.className
  264. container.appendChild(ele)
  265. } else {
  266. // 加载完成 初始化
  267. loadOk = true
  268. // initConmand()
  269. updateButtonStatus(ele, ele.copytype, '', 100)
  270. clearTimeId()
  271. }
  272.  
  273. if (type == SUPPORT_TYPE['md']) {
  274. const markdown = toMarkdown(htmlContent)
  275. copy(markdown, ele)
  276. } else if (type == SUPPORT_TYPE['txt']) {
  277. const d = document.createElement('div')
  278. d.innerHTML = htmlContent
  279. const txt = handlerText(d.textContent, title)
  280. copy(txt, ele)
  281. } else if (type == SUPPORT_TYPE['html']) {
  282. // html
  283. copy(htmlContent, ele)
  284. } else {
  285. console.warn('no support format ' + type)
  286. }
  287.  
  288. }
  289.  
  290. const handlerText = (str, title = '') => {
  291. if (!str) return str
  292. // 移出空白字符
  293. str = str.replaceAll(' ', '')
  294. str = str.replaceAll('​​​​​​​​​​​​​​​​​​​​​​​', '')
  295. str = str.replaceAll('&nbsp;', '')
  296. str = str.replace('。', "。\n")
  297. str = str.replace(/\n{2,}/g, "\n")
  298. str = str.replace('http', '\n\nhttp')
  299. str = str.replaceAll('示例', "\n示例")
  300. // 替换提示部分内容范围
  301. let tip_pos = str.lastIndexOf('提示')
  302. let tip = ''
  303. if (tip_pos != -1) {
  304. str = str.substring(0,tip_pos)
  305. tip = str.substring(tip_pos, str.length)
  306. tip = tip.replace('231', '2^31')
  307. tip = tip.replace(/10(?!0)(\d+)/g, '10^$1')
  308. tip = tip.replace('提示', "\n提示")
  309. }
  310. str = str + tip
  311. if (title != '') {
  312. str = str.replace(title, title + "\n\n")
  313. }
  314. return str
  315. }
  316.  
  317.  
  318. const updateButtonStatus = (element, newText = 'copied!', newClass = '', timeout = 1500) => {
  319. if (!element) {
  320. return;
  321. }
  322. // console.log('update button status', element, newText)
  323. element.textContent = newText
  324. if (newClass) {
  325. element.className = newClass
  326. }
  327. setTimeout(() => {
  328. element.textContent = element.copytype
  329. element.className = element.originClass
  330. }, timeout)
  331. }
  332.  
  333.  
  334.  
  335.  
  336. const initConmand = () => {
  337. try {
  338. const isAutoPluginCommand = GM_registerMenuCommand(`当前页面 ${isUsePluginInThis() ? '关闭' : '启用'} 插件 `, () => {
  339. GM_setValue(isAutoKey, !isUsePluginInThis())
  340. window.location.reload()
  341. }, { title: `当前页面 ${isUseHTML() ? '关闭' : '启用'} 插件 ` })
  342.  
  343.  
  344.  
  345. if (!isUsePluginInThis()) {
  346. return;
  347. }
  348.  
  349. // const message = (u, type) => u ? '关闭' : '启用' + (type == 'md' ? ' markdown ' : ` ${type} `)
  350.  
  351. const html_to_markdown = GM_registerMenuCommand(`${isUseMarkDown() ? '关闭' : '启用'} markdown `, () => {
  352. GM_setValue(MARKDOWN_CONVERT, !isUseMarkDown())
  353. updateElementShow(markdownButton)
  354. }, { title: `点击 ${isUseMarkDown() ? '关闭' : '启用'} markdown ` })
  355.  
  356.  
  357. const html_to_txt = GM_registerMenuCommand(`${isUseTxt() ? '关闭' : '启用'} txt `, () => {
  358. GM_setValue(TXT_CONVERT, !isUseTxt())
  359. updateElementShow(txtButton)
  360. }, { title: `点击 ${isUseTxt() ? '关闭' : '启用'} txt ` })
  361.  
  362. const html_to_html = GM_registerMenuCommand(`${isUseHTML() ? '关闭' : '启用'} html `, () => {
  363. GM_setValue(HTML_CONVERT, !isUseHTML())
  364. updateElementShow(htmlButton)
  365. }, { title: `点击 ${isUseHTML() ? '关闭' : '启用'} html ` })
  366.  
  367.  
  368.  
  369. const html_to_markdown_web = GM_registerMenuCommand('html转换markdown网站', () => {
  370. window.open(markdownURL, '_blank')
  371. }, { title: '如果格式转换有问题,请复制为 html 然后用这个网站转换' })
  372.  
  373.  
  374.  
  375. } catch (e) {
  376. console.log('init command error', e)
  377. }
  378.  
  379. }
  380.  
  381.  
  382. let times = 0
  383. const MAX_CNT = 10
  384. initConmand()
  385.  
  386. function clearTimeId() {
  387. if (timerId != null) {
  388. window.cancelIdleCallback(timerId)
  389. window.clearInterval(timerId)
  390. window.clearTimeout(timerId)
  391. timerId = null;
  392. }
  393. }
  394.  
  395. const start = () => {
  396. if (!isUsePlugins() || !isUsePluginInThis()) {
  397. clearTimeId()
  398. return;
  399. }
  400. if (loadOk) {
  401. console.log('load ok')
  402. return
  403. }
  404. timerId = requestIdleCallback(() => {
  405.  
  406. try {
  407. let support = true
  408. if (isDiscuss()) {
  409. runQuestionActionsContainer()
  410. } else if (isProblem() || isContest()) {
  411. runProblems()
  412. } else {
  413. support = false
  414. }
  415. times += 1
  416. if (times > MAX_CNT && timerId != null || !support) {
  417. clearTimeId()
  418. } else if (!loadOk) {
  419. start()
  420. }
  421. } catch (e) {
  422. console.error('install fail ', e)
  423. }
  424. }, { timeout: 3000 })
  425.  
  426. }
  427.  
  428.  
  429.  
  430. const updateUrl = () => {
  431. timerId = requestIdleCallback(() => {
  432. if (isDiscuss()) {
  433. runQuestionActionsContainer()
  434. } else if (isProblem() || isContest()) {
  435. runProblems()
  436. }
  437. updateTimes += 1
  438. if (updateTimes >= 10 || urlChangeLoadOk) {
  439. clearTimeId()
  440. } else {
  441. updateUrl()
  442. }
  443. }, { timeout: 200 })
  444. }
  445.  
  446.  
  447. window.onload = () => {
  448. times = 0
  449. start()
  450. }
  451.  
  452. // 监听地址改变
  453. // 重新修改描述
  454. let urlChangeLoadOk = false
  455. let updateTimes = 0
  456. window.addEventListener("urlchange", () => {
  457. updateTimes = 0
  458. urlChangeLoadOk = false
  459. updateUrl();
  460. })
  461.  
  462.  
  463. })();