ocean-engine-doc-maker.user.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. // ==UserScript==
  2. // @name OceanEngine Table Transformer Kotlin
  3. // @namespace http://tampermonkey.net/
  4. // @version 2.0
  5. // @description try to take over the world!
  6. // @author You
  7. // @match https://open.oceanengine.com/labels/7/docs/*
  8. // @grant GM_setClipboard
  9. // @run-at document-start
  10. // ==/UserScript==
  11. (function() {
  12. 'use strict';
  13. const makeClassName = s => s?.replace(/(?:_|^)([a-z])/g, g => g.substring(g.length - 1).toUpperCase()) || ''
  14. const convertType = (type, name) => {
  15. const isList = type.endsWith('[]')
  16. if (isList) type = type.substring(0, type.length - 2)
  17. switch (type.toLowerCase()) {
  18. case 'float': type = 'Float'; break
  19. case 'double': type = 'Double'; break
  20. case 'number':
  21. case 'int':
  22. case 'long':
  23. case 'integer': type = 'Long'; break
  24. case 'boolean': type = 'Boolean'; break
  25. case 'string': type = 'String'; break
  26. case 'json':
  27. case 'object': type = makeClassName(name) || 'Object'; break
  28. }
  29. if (isList) type = `List<${type}>`
  30. return type
  31. }
  32. const parseName = (childNodes) => {
  33. if (!childNodes) return
  34. for (const node of childNodes) {
  35. if (node.nodeType === Node.TEXT_NODE) {
  36. const text = node.textContent.trim()
  37. if (text) return text.replace(/\n/g, '')
  38. }
  39. }
  40. }
  41. const parseRow = (tds) => {
  42. const name = parseName(tds[0].querySelector('div')?.childNodes)
  43. if (!name) return ''
  44. const optional = tds[0].querySelector('span.tag')?.innerText?.trim() !== '必填'
  45. const type = tds[1].innerText.trim()
  46. const comment = tds[2].innerText.trim()
  47. return ` val ${name}: ${convertType(type, name)}${optional ? '? = null' : ''}, // ${comment.replace(/\n/g, ' ')}\n`
  48. }
  49. const parseEnumRow = (tds) => {
  50. const name = parseName(tds[0].querySelector('div')?.childNodes)
  51. if (!name) return ''
  52. let safeName = name.toUpperCase().replace(/\n/g, '').replace(/[^A-Z0-9_]/g, '_')
  53. if (!/^[A-Z]/.test(safeName)) safeName = `_${safeName}`
  54. const comment = tds[1].innerText.trim()
  55. return `${name === safeName ? '' : ` @SerializedName("${name}")\n`} ${safeName}, // ${comment.replace(/\n/g, ' ')}\n`
  56. }
  57. const parseTable = (table, selector, parentSelector, result) => {
  58. const getOuterTitle = () => {
  59. let node = table.previousElementSibling
  60. let title = 'Root'
  61. while (node) {
  62. if (/^H\d$/.test(node.tagName)) {
  63. title = node.innerText.replace(/\s/g, '')
  64. break
  65. }
  66. node = node.previousElementSibling
  67. }
  68. return title
  69. }
  70. const boundaries = parentSelector ? Array.from(table.querySelectorAll(parentSelector)).map(node => [parseName(node.querySelector('div.tdData').childNodes)?.replace(/(?:_|^)([a-z])/g, g => g.substring(g.length - 1).toUpperCase()), node]) : [[getOuterTitle(), null]] // [title as string, boundary as Node]
  71. console.log(boundaries)
  72. const isEnum = table.querySelector('th')?.innerText?.trim() === '值'
  73. const closingTag = isEnum ? '}' : ')'
  74. let content = ''
  75. table.querySelectorAll(selector).forEach(row => {
  76. const prevNode = row.previousSibling
  77. const boundary = boundaries.find(b => prevNode === b[1])
  78. if (boundary) {
  79. if (content) {
  80. // not first entity, close current item
  81. content += closingTag + '\n'
  82. }
  83. const title = boundary[0]
  84. content += isEnum ? `enum class ${title} {\n` : `data class ${title} (\n`
  85. }
  86. content += (isEnum ? parseEnumRow : parseRow)(row.querySelectorAll('td'))
  87. })
  88. if (content) content += closingTag
  89. result.innerText = content
  90. result.style.display = ''
  91. GM_setClipboard(result.innerText)
  92. }
  93. const ENUM_HINT = ['允许值', '枚举值']
  94. const hasEnumHit = s => ENUM_HINT.some(hint => s?.includes?.(hint))
  95. const processEnumerationNode = (node) => {
  96. if (node.nodeType === Node.ELEMENT_NODE && node.tagName === 'CODE') {
  97. if (node.previousSibling?.tagName !== 'BR') node.parentNode.insertBefore(document.createElement('br'), node)
  98. node.innerText = node.innerText.replace(/["'\s]/g, '')
  99. } else if (node.nodeType === Node.TEXT_NODE && node.previousSibling?.tagName === 'CODE') {
  100. const comment = node.textContent.trim().replace(/、|,|,$/g, '')
  101. node.textContent = comment ? `,\u00A0//\u00A0${comment}` : ','
  102. }
  103. }
  104. const formatEnumerations = (table) => {
  105. table.querySelectorAll('tr > td:nth-child(3) > div').forEach(div => {
  106. if (hasEnumHit(div.innerText)) {
  107. // 提示模式 允许值:blahblah
  108. let started = false
  109. let node = div.childNodes[0]
  110. while (node) {
  111. if (started) {
  112. processEnumerationNode(node)
  113. } else if (node.nodeType === Node.TEXT_NODE && hasEnumHit(node.textContent)) {
  114. started = true
  115. }
  116. node = node.nextSibling
  117. }
  118. } else {
  119. // 行首模式
  120. let node = div.querySelector('br + code')
  121. if (node?.previousSibling?.tagName !== 'BR') return
  122. while (node) {
  123. processEnumerationNode(node)
  124. node = node.nextSibling
  125. }
  126. }
  127. })
  128. }
  129. const createButton = (table) => {
  130. if (table.dataset.done) return
  131. table.dataset.done = true
  132. formatEnumerations(table)
  133. const levels = Array.from(table.querySelectorAll('tr')).reduce((s, row) => {
  134. if (row.className) s.add(row.className)
  135. return s
  136. }, new Set())
  137. const container = document.createElement('div')
  138. const result = document.createElement('pre')
  139. result.style.display = 'none'
  140. table.parentNode.insertBefore(container, table)
  141. table.parentNode.insertBefore(result, table)
  142. const addBtn = (level, parentLevel) => {
  143. const btn = document.createElement('button')
  144. btn.append(document.createTextNode(level))
  145. btn.addEventListener('click', () => parseTable(table, `tbody > tr.${level}`, parentLevel ? `tbody > tr.${parentLevel}` : undefined, result))
  146. container.append(btn)
  147. }
  148. Array.from(levels.values()).forEach((lv, i, a) => addBtn(lv, a[i - 1]))
  149. }
  150. const ob = new MutationObserver(mutations => {
  151. mutations.forEach(({ target }) => {
  152. if (target?.tagName === 'DIV' && target?.classList?.contains('doc-content-body')) {
  153. target.querySelectorAll('table').forEach(createButton)
  154. }
  155. })
  156. })
  157. ob.observe(document.body, { subtree: true, childList: true })
  158. setTimeout(() => document.querySelectorAll('table').forEach(createButton), 3000)
  159. })();