Skip to content

Instantly share code, notes, and snippets.

@Saber2pr
Created September 29, 2021 06:35
Show Gist options
  • Save Saber2pr/4f4026c8a7c305b90fdb2530a44bca1f to your computer and use it in GitHub Desktop.
Save Saber2pr/4f4026c8a7c305b90fdb2530a44bca1f to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name Kibana Pretty
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @match https://*/app/kibana
// @grant none
// ==/UserScript==
(function () {
const isJSON = (str) => {
if (typeof str == 'string') {
try {
const obj = JSON.parse(str)
if (typeof obj === 'object' && obj) {
return true
} else {
return false
}
} catch (e) {
return false
}
} else {
return false
}
}
const clone = value => {
if (typeof value !== "object") {
if (isJSON(value)) return JSON.parse(value)
return value
}
if (value === null || value === undefined) return value
return Object.keys(value).reduce(
(out, key) =>
Object.assign(out, {
[key]: clone(value[key])
}),
{}
)
}
const prettyData = (data) => JSON.stringify(clone(JSON.parse(data)), null, 2)
const waitEl = (callback, ...selectors) => {
setInterval(() => {
if (selectors.every(selector => !!document.querySelector(selector))) {
callback()
}
}, 500)
}
const copy_selector = '[aria-label="Copy"]'
const code_selector = '[aria-label="Read only JSON view of an elasticsearch document"]'
const formatBtn_class = 'click-format-json'
const getCodeByCopyBtn = el => el.parentElement.parentElement.parentElement.previousElementSibling.firstChild
const PreId = 'Kibana-Pretty-Pre'
const replacePre = (code, content) => {
const container = code.parentElement
let pre = container.querySelector(`#${PreId}`)
if (!pre) {
pre = document.createElement('pre')
pre.id = PreId
pre.style.width = '100%'
pre.style.height = '100%'
pre.style.overflow = 'auto'
pre.style.display = 'none'
container.append(pre)
}
if (pre.style.display === 'block') {
pre.style.display = 'none'
code.style.display = 'block'
} else {
pre.style.display = 'block'
code.style.display = 'none'
}
pre.textContent = content
}
const createPretty = (copy) => {
if (copy.previousElementSibling && copy.previousElementSibling.className === formatBtn_class) {
return
}
const code = getCodeByCopyBtn(copy)
const prettyBtn = document.createElement('button')
const [formatText, unFormatText] = ['格式化查看', '取消格式化']
prettyBtn.textContent = formatText
prettyBtn.onclick = () => {
replacePre(code, prettyData(code.textContent))
prettyBtn.textContent = prettyBtn.textContent === unFormatText ? formatText : unFormatText
}
prettyBtn.className = formatBtn_class
copy.before(prettyBtn)
}
waitEl(() => {
const copy = Array.from(document.querySelectorAll(copy_selector))
copy.forEach(createPretty)
}, copy_selector, code_selector)
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment