feat: add JSON Viewer support and related configurations (#643)

* feat: add JSON Viewer support and related configurations

* feat: add JSON Viewer initialization and theme switching support
This commit is contained in:
Cell
2025-10-14 15:03:45 +08:00
committed by GitHub
parent 55a9cc7671
commit fa94e69877
23 changed files with 184 additions and 14 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
# To get started with Dependabot version updates, you'll need to specify which # To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located. # package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options: # Please see the documentation for all configuration options:
# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2 version: 2
updates: updates:
@@ -0,0 +1,84 @@
---
title: JSON Viewer Test
date: 2025-10-14T12:29:06+08:00
collections:
- Tests
categories:
- Markdown
tags:
- json
---
Testing JSON viewer in FixIt theme.
```json {boxed=false}
{
"foo": "bar"
}
```
<!--more-->
## JSON Viewer
```json
{
"name": "John Doe",
"age": 30,
"isEmployed": true,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"postalCode": "12345"
},
"phoneNumbers": [
{
"type": "home",
"number": "555-1234"
},
{
"type": "work",
"number": "555-5678"
}
],
"children": [],
"spouse": null
}
```
disabled copy:
```json {copyable=false}
{
"foo": "bar"
}
```
## JSON Code
```json {enable=false}
{
"name": "John Doe",
"age": 30,
"isEmployed": true,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"postalCode": "12345"
},
"phoneNumbers": [
{
"type": "home",
"number": "555-1234"
},
{
"type": "work",
"number": "555-5678"
}
],
"children": [],
"spouse": null
}
```
+2
View File
@@ -39,6 +39,8 @@ libFiles:
gitalkJS: gitalk@1.7.2/dist/gitalk.min.js gitalkJS: gitalk@1.7.2/dist/gitalk.min.js
# instant.page@5.2.0 https://github.com/instantpage/instant.page # instant.page@5.2.0 https://github.com/instantpage/instant.page
instantPage: instant.page@5.2.0/instantpage.min.js instantPage: instant.page@5.2.0/instantpage.min.js
# json-viewer-element@1.0.0 https://github.com/Lruihao/json-viewer-element
jsonViewerElementJS: json-viewer-element@1.0.0/dist/json-viewer-element.umd.js
# katex@0.16.22 https://github.com/KaTeX/KaTeX # katex@0.16.22 https://github.com/KaTeX/KaTeX
katexCopyTexJS: katex@0.16.22/dist/contrib/copy-tex.min.js katexCopyTexJS: katex@0.16.22/dist/contrib/copy-tex.min.js
katexCSS: katex@0.16.22/dist/katex.min.css katexCSS: katex@0.16.22/dist/katex.min.css
+2
View File
@@ -39,6 +39,8 @@ libFiles:
gitalkJS: gitalk@1.7.2/dist/gitalk.min.js gitalkJS: gitalk@1.7.2/dist/gitalk.min.js
# instant.page@5.2.0 https://github.com/instantpage/instant.page # instant.page@5.2.0 https://github.com/instantpage/instant.page
instantPage: instant.page@5.2.0/instantpage.js instantPage: instant.page@5.2.0/instantpage.js
# json-viewer-element@1.0.0 https://github.com/Lruihao/json-viewer-element
jsonViewerElementJS: json-viewer-element@1.0.0/dist/json-viewer-element.umd.js
# katex@0.16.22 https://github.com/KaTeX/KaTeX # katex@0.16.22 https://github.com/KaTeX/KaTeX
katexCopyTexJS: katex@0.16.22/dist/contrib/copy-tex.min.js katexCopyTexJS: katex@0.16.22/dist/contrib/copy-tex.min.js
katexCSS: katex@0.16.22/dist/katex.min.css katexCSS: katex@0.16.22/dist/katex.min.css
+16
View File
@@ -1083,6 +1083,19 @@ class FixIt {
window.MathJax?.typeset && window.MathJax.typeset(); window.MathJax?.typeset && window.MathJax.typeset();
} }
initJsonViewer() {
if (!window.JsonViewerElement) {
return;
}
this._jsonViewerOnSwitchTheme = this._jsonViewerOnSwitchTheme || (() => {
this.util.forEach(document.getElementsByTagName('json-viewer'), ($el) => {
$el.setAttribute('theme', this.isDark ? 'dark' : 'light');
});
});
this.switchThemeEventSet.add(this._jsonViewerOnSwitchTheme);
this._jsonViewerOnSwitchTheme();
}
initFixItDecryptor() { initFixItDecryptor() {
this.decryptor = new FixItDecryptor({ this.decryptor = new FixItDecryptor({
decrypted: () => { decrypted: () => {
@@ -1100,6 +1113,7 @@ class FixIt {
this.initTocListener(); this.initTocListener();
this.initPangu(); this.initPangu();
this.initMathJax(); this.initMathJax();
this.initJsonViewer();
window.FixItMermaid?.init?.(); window.FixItMermaid?.init?.();
this.util.forEach(document.querySelectorAll('.encrypted-hidden'), ($element) => { this.util.forEach(document.querySelectorAll('.encrypted-hidden'), ($element) => {
$element.classList.replace('encrypted-hidden', 'decrypted-shown'); $element.classList.replace('encrypted-hidden', 'decrypted-shown');
@@ -1117,6 +1131,7 @@ class FixIt {
this.initMapbox(); this.initMapbox();
this.initPangu(); this.initPangu();
this.initMathJax(); this.initMathJax();
this.initJsonViewer();
window.FixItMermaid?.init?.(); window.FixItMermaid?.init?.();
this.util.forEach($content.querySelectorAll('.encrypted-hidden'), ($element) => { this.util.forEach($content.querySelectorAll('.encrypted-hidden'), ($element) => {
$element.classList.replace('encrypted-hidden', 'decrypted-shown'); $element.classList.replace('encrypted-hidden', 'decrypted-shown');
@@ -1318,6 +1333,7 @@ class FixIt {
this.initTypeit(); this.initTypeit();
this.initMapbox(); this.initMapbox();
this.initPangu(); this.initPangu();
this.initJsonViewer();
} }
this.initThemeColor(); this.initThemeColor();
this.initSVGIcon(); this.initSVGIcon();
File diff suppressed because one or more lines are too long
+9
View File
@@ -1083,6 +1083,15 @@ cacheRemote = false
# Image resizing and optimisation # Image resizing and optimisation
optimise = false optimise = false
# FixIt 0.4.0 | NEW JSON Viewer config
# See https://github.com/Lruihao/json-viewer-element
[params.jsonViewer]
enable = true
expandDepth = 1
copyable = true
sort = false
boxed = true
# FixIt 0.3.12 | NEW Custom partials config # FixIt 0.3.12 | NEW Custom partials config
# Custom partials must be stored in the /layouts/partials/ directory. # Custom partials must be stored in the /layouts/partials/ directory.
# Depends on open custom blocks https://fixit.lruihao.cn/references/blocks/ # Depends on open custom blocks https://fixit.lruihao.cn/references/blocks/
+3 -1
View File
@@ -97,8 +97,10 @@ clear = "Leeren"
cancel = "Abbrechen" cancel = "Abbrechen"
noResultsFound = "Keine Ergebnisse gefunden" noResultsFound = "Keine Ergebnisse gefunden"
copyToClipboard = "In Zwischenablage kopieren" copyToClipboard = "In Zwischenablage kopieren"
copyText = "Kopieren"
copiedText = "Kopiert"
editLockTitle = "Bearbeitbaren Codeblock sperren" editLockTitle = "Bearbeitbaren Codeblock sperren"
editUnLockTitle = "Bearbeiten des Codeblocks entsperren" editUnLockTitle = "Bearbeitbaren Codeblock entsperren"
cookieconsentMessage = "Diese Website verwendet Cookies, um Ihre Erfahrung zu verbessern." cookieconsentMessage = "Diese Website verwendet Cookies, um Ihre Erfahrung zu verbessern."
cookieconsentDismiss = "Zustimmen" cookieconsentDismiss = "Zustimmen"
cookieconsentLink = "Erfahren Sie mehr" cookieconsentLink = "Erfahren Sie mehr"
+2
View File
@@ -97,6 +97,8 @@ clear = "Clear"
cancel = "Cancel" cancel = "Cancel"
noResultsFound = "No results found" noResultsFound = "No results found"
copyToClipboard = "Copy to clipboard" copyToClipboard = "Copy to clipboard"
copyText = "Copy"
copiedText = "Copied"
editLockTitle = "Lock editable code block" editLockTitle = "Lock editable code block"
editUnLockTitle = "Unlock editable code block" editUnLockTitle = "Unlock editable code block"
cookieconsentMessage = "This website uses Cookies to improve your experience." cookieconsentMessage = "This website uses Cookies to improve your experience."
+2
View File
@@ -97,6 +97,8 @@ clear = "Limpiar"
cancel = "Cancelar" cancel = "Cancelar"
noResultsFound = "No se encontraron resultados" noResultsFound = "No se encontraron resultados"
copyToClipboard = "Copiar al portapapeles" copyToClipboard = "Copiar al portapapeles"
copyText = "Copiar"
copiedText = "Copiado"
editLockTitle = "Bloquear bloque de código editable" editLockTitle = "Bloquear bloque de código editable"
editUnLockTitle = "Desbloquear bloque de código editable" editUnLockTitle = "Desbloquear bloque de código editable"
cookieconsentMessage = "Este sitio web utiliza Cookies para mejorar su experiencia." cookieconsentMessage = "Este sitio web utiliza Cookies para mejorar su experiencia."
+2
View File
@@ -97,6 +97,8 @@ clear = "Effacer"
cancel = "Annuler" cancel = "Annuler"
noResultsFound = "Aucun résultat trouvé" noResultsFound = "Aucun résultat trouvé"
copyToClipboard = "Copier dans le presse-papiers" copyToClipboard = "Copier dans le presse-papiers"
copyText = "Copier"
copiedText = "Copié"
editLockTitle = "Verrouiller le bloc de code modifiable" editLockTitle = "Verrouiller le bloc de code modifiable"
editUnLockTitle = "Déverrouiller le bloc de code modifiable" editUnLockTitle = "Déverrouiller le bloc de code modifiable"
cookieconsentMessage = "Ce site Web utilise des Cookies pour améliorer votre expérience." cookieconsentMessage = "Ce site Web utilise des Cookies pour améliorer votre expérience."
+4 -2
View File
@@ -98,8 +98,10 @@ clear = "साफ़ करें"
cancel = "रद्द करें" cancel = "रद्द करें"
noResultsFound = "कोई परिणाम नहीं मिला" noResultsFound = "कोई परिणाम नहीं मिला"
copyToClipboard = "क्लिपबोर्ड पर कॉपी करें" copyToClipboard = "क्लिपबोर्ड पर कॉपी करें"
editLockTitle = "संपादन योग्य कोड ब्लॉक को लॉक करें" copyText = "कॉपी करें"
editUnLockTitle = "संपादन योग्य कोड ब्लॉक को अनलॉक करें" copiedText = "कॉपी किया गया"
editLockTitle = "संपादन योग्य कोड ब्लॉक लॉक करें"
editUnLockTitle = "संपादन योग्य कोड ब्लॉक अनलॉक करें"
cookieconsentMessage = "यह वेबसाइट आपके अनुभव को बेहतर बनाने के लिए कुकीज़ का उपयोग करती है।" cookieconsentMessage = "यह वेबसाइट आपके अनुभव को बेहतर बनाने के लिए कुकीज़ का उपयोग करती है।"
cookieconsentDismiss = "समझ गया!" cookieconsentDismiss = "समझ गया!"
cookieconsentLink = "और अधिक जानें" cookieconsentLink = "और अधिक जानें"
+4 -2
View File
@@ -97,8 +97,10 @@ clear = "Chiaro"
cancel = "Annulla" cancel = "Annulla"
noResultsFound = "Nessun risultato trovato" noResultsFound = "Nessun risultato trovato"
copyToClipboard = "Copia negli appunti" copyToClipboard = "Copia negli appunti"
editLockTitle = "Blocca blocco di codice modificabile" copyText = "Copia"
editUnLockTitle = "Sblocca il blocco di codice modificabile" copiedText = "Copiato"
editLockTitle = "Blocca blocco codice modificabile"
editUnLockTitle = "Sblocca blocco codice modificabile"
cookieconsentMessage = "Questo sito Web utilizza i Cookies per migliorare la tua esperienza." cookieconsentMessage = "Questo sito Web utilizza i Cookies per migliorare la tua esperienza."
cookieconsentDismiss = "Essere d'accordo" cookieconsentDismiss = "Essere d'accordo"
cookieconsentLink = "Per saperne di più" cookieconsentLink = "Per saperne di più"
+2
View File
@@ -97,6 +97,8 @@ clear = "Pusty"
cancel = "Anuluj" cancel = "Anuluj"
noResultsFound = "Nie znaleziono wyników" noResultsFound = "Nie znaleziono wyników"
copyToClipboard = "Skopiuj do schowka" copyToClipboard = "Skopiuj do schowka"
copyText = "Kopiuj"
copiedText = "Skopiowano"
editLockTitle = "Zablokuj edytowalny blok kodu" editLockTitle = "Zablokuj edytowalny blok kodu"
editUnLockTitle = "Odblokuj edytowalny blok kodu" editUnLockTitle = "Odblokuj edytowalny blok kodu"
cookieconsentMessage = "Ta strona korzysta z plików Cookies, aby poprawić komfort użytkowania." cookieconsentMessage = "Ta strona korzysta z plików Cookies, aby poprawić komfort użytkowania."
+3 -1
View File
@@ -98,8 +98,10 @@ clear = "Limpar"
cancel = "Cancelar" cancel = "Cancelar"
noResultsFound = "Nenhum resultado encontrado" noResultsFound = "Nenhum resultado encontrado"
copyToClipboard = "Copiar para a área de transferência" copyToClipboard = "Copiar para a área de transferência"
copyText = "Copiar"
copiedText = "Copiado"
editLockTitle = "Bloquear bloco de código editável" editLockTitle = "Bloquear bloco de código editável"
editUnLockTitle = "Desbloquear o bloco de código editável" editUnLockTitle = "Desbloquear bloco de código editável"
cookieconsentMessage = "Este site usa Cookies para melhorar sua experiência." cookieconsentMessage = "Este site usa Cookies para melhorar sua experiência."
cookieconsentDismiss = "Aceitar" cookieconsentDismiss = "Aceitar"
cookieconsentLink = "Saber mais" cookieconsentLink = "Saber mais"
+2
View File
@@ -97,6 +97,8 @@ clear = "Golire"
cancel = "Anulare" cancel = "Anulare"
noResultsFound = "Nici un rezultat gasit" noResultsFound = "Nici un rezultat gasit"
copyToClipboard = "Copiați în clipboard" copyToClipboard = "Copiați în clipboard"
copyText = "Copiază"
copiedText = "Copiat"
editLockTitle = "Blocați blocul de cod editabil" editLockTitle = "Blocați blocul de cod editabil"
editUnLockTitle = "Deblocați blocul de cod editabil" editUnLockTitle = "Deblocați blocul de cod editabil"
cookieconsentMessage = "Acest site web utilizează Cookies pentru a vă îmbunătăți experiența." cookieconsentMessage = "Acest site web utilizează Cookies pentru a vă îmbunătăți experiența."
+4 -2
View File
@@ -95,9 +95,11 @@ searchIn = "Поиск в {{ . }}"
gotoResultsPage = "Перейти на страницу результатов поиска ..." gotoResultsPage = "Перейти на страницу результатов поиска ..."
clear = "Очистить" clear = "Очистить"
cancel = "Отменить" cancel = "Отменить"
noResultsFound = "Результатов не найдено" noResultsFound = "Результаты не найдены"
copyToClipboard = "Копировать в буфер обмена" copyToClipboard = "Копировать в буфер обмена"
editLockTitle = "Заблокировать редактируемый кодовый блок" copyText = "Копировать"
copiedText = "Скопировано"
editLockTitle = "Заблокировать редактируемый блок кода"
editUnLockTitle = "Разблокировать редактируемый блок кода" editUnLockTitle = "Разблокировать редактируемый блок кода"
cookieconsentMessage = "Этот сайт использует Cookies для улучшения вашего опыта." cookieconsentMessage = "Этот сайт использует Cookies для улучшения вашего опыта."
cookieconsentDismiss = "Согласен" cookieconsentDismiss = "Согласен"
+4 -2
View File
@@ -95,10 +95,12 @@ searchIn = "Претражи у {{ . }}"
gotoResultsPage = "Иди на страницу резултата претраге ..." gotoResultsPage = "Иди на страницу резултата претраге ..."
clear = "Очисти" clear = "Очисти"
cancel = "Поништи" cancel = "Поништи"
noResultsFound = "Без резултата" noResultsFound = "Резултати нису пронађени"
copyToClipboard = "Копирај на радну таблу" copyToClipboard = "Копирај на радну таблу"
copyText = "Копирај"
copiedText = "Копирано"
editLockTitle = "Закључај блок кода који се може уређивати" editLockTitle = "Закључај блок кода који се може уређивати"
editUnLockTitle = "Откључајте блок кода који се може уређивати" editUnLockTitle = "Откључај блок кода који се може уређивати"
cookieconsentMessage = "Ова веб локација користи Cookies да би побољшала ваше искуство." cookieconsentMessage = "Ова веб локација користи Cookies да би побољшала ваше искуство."
cookieconsentDismiss = "Договорити се" cookieconsentDismiss = "Договорити се"
cookieconsentLink = "Сазнајте више" cookieconsentLink = "Сазнајте више"
+3 -1
View File
@@ -94,8 +94,10 @@ searchIn = "Tìm kiếm trong {{ . }}"
gotoResultsPage = "Đi đến trang kết quả tìm kiếm ..." gotoResultsPage = "Đi đến trang kết quả tìm kiếm ..."
clear = "Xoá" clear = "Xoá"
cancel = "Huỷ" cancel = "Huỷ"
noResultsFound = "Không tìm thấy" noResultsFound = "Không tìm thấy kết quả"
copyToClipboard = "Sao chép vào bộ nhớ tạm" copyToClipboard = "Sao chép vào bộ nhớ tạm"
copyText = "Sao chép"
copiedText = "Đã sao chép"
editLockTitle = "Khóa khối mã có thể chỉnh sửa" editLockTitle = "Khóa khối mã có thể chỉnh sửa"
editUnLockTitle = "Mở khóa khối mã có thể chỉnh sửa" editUnLockTitle = "Mở khóa khối mã có thể chỉnh sửa"
cookieconsentMessage = "Trang web này sử dụng Cookies để cải thiện trải nghiệm của bạn." cookieconsentMessage = "Trang web này sử dụng Cookies để cải thiện trải nghiệm của bạn."
+2
View File
@@ -95,6 +95,8 @@ clear = "清空"
cancel = "取消" cancel = "取消"
noResultsFound = "没有找到结果" noResultsFound = "没有找到结果"
copyToClipboard = "复制到剪贴板" copyToClipboard = "复制到剪贴板"
copyText = "复制"
copiedText = "已复制"
editLockTitle = "锁定可编辑代码块" editLockTitle = "锁定可编辑代码块"
editUnLockTitle = "解锁可编辑代码块" editUnLockTitle = "解锁可编辑代码块"
cookieconsentMessage = "本网站使用 Cookies 来改善您的浏览体验。" cookieconsentMessage = "本网站使用 Cookies 来改善您的浏览体验。"
+4 -2
View File
@@ -95,8 +95,10 @@ clear = "清除"
cancel = "取消" cancel = "取消"
noResultsFound = "沒有找到結果" noResultsFound = "沒有找到結果"
copyToClipboard = "複製到剪貼板" copyToClipboard = "複製到剪貼板"
editLockTitle = "鎖定可編輯代碼塊" copyText = "複製"
editUnLockTitle = "解鎖可編輯代碼塊" copiedText = "已複製"
editLockTitle = "鎖定可編輯程式碼區塊"
editUnLockTitle = "解鎖可編輯程式碼區塊"
cookieconsentMessage = "本網站使用 Cookies 來改善您的流覽體驗。" cookieconsentMessage = "本網站使用 Cookies 來改善您的流覽體驗。"
cookieconsentDismiss = "同意" cookieconsentDismiss = "同意"
cookieconsentLink = "瞭解更多" cookieconsentLink = "瞭解更多"
@@ -0,0 +1,22 @@
{{- $jsonViewer := .Attributes | merge (.Page.Param "jsonViewer") -}}
{{- if $jsonViewer.enable -}}
{{- $attrs := printf `expand-depth="%v"` $jsonViewer.expanddepth -}}
{{- $copyable := false -}}
{{- with $jsonViewer.copyable -}}
{{- $copyable = dict "copyText" (T "assets.copyText") "copiedText" (T "assets.copiedText") -}}
{{- end -}}
{{- with $jsonViewer.sort -}}
{{- $attrs = " sort" | add $attrs -}}
{{- end -}}
{{- with $jsonViewer.boxed -}}
{{- $attrs = " boxed" | add $attrs -}}
{{- end -}}
<json-viewer value="{{ .Inner | jsonify }}" {{ $attrs | safeHTMLAttr }}{{ with $copyable}} copyable="{{ . | jsonify }}"{{ end }}></json-viewer>
{{- .Page.Store.Set "hasJsonViewer" true -}}
{{- if eq hugo.Context.MarkupScope "home" -}}
{{- site.Home.Store.Set "hasJsonViewer" true -}}
{{- end -}}
{{- else -}}
{{- $result := transform.HighlightCodeBlock . -}}
{{- $result.Wrapped -}}
{{- end -}}
+6
View File
@@ -60,6 +60,12 @@ FixIt theme assets partial
{{- dict "Source" $source "Fingerprint" $fingerprint "Attr" `type="module"` "Async" true "Defer" true | dict "Page" . "Data" | partial "store/script.html" -}} {{- dict "Source" $source "Fingerprint" $fingerprint "Attr" `type="module"` "Async" true "Defer" true | dict "Page" . "Data" | partial "store/script.html" -}}
{{- end -}} {{- end -}}
{{- /* JSON Viewer */ -}}
{{- if .Store.Get "hasJsonViewer" -}}
{{- $source := $cdn.jsonViewerElementJS | default "lib/json-viewer-element/json-viewer-element.umd.js" -}}
{{- dict "Source" $source "Fingerprint" $fingerprint "Defer" true | dict "Page" . "Data" | partial "store/script.html" -}}
{{- end -}}
{{- /* twemoji */ -}} {{- /* twemoji */ -}}
{{- if $params.twemoji -}} {{- if $params.twemoji -}}
{{- $source := $cdn.twemojiJS | default "lib/twemoji/twemoji.min.js" -}} {{- $source := $cdn.twemojiJS | default "lib/twemoji/twemoji.min.js" -}}