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/LtddNwAsrjD0H2Jyhhsuf//0Y83mA74Br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nY6LWrCOihwBvCljyMhANgfWfgNsD77GuurgLW12djR2KrT4xAAzMArTRW4Zn1jl2dN+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. str = str.replace('231', '2^31')
  301. str = str.replace(/10(?!0)(\d+)/g, '10^$1')
  302. str = str.replace('提示', "\n提示")
  303. if (title != '') {
  304. str = str.replace(title, title + "\n\n")
  305. }
  306. return str
  307. }
  308.  
  309.  
  310. const updateButtonStatus = (element, newText = 'copied!', newClass = '', timeout = 1500) => {
  311. if (!element) {
  312. return;
  313. }
  314. // console.log('update button status', element, newText)
  315. element.textContent = newText
  316. if (newClass) {
  317. element.className = newClass
  318. }
  319. setTimeout(() => {
  320. element.textContent = element.copytype
  321. element.className = element.originClass
  322. }, timeout)
  323. }
  324.  
  325.  
  326.  
  327.  
  328. const initConmand = () => {
  329. try {
  330. const isAutoPluginCommand = GM_registerMenuCommand(`当前页面 ${isUsePluginInThis() ? '关闭' : '启用'} 插件 `, () => {
  331. GM_setValue(isAutoKey, !isUsePluginInThis())
  332. window.location.reload()
  333. }, { title: `当前页面 ${isUseHTML() ? '关闭' : '启用'} 插件 ` })
  334.  
  335.  
  336.  
  337. if (!isUsePluginInThis()) {
  338. return;
  339. }
  340.  
  341. // const message = (u, type) => u ? '关闭' : '启用' + (type == 'md' ? ' markdown ' : ` ${type} `)
  342.  
  343. const html_to_markdown = GM_registerMenuCommand(`${isUseMarkDown() ? '关闭' : '启用'} markdown `, () => {
  344. GM_setValue(MARKDOWN_CONVERT, !isUseMarkDown())
  345. updateElementShow(markdownButton)
  346. }, { title: `点击 ${isUseMarkDown() ? '关闭' : '启用'} markdown ` })
  347.  
  348.  
  349. const html_to_txt = GM_registerMenuCommand(`${isUseTxt() ? '关闭' : '启用'} txt `, () => {
  350. GM_setValue(TXT_CONVERT, !isUseTxt())
  351. updateElementShow(txtButton)
  352. }, { title: `点击 ${isUseTxt() ? '关闭' : '启用'} txt ` })
  353.  
  354. const html_to_html = GM_registerMenuCommand(`${isUseHTML() ? '关闭' : '启用'} html `, () => {
  355. GM_setValue(HTML_CONVERT, !isUseHTML())
  356. updateElementShow(htmlButton)
  357. }, { title: `点击 ${isUseHTML() ? '关闭' : '启用'} html ` })
  358.  
  359.  
  360.  
  361. const html_to_markdown_web = GM_registerMenuCommand('html转换markdown网站', () => {
  362. window.open(markdownURL, '_blank')
  363. }, { title: '如果格式转换有问题,请复制为 html 然后用这个网站转换' })
  364.  
  365.  
  366.  
  367. } catch (e) {
  368. console.log('init command error', e)
  369. }
  370.  
  371. }
  372.  
  373.  
  374. let times = 0
  375. const MAX_CNT = 10
  376. initConmand()
  377.  
  378. function clearTimeId() {
  379. if (timerId != null) {
  380. window.cancelIdleCallback(timerId)
  381. window.clearInterval(timerId)
  382. window.clearTimeout(timerId)
  383. timerId = null;
  384. }
  385. }
  386.  
  387. const start = () => {
  388. if (!isUsePlugins() || !isUsePluginInThis()) {
  389. clearTimeId()
  390. return;
  391. }
  392. if (loadOk) {
  393. console.log('load ok')
  394. return
  395. }
  396. timerId = requestIdleCallback(() => {
  397.  
  398. try {
  399. let support = true
  400. if (isDiscuss()) {
  401. runQuestionActionsContainer()
  402. } else if (isProblem() || isContest()) {
  403. runProblems()
  404. } else {
  405. support = false
  406. }
  407. times += 1
  408. if (times > MAX_CNT && timerId != null || !support) {
  409. clearTimeId()
  410. } else if (!loadOk) {
  411. start()
  412. }
  413. } catch (e) {
  414. console.error('install fail ', e)
  415. }
  416. }, { timeout: 3000 })
  417.  
  418. }
  419.  
  420.  
  421.  
  422. const updateUrl = () => {
  423. timerId = requestIdleCallback(() => {
  424. if (isDiscuss()) {
  425. runQuestionActionsContainer()
  426. } else if (isProblem() || isContest()) {
  427. runProblems()
  428. }
  429. updateTimes += 1
  430. if (updateTimes >= 10 || urlChangeLoadOk) {
  431. clearTimeId()
  432. } else {
  433. updateUrl()
  434. }
  435. }, { timeout: 200 })
  436. }
  437.  
  438.  
  439. window.onload = () => {
  440. times = 0
  441. start()
  442. }
  443.  
  444. // 监听地址改变
  445. // 重新修改描述
  446. let urlChangeLoadOk = false
  447. let updateTimes = 0
  448. window.addEventListener("urlchange", () => {
  449. updateTimes = 0
  450. urlChangeLoadOk = false
  451. updateUrl();
  452. })
  453.  
  454.  
  455. })();