🏠 Home 

Greasy Fork is available in English.

GreasyFork markdown

Standardformatet brugt i forummet erMarkdown,Tilføj format hjælpelink og udgiv nyt script,Værktøjslinjen Svartid med hurtig redigering aktiveret


Installer dette script?
Skaberens foreslåede script

Du vil måske også kunne lide Greasyfork Lim håndværker


Installer dette script
  1. // ==UserScript==
  2. // @name Markdown toolbar for GreasyFork
  3. // @name:zh-CN GreasyFork markdown
  4. // @description:zh-CN 在论坛默认使用格式为Markdown,添加格式帮助链接及在发布新脚本,回复时间启用快速编辑的工具栏
  5. // @name:ar GreasyFork markdown
  6. // @description:ar التنسيق الافتراضي المستخدم في المنتدى هوMarkdown,إضافة رابط تعليمات التنسيق ونشر برنامج نصي جديد,شريط أدوات وقت الرد مع تمكين التحرير السريع
  7. // @name:bg GreasyFork markdown
  8. // @description:bg Форматът по подразбиране, използван във форума, еMarkdown,Добавете връзка за помощ при форматиране и публикувайте нов скрипт,Лента с инструменти за време за отговор с активирано бързо редактиране
  9. // @name:cs GreasyFork markdown
  10. // @description:cs Výchozí formát používaný ve fóru jeMarkdown,Přidejte odkaz na nápovědu formátu a publikujte nový skript,Panel nástrojů doby odpovědi s povolenou rychlou úpravou
  11. // @name:da GreasyFork markdown
  12. // @description:da Standardformatet brugt i forummet erMarkdown,Tilføj format hjælpelink og udgiv nyt script,Værktøjslinjen Svartid med hurtig redigering aktiveret
  13. // @name:de GreasyFork markdown
  14. // @description:de Das im Forum verwendete Standardformat istMarkdown,Fügen Sie einen Link zur Formathilfe hinzu und veröffentlichen Sie ein neues Skript,Symbolleiste „Antwortzeit“ mit aktivierter Schnellbearbeitung
  15. // @name:el GreasyFork markdown
  16. // @description:el Η προεπιλεγμένη μορφή που χρησιμοποιείται στο φόρουμ είναιMarkdown,Προσθήκη συνδέσμου βοήθειας μορφής και δημοσίευση νέου σεναρίου,Γραμμή εργαλείων χρόνου απάντησης με ενεργοποιημένη τη γρήγορη επεξεργασία
  17. // @name:en GreasyFork markdown
  18. // @description:en The default format used in the forum isMarkdown,Add format help link and publish new script,Reply time toolbar with quick editing enabled
  19. // @name:eo GreasyFork markdown
  20. // @description:eo La defaŭlta formato uzata en la forumo estasMarkdown,Aldonu formatan helpligon kaj publikigu novan skripton,Ilobreto de responda tempo kun rapida redaktado ebligita
  21. // @name:es GreasyFork markdown
  22. // @description:es El formato predeterminado utilizado en el foro esMarkdown,Agregue un enlace de ayuda de formato y publique un nuevo script,Barra de herramientas de tiempo de respuesta con edición rápida habilitada
  23. // @name:fi GreasyFork markdown
  24. // @description:fi Foorumilla käytetty oletusmuoto onMarkdown,Lisää muodon ohjelinkki ja julkaise uusi skripti,Vastausajan työkalupalkki, jossa pikamuokkaus käytössä
  25. // @name:fr GreasyFork markdown
  26. // @description:fr Le format par défaut utilisé dans le forum estMarkdown,Ajouter un lien d’aide au format et publier un nouveau script,Barre d’outils de temps de réponse avec édition rapide activée
  27. // @name:he GreasyFork markdown
  28. // @description:he פורמט ברירת המחדל בשימוש בפורום הואMarkdown,הוסף קישור עזרה בפורמט ופרסם סקריפט חדש,סרגל הכלים של זמן תשובה עם עריכה מהירה מופעלת
  29. // @name:hr GreasyFork markdown
  30. // @description:hr Zadani format koji se koristi na forumu jeMarkdown,Dodajte vezu za pomoć u formatu i objavite novu skriptu,Alatna traka vremena odgovora s omogućenim brzim uređivanjem
  31. // @name:hu GreasyFork markdown
  32. // @description:hu A fórumban használt alapértelmezett formátum aMarkdown,Formátum súgóhivatkozás hozzáadása és új szkript közzététele,Válaszidő eszköztár a gyors szerkesztés engedélyezésével
  33. // @name:id GreasyFork markdown
  34. // @description:id Format default yang digunakan dalam forum adalahMarkdown,Tambahkan tautan bantuan format dan publikasikan skrip baru,Bilah alat waktu balasan dengan pengeditan cepat diaktifkan
  35. // @name:it GreasyFork markdown
  36. // @description:it Il formato predefinito utilizzato nel forum èMarkdown,Aggiungi il collegamento alla guida sul formato e pubblica un nuovo script,Barra degli strumenti del tempo di risposta con modifica rapida abilitata
  37. // @name:ja GreasyFork markdown
  38. // @description:ja フォーラムで使用されるデフォルトの形式は次のとおりです。Markdown,フォーマットヘルプリンクを追加し、新しいスクリプトを公開します,クイック編集が有効になった返信時間ツールバー
  39. // @name:ka GreasyFork markdown
  40. // @description:ka ფორუმში გამოყენებული ნაგულისხმევი ფორმატი არისMarkdown,დაამატეთ ფორმატის დახმარების ბმული და გამოაქვეყნეთ ახალი სკრიპტი,პასუხის დროის ინსტრუმენტთა პანელი ჩართულია სწრაფი რედაქტირებით
  41. // @name:ko GreasyFork markdown
  42. // @description:ko 포럼에서 사용되는 기본 형식은 다음과 같습니다.Markdown,형식 도움말 링크 추가 및 새 스크립트 게시,빠른 편집이 활성화된 응답 시간 도구 모음
  43. // @name:nl GreasyFork markdown
  44. // @description:nl Het standaardformaat dat op het forum wordt gebruikt isMarkdown,Voeg de Help-link voor het formaat toe en publiceer een nieuw script,Werkbalk Antwoordtijd met snelle bewerking ingeschakeld
  45. // @name:nb GreasyFork markdown
  46. // @description:nb Standardformatet som brukes i forumet erMarkdown,Legg til format hjelpekobling og publiser nytt skript,Verktøylinje for svartid med hurtigredigering aktivert
  47. // @name:pl GreasyFork markdown
  48. // @description:pl Domyślnym formatem używanym na forum jestMarkdown,Dodaj link pomocy formatu i opublikuj nowy skrypt,Pasek narzędzi czasu odpowiedzi z włączoną szybką edycją
  49. // @name:pt-BR GreasyFork markdown
  50. // @description:pt-BR O formato padrão usado no fórum éMarkdown,Adicionar link de ajuda de formato e publicar novo script,Barra de ferramentas de tempo de resposta com edição rápida habilitada
  51. // @name:ro GreasyFork markdown
  52. // @description:ro Formatul implicit folosit în forum esteMarkdown,Adăugați linkul de ajutor pentru format și publicați un nou script,Bara de instrumente pentru timpul de răspuns cu editarea rapidă activată
  53. // @name:ru GreasyFork markdown
  54. // @description:ru Формат по умолчанию, используемый на форуме:Markdown,Добавьте ссылку на справку по формату и опубликуйте новый скрипт.,Панель инструментов времени ответа с включенным быстрым редактированием
  55. // @name:sk GreasyFork markdown
  56. // @description:sk Predvolený formát používaný vo fóre jeMarkdown,Pridajte odkaz na pomoc s formátom a publikujte nový skript,Panel s nástrojmi času odpovede s povolenou rýchlou úpravou
  57. // @name:sr GreasyFork markdown
  58. // @description:sr Подразумевани формат који се користи на форуму јеMarkdown,Додајте везу за помоћ за формат и објавите нову скрипту,Трака са алаткама за време одговора са омогућеним брзим уређивањем
  59. // @name:sv GreasyFork markdown
  60. // @description:sv Standardformatet som används i forumet ärMarkdown,Lägg till hjälplänk för format och publicera nytt skript,Verktygsfältet Svarstid med snabb redigering aktiverad
  61. // @name:th GreasyFork markdown
  62. // @description:th รูปแบบเริ่มต้นที่ใช้ในฟอรั่มคือMarkdown,เพิ่มลิงก์วิธีใช้รูปแบบและเผยแพร่สคริปต์ใหม่,แถบเครื่องมือเวลาตอบกลับพร้อมเปิดใช้งานการแก้ไขด่วน
  63. // @name:tr GreasyFork markdown
  64. // @description:tr Forumda kullanılan varsayılan format:Markdown,Biçim yardım bağlantısı ekleyin ve yeni komut dosyası yayınlayın,Hızlı düzenlemenin etkin olduğu yanıt süresi araç çubuğu
  65. // @name:ug GreasyFork markdown
  66. // @description:ug مۇنبەردە ئىشلىتىلگەن سۈكۈتتىكى فورماتىMarkdown,فورمات ياردەم ئۇلانمىسىنى قوشۇڭ ۋە يېڭى قوليازما ئېلان قىلىڭ,تېز تەھرىرلەش ئىقتىدارى بىلەن ۋاقىت قورال ستونىغا جاۋاب قايتۇرۇڭ
  67. // @name:uk GreasyFork markdown
  68. // @description:uk Стандартний формат, який використовується на форуміMarkdown,Додайте посилання на довідку щодо формату та опублікуйте новий сценарій,Панель інструментів часу відповіді з увімкненим швидким редагуванням
  69. // @name:vi GreasyFork markdown
  70. // @description:vi Định dạng mặc định được sử dụng trong diễn đàn làMarkdown,Thêm liên kết trợ giúp định dạng và xuất bản tập lệnh mới,Thanh công cụ thời gian trả lời có bật tính năng chỉnh sửa nhanh
  71. // @name:zh-TW GreasyFork markdown
  72. // @description:zh-TW 在論壇預設使用格式為Markdown,新增格式幫助連結及在發布新腳本,回覆時間啟用快速編輯的工具列
  73. // @name:zh-HK GreasyFork markdown
  74. // @description:zh-HK 在論壇預設使用格式為Markdown,新增格式幫助連結及在發布新腳本,回覆時間啟用快速編輯的工具列
  75. // @name:fr-CA GreasyFork markdown
  76. // @description:fr-CA Le format par défaut utilisé dans le forum estMarkdown,Ajouter un lien d’aide au format et publier un nouveau script,Barre d’outils de temps de réponse avec édition rapide activée
  77. // @namespace https://github.com/#####GodMan/UserScripts
  78. // @description Select Markdown format by default, add help links, add toolbar formatting buttons for markdown
  79. // @author wOxxOm, darkred, 人民的勤务员 <china.qinwuyuan@gmail.com>
  80. // @contributor JixunMoe
  81. // @contributor 人民的勤务员 <china.qinwuyuan@gmail.com>
  82. // @license MIT
  83. // @grant GM_xmlhttpRequest
  84. // @include https://greasyfork.org/*discussions/*
  85. // @include https://greasyfork.org/*scripts/*/versions/new*
  86. // @include https://greasyfork.org/*scripts/*/feedback*
  87. // @include https://greasyfork.org/*script_versions/new*
  88. // @include https://greasyfork.org/*/conversations/*
  89. // @include https://greasyfork.org/*/users/edit
  90. // @include https://greasyfork.org/*/reports/new*
  91. // @grant GM_addStyle
  92. // @run-at document-start
  93. // @version 2.0.5
  94. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEIAAAAoCAQAAADgMuRfAAABWklEQVR4Ae3YJQIUYRxA8R8OESs4BXcOsHXqngDnFtglKFjEqVOwjtNxd3f547Duux/2Xhx7Y98ITLbHdZHA6/aYDLM9EAl9YB77RWIP8Vgk9hkhvaKp/yP+R5SyXdRxl1KipqV0ETHGGVHDM8YMLoKZHogKH5jJICPIRIUZg45giyhxCykihsnFd3PD0kQwzkUhXDGOVBEs9+azy0kZwZrPShFRf7MrBxfx0hK1WOLl4CLCReNqX6Z1NrFeM9a3HxFyleSibsQbBY0oeNNJRNiolI1NDvZd09Rjmruis4j3Mj/IvG8SEc4boxZjnBedRZQ+sqZ50NJld0gt9otuIsJJIz97suVrf6NKNopuI8L2z7ZzAxaVUhRdR3Qw3zML/WChZ2kiwkUTwUQXRaqIcNzIzx4RKSPC1s/+ia/8/yP+R/wmP0kOicQeYl76H2cw2X63RAJv2W8ynwCwbA7V/z22eQAAAABJRU5ErkJggg==
  95. // @iconbak https://raw.githubusercontent.com/dcurtis/markdown-mark/master/png/66x40-solid.png
  96. // @supportURL https://github.com/darkred/Userscripts/issues
  97. // ==/UserScript==
  98. // Example URLS to test:
  99. // https://greasyfork.org/en/discussions/new
  100. // https://greasyfork.org/en/scripts/422887-markdown-toolbar-for-greasyfork/discussions/78139
  101. // https://greasyfork.org/en/scripts/23493/versions/new
  102. // https://greasyfork.org/en/scripts/422445-github-watcher/feedback
  103. // https://greasyfork.org/en/users/2160-darkred/conversations/new
  104. // https://greasyfork.org/en/users/edit
  105. var translate = 'en'
  106. var inForum = location.href.indexOf('/discussions') > 0
  107. var inPostNewScriptVer = location.href.indexOf('/versions/new') > 0
  108. function contains(selector, text) {
  109. var elements = document.querySelectorAll(selector)
  110. return Array.from(elements).filter(function (element) {
  111. return RegExp(text).test(element.textContent)
  112. })
  113. }
  114. //DOMContentLoaded有时会和其他脚本冲突导致监听失败
  115. window.addEventListener('load', function (e) {
  116. var refElements = document.querySelectorAll(`
  117. input[name="authenticity_token"] + .label-note,
  118. label[for="script-version-additional-info-0"] + .label-note,
  119. label[for="changelog"] + .label-note,
  120. label[for="conversation_messages_attributes_0_content"] + .label-note,
  121. label[for="user_profile"] + .label-note,
  122. form > .label-note
  123. `)
  124. if (inForum) {
  125. refElements.forEach(element => {
  126. element.insertAdjacentHTML('beforeend', '<br>')
  127. addFeatures(element)
  128. })
  129. } else { // not in Forum
  130. // This page has 2 non-code textareas: 'Additional info' and 'Changelog'
  131. if (inPostNewScriptVer) {
  132. refElements.forEach(element => {
  133. addFeatures(element.appendChild(document.createElement('br')))
  134. })
  135. } else { // every other page
  136. var nn = document.querySelectorAll('input[value="markdown"]')
  137. if (nn.length > 0) {
  138. for (var n, i = 0; (i < nn.length) && (n = nn[i]); i++) {
  139. if (location.href.indexOf('/script_versions/') !== -1) {
  140. n.click()
  141. }
  142. n.click() // 继续点击
  143. addFeatures(n.parentNode.appendChild(document.createElement('br')))
  144. }
  145. }
  146. }
  147. }
  148. })
  149. function addFeatures(n) {
  150. if (!n) {
  151. return
  152. }
  153. var form = n.closest('form')
  154. if (form.action.indexOf('/edit') < 0) {
  155. //NOTE - 取消自动点击
  156. // n.click()
  157. }
  158. if (inPostNewScriptVer) {
  159. n.parentNode.textAreaNode = n.parentNode.querySelector('textarea.TextBox, textarea.previewable, div.previewable textarea')
  160. } else {
  161. n.parentNode.textAreaNode = form.querySelector('textarea.TextBox, textarea.previewable, div.previewable textarea')
  162. }
  163. GM_addStyle(`
  164. .mdButton {
  165. display: inline-block;
  166. cursor: pointer;
  167. margin: 0px;
  168. font-size: 12px;
  169. line-height: 1;
  170. font-weight: bold;
  171. padding: 4px 6px;
  172. background: -moz-linear-gradient(center bottom , #CCC 0%, #FAFAFA 100%) repeat scroll 0% 0% #F8F8F8;
  173. border: 1px solid #999;
  174. border-radius: 2px;
  175. white-space: nowrap;
  176. text-shadow: 0px 1px 0px #FFF;
  177. box-shadow: 0px 1px 0px #FFF inset, 0px -1px 2px #BBB inset;
  178. color: #333;
  179. }
  180. `)
  181. // Add buttons
  182. btnMake(n, '<b>' + __('B') + '</b>', __('Bold'), '**')
  183. btnMake(n, __('#'), __('Title'), '#', ' ')
  184. btnMake(n, '<li>' + __('-') + '</li>', __('List'), '- ', ' ')
  185. btnMake(n, __('>'), __('blockquote'), '<blockquote>', '</blockquote>')
  186. btnMake(n, '<mark>' + __('标记') + '</mark>', __('高亮显示选中文本'), '<mark>', '</mark>')
  187. btnMake(n, '<i>' + __('I') + '</i>', __('Italic'), '*')
  188. btnMake(n, '<center>' + __('居中') + '</center>', __('内容居中显示'), '<center>', '</center>')
  189. btnMake(n, '<u>' + __('U') + '</u>', __('Underline'), '<u>', '</u>')
  190. btnMake(n, '<s>' + __('S') + '</s>', __('Strikethrough'), '<s>', '</s>')
  191. btnMake(n, '&lt;br&gt;', __('Force line break'), '<br>', '', true)
  192. btnMake(n, __('---'), __('Horizontal line'), '\n\n---\n\n', '', true)
  193. btnMake(n, __('URL'), __('Add URL to selected text'),
  194. function (e) {
  195. try {
  196. edWrapInTag('[', '](' + prompt(__('URL') + ':') + ')', edInit(e.target))
  197. } catch (ex) { }
  198. }
  199. )
  200. btnMake(n, __('Image (https)'), __('Convert selected https://url to inline image'), '![' + __('image') + '](', ')')
  201. // if (inForum) {
  202. btnMake(n, __('Table'), __('Insert table template'), __('\n| head1 | head2 |\n|-------|-------|\n| cell1 | cell2 |\n| cell3 | cell4 |\n'), '', true)
  203. //} 都添加表格
  204. btnMake(n, __('Code'), __('Apply CODE markdown to selected text'),
  205. function (e) {
  206. var ed = edInit(e.target)
  207. if (ed.sel.indexOf('\n') < 0) {
  208. edWrapInTag('`', '`', ed)
  209. } else {
  210. edWrapInTag(
  211. ((ed.sel1 == 0) || (ed.text.charAt(ed.sel1 - 1) == '\n') ? '' : '\n') + '```' + (ed.sel.charAt(0) == '\n' ? '' : '\n'),
  212. (ed.sel.substr(-1) == '\n' ? '' : '\n') + '```' + (ed.text.substr(ed.sel2, 1) == '\n' ? '' : '\n'),
  213. ed
  214. )
  215. }
  216. }
  217. )
  218. btnMake(n, __('谷歌翻译'), __('快速翻译选中的内容'),
  219. function (e) {
  220. const translatedzh = edInit(e.target)
  221. translateText(translatedzh.sel).then(translatedText => {
  222. edWrapInTag('', translatedText, translatedzh, true)
  223. }).catch(error => {
  224. alert(' GoogleTranslate ERROR!!! ')
  225. })
  226. }
  227. )
  228. const WeiWeiimages = [
  229. ['npzhyrb4txdoegwl82bkapekufb5', '维维发问:你有眼界吗?'],
  230. ['gkhj9p2qhtm62uza3qveshtooe2u', '维维被你震撼到了!'],
  231. ['p0i0f5xubhln1wvph3ip70zhpzqq', '维维发问:什么叫做搬起石头砸自己的脚?'],
  232. ['nahzae6vc3d3osq861cbt8uaopkk', '维维断言:这就是个国际笑话'],
  233. ['kzpmox79idq4gmsbyoj0yyuhx13v', '维维发问:你怎么敢讲这种话的?']
  234. ]
  235. const WeiWeiLoveYou = WeiWei(WeiWeiimages, true)
  236. btnMake(n, '维维嘲讽', '来自爱国教授维维的五连问', __('\n\n' + WeiWeiLoveYou + `\n\n
  237. `), '', true)
  238. function WeiWei(images, WeiWeiSays) {
  239. let html = `
  240. <div style="background-color: #FFF3E0;color: #FF5722;border: 1px solid #FF5722;"><center><h3 style="color: red;">爱国教授维维有话对你说</h3></center><p><br>
  241. <center>`
  242. images.forEach(([imgSrc, rtText]) => {
  243. const WeiWeiImg = `https://greasyfork.s3.us-east-2.amazonaws.com/${imgSrc} `
  244. if (WeiWeiSays) {
  245. html += `
  246. <ruby>
  247. <img src="${WeiWeiImg}" alt="">
  248. <rt>${rtText}</rt>
  249. </ruby>`
  250. } else {
  251. html += `\n<img src="${WeiWeiImg}" alt="">`
  252. }
  253. })
  254. html += `
  255. </center>
  256. </p>
  257. </div>`
  258. return html
  259. }
  260. var allPreviewTabs = contains('.preview-tab', 'Preview')
  261. allPreviewTabs.forEach(element => {
  262. element.onclick = function (event) {
  263. let target = event.target // delegation: where was the click?
  264. if (target.tagName !== 'A' && target.tagName !== 'SPAN') { return }
  265. form.querySelectorAll('.Button').forEach(element2 => element2.style.display = 'none')
  266. }
  267. })
  268. var allWriteTabs = contains('.write-tab', 'Write')
  269. allWriteTabs.forEach(element => {
  270. element.onclick = function (event) {
  271. let target = event.target // where was the click?
  272. if (target.tagName !== 'A' && target.tagName !== 'SPAN') { return }
  273. form.querySelectorAll('.Button').forEach(element2 => element2.style.display = 'inline-block')
  274. }
  275. })
  276. }
  277. function btnMake(afterNode, label, title, tag1_or_cb, tag2, noWrap) {
  278. var a = document.createElement('a')
  279. a.className = 'mdButton'
  280. a.innerHTML = label
  281. a.title = title
  282. a.addEventListener('click',
  283. typeof (tag1_or_cb) === 'function' ? tag1_or_cb : // if
  284. noWrap ? function (e) { edInsertText(tag1_or_cb, edInit(e.target)) } : // else if
  285. function (e) { edWrapInTag(tag1_or_cb, tag2, edInit(e.target)) } // else
  286. )
  287. var nparent
  288. inForum ? nparent = afterNode : nparent = afterNode.parentNode
  289. a.textAreaNode = nparent.textAreaNode || nparent.parentNode.querySelector('textArea')
  290. nparent.appendChild(a)
  291. }
  292. function edInit(btn) {
  293. var ed = { node: btn.textAreaNode || btn.parentNode.textAreaNode }
  294. ed.sel1 = ed.node.selectionStart
  295. ed.sel2 = ed.node.selectionEnd
  296. ed.text = ed.node.value
  297. ed.sel = ed.text.substring(ed.sel1, ed.sel2)
  298. return ed
  299. }
  300. function edWrapInTag(tag1, tag2, ed, rep = false) {
  301. if (rep) {
  302. ed.node.value = ed.text.substr(0, ed.sel1) + (tag2 ? tag2 : tag1) + ed.text.substr(ed.sel2)
  303. } else {
  304. ed.node.value = ed.text.substr(0, ed.sel1) + tag1 + ed.sel + (tag2 ? tag2 : tag1) + ed.text.substr(ed.sel2)
  305. }
  306. ed.node.setSelectionRange(ed.sel1 + tag1.length, ed.sel1 + tag1.length + ed.sel.length)
  307. if (rep) return//不选中,文本太长了,选中干啥,
  308. ed.node.focus()
  309. }
  310. function edInsertText(text, ed) {
  311. ed.node.value = ed.text.substr(0, ed.sel2) + text + ed.text.substr(ed.sel2)
  312. ed.node.setSelectionRange(ed.sel2 + text.length, ed.sel2 + text.length)
  313. ed.node.focus()
  314. }
  315. var __ = (function (l, langs) {
  316. var lang = langs[l] || langs[l.replace(/-.+/, '')]
  317. return lang ? function (text) { return lang[text] || text }
  318. : function (text) { return text } // No matching language, fallback to english
  319. })(location.pathname.match(/^\/(.+?)\//)[1], {
  320. 'zh-CN': {
  321. 'B': '粗体',
  322. 'I': '斜体',
  323. 'U': '下划线',
  324. 'S': '删除线',
  325. 'Bold': '粗体',
  326. '-': '列表',
  327. '#': '标题',
  328. '>': '引用',
  329. '---': '分割线',
  330. 'Italic': '斜体',
  331. 'Underline': '下划线',
  332. 'Strikethrough': '删除线',
  333. 'Force line break': '强制换行',
  334. 'Horizontal line': '水平分割线',
  335. 'URL': '链接',
  336. 'Title': '正文标题H1',
  337. 'List': '无序列表,用作分类下的信息展示',
  338. 'Add URL to selected text': '为所选文字添加链接',
  339. 'Image (https)': '图片 (https)',
  340. 'Convert selected https://url to inline image': '将所选地址转换为行内图片',
  341. 'image': '图片描述', // Default image alt value
  342. 'Table': '表格',
  343. 'blockquote': '引用文本',
  344. 'Insert table template': '插入表格模板',
  345. 'Code': '代码',
  346. 'Apply CODE markdown to selected text': '将选中代码围起来',
  347. '\n| head1 | head2 |\n|-------|-------|\n| cell1 | cell2 |\n| cell3 | cell4 |\n':
  348. '\n| 表头 1 | 表头 2 |\n|-------|-------|\n| 表格 1 | 表格 2 |\n| 表格 3 | 表格 4 |\n'
  349. },
  350. 'ru': {
  351. 'B': 'Ж',
  352. 'I': 'К',
  353. 'U': 'Ч',
  354. 'S': 'П',
  355. 'Bold': 'Жирный',
  356. 'Italic': 'Курсив',
  357. 'Underline': 'Подчеркнутый',
  358. 'Strikethrough': 'Перечеркнутый',
  359. 'Force line break': 'Новая строка',
  360. 'Horizontal line': 'Горизонтальная линия',
  361. 'URL': 'ссылка',
  362. 'Title': 'Заголовок',
  363. 'List': 'Неупорядоченный список',
  364. 'Add URL to selected text': 'Добавить ссылку к выделенному тексту',
  365. 'Image (https)': 'Картинка (https)',
  366. 'Convert selected https://url to inline image': 'Преобразовать выделенный https:// адрес в картинку',
  367. 'image': 'картинка', // Default image alt value
  368. 'Table': 'Таблица',
  369. 'Insert table template': 'Вставить шаблон таблицы',
  370. 'Code': 'Код',
  371. 'Apply CODE markdown to selected text': 'Пометить выделенный фрагмент как программный код',
  372. '\n| head1 | head2 |\n|-------|-------|\n| cell1 | cell2 |\n| cell3 | cell4 |\n':
  373. '\n| заголовок1 | заголовок2 |\n|-------|-------|\n| ячейка1 | ячейка2 |\n| ячейка3 | ячейка4 |\n'
  374. },
  375. 'fr': {
  376. 'B': 'G',
  377. 'I': 'I',
  378. 'U': 'S',
  379. 'S': 'B',
  380. 'Bold': 'Gras',
  381. 'Italic': 'Italique',
  382. 'Underline': 'Souligné',
  383. 'Strikethrough': 'Barré',
  384. 'Force line break': 'Forcer le saut de ligne',
  385. 'Horizontal line': 'Ligne horizontale',
  386. 'URL': 'URL',
  387. 'Title': 'Titre',
  388. 'List': 'Liste non ordonnée',
  389. 'Add URL to selected text': 'Ajouter URL au texte sélectionné',
  390. 'Image (https)': 'Image (https)',
  391. 'Convert selected https://url to inline image': 'Convertir https://url sélectionnés en images',
  392. 'image': 'image', // Default image alt value
  393. 'Table': 'Tableau',
  394. 'Insert table template': 'Insérer un modèle de table',
  395. 'Code': 'Code',
  396. 'Apply CODE markdown to selected text': 'Appliquer CODE markdown au texte sélectionné',
  397. '\n| head1 | head2 |\n|-------|-------|\n| cell1 | cell2 |\n| cell3 | cell4 |\n':
  398. '\n| En-tête 1 | En-tête 2 |\n|-------|-------|\n| cellule 1 | cellule 2 |\n| cellule 3 | cellule 4 |\n'
  399. }
  400. })
  401. function translateText(text) {
  402. return new Promise((resolve, reject) => {
  403. var api = 'https://translate.googleapis.com/translate_a/single'
  404. var params = {
  405. client: 'gtx',
  406. dt: 't',
  407. sl: 'auto',
  408. tl: translate,
  409. q: text
  410. }
  411. GM_xmlhttpRequest({
  412. method: 'GET',
  413. url: api + buildQueryString(params),
  414. onload: function (response) {
  415. try {
  416. var data = JSON.parse(response.responseText.replace('\'', '\u2019'))
  417. var translatedText = data[0].reduce((acc, item) => acc + item[0], '')
  418. resolve(translatedText)
  419. } catch (error) {
  420. console.error('翻译失败:', error)
  421. reject('翻译失败')
  422. }
  423. },
  424. onerror: function (response) {
  425. console.error('请求翻译失败:', response.statusText)
  426. reject('请求翻译失败')
  427. }
  428. })
  429. })
  430. }
  431. function buildQueryString(params) {
  432. return '?' + Object.keys(params).map(function (key) {
  433. return encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
  434. }).join('&')
  435. }