Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions bun.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -71,6 +71,7 @@
"luxon": "3.6.1",
"marked": "17.0.1",
"marked-shiki": "1.2.1",
"mermaid": "11.4.1",
"remend": "1.3.0",
"@playwright/test": "1.59.1",
"semver": "7.7.4",
Expand Down
1 change: 1 addition & 0 deletions packages/app/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -84,6 +84,7 @@
"luxon": "catalog:",
"marked": "catalog:",
"marked-shiki": "catalog:",
"mermaid": "catalog:",
"remeda": "catalog:",
"shiki": "catalog:",
"solid-js": "catalog:",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ar.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -571,6 +571,8 @@ export const dict = {
"session.files.all": "كل الملفات",
"session.files.empty": "لا توجد ملفات",
"session.files.binaryContent": "ملف ثنائي (لا يمكن عرض المحتوى)",
"session.files.viewPreview": "معاينة",
"session.files.viewSource": "مصدر",
"session.messages.renderEarlier": "عرض الرسائل السابقة",
"session.messages.loadingEarlier": "جارٍ تحميل الرسائل السابقة...",
"session.messages.loadEarlier": "تحميل الرسائل السابقة",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/br.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,6 +576,8 @@ export const dict = {
"session.files.all": "Todos os arquivos",
"session.files.empty": "Nenhum arquivo",
"session.files.binaryContent": "Arquivo binário (conteúdo não pode ser exibido)",
"session.files.viewPreview": "Pré-visualização",
"session.files.viewSource": "Código-fonte",
"session.messages.renderEarlier": "Renderizar mensagens anteriores",
"session.messages.loadingEarlier": "Carregando mensagens anteriores...",
"session.messages.loadEarlier": "Carregar mensagens anteriores",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/bs.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -629,6 +629,8 @@ export const dict = {
"session.files.all": "Sve datoteke",
"session.files.empty": "Nema datoteka",
"session.files.binaryContent": "Binarna datoteka (sadržaj se ne može prikazati)",
"session.files.viewPreview": "Pregled",
"session.files.viewSource": "Izvor",

"session.messages.renderEarlier": "Prikaži ranije poruke",
"session.messages.loadingEarlier": "Učitavanje ranijih poruka...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/da.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -625,6 +625,8 @@ export const dict = {
"session.files.all": "Alle filer",
"session.files.empty": "Ingen filer",
"session.files.binaryContent": "Binær fil (indhold kan ikke vises)",
"session.files.viewPreview": "Forhåndsvisning",
"session.files.viewSource": "Kilde",
"session.messages.renderEarlier": "Vis tidligere beskeder",
"session.messages.loadingEarlier": "Indlæser tidligere beskeder...",
"session.messages.loadEarlier": "Indlæs tidligere beskeder",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/de.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -585,6 +585,8 @@ export const dict = {
"session.files.all": "Alle Dateien",
"session.files.empty": "Keine Dateien",
"session.files.binaryContent": "Binärdatei (Inhalt kann nicht angezeigt werden)",
"session.files.viewPreview": "Vorschau",
"session.files.viewSource": "Quelle",
"session.messages.renderEarlier": "Frühere Nachrichten rendern",
"session.messages.loadingEarlier": "Lade frühere Nachrichten...",
"session.messages.loadEarlier": "Frühere Nachrichten laden",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/en.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -651,6 +651,8 @@ export const dict = {
"session.files.all": "All files",
"session.files.empty": "No files",
"session.files.binaryContent": "Binary file (content cannot be displayed)",
"session.files.viewPreview": "Preview",
"session.files.viewSource": "Source",

"session.messages.renderEarlier": "Render earlier messages",
"session.messages.loadingEarlier": "Loading earlier messages...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/es.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -630,6 +630,8 @@ export const dict = {
"session.files.all": "Todos los archivos",
"session.files.empty": "Sin archivos",
"session.files.binaryContent": "Archivo binario (el contenido no puede ser mostrado)",
"session.files.viewPreview": "Vista previa",
"session.files.viewSource": "Fuente",

"session.messages.renderEarlier": "Renderizar mensajes anteriores",
"session.messages.loadingEarlier": "Cargando mensajes anteriores...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/fr.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -581,6 +581,8 @@ export const dict = {
"session.files.all": "Tous les fichiers",
"session.files.empty": "Aucun fichier",
"session.files.binaryContent": "Fichier binaire (le contenu ne peut pas être affiché)",
"session.files.viewPreview": "Aperçu",
"session.files.viewSource": "Source",
"session.messages.renderEarlier": "Afficher les messages précédents",
"session.messages.loadingEarlier": "Chargement des messages précédents...",
"session.messages.loadEarlier": "Charger les messages précédents",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ja.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -573,6 +573,8 @@ export const dict = {
"session.files.all": "すべてのファイル",
"session.files.empty": "ファイルなし",
"session.files.binaryContent": "バイナリファイル(内容を表示できません)",
"session.files.viewPreview": "プレビュー",
"session.files.viewSource": "ソース",
"session.messages.renderEarlier": "以前のメッセージを表示",
"session.messages.loadingEarlier": "以前のメッセージを読み込み中...",
"session.messages.loadEarlier": "以前のメッセージを読み込む",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ko.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -465,6 +465,8 @@ export const dict = {
"session.files.all": "모든 파일",
"session.files.empty": "파일 없음",
"session.files.binaryContent": "바이너리 파일 (내용을 표시할 수 없음)",
"session.files.viewPreview": "미리보기",
"session.files.viewSource": "소스",
"session.messages.renderEarlier": "이전 메시지 렌더링",
"session.messages.loadingEarlier": "이전 메시지 로드 중...",
"session.messages.loadEarlier": "이전 메시지 로드",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/no.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -524,6 +524,8 @@ export const dict = {
"session.files.all": "Alle filer",
"session.files.empty": "Ingen filer",
"session.files.binaryContent": "Binær fil (innhold kan ikke vises)",
"session.files.viewPreview": "Forhåndsvisning",
"session.files.viewSource": "Kilde",

"session.messages.renderEarlier": "Vis tidligere meldinger",
"session.messages.loadingEarlier": "Laster inn tidligere meldinger...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/pl.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,6 +576,8 @@ export const dict = {
"session.files.all": "Wszystkie pliki",
"session.files.empty": "Brak plików",
"session.files.binaryContent": "Plik binarny (zawartość nie może być wyświetlona)",
"session.files.viewPreview": "Podgląd",
"session.files.viewSource": "Źródło",
"session.messages.renderEarlier": "Renderuj wcześniejsze wiadomości",
"session.messages.loadingEarlier": "Ładowanie wcześniejszych wiadomości...",
"session.messages.loadEarlier": "Załaduj wcześniejsze wiadomości",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ru.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -628,6 +628,8 @@ export const dict = {
"session.files.all": "Все файлы",
"session.files.empty": "Нет файлов",
"session.files.binaryContent": "Двоичный файл (содержимое не может быть отображено)",
"session.files.viewPreview": "Предпросмотр",
"session.files.viewSource": "Исходный код",
"session.messages.renderEarlier": "Показать предыдущие сообщения",
"session.messages.loadingEarlier": "Загрузка предыдущих сообщений...",
"session.messages.loadEarlier": "Загрузить предыдущие сообщения",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/th.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -624,6 +624,8 @@ export const dict = {
"session.files.empty": "ไม่มีไฟล์",
"session.files.all": "ไฟล์ทั้งหมด",
"session.files.binaryContent": "ไฟล์ไบนารี (ไม่สามารถแสดงเนื้อหาได้)",
"session.files.viewPreview": "ดูตัวอย่าง",
"session.files.viewSource": "ซอร์สโค้ด",

"session.messages.renderEarlier": "แสดงข้อความก่อนหน้า",
"session.messages.loadingEarlier": "กำลังโหลดข้อความก่อนหน้า...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/tr.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -634,6 +634,8 @@ export const dict = {
"session.files.all": "Tüm dosyalar",
"session.files.empty": "Dosya yok",
"session.files.binaryContent": "İkili dosya (içerik görüntülenemiyor)",
"session.files.viewPreview": "Önizleme",
"session.files.viewSource": "Kaynak",

"session.messages.renderEarlier": "Önceki mesajları göster",
"session.messages.loadingEarlier": "Önceki mesajlar yükleniyor...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/zh.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -624,6 +624,8 @@ export const dict = {
"session.files.all": "所有文件",
"session.files.empty": "无文件",
"session.files.binaryContent": "二进制文件(无法显示内容)",
"session.files.viewPreview": "预览",
"session.files.viewSource": "源代码",
"session.messages.renderEarlier": "显示更早的消息",
"session.messages.loadingEarlier": "正在加载更早的消息...",
"session.messages.loadEarlier": "加载更早的消息",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/zht.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -619,6 +619,8 @@ export const dict = {
"session.files.all": "所有檔案",
"session.files.empty": "沒有檔案",
"session.files.binaryContent": "二進位檔案(無法顯示內容)",
"session.files.viewPreview": "預覽",
"session.files.viewSource": "原始碼",
"session.messages.renderEarlier": "顯示更早的訊息",
"session.messages.loadingEarlier": "正在載入更早的訊息...",
"session.messages.loadEarlier": "載入更早的訊息",
Expand Down
100 changes: 99 additions & 1 deletion packages/app/src/pages/session/file-tabs.tsx
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { createEffect, createMemo, createSignal, Match, on, onCleanup, Switch } from "solid-js"
import { createEffect, createMemo, createSignal, Match, on, onCleanup, Show, Switch } from "solid-js"
import { createStore } from "solid-js/store"
import { Dynamic } from "solid-js/web"
import { makeEventListener } from "@solid-primitives/event-listener"
Expand DownExpand Up@@ -211,6 +211,73 @@ export function FileTabContent(props: { tab: string }) {
view,
})

const isMarkdown = createMemo(() => {
const p = path()
return p ? /\.(?:md|markdown)$/i.test(p) : false
})
const [preview, setPreview] = createSignal(true)

let mermaidContainer: HTMLDivElement | undefined

const setupMermaidContainer = (el: HTMLDivElement) => {
mermaidContainer = el
}

createEffect(
on(
() => [mermaidContainer, preview(), contents()] as const,
([container, isPreview]) => {
if (typeof window === "undefined") return
if (!container || !isPreview) return
if (!isMarkdown()) return

const renderMermaid = () => {
mermaid.initialize({ startOnLoad: false })

const preBlocks = container.querySelectorAll("pre.shiki")
if (preBlocks.length === 0) return

preBlocks.forEach((pre) => {
if (!(pre instanceof HTMLPreElement)) return

const code = pre.querySelector("code")
if (!code) return

const lines = code.querySelectorAll(".line")
const text = Array.from(lines).map((line) => line.textContent).join("\n")

const mermaidKeywords =
/\b(graph|flowchart|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|journey|gitGraph|mindmap|requirement|timeline|zenuml)\b|->>|-->>|Note\b|loop\b|alt\b|opt\b\par\b/i.test(
text,
)
if (!mermaidKeywords) return

const div = document.createElement("div")
div.className = "mermaid"
div.textContent = text

pre.replaceWith(div)
})

const blocks = container.querySelectorAll(".mermaid")
if (blocks.length === 0) return

mermaid.run({ nodes: Array.from(blocks) as HTMLElement[] }).catch(() => {})
}

const tryRender = () => {
renderMermaid()
if (container.querySelectorAll(".mermaid").length === 0) {
setTimeout(tryRender, 100)
}
}

setTimeout(tryRender, 0)
},
{ defer: true },
),
)

const selectionPreview = (source: string, selection: FileSelection) => {
return previewSelectedLines(source, {
start: selection.startLine,
Expand DownExpand Up@@ -359,11 +426,21 @@ export function FileTabContent(props: { tab: string }) {
path,
() => {
commentsUi.note.reset()
setPreview(true)
},
{ defer: true },
),
)

createEffect(() => {
const focus = comments.focus()
const p = path()
if (!focus || !p) return
if (focus.file !== p) return
if (activeFileTab() !== props.tab) return
if (preview()) setPreview(false)
})

createEffect(() => {
const focus = comments.focus()
const p = path()
Expand DownExpand Up@@ -442,7 +519,28 @@ export function FileTabContent(props: { tab: string }) {
return (
<Tabs.Content value={props.tab} class="mt-3 relative h-full">
<ScrollView class="h-full" viewportRef={scrollSync.setViewport} onScroll={scrollSync.handleScroll as any}>
<Show when={state()?.loaded && isMarkdown() && state()?.content?.type !== "binary"}>
<div class="sticky top-0 z-10 flex items-center gap-1 bg-background-base px-4 py-1.5 border-b border-border-base">
<button
class={"px-2 py-0.5 rounded text-sm " + (preview() ? "bg-surface-base-active text-text-base" : "text-text-weak hover:text-text-base")}
onClick={() => setPreview(true)}
>
{language.t("session.files.viewPreview")}
</button>
<button
class={"px-2 py-0.5 rounded text-sm " + (!preview() ? "bg-surface-base-active text-text-base" : "text-text-weak hover:text-text-base")}
onClick={() => setPreview(false)}
>
{language.t("session.files.viewSource")}
</button>
</div>
</Show>
<Switch>
<Match when={state()?.loaded && isMarkdown() && preview() && state()?.content?.type !== "binary"}>
<div ref={setupMermaidContainer} class="px-6 py-4 pb-40">
<Markdown text={contents()} cacheKey={cacheKey()} />
</div>
</Match>
<Match when={state()?.loaded}>{renderFile(contents())}</Match>
<Match when={state()?.loading}>
<div class="px-6 py-4 text-text-weak">{language.t("common.loading")}...</div>
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
feat(app): add markdown preview with mermaid diagram support by Kiruno-lz · Pull Request #23688 · anomalyco/opencode · GitHub
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions bun.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -71,6 +71,7 @@
"luxon": "3.6.1",
"marked": "17.0.1",
"marked-shiki": "1.2.1",
"mermaid": "11.4.1",
"remend": "1.3.0",
"@playwright/test": "1.59.1",
"semver": "7.7.4",
Expand Down
1 change: 1 addition & 0 deletions packages/app/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -84,6 +84,7 @@
"luxon": "catalog:",
"marked": "catalog:",
"marked-shiki": "catalog:",
"mermaid": "catalog:",
"remeda": "catalog:",
"shiki": "catalog:",
"solid-js": "catalog:",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ar.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -571,6 +571,8 @@ export const dict = {
"session.files.all": "كل الملفات",
"session.files.empty": "لا توجد ملفات",
"session.files.binaryContent": "ملف ثنائي (لا يمكن عرض المحتوى)",
"session.files.viewPreview": "معاينة",
"session.files.viewSource": "مصدر",
"session.messages.renderEarlier": "عرض الرسائل السابقة",
"session.messages.loadingEarlier": "جارٍ تحميل الرسائل السابقة...",
"session.messages.loadEarlier": "تحميل الرسائل السابقة",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/br.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,6 +576,8 @@ export const dict = {
"session.files.all": "Todos os arquivos",
"session.files.empty": "Nenhum arquivo",
"session.files.binaryContent": "Arquivo binário (conteúdo não pode ser exibido)",
"session.files.viewPreview": "Pré-visualização",
"session.files.viewSource": "Código-fonte",
"session.messages.renderEarlier": "Renderizar mensagens anteriores",
"session.messages.loadingEarlier": "Carregando mensagens anteriores...",
"session.messages.loadEarlier": "Carregar mensagens anteriores",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/bs.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -629,6 +629,8 @@ export const dict = {
"session.files.all": "Sve datoteke",
"session.files.empty": "Nema datoteka",
"session.files.binaryContent": "Binarna datoteka (sadržaj se ne može prikazati)",
"session.files.viewPreview": "Pregled",
"session.files.viewSource": "Izvor",

"session.messages.renderEarlier": "Prikaži ranije poruke",
"session.messages.loadingEarlier": "Učitavanje ranijih poruka...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/da.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -625,6 +625,8 @@ export const dict = {
"session.files.all": "Alle filer",
"session.files.empty": "Ingen filer",
"session.files.binaryContent": "Binær fil (indhold kan ikke vises)",
"session.files.viewPreview": "Forhåndsvisning",
"session.files.viewSource": "Kilde",
"session.messages.renderEarlier": "Vis tidligere beskeder",
"session.messages.loadingEarlier": "Indlæser tidligere beskeder...",
"session.messages.loadEarlier": "Indlæs tidligere beskeder",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/de.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -585,6 +585,8 @@ export const dict = {
"session.files.all": "Alle Dateien",
"session.files.empty": "Keine Dateien",
"session.files.binaryContent": "Binärdatei (Inhalt kann nicht angezeigt werden)",
"session.files.viewPreview": "Vorschau",
"session.files.viewSource": "Quelle",
"session.messages.renderEarlier": "Frühere Nachrichten rendern",
"session.messages.loadingEarlier": "Lade frühere Nachrichten...",
"session.messages.loadEarlier": "Frühere Nachrichten laden",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/en.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -651,6 +651,8 @@ export const dict = {
"session.files.all": "All files",
"session.files.empty": "No files",
"session.files.binaryContent": "Binary file (content cannot be displayed)",
"session.files.viewPreview": "Preview",
"session.files.viewSource": "Source",

"session.messages.renderEarlier": "Render earlier messages",
"session.messages.loadingEarlier": "Loading earlier messages...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/es.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -630,6 +630,8 @@ export const dict = {
"session.files.all": "Todos los archivos",
"session.files.empty": "Sin archivos",
"session.files.binaryContent": "Archivo binario (el contenido no puede ser mostrado)",
"session.files.viewPreview": "Vista previa",
"session.files.viewSource": "Fuente",

"session.messages.renderEarlier": "Renderizar mensajes anteriores",
"session.messages.loadingEarlier": "Cargando mensajes anteriores...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/fr.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -581,6 +581,8 @@ export const dict = {
"session.files.all": "Tous les fichiers",
"session.files.empty": "Aucun fichier",
"session.files.binaryContent": "Fichier binaire (le contenu ne peut pas être affiché)",
"session.files.viewPreview": "Aperçu",
"session.files.viewSource": "Source",
"session.messages.renderEarlier": "Afficher les messages précédents",
"session.messages.loadingEarlier": "Chargement des messages précédents...",
"session.messages.loadEarlier": "Charger les messages précédents",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ja.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -573,6 +573,8 @@ export const dict = {
"session.files.all": "すべてのファイル",
"session.files.empty": "ファイルなし",
"session.files.binaryContent": "バイナリファイル(内容を表示できません)",
"session.files.viewPreview": "プレビュー",
"session.files.viewSource": "ソース",
"session.messages.renderEarlier": "以前のメッセージを表示",
"session.messages.loadingEarlier": "以前のメッセージを読み込み中...",
"session.messages.loadEarlier": "以前のメッセージを読み込む",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ko.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -465,6 +465,8 @@ export const dict = {
"session.files.all": "모든 파일",
"session.files.empty": "파일 없음",
"session.files.binaryContent": "바이너리 파일 (내용을 표시할 수 없음)",
"session.files.viewPreview": "미리보기",
"session.files.viewSource": "소스",
"session.messages.renderEarlier": "이전 메시지 렌더링",
"session.messages.loadingEarlier": "이전 메시지 로드 중...",
"session.messages.loadEarlier": "이전 메시지 로드",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/no.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -524,6 +524,8 @@ export const dict = {
"session.files.all": "Alle filer",
"session.files.empty": "Ingen filer",
"session.files.binaryContent": "Binær fil (innhold kan ikke vises)",
"session.files.viewPreview": "Forhåndsvisning",
"session.files.viewSource": "Kilde",

"session.messages.renderEarlier": "Vis tidligere meldinger",
"session.messages.loadingEarlier": "Laster inn tidligere meldinger...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/pl.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,6 +576,8 @@ export const dict = {
"session.files.all": "Wszystkie pliki",
"session.files.empty": "Brak plików",
"session.files.binaryContent": "Plik binarny (zawartość nie może być wyświetlona)",
"session.files.viewPreview": "Podgląd",
"session.files.viewSource": "Źródło",
"session.messages.renderEarlier": "Renderuj wcześniejsze wiadomości",
"session.messages.loadingEarlier": "Ładowanie wcześniejszych wiadomości...",
"session.messages.loadEarlier": "Załaduj wcześniejsze wiadomości",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ru.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -628,6 +628,8 @@ export const dict = {
"session.files.all": "Все файлы",
"session.files.empty": "Нет файлов",
"session.files.binaryContent": "Двоичный файл (содержимое не может быть отображено)",
"session.files.viewPreview": "Предпросмотр",
"session.files.viewSource": "Исходный код",
"session.messages.renderEarlier": "Показать предыдущие сообщения",
"session.messages.loadingEarlier": "Загрузка предыдущих сообщений...",
"session.messages.loadEarlier": "Загрузить предыдущие сообщения",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/th.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -624,6 +624,8 @@ export const dict = {
"session.files.empty": "ไม่มีไฟล์",
"session.files.all": "ไฟล์ทั้งหมด",
"session.files.binaryContent": "ไฟล์ไบนารี (ไม่สามารถแสดงเนื้อหาได้)",
"session.files.viewPreview": "ดูตัวอย่าง",
"session.files.viewSource": "ซอร์สโค้ด",

"session.messages.renderEarlier": "แสดงข้อความก่อนหน้า",
"session.messages.loadingEarlier": "กำลังโหลดข้อความก่อนหน้า...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/tr.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -634,6 +634,8 @@ export const dict = {
"session.files.all": "Tüm dosyalar",
"session.files.empty": "Dosya yok",
"session.files.binaryContent": "İkili dosya (içerik görüntülenemiyor)",
"session.files.viewPreview": "Önizleme",
"session.files.viewSource": "Kaynak",

"session.messages.renderEarlier": "Önceki mesajları göster",
"session.messages.loadingEarlier": "Önceki mesajlar yükleniyor...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/zh.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -624,6 +624,8 @@ export const dict = {
"session.files.all": "所有文件",
"session.files.empty": "无文件",
"session.files.binaryContent": "二进制文件(无法显示内容)",
"session.files.viewPreview": "预览",
"session.files.viewSource": "源代码",
"session.messages.renderEarlier": "显示更早的消息",
"session.messages.loadingEarlier": "正在加载更早的消息...",
"session.messages.loadEarlier": "加载更早的消息",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/zht.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -619,6 +619,8 @@ export const dict = {
"session.files.all": "所有檔案",
"session.files.empty": "沒有檔案",
"session.files.binaryContent": "二進位檔案(無法顯示內容)",
"session.files.viewPreview": "預覽",
"session.files.viewSource": "原始碼",
"session.messages.renderEarlier": "顯示更早的訊息",
"session.messages.loadingEarlier": "正在載入更早的訊息...",
"session.messages.loadEarlier": "載入更早的訊息",
Expand Down
100 changes: 99 additions & 1 deletion packages/app/src/pages/session/file-tabs.tsx
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { createEffect, createMemo, createSignal, Match, on, onCleanup, Switch } from "solid-js"
import { createEffect, createMemo, createSignal, Match, on, onCleanup, Show, Switch } from "solid-js"
import { createStore } from "solid-js/store"
import { Dynamic } from "solid-js/web"
import { makeEventListener } from "@solid-primitives/event-listener"
Expand DownExpand Up@@ -211,6 +211,73 @@ export function FileTabContent(props: { tab: string }) {
view,
})

const isMarkdown = createMemo(() => {
const p = path()
return p ? /\.(?:md|markdown)$/i.test(p) : false
})
const [preview, setPreview] = createSignal(true)

let mermaidContainer: HTMLDivElement | undefined

const setupMermaidContainer = (el: HTMLDivElement) => {
mermaidContainer = el
}

createEffect(
on(
() => [mermaidContainer, preview(), contents()] as const,
([container, isPreview]) => {
if (typeof window === "undefined") return
if (!container || !isPreview) return
if (!isMarkdown()) return

const renderMermaid = () => {
mermaid.initialize({ startOnLoad: false })

const preBlocks = container.querySelectorAll("pre.shiki")
if (preBlocks.length === 0) return

preBlocks.forEach((pre) => {
if (!(pre instanceof HTMLPreElement)) return

const code = pre.querySelector("code")
if (!code) return

const lines = code.querySelectorAll(".line")
const text = Array.from(lines).map((line) => line.textContent).join("\n")

const mermaidKeywords =
/\b(graph|flowchart|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|journey|gitGraph|mindmap|requirement|timeline|zenuml)\b|->>|-->>|Note\b|loop\b|alt\b|opt\b\par\b/i.test(
text,
)
if (!mermaidKeywords) return

const div = document.createElement("div")
div.className = "mermaid"
div.textContent = text

pre.replaceWith(div)
})

const blocks = container.querySelectorAll(".mermaid")
if (blocks.length === 0) return

mermaid.run({ nodes: Array.from(blocks) as HTMLElement[] }).catch(() => {})
}

const tryRender = () => {
renderMermaid()
if (container.querySelectorAll(".mermaid").length === 0) {
setTimeout(tryRender, 100)
}
}

setTimeout(tryRender, 0)
},
{ defer: true },
),
)

const selectionPreview = (source: string, selection: FileSelection) => {
return previewSelectedLines(source, {
start: selection.startLine,
Expand DownExpand Up@@ -359,11 +426,21 @@ export function FileTabContent(props: { tab: string }) {
path,
() => {
commentsUi.note.reset()
setPreview(true)
},
{ defer: true },
),
)

createEffect(() => {
const focus = comments.focus()
const p = path()
if (!focus || !p) return
if (focus.file !== p) return
if (activeFileTab() !== props.tab) return
if (preview()) setPreview(false)
})

createEffect(() => {
const focus = comments.focus()
const p = path()
Expand DownExpand Up@@ -442,7 +519,28 @@ export function FileTabContent(props: { tab: string }) {
return (
<Tabs.Content value={props.tab} class="mt-3 relative h-full">
<ScrollView class="h-full" viewportRef={scrollSync.setViewport} onScroll={scrollSync.handleScroll as any}>
<Show when={state()?.loaded && isMarkdown() && state()?.content?.type !== "binary"}>
<div class="sticky top-0 z-10 flex items-center gap-1 bg-background-base px-4 py-1.5 border-b border-border-base">
<button
class={"px-2 py-0.5 rounded text-sm " + (preview() ? "bg-surface-base-active text-text-base" : "text-text-weak hover:text-text-base")}
onClick={() => setPreview(true)}
>
{language.t("session.files.viewPreview")}
</button>
<button
class={"px-2 py-0.5 rounded text-sm " + (!preview() ? "bg-surface-base-active text-text-base" : "text-text-weak hover:text-text-base")}
onClick={() => setPreview(false)}
>
{language.t("session.files.viewSource")}
</button>
</div>
</Show>
<Switch>
<Match when={state()?.loaded && isMarkdown() && preview() && state()?.content?.type !== "binary"}>
<div ref={setupMermaidContainer} class="px-6 py-4 pb-40">
<Markdown text={contents()} cacheKey={cacheKey()} />
</div>
</Match>
<Match when={state()?.loaded}>{renderFile(contents())}</Match>
<Match when={state()?.loading}>
<div class="px-6 py-4 text-text-weak">{language.t("common.loading")}...</div>
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(app): add markdown preview with mermaid diagram support by Kiruno-lz · Pull Request #23688 · anomalyco/opencode · GitHub
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions bun.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -71,6 +71,7 @@
"luxon": "3.6.1",
"marked": "17.0.1",
"marked-shiki": "1.2.1",
"mermaid": "11.4.1",
"remend": "1.3.0",
"@playwright/test": "1.59.1",
"semver": "7.7.4",
Expand Down
1 change: 1 addition & 0 deletions packages/app/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -84,6 +84,7 @@
"luxon": "catalog:",
"marked": "catalog:",
"marked-shiki": "catalog:",
"mermaid": "catalog:",
"remeda": "catalog:",
"shiki": "catalog:",
"solid-js": "catalog:",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ar.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -571,6 +571,8 @@ export const dict = {
"session.files.all": "كل الملفات",
"session.files.empty": "لا توجد ملفات",
"session.files.binaryContent": "ملف ثنائي (لا يمكن عرض المحتوى)",
"session.files.viewPreview": "معاينة",
"session.files.viewSource": "مصدر",
"session.messages.renderEarlier": "عرض الرسائل السابقة",
"session.messages.loadingEarlier": "جارٍ تحميل الرسائل السابقة...",
"session.messages.loadEarlier": "تحميل الرسائل السابقة",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/br.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,6 +576,8 @@ export const dict = {
"session.files.all": "Todos os arquivos",
"session.files.empty": "Nenhum arquivo",
"session.files.binaryContent": "Arquivo binário (conteúdo não pode ser exibido)",
"session.files.viewPreview": "Pré-visualização",
"session.files.viewSource": "Código-fonte",
"session.messages.renderEarlier": "Renderizar mensagens anteriores",
"session.messages.loadingEarlier": "Carregando mensagens anteriores...",
"session.messages.loadEarlier": "Carregar mensagens anteriores",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/bs.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -629,6 +629,8 @@ export const dict = {
"session.files.all": "Sve datoteke",
"session.files.empty": "Nema datoteka",
"session.files.binaryContent": "Binarna datoteka (sadržaj se ne može prikazati)",
"session.files.viewPreview": "Pregled",
"session.files.viewSource": "Izvor",

"session.messages.renderEarlier": "Prikaži ranije poruke",
"session.messages.loadingEarlier": "Učitavanje ranijih poruka...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/da.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -625,6 +625,8 @@ export const dict = {
"session.files.all": "Alle filer",
"session.files.empty": "Ingen filer",
"session.files.binaryContent": "Binær fil (indhold kan ikke vises)",
"session.files.viewPreview": "Forhåndsvisning",
"session.files.viewSource": "Kilde",
"session.messages.renderEarlier": "Vis tidligere beskeder",
"session.messages.loadingEarlier": "Indlæser tidligere beskeder...",
"session.messages.loadEarlier": "Indlæs tidligere beskeder",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/de.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -585,6 +585,8 @@ export const dict = {
"session.files.all": "Alle Dateien",
"session.files.empty": "Keine Dateien",
"session.files.binaryContent": "Binärdatei (Inhalt kann nicht angezeigt werden)",
"session.files.viewPreview": "Vorschau",
"session.files.viewSource": "Quelle",
"session.messages.renderEarlier": "Frühere Nachrichten rendern",
"session.messages.loadingEarlier": "Lade frühere Nachrichten...",
"session.messages.loadEarlier": "Frühere Nachrichten laden",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/en.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -651,6 +651,8 @@ export const dict = {
"session.files.all": "All files",
"session.files.empty": "No files",
"session.files.binaryContent": "Binary file (content cannot be displayed)",
"session.files.viewPreview": "Preview",
"session.files.viewSource": "Source",

"session.messages.renderEarlier": "Render earlier messages",
"session.messages.loadingEarlier": "Loading earlier messages...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/es.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -630,6 +630,8 @@ export const dict = {
"session.files.all": "Todos los archivos",
"session.files.empty": "Sin archivos",
"session.files.binaryContent": "Archivo binario (el contenido no puede ser mostrado)",
"session.files.viewPreview": "Vista previa",
"session.files.viewSource": "Fuente",

"session.messages.renderEarlier": "Renderizar mensajes anteriores",
"session.messages.loadingEarlier": "Cargando mensajes anteriores...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/fr.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -581,6 +581,8 @@ export const dict = {
"session.files.all": "Tous les fichiers",
"session.files.empty": "Aucun fichier",
"session.files.binaryContent": "Fichier binaire (le contenu ne peut pas être affiché)",
"session.files.viewPreview": "Aperçu",
"session.files.viewSource": "Source",
"session.messages.renderEarlier": "Afficher les messages précédents",
"session.messages.loadingEarlier": "Chargement des messages précédents...",
"session.messages.loadEarlier": "Charger les messages précédents",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ja.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -573,6 +573,8 @@ export const dict = {
"session.files.all": "すべてのファイル",
"session.files.empty": "ファイルなし",
"session.files.binaryContent": "バイナリファイル(内容を表示できません)",
"session.files.viewPreview": "プレビュー",
"session.files.viewSource": "ソース",
"session.messages.renderEarlier": "以前のメッセージを表示",
"session.messages.loadingEarlier": "以前のメッセージを読み込み中...",
"session.messages.loadEarlier": "以前のメッセージを読み込む",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ko.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -465,6 +465,8 @@ export const dict = {
"session.files.all": "모든 파일",
"session.files.empty": "파일 없음",
"session.files.binaryContent": "바이너리 파일 (내용을 표시할 수 없음)",
"session.files.viewPreview": "미리보기",
"session.files.viewSource": "소스",
"session.messages.renderEarlier": "이전 메시지 렌더링",
"session.messages.loadingEarlier": "이전 메시지 로드 중...",
"session.messages.loadEarlier": "이전 메시지 로드",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/no.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -524,6 +524,8 @@ export const dict = {
"session.files.all": "Alle filer",
"session.files.empty": "Ingen filer",
"session.files.binaryContent": "Binær fil (innhold kan ikke vises)",
"session.files.viewPreview": "Forhåndsvisning",
"session.files.viewSource": "Kilde",

"session.messages.renderEarlier": "Vis tidligere meldinger",
"session.messages.loadingEarlier": "Laster inn tidligere meldinger...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/pl.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,6 +576,8 @@ export const dict = {
"session.files.all": "Wszystkie pliki",
"session.files.empty": "Brak plików",
"session.files.binaryContent": "Plik binarny (zawartość nie może być wyświetlona)",
"session.files.viewPreview": "Podgląd",
"session.files.viewSource": "Źródło",
"session.messages.renderEarlier": "Renderuj wcześniejsze wiadomości",
"session.messages.loadingEarlier": "Ładowanie wcześniejszych wiadomości...",
"session.messages.loadEarlier": "Załaduj wcześniejsze wiadomości",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ru.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -628,6 +628,8 @@ export const dict = {
"session.files.all": "Все файлы",
"session.files.empty": "Нет файлов",
"session.files.binaryContent": "Двоичный файл (содержимое не может быть отображено)",
"session.files.viewPreview": "Предпросмотр",
"session.files.viewSource": "Исходный код",
"session.messages.renderEarlier": "Показать предыдущие сообщения",
"session.messages.loadingEarlier": "Загрузка предыдущих сообщений...",
"session.messages.loadEarlier": "Загрузить предыдущие сообщения",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/th.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -624,6 +624,8 @@ export const dict = {
"session.files.empty": "ไม่มีไฟล์",
"session.files.all": "ไฟล์ทั้งหมด",
"session.files.binaryContent": "ไฟล์ไบนารี (ไม่สามารถแสดงเนื้อหาได้)",
"session.files.viewPreview": "ดูตัวอย่าง",
"session.files.viewSource": "ซอร์สโค้ด",

"session.messages.renderEarlier": "แสดงข้อความก่อนหน้า",
"session.messages.loadingEarlier": "กำลังโหลดข้อความก่อนหน้า...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/tr.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -634,6 +634,8 @@ export const dict = {
"session.files.all": "Tüm dosyalar",
"session.files.empty": "Dosya yok",
"session.files.binaryContent": "İkili dosya (içerik görüntülenemiyor)",
"session.files.viewPreview": "Önizleme",
"session.files.viewSource": "Kaynak",

"session.messages.renderEarlier": "Önceki mesajları göster",
"session.messages.loadingEarlier": "Önceki mesajlar yükleniyor...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/zh.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -624,6 +624,8 @@ export const dict = {
"session.files.all": "所有文件",
"session.files.empty": "无文件",
"session.files.binaryContent": "二进制文件(无法显示内容)",
"session.files.viewPreview": "预览",
"session.files.viewSource": "源代码",
"session.messages.renderEarlier": "显示更早的消息",
"session.messages.loadingEarlier": "正在加载更早的消息...",
"session.messages.loadEarlier": "加载更早的消息",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/zht.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -619,6 +619,8 @@ export const dict = {
"session.files.all": "所有檔案",
"session.files.empty": "沒有檔案",
"session.files.binaryContent": "二進位檔案(無法顯示內容)",
"session.files.viewPreview": "預覽",
"session.files.viewSource": "原始碼",
"session.messages.renderEarlier": "顯示更早的訊息",
"session.messages.loadingEarlier": "正在載入更早的訊息...",
"session.messages.loadEarlier": "載入更早的訊息",
Expand Down
100 changes: 99 additions & 1 deletion packages/app/src/pages/session/file-tabs.tsx
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { createEffect, createMemo, createSignal, Match, on, onCleanup, Switch } from "solid-js"
import { createEffect, createMemo, createSignal, Match, on, onCleanup, Show, Switch } from "solid-js"
import { createStore } from "solid-js/store"
import { Dynamic } from "solid-js/web"
import { makeEventListener } from "@solid-primitives/event-listener"
Expand DownExpand Up@@ -211,6 +211,73 @@ export function FileTabContent(props: { tab: string }) {
view,
})

const isMarkdown = createMemo(() => {
const p = path()
return p ? /\.(?:md|markdown)$/i.test(p) : false
})
const [preview, setPreview] = createSignal(true)

let mermaidContainer: HTMLDivElement | undefined

const setupMermaidContainer = (el: HTMLDivElement) => {
mermaidContainer = el
}

createEffect(
on(
() => [mermaidContainer, preview(), contents()] as const,
([container, isPreview]) => {
if (typeof window === "undefined") return
if (!container || !isPreview) return
if (!isMarkdown()) return

const renderMermaid = () => {
mermaid.initialize({ startOnLoad: false })

const preBlocks = container.querySelectorAll("pre.shiki")
if (preBlocks.length === 0) return

preBlocks.forEach((pre) => {
if (!(pre instanceof HTMLPreElement)) return

const code = pre.querySelector("code")
if (!code) return

const lines = code.querySelectorAll(".line")
const text = Array.from(lines).map((line) => line.textContent).join("\n")

const mermaidKeywords =
/\b(graph|flowchart|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|journey|gitGraph|mindmap|requirement|timeline|zenuml)\b|->>|-->>|Note\b|loop\b|alt\b|opt\b\par\b/i.test(
text,
)
if (!mermaidKeywords) return

const div = document.createElement("div")
div.className = "mermaid"
div.textContent = text

pre.replaceWith(div)
})

const blocks = container.querySelectorAll(".mermaid")
if (blocks.length === 0) return

mermaid.run({ nodes: Array.from(blocks) as HTMLElement[] }).catch(() => {})
}

const tryRender = () => {
renderMermaid()
if (container.querySelectorAll(".mermaid").length === 0) {
setTimeout(tryRender, 100)
}
}

setTimeout(tryRender, 0)
},
{ defer: true },
),
)

const selectionPreview = (source: string, selection: FileSelection) => {
return previewSelectedLines(source, {
start: selection.startLine,
Expand DownExpand Up@@ -359,11 +426,21 @@ export function FileTabContent(props: { tab: string }) {
path,
() => {
commentsUi.note.reset()
setPreview(true)
},
{ defer: true },
),
)

createEffect(() => {
const focus = comments.focus()
const p = path()
if (!focus || !p) return
if (focus.file !== p) return
if (activeFileTab() !== props.tab) return
if (preview()) setPreview(false)
})

createEffect(() => {
const focus = comments.focus()
const p = path()
Expand DownExpand Up@@ -442,7 +519,28 @@ export function FileTabContent(props: { tab: string }) {
return (
<Tabs.Content value={props.tab} class="mt-3 relative h-full">
<ScrollView class="h-full" viewportRef={scrollSync.setViewport} onScroll={scrollSync.handleScroll as any}>
<Show when={state()?.loaded && isMarkdown() && state()?.content?.type !== "binary"}>
<div class="sticky top-0 z-10 flex items-center gap-1 bg-background-base px-4 py-1.5 border-b border-border-base">
<button
class={"px-2 py-0.5 rounded text-sm " + (preview() ? "bg-surface-base-active text-text-base" : "text-text-weak hover:text-text-base")}
onClick={() => setPreview(true)}
>
{language.t("session.files.viewPreview")}
</button>
<button
class={"px-2 py-0.5 rounded text-sm " + (!preview() ? "bg-surface-base-active text-text-base" : "text-text-weak hover:text-text-base")}
onClick={() => setPreview(false)}
>
{language.t("session.files.viewSource")}
</button>
</div>
</Show>
<Switch>
<Match when={state()?.loaded && isMarkdown() && preview() && state()?.content?.type !== "binary"}>
<div ref={setupMermaidContainer} class="px-6 py-4 pb-40">
<Markdown text={contents()} cacheKey={cacheKey()} />
</div>
</Match>
<Match when={state()?.loaded}>{renderFile(contents())}</Match>
<Match when={state()?.loading}>
<div class="px-6 py-4 text-text-weak">{language.t("common.loading")}...</div>
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(app): add markdown preview with mermaid diagram support by Kiruno-lz · Pull Request #23688 · anomalyco/opencode · GitHub
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions bun.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -71,6 +71,7 @@
"luxon": "3.6.1",
"marked": "17.0.1",
"marked-shiki": "1.2.1",
"mermaid": "11.4.1",
"remend": "1.3.0",
"@playwright/test": "1.59.1",
"semver": "7.7.4",
Expand Down
1 change: 1 addition & 0 deletions packages/app/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -84,6 +84,7 @@
"luxon": "catalog:",
"marked": "catalog:",
"marked-shiki": "catalog:",
"mermaid": "catalog:",
"remeda": "catalog:",
"shiki": "catalog:",
"solid-js": "catalog:",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ar.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -571,6 +571,8 @@ export const dict = {
"session.files.all": "كل الملفات",
"session.files.empty": "لا توجد ملفات",
"session.files.binaryContent": "ملف ثنائي (لا يمكن عرض المحتوى)",
"session.files.viewPreview": "معاينة",
"session.files.viewSource": "مصدر",
"session.messages.renderEarlier": "عرض الرسائل السابقة",
"session.messages.loadingEarlier": "جارٍ تحميل الرسائل السابقة...",
"session.messages.loadEarlier": "تحميل الرسائل السابقة",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/br.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,6 +576,8 @@ export const dict = {
"session.files.all": "Todos os arquivos",
"session.files.empty": "Nenhum arquivo",
"session.files.binaryContent": "Arquivo binário (conteúdo não pode ser exibido)",
"session.files.viewPreview": "Pré-visualização",
"session.files.viewSource": "Código-fonte",
"session.messages.renderEarlier": "Renderizar mensagens anteriores",
"session.messages.loadingEarlier": "Carregando mensagens anteriores...",
"session.messages.loadEarlier": "Carregar mensagens anteriores",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/bs.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -629,6 +629,8 @@ export const dict = {
"session.files.all": "Sve datoteke",
"session.files.empty": "Nema datoteka",
"session.files.binaryContent": "Binarna datoteka (sadržaj se ne može prikazati)",
"session.files.viewPreview": "Pregled",
"session.files.viewSource": "Izvor",

"session.messages.renderEarlier": "Prikaži ranije poruke",
"session.messages.loadingEarlier": "Učitavanje ranijih poruka...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/da.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -625,6 +625,8 @@ export const dict = {
"session.files.all": "Alle filer",
"session.files.empty": "Ingen filer",
"session.files.binaryContent": "Binær fil (indhold kan ikke vises)",
"session.files.viewPreview": "Forhåndsvisning",
"session.files.viewSource": "Kilde",
"session.messages.renderEarlier": "Vis tidligere beskeder",
"session.messages.loadingEarlier": "Indlæser tidligere beskeder...",
"session.messages.loadEarlier": "Indlæs tidligere beskeder",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/de.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -585,6 +585,8 @@ export const dict = {
"session.files.all": "Alle Dateien",
"session.files.empty": "Keine Dateien",
"session.files.binaryContent": "Binärdatei (Inhalt kann nicht angezeigt werden)",
"session.files.viewPreview": "Vorschau",
"session.files.viewSource": "Quelle",
"session.messages.renderEarlier": "Frühere Nachrichten rendern",
"session.messages.loadingEarlier": "Lade frühere Nachrichten...",
"session.messages.loadEarlier": "Frühere Nachrichten laden",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/en.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -651,6 +651,8 @@ export const dict = {
"session.files.all": "All files",
"session.files.empty": "No files",
"session.files.binaryContent": "Binary file (content cannot be displayed)",
"session.files.viewPreview": "Preview",
"session.files.viewSource": "Source",

"session.messages.renderEarlier": "Render earlier messages",
"session.messages.loadingEarlier": "Loading earlier messages...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/es.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -630,6 +630,8 @@ export const dict = {
"session.files.all": "Todos los archivos",
"session.files.empty": "Sin archivos",
"session.files.binaryContent": "Archivo binario (el contenido no puede ser mostrado)",
"session.files.viewPreview": "Vista previa",
"session.files.viewSource": "Fuente",

"session.messages.renderEarlier": "Renderizar mensajes anteriores",
"session.messages.loadingEarlier": "Cargando mensajes anteriores...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/fr.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -581,6 +581,8 @@ export const dict = {
"session.files.all": "Tous les fichiers",
"session.files.empty": "Aucun fichier",
"session.files.binaryContent": "Fichier binaire (le contenu ne peut pas être affiché)",
"session.files.viewPreview": "Aperçu",
"session.files.viewSource": "Source",
"session.messages.renderEarlier": "Afficher les messages précédents",
"session.messages.loadingEarlier": "Chargement des messages précédents...",
"session.messages.loadEarlier": "Charger les messages précédents",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ja.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -573,6 +573,8 @@ export const dict = {
"session.files.all": "すべてのファイル",
"session.files.empty": "ファイルなし",
"session.files.binaryContent": "バイナリファイル(内容を表示できません)",
"session.files.viewPreview": "プレビュー",
"session.files.viewSource": "ソース",
"session.messages.renderEarlier": "以前のメッセージを表示",
"session.messages.loadingEarlier": "以前のメッセージを読み込み中...",
"session.messages.loadEarlier": "以前のメッセージを読み込む",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ko.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -465,6 +465,8 @@ export const dict = {
"session.files.all": "모든 파일",
"session.files.empty": "파일 없음",
"session.files.binaryContent": "바이너리 파일 (내용을 표시할 수 없음)",
"session.files.viewPreview": "미리보기",
"session.files.viewSource": "소스",
"session.messages.renderEarlier": "이전 메시지 렌더링",
"session.messages.loadingEarlier": "이전 메시지 로드 중...",
"session.messages.loadEarlier": "이전 메시지 로드",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/no.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -524,6 +524,8 @@ export const dict = {
"session.files.all": "Alle filer",
"session.files.empty": "Ingen filer",
"session.files.binaryContent": "Binær fil (innhold kan ikke vises)",
"session.files.viewPreview": "Forhåndsvisning",
"session.files.viewSource": "Kilde",

"session.messages.renderEarlier": "Vis tidligere meldinger",
"session.messages.loadingEarlier": "Laster inn tidligere meldinger...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/pl.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,6 +576,8 @@ export const dict = {
"session.files.all": "Wszystkie pliki",
"session.files.empty": "Brak plików",
"session.files.binaryContent": "Plik binarny (zawartość nie może być wyświetlona)",
"session.files.viewPreview": "Podgląd",
"session.files.viewSource": "Źródło",
"session.messages.renderEarlier": "Renderuj wcześniejsze wiadomości",
"session.messages.loadingEarlier": "Ładowanie wcześniejszych wiadomości...",
"session.messages.loadEarlier": "Załaduj wcześniejsze wiadomości",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ru.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -628,6 +628,8 @@ export const dict = {
"session.files.all": "Все файлы",
"session.files.empty": "Нет файлов",
"session.files.binaryContent": "Двоичный файл (содержимое не может быть отображено)",
"session.files.viewPreview": "Предпросмотр",
"session.files.viewSource": "Исходный код",
"session.messages.renderEarlier": "Показать предыдущие сообщения",
"session.messages.loadingEarlier": "Загрузка предыдущих сообщений...",
"session.messages.loadEarlier": "Загрузить предыдущие сообщения",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/th.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -624,6 +624,8 @@ export const dict = {
"session.files.empty": "ไม่มีไฟล์",
"session.files.all": "ไฟล์ทั้งหมด",
"session.files.binaryContent": "ไฟล์ไบนารี (ไม่สามารถแสดงเนื้อหาได้)",
"session.files.viewPreview": "ดูตัวอย่าง",
"session.files.viewSource": "ซอร์สโค้ด",

"session.messages.renderEarlier": "แสดงข้อความก่อนหน้า",
"session.messages.loadingEarlier": "กำลังโหลดข้อความก่อนหน้า...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/tr.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -634,6 +634,8 @@ export const dict = {
"session.files.all": "Tüm dosyalar",
"session.files.empty": "Dosya yok",
"session.files.binaryContent": "İkili dosya (içerik görüntülenemiyor)",
"session.files.viewPreview": "Önizleme",
"session.files.viewSource": "Kaynak",

"session.messages.renderEarlier": "Önceki mesajları göster",
"session.messages.loadingEarlier": "Önceki mesajlar yükleniyor...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/zh.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -624,6 +624,8 @@ export const dict = {
"session.files.all": "所有文件",
"session.files.empty": "无文件",
"session.files.binaryContent": "二进制文件(无法显示内容)",
"session.files.viewPreview": "预览",
"session.files.viewSource": "源代码",
"session.messages.renderEarlier": "显示更早的消息",
"session.messages.loadingEarlier": "正在加载更早的消息...",
"session.messages.loadEarlier": "加载更早的消息",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/zht.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -619,6 +619,8 @@ export const dict = {
"session.files.all": "所有檔案",
"session.files.empty": "沒有檔案",
"session.files.binaryContent": "二進位檔案(無法顯示內容)",
"session.files.viewPreview": "預覽",
"session.files.viewSource": "原始碼",
"session.messages.renderEarlier": "顯示更早的訊息",
"session.messages.loadingEarlier": "正在載入更早的訊息...",
"session.messages.loadEarlier": "載入更早的訊息",
Expand Down
100 changes: 99 additions & 1 deletion packages/app/src/pages/session/file-tabs.tsx
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { createEffect, createMemo, createSignal, Match, on, onCleanup, Switch } from "solid-js"
import { createEffect, createMemo, createSignal, Match, on, onCleanup, Show, Switch } from "solid-js"
import { createStore } from "solid-js/store"
import { Dynamic } from "solid-js/web"
import { makeEventListener } from "@solid-primitives/event-listener"
Expand DownExpand Up@@ -211,6 +211,73 @@ export function FileTabContent(props: { tab: string }) {
view,
})

const isMarkdown = createMemo(() => {
const p = path()
return p ? /\.(?:md|markdown)$/i.test(p) : false
})
const [preview, setPreview] = createSignal(true)

let mermaidContainer: HTMLDivElement | undefined

const setupMermaidContainer = (el: HTMLDivElement) => {
mermaidContainer = el
}

createEffect(
on(
() => [mermaidContainer, preview(), contents()] as const,
([container, isPreview]) => {
if (typeof window === "undefined") return
if (!container || !isPreview) return
if (!isMarkdown()) return

const renderMermaid = () => {
mermaid.initialize({ startOnLoad: false })

const preBlocks = container.querySelectorAll("pre.shiki")
if (preBlocks.length === 0) return

preBlocks.forEach((pre) => {
if (!(pre instanceof HTMLPreElement)) return

const code = pre.querySelector("code")
if (!code) return

const lines = code.querySelectorAll(".line")
const text = Array.from(lines).map((line) => line.textContent).join("\n")

const mermaidKeywords =
/\b(graph|flowchart|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|journey|gitGraph|mindmap|requirement|timeline|zenuml)\b|->>|-->>|Note\b|loop\b|alt\b|opt\b\par\b/i.test(
text,
)
if (!mermaidKeywords) return

const div = document.createElement("div")
div.className = "mermaid"
div.textContent = text

pre.replaceWith(div)
})

const blocks = container.querySelectorAll(".mermaid")
if (blocks.length === 0) return

mermaid.run({ nodes: Array.from(blocks) as HTMLElement[] }).catch(() => {})
}

const tryRender = () => {
renderMermaid()
if (container.querySelectorAll(".mermaid").length === 0) {
setTimeout(tryRender, 100)
}
}

setTimeout(tryRender, 0)
},
{ defer: true },
),
)

const selectionPreview = (source: string, selection: FileSelection) => {
return previewSelectedLines(source, {
start: selection.startLine,
Expand DownExpand Up@@ -359,11 +426,21 @@ export function FileTabContent(props: { tab: string }) {
path,
() => {
commentsUi.note.reset()
setPreview(true)
},
{ defer: true },
),
)

createEffect(() => {
const focus = comments.focus()
const p = path()
if (!focus || !p) return
if (focus.file !== p) return
if (activeFileTab() !== props.tab) return
if (preview()) setPreview(false)
})

createEffect(() => {
const focus = comments.focus()
const p = path()
Expand DownExpand Up@@ -442,7 +519,28 @@ export function FileTabContent(props: { tab: string }) {
return (
<Tabs.Content value={props.tab} class="mt-3 relative h-full">
<ScrollView class="h-full" viewportRef={scrollSync.setViewport} onScroll={scrollSync.handleScroll as any}>
<Show when={state()?.loaded && isMarkdown() && state()?.content?.type !== "binary"}>
<div class="sticky top-0 z-10 flex items-center gap-1 bg-background-base px-4 py-1.5 border-b border-border-base">
<button
class={"px-2 py-0.5 rounded text-sm " + (preview() ? "bg-surface-base-active text-text-base" : "text-text-weak hover:text-text-base")}
onClick={() => setPreview(true)}
>
{language.t("session.files.viewPreview")}
</button>
<button
class={"px-2 py-0.5 rounded text-sm " + (!preview() ? "bg-surface-base-active text-text-base" : "text-text-weak hover:text-text-base")}
onClick={() => setPreview(false)}
>
{language.t("session.files.viewSource")}
</button>
</div>
</Show>
<Switch>
<Match when={state()?.loaded && isMarkdown() && preview() && state()?.content?.type !== "binary"}>
<div ref={setupMermaidContainer} class="px-6 py-4 pb-40">
<Markdown text={contents()} cacheKey={cacheKey()} />
</div>
</Match>
<Match when={state()?.loaded}>{renderFile(contents())}</Match>
<Match when={state()?.loading}>
<div class="px-6 py-4 text-text-weak">{language.t("common.loading")}...</div>
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' feat(app): add markdown preview with mermaid diagram support by Kiruno-lz · Pull Request #23688 · anomalyco/opencode · GitHub
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions bun.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -71,6 +71,7 @@
"luxon": "3.6.1",
"marked": "17.0.1",
"marked-shiki": "1.2.1",
"mermaid": "11.4.1",
"remend": "1.3.0",
"@playwright/test": "1.59.1",
"semver": "7.7.4",
Expand Down
1 change: 1 addition & 0 deletions packages/app/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -84,6 +84,7 @@
"luxon": "catalog:",
"marked": "catalog:",
"marked-shiki": "catalog:",
"mermaid": "catalog:",
"remeda": "catalog:",
"shiki": "catalog:",
"solid-js": "catalog:",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ar.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -571,6 +571,8 @@ export const dict = {
"session.files.all": "كل الملفات",
"session.files.empty": "لا توجد ملفات",
"session.files.binaryContent": "ملف ثنائي (لا يمكن عرض المحتوى)",
"session.files.viewPreview": "معاينة",
"session.files.viewSource": "مصدر",
"session.messages.renderEarlier": "عرض الرسائل السابقة",
"session.messages.loadingEarlier": "جارٍ تحميل الرسائل السابقة...",
"session.messages.loadEarlier": "تحميل الرسائل السابقة",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/br.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,6 +576,8 @@ export const dict = {
"session.files.all": "Todos os arquivos",
"session.files.empty": "Nenhum arquivo",
"session.files.binaryContent": "Arquivo binário (conteúdo não pode ser exibido)",
"session.files.viewPreview": "Pré-visualização",
"session.files.viewSource": "Código-fonte",
"session.messages.renderEarlier": "Renderizar mensagens anteriores",
"session.messages.loadingEarlier": "Carregando mensagens anteriores...",
"session.messages.loadEarlier": "Carregar mensagens anteriores",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/bs.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -629,6 +629,8 @@ export const dict = {
"session.files.all": "Sve datoteke",
"session.files.empty": "Nema datoteka",
"session.files.binaryContent": "Binarna datoteka (sadržaj se ne može prikazati)",
"session.files.viewPreview": "Pregled",
"session.files.viewSource": "Izvor",

"session.messages.renderEarlier": "Prikaži ranije poruke",
"session.messages.loadingEarlier": "Učitavanje ranijih poruka...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/da.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -625,6 +625,8 @@ export const dict = {
"session.files.all": "Alle filer",
"session.files.empty": "Ingen filer",
"session.files.binaryContent": "Binær fil (indhold kan ikke vises)",
"session.files.viewPreview": "Forhåndsvisning",
"session.files.viewSource": "Kilde",
"session.messages.renderEarlier": "Vis tidligere beskeder",
"session.messages.loadingEarlier": "Indlæser tidligere beskeder...",
"session.messages.loadEarlier": "Indlæs tidligere beskeder",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/de.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -585,6 +585,8 @@ export const dict = {
"session.files.all": "Alle Dateien",
"session.files.empty": "Keine Dateien",
"session.files.binaryContent": "Binärdatei (Inhalt kann nicht angezeigt werden)",
"session.files.viewPreview": "Vorschau",
"session.files.viewSource": "Quelle",
"session.messages.renderEarlier": "Frühere Nachrichten rendern",
"session.messages.loadingEarlier": "Lade frühere Nachrichten...",
"session.messages.loadEarlier": "Frühere Nachrichten laden",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/en.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -651,6 +651,8 @@ export const dict = {
"session.files.all": "All files",
"session.files.empty": "No files",
"session.files.binaryContent": "Binary file (content cannot be displayed)",
"session.files.viewPreview": "Preview",
"session.files.viewSource": "Source",

"session.messages.renderEarlier": "Render earlier messages",
"session.messages.loadingEarlier": "Loading earlier messages...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/es.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -630,6 +630,8 @@ export const dict = {
"session.files.all": "Todos los archivos",
"session.files.empty": "Sin archivos",
"session.files.binaryContent": "Archivo binario (el contenido no puede ser mostrado)",
"session.files.viewPreview": "Vista previa",
"session.files.viewSource": "Fuente",

"session.messages.renderEarlier": "Renderizar mensajes anteriores",
"session.messages.loadingEarlier": "Cargando mensajes anteriores...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/fr.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -581,6 +581,8 @@ export const dict = {
"session.files.all": "Tous les fichiers",
"session.files.empty": "Aucun fichier",
"session.files.binaryContent": "Fichier binaire (le contenu ne peut pas être affiché)",
"session.files.viewPreview": "Aperçu",
"session.files.viewSource": "Source",
"session.messages.renderEarlier": "Afficher les messages précédents",
"session.messages.loadingEarlier": "Chargement des messages précédents...",
"session.messages.loadEarlier": "Charger les messages précédents",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ja.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -573,6 +573,8 @@ export const dict = {
"session.files.all": "すべてのファイル",
"session.files.empty": "ファイルなし",
"session.files.binaryContent": "バイナリファイル(内容を表示できません)",
"session.files.viewPreview": "プレビュー",
"session.files.viewSource": "ソース",
"session.messages.renderEarlier": "以前のメッセージを表示",
"session.messages.loadingEarlier": "以前のメッセージを読み込み中...",
"session.messages.loadEarlier": "以前のメッセージを読み込む",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ko.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -465,6 +465,8 @@ export const dict = {
"session.files.all": "모든 파일",
"session.files.empty": "파일 없음",
"session.files.binaryContent": "바이너리 파일 (내용을 표시할 수 없음)",
"session.files.viewPreview": "미리보기",
"session.files.viewSource": "소스",
"session.messages.renderEarlier": "이전 메시지 렌더링",
"session.messages.loadingEarlier": "이전 메시지 로드 중...",
"session.messages.loadEarlier": "이전 메시지 로드",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/no.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -524,6 +524,8 @@ export const dict = {
"session.files.all": "Alle filer",
"session.files.empty": "Ingen filer",
"session.files.binaryContent": "Binær fil (innhold kan ikke vises)",
"session.files.viewPreview": "Forhåndsvisning",
"session.files.viewSource": "Kilde",

"session.messages.renderEarlier": "Vis tidligere meldinger",
"session.messages.loadingEarlier": "Laster inn tidligere meldinger...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/pl.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,6 +576,8 @@ export const dict = {
"session.files.all": "Wszystkie pliki",
"session.files.empty": "Brak plików",
"session.files.binaryContent": "Plik binarny (zawartość nie może być wyświetlona)",
"session.files.viewPreview": "Podgląd",
"session.files.viewSource": "Źródło",
"session.messages.renderEarlier": "Renderuj wcześniejsze wiadomości",
"session.messages.loadingEarlier": "Ładowanie wcześniejszych wiadomości...",
"session.messages.loadEarlier": "Załaduj wcześniejsze wiadomości",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ru.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -628,6 +628,8 @@ export const dict = {
"session.files.all": "Все файлы",
"session.files.empty": "Нет файлов",
"session.files.binaryContent": "Двоичный файл (содержимое не может быть отображено)",
"session.files.viewPreview": "Предпросмотр",
"session.files.viewSource": "Исходный код",
"session.messages.renderEarlier": "Показать предыдущие сообщения",
"session.messages.loadingEarlier": "Загрузка предыдущих сообщений...",
"session.messages.loadEarlier": "Загрузить предыдущие сообщения",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/th.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -624,6 +624,8 @@ export const dict = {
"session.files.empty": "ไม่มีไฟล์",
"session.files.all": "ไฟล์ทั้งหมด",
"session.files.binaryContent": "ไฟล์ไบนารี (ไม่สามารถแสดงเนื้อหาได้)",
"session.files.viewPreview": "ดูตัวอย่าง",
"session.files.viewSource": "ซอร์สโค้ด",

"session.messages.renderEarlier": "แสดงข้อความก่อนหน้า",
"session.messages.loadingEarlier": "กำลังโหลดข้อความก่อนหน้า...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/tr.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -634,6 +634,8 @@ export const dict = {
"session.files.all": "Tüm dosyalar",
"session.files.empty": "Dosya yok",
"session.files.binaryContent": "İkili dosya (içerik görüntülenemiyor)",
"session.files.viewPreview": "Önizleme",
"session.files.viewSource": "Kaynak",

"session.messages.renderEarlier": "Önceki mesajları göster",
"session.messages.loadingEarlier": "Önceki mesajlar yükleniyor...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/zh.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -624,6 +624,8 @@ export const dict = {
"session.files.all": "所有文件",
"session.files.empty": "无文件",
"session.files.binaryContent": "二进制文件(无法显示内容)",
"session.files.viewPreview": "预览",
"session.files.viewSource": "源代码",
"session.messages.renderEarlier": "显示更早的消息",
"session.messages.loadingEarlier": "正在加载更早的消息...",
"session.messages.loadEarlier": "加载更早的消息",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/zht.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -619,6 +619,8 @@ export const dict = {
"session.files.all": "所有檔案",
"session.files.empty": "沒有檔案",
"session.files.binaryContent": "二進位檔案(無法顯示內容)",
"session.files.viewPreview": "預覽",
"session.files.viewSource": "原始碼",
"session.messages.renderEarlier": "顯示更早的訊息",
"session.messages.loadingEarlier": "正在載入更早的訊息...",
"session.messages.loadEarlier": "載入更早的訊息",
Expand Down
100 changes: 99 additions & 1 deletion packages/app/src/pages/session/file-tabs.tsx
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { createEffect, createMemo, createSignal, Match, on, onCleanup, Switch } from "solid-js"
import { createEffect, createMemo, createSignal, Match, on, onCleanup, Show, Switch } from "solid-js"
import { createStore } from "solid-js/store"
import { Dynamic } from "solid-js/web"
import { makeEventListener } from "@solid-primitives/event-listener"
Expand DownExpand Up@@ -211,6 +211,73 @@ export function FileTabContent(props: { tab: string }) {
view,
})

const isMarkdown = createMemo(() => {
const p = path()
return p ? /\.(?:md|markdown)$/i.test(p) : false
})
const [preview, setPreview] = createSignal(true)

let mermaidContainer: HTMLDivElement | undefined

const setupMermaidContainer = (el: HTMLDivElement) => {
mermaidContainer = el
}

createEffect(
on(
() => [mermaidContainer, preview(), contents()] as const,
([container, isPreview]) => {
if (typeof window === "undefined") return
if (!container || !isPreview) return
if (!isMarkdown()) return

const renderMermaid = () => {
mermaid.initialize({ startOnLoad: false })

const preBlocks = container.querySelectorAll("pre.shiki")
if (preBlocks.length === 0) return

preBlocks.forEach((pre) => {
if (!(pre instanceof HTMLPreElement)) return

const code = pre.querySelector("code")
if (!code) return

const lines = code.querySelectorAll(".line")
const text = Array.from(lines).map((line) => line.textContent).join("\n")

const mermaidKeywords =
/\b(graph|flowchart|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|journey|gitGraph|mindmap|requirement|timeline|zenuml)\b|->>|-->>|Note\b|loop\b|alt\b|opt\b\par\b/i.test(
text,
)
if (!mermaidKeywords) return

const div = document.createElement("div")
div.className = "mermaid"
div.textContent = text

pre.replaceWith(div)
})

const blocks = container.querySelectorAll(".mermaid")
if (blocks.length === 0) return

mermaid.run({ nodes: Array.from(blocks) as HTMLElement[] }).catch(() => {})
}

const tryRender = () => {
renderMermaid()
if (container.querySelectorAll(".mermaid").length === 0) {
setTimeout(tryRender, 100)
}
}

setTimeout(tryRender, 0)
},
{ defer: true },
),
)

const selectionPreview = (source: string, selection: FileSelection) => {
return previewSelectedLines(source, {
start: selection.startLine,
Expand DownExpand Up@@ -359,11 +426,21 @@ export function FileTabContent(props: { tab: string }) {
path,
() => {
commentsUi.note.reset()
setPreview(true)
},
{ defer: true },
),
)

createEffect(() => {
const focus = comments.focus()
const p = path()
if (!focus || !p) return
if (focus.file !== p) return
if (activeFileTab() !== props.tab) return
if (preview()) setPreview(false)
})

createEffect(() => {
const focus = comments.focus()
const p = path()
Expand DownExpand Up@@ -442,7 +519,28 @@ export function FileTabContent(props: { tab: string }) {
return (
<Tabs.Content value={props.tab} class="mt-3 relative h-full">
<ScrollView class="h-full" viewportRef={scrollSync.setViewport} onScroll={scrollSync.handleScroll as any}>
<Show when={state()?.loaded && isMarkdown() && state()?.content?.type !== "binary"}>
<div class="sticky top-0 z-10 flex items-center gap-1 bg-background-base px-4 py-1.5 border-b border-border-base">
<button
class={"px-2 py-0.5 rounded text-sm " + (preview() ? "bg-surface-base-active text-text-base" : "text-text-weak hover:text-text-base")}
onClick={() => setPreview(true)}
>
{language.t("session.files.viewPreview")}
</button>
<button
class={"px-2 py-0.5 rounded text-sm " + (!preview() ? "bg-surface-base-active text-text-base" : "text-text-weak hover:text-text-base")}
onClick={() => setPreview(false)}
>
{language.t("session.files.viewSource")}
</button>
</div>
</Show>
<Switch>
<Match when={state()?.loaded && isMarkdown() && preview() && state()?.content?.type !== "binary"}>
<div ref={setupMermaidContainer} class="px-6 py-4 pb-40">
<Markdown text={contents()} cacheKey={cacheKey()} />
</div>
</Match>
<Match when={state()?.loaded}>{renderFile(contents())}</Match>
<Match when={state()?.loading}>
<div class="px-6 py-4 text-text-weak">{language.t("common.loading")}...</div>
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(app): add markdown preview with mermaid diagram support by Kiruno-lz · Pull Request #23688 · anomalyco/opencode · GitHub
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions bun.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -71,6 +71,7 @@
"luxon": "3.6.1",
"marked": "17.0.1",
"marked-shiki": "1.2.1",
"mermaid": "11.4.1",
"remend": "1.3.0",
"@playwright/test": "1.59.1",
"semver": "7.7.4",
Expand Down
1 change: 1 addition & 0 deletions packages/app/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -84,6 +84,7 @@
"luxon": "catalog:",
"marked": "catalog:",
"marked-shiki": "catalog:",
"mermaid": "catalog:",
"remeda": "catalog:",
"shiki": "catalog:",
"solid-js": "catalog:",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ar.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -571,6 +571,8 @@ export const dict = {
"session.files.all": "كل الملفات",
"session.files.empty": "لا توجد ملفات",
"session.files.binaryContent": "ملف ثنائي (لا يمكن عرض المحتوى)",
"session.files.viewPreview": "معاينة",
"session.files.viewSource": "مصدر",
"session.messages.renderEarlier": "عرض الرسائل السابقة",
"session.messages.loadingEarlier": "جارٍ تحميل الرسائل السابقة...",
"session.messages.loadEarlier": "تحميل الرسائل السابقة",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/br.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,6 +576,8 @@ export const dict = {
"session.files.all": "Todos os arquivos",
"session.files.empty": "Nenhum arquivo",
"session.files.binaryContent": "Arquivo binário (conteúdo não pode ser exibido)",
"session.files.viewPreview": "Pré-visualização",
"session.files.viewSource": "Código-fonte",
"session.messages.renderEarlier": "Renderizar mensagens anteriores",
"session.messages.loadingEarlier": "Carregando mensagens anteriores...",
"session.messages.loadEarlier": "Carregar mensagens anteriores",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/bs.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -629,6 +629,8 @@ export const dict = {
"session.files.all": "Sve datoteke",
"session.files.empty": "Nema datoteka",
"session.files.binaryContent": "Binarna datoteka (sadržaj se ne može prikazati)",
"session.files.viewPreview": "Pregled",
"session.files.viewSource": "Izvor",

"session.messages.renderEarlier": "Prikaži ranije poruke",
"session.messages.loadingEarlier": "Učitavanje ranijih poruka...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/da.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -625,6 +625,8 @@ export const dict = {
"session.files.all": "Alle filer",
"session.files.empty": "Ingen filer",
"session.files.binaryContent": "Binær fil (indhold kan ikke vises)",
"session.files.viewPreview": "Forhåndsvisning",
"session.files.viewSource": "Kilde",
"session.messages.renderEarlier": "Vis tidligere beskeder",
"session.messages.loadingEarlier": "Indlæser tidligere beskeder...",
"session.messages.loadEarlier": "Indlæs tidligere beskeder",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/de.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -585,6 +585,8 @@ export const dict = {
"session.files.all": "Alle Dateien",
"session.files.empty": "Keine Dateien",
"session.files.binaryContent": "Binärdatei (Inhalt kann nicht angezeigt werden)",
"session.files.viewPreview": "Vorschau",
"session.files.viewSource": "Quelle",
"session.messages.renderEarlier": "Frühere Nachrichten rendern",
"session.messages.loadingEarlier": "Lade frühere Nachrichten...",
"session.messages.loadEarlier": "Frühere Nachrichten laden",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/en.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -651,6 +651,8 @@ export const dict = {
"session.files.all": "All files",
"session.files.empty": "No files",
"session.files.binaryContent": "Binary file (content cannot be displayed)",
"session.files.viewPreview": "Preview",
"session.files.viewSource": "Source",

"session.messages.renderEarlier": "Render earlier messages",
"session.messages.loadingEarlier": "Loading earlier messages...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/es.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -630,6 +630,8 @@ export const dict = {
"session.files.all": "Todos los archivos",
"session.files.empty": "Sin archivos",
"session.files.binaryContent": "Archivo binario (el contenido no puede ser mostrado)",
"session.files.viewPreview": "Vista previa",
"session.files.viewSource": "Fuente",

"session.messages.renderEarlier": "Renderizar mensajes anteriores",
"session.messages.loadingEarlier": "Cargando mensajes anteriores...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/fr.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -581,6 +581,8 @@ export const dict = {
"session.files.all": "Tous les fichiers",
"session.files.empty": "Aucun fichier",
"session.files.binaryContent": "Fichier binaire (le contenu ne peut pas être affiché)",
"session.files.viewPreview": "Aperçu",
"session.files.viewSource": "Source",
"session.messages.renderEarlier": "Afficher les messages précédents",
"session.messages.loadingEarlier": "Chargement des messages précédents...",
"session.messages.loadEarlier": "Charger les messages précédents",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ja.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -573,6 +573,8 @@ export const dict = {
"session.files.all": "すべてのファイル",
"session.files.empty": "ファイルなし",
"session.files.binaryContent": "バイナリファイル(内容を表示できません)",
"session.files.viewPreview": "プレビュー",
"session.files.viewSource": "ソース",
"session.messages.renderEarlier": "以前のメッセージを表示",
"session.messages.loadingEarlier": "以前のメッセージを読み込み中...",
"session.messages.loadEarlier": "以前のメッセージを読み込む",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ko.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -465,6 +465,8 @@ export const dict = {
"session.files.all": "모든 파일",
"session.files.empty": "파일 없음",
"session.files.binaryContent": "바이너리 파일 (내용을 표시할 수 없음)",
"session.files.viewPreview": "미리보기",
"session.files.viewSource": "소스",
"session.messages.renderEarlier": "이전 메시지 렌더링",
"session.messages.loadingEarlier": "이전 메시지 로드 중...",
"session.messages.loadEarlier": "이전 메시지 로드",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/no.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -524,6 +524,8 @@ export const dict = {
"session.files.all": "Alle filer",
"session.files.empty": "Ingen filer",
"session.files.binaryContent": "Binær fil (innhold kan ikke vises)",
"session.files.viewPreview": "Forhåndsvisning",
"session.files.viewSource": "Kilde",

"session.messages.renderEarlier": "Vis tidligere meldinger",
"session.messages.loadingEarlier": "Laster inn tidligere meldinger...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/pl.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,6 +576,8 @@ export const dict = {
"session.files.all": "Wszystkie pliki",
"session.files.empty": "Brak plików",
"session.files.binaryContent": "Plik binarny (zawartość nie może być wyświetlona)",
"session.files.viewPreview": "Podgląd",
"session.files.viewSource": "Źródło",
"session.messages.renderEarlier": "Renderuj wcześniejsze wiadomości",
"session.messages.loadingEarlier": "Ładowanie wcześniejszych wiadomości...",
"session.messages.loadEarlier": "Załaduj wcześniejsze wiadomości",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ru.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -628,6 +628,8 @@ export const dict = {
"session.files.all": "Все файлы",
"session.files.empty": "Нет файлов",
"session.files.binaryContent": "Двоичный файл (содержимое не может быть отображено)",
"session.files.viewPreview": "Предпросмотр",
"session.files.viewSource": "Исходный код",
"session.messages.renderEarlier": "Показать предыдущие сообщения",
"session.messages.loadingEarlier": "Загрузка предыдущих сообщений...",
"session.messages.loadEarlier": "Загрузить предыдущие сообщения",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/th.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -624,6 +624,8 @@ export const dict = {
"session.files.empty": "ไม่มีไฟล์",
"session.files.all": "ไฟล์ทั้งหมด",
"session.files.binaryContent": "ไฟล์ไบนารี (ไม่สามารถแสดงเนื้อหาได้)",
"session.files.viewPreview": "ดูตัวอย่าง",
"session.files.viewSource": "ซอร์สโค้ด",

"session.messages.renderEarlier": "แสดงข้อความก่อนหน้า",
"session.messages.loadingEarlier": "กำลังโหลดข้อความก่อนหน้า...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/tr.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -634,6 +634,8 @@ export const dict = {
"session.files.all": "Tüm dosyalar",
"session.files.empty": "Dosya yok",
"session.files.binaryContent": "İkili dosya (içerik görüntülenemiyor)",
"session.files.viewPreview": "Önizleme",
"session.files.viewSource": "Kaynak",

"session.messages.renderEarlier": "Önceki mesajları göster",
"session.messages.loadingEarlier": "Önceki mesajlar yükleniyor...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/zh.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -624,6 +624,8 @@ export const dict = {
"session.files.all": "所有文件",
"session.files.empty": "无文件",
"session.files.binaryContent": "二进制文件(无法显示内容)",
"session.files.viewPreview": "预览",
"session.files.viewSource": "源代码",
"session.messages.renderEarlier": "显示更早的消息",
"session.messages.loadingEarlier": "正在加载更早的消息...",
"session.messages.loadEarlier": "加载更早的消息",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/zht.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -619,6 +619,8 @@ export const dict = {
"session.files.all": "所有檔案",
"session.files.empty": "沒有檔案",
"session.files.binaryContent": "二進位檔案(無法顯示內容)",
"session.files.viewPreview": "預覽",
"session.files.viewSource": "原始碼",
"session.messages.renderEarlier": "顯示更早的訊息",
"session.messages.loadingEarlier": "正在載入更早的訊息...",
"session.messages.loadEarlier": "載入更早的訊息",
Expand Down
100 changes: 99 additions & 1 deletion packages/app/src/pages/session/file-tabs.tsx
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { createEffect, createMemo, createSignal, Match, on, onCleanup, Switch } from "solid-js"
import { createEffect, createMemo, createSignal, Match, on, onCleanup, Show, Switch } from "solid-js"
import { createStore } from "solid-js/store"
import { Dynamic } from "solid-js/web"
import { makeEventListener } from "@solid-primitives/event-listener"
Expand DownExpand Up@@ -211,6 +211,73 @@ export function FileTabContent(props: { tab: string }) {
view,
})

const isMarkdown = createMemo(() => {
const p = path()
return p ? /\.(?:md|markdown)$/i.test(p) : false
})
const [preview, setPreview] = createSignal(true)

let mermaidContainer: HTMLDivElement | undefined

const setupMermaidContainer = (el: HTMLDivElement) => {
mermaidContainer = el
}

createEffect(
on(
() => [mermaidContainer, preview(), contents()] as const,
([container, isPreview]) => {
if (typeof window === "undefined") return
if (!container || !isPreview) return
if (!isMarkdown()) return

const renderMermaid = () => {
mermaid.initialize({ startOnLoad: false })

const preBlocks = container.querySelectorAll("pre.shiki")
if (preBlocks.length === 0) return

preBlocks.forEach((pre) => {
if (!(pre instanceof HTMLPreElement)) return

const code = pre.querySelector("code")
if (!code) return

const lines = code.querySelectorAll(".line")
const text = Array.from(lines).map((line) => line.textContent).join("\n")

const mermaidKeywords =
/\b(graph|flowchart|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|journey|gitGraph|mindmap|requirement|timeline|zenuml)\b|->>|-->>|Note\b|loop\b|alt\b|opt\b\par\b/i.test(
text,
)
if (!mermaidKeywords) return

const div = document.createElement("div")
div.className = "mermaid"
div.textContent = text

pre.replaceWith(div)
})

const blocks = container.querySelectorAll(".mermaid")
if (blocks.length === 0) return

mermaid.run({ nodes: Array.from(blocks) as HTMLElement[] }).catch(() => {})
}

const tryRender = () => {
renderMermaid()
if (container.querySelectorAll(".mermaid").length === 0) {
setTimeout(tryRender, 100)
}
}

setTimeout(tryRender, 0)
},
{ defer: true },
),
)

const selectionPreview = (source: string, selection: FileSelection) => {
return previewSelectedLines(source, {
start: selection.startLine,
Expand DownExpand Up@@ -359,11 +426,21 @@ export function FileTabContent(props: { tab: string }) {
path,
() => {
commentsUi.note.reset()
setPreview(true)
},
{ defer: true },
),
)

createEffect(() => {
const focus = comments.focus()
const p = path()
if (!focus || !p) return
if (focus.file !== p) return
if (activeFileTab() !== props.tab) return
if (preview()) setPreview(false)
})

createEffect(() => {
const focus = comments.focus()
const p = path()
Expand DownExpand Up@@ -442,7 +519,28 @@ export function FileTabContent(props: { tab: string }) {
return (
<Tabs.Content value={props.tab} class="mt-3 relative h-full">
<ScrollView class="h-full" viewportRef={scrollSync.setViewport} onScroll={scrollSync.handleScroll as any}>
<Show when={state()?.loaded && isMarkdown() && state()?.content?.type !== "binary"}>
<div class="sticky top-0 z-10 flex items-center gap-1 bg-background-base px-4 py-1.5 border-b border-border-base">
<button
class={"px-2 py-0.5 rounded text-sm " + (preview() ? "bg-surface-base-active text-text-base" : "text-text-weak hover:text-text-base")}
onClick={() => setPreview(true)}
>
{language.t("session.files.viewPreview")}
</button>
<button
class={"px-2 py-0.5 rounded text-sm " + (!preview() ? "bg-surface-base-active text-text-base" : "text-text-weak hover:text-text-base")}
onClick={() => setPreview(false)}
>
{language.t("session.files.viewSource")}
</button>
</div>
</Show>
<Switch>
<Match when={state()?.loaded && isMarkdown() && preview() && state()?.content?.type !== "binary"}>
<div ref={setupMermaidContainer} class="px-6 py-4 pb-40">
<Markdown text={contents()} cacheKey={cacheKey()} />
</div>
</Match>
<Match when={state()?.loaded}>{renderFile(contents())}</Match>
<Match when={state()?.loading}>
<div class="px-6 py-4 text-text-weak">{language.t("common.loading")}...</div>
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(app): add markdown preview with mermaid diagram support by Kiruno-lz · Pull Request #23688 · anomalyco/opencode · GitHub
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions bun.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -71,6 +71,7 @@
"luxon": "3.6.1",
"marked": "17.0.1",
"marked-shiki": "1.2.1",
"mermaid": "11.4.1",
"remend": "1.3.0",
"@playwright/test": "1.59.1",
"semver": "7.7.4",
Expand Down
1 change: 1 addition & 0 deletions packages/app/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -84,6 +84,7 @@
"luxon": "catalog:",
"marked": "catalog:",
"marked-shiki": "catalog:",
"mermaid": "catalog:",
"remeda": "catalog:",
"shiki": "catalog:",
"solid-js": "catalog:",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ar.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -571,6 +571,8 @@ export const dict = {
"session.files.all": "كل الملفات",
"session.files.empty": "لا توجد ملفات",
"session.files.binaryContent": "ملف ثنائي (لا يمكن عرض المحتوى)",
"session.files.viewPreview": "معاينة",
"session.files.viewSource": "مصدر",
"session.messages.renderEarlier": "عرض الرسائل السابقة",
"session.messages.loadingEarlier": "جارٍ تحميل الرسائل السابقة...",
"session.messages.loadEarlier": "تحميل الرسائل السابقة",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/br.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,6 +576,8 @@ export const dict = {
"session.files.all": "Todos os arquivos",
"session.files.empty": "Nenhum arquivo",
"session.files.binaryContent": "Arquivo binário (conteúdo não pode ser exibido)",
"session.files.viewPreview": "Pré-visualização",
"session.files.viewSource": "Código-fonte",
"session.messages.renderEarlier": "Renderizar mensagens anteriores",
"session.messages.loadingEarlier": "Carregando mensagens anteriores...",
"session.messages.loadEarlier": "Carregar mensagens anteriores",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/bs.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -629,6 +629,8 @@ export const dict = {
"session.files.all": "Sve datoteke",
"session.files.empty": "Nema datoteka",
"session.files.binaryContent": "Binarna datoteka (sadržaj se ne može prikazati)",
"session.files.viewPreview": "Pregled",
"session.files.viewSource": "Izvor",

"session.messages.renderEarlier": "Prikaži ranije poruke",
"session.messages.loadingEarlier": "Učitavanje ranijih poruka...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/da.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -625,6 +625,8 @@ export const dict = {
"session.files.all": "Alle filer",
"session.files.empty": "Ingen filer",
"session.files.binaryContent": "Binær fil (indhold kan ikke vises)",
"session.files.viewPreview": "Forhåndsvisning",
"session.files.viewSource": "Kilde",
"session.messages.renderEarlier": "Vis tidligere beskeder",
"session.messages.loadingEarlier": "Indlæser tidligere beskeder...",
"session.messages.loadEarlier": "Indlæs tidligere beskeder",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/de.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -585,6 +585,8 @@ export const dict = {
"session.files.all": "Alle Dateien",
"session.files.empty": "Keine Dateien",
"session.files.binaryContent": "Binärdatei (Inhalt kann nicht angezeigt werden)",
"session.files.viewPreview": "Vorschau",
"session.files.viewSource": "Quelle",
"session.messages.renderEarlier": "Frühere Nachrichten rendern",
"session.messages.loadingEarlier": "Lade frühere Nachrichten...",
"session.messages.loadEarlier": "Frühere Nachrichten laden",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/en.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -651,6 +651,8 @@ export const dict = {
"session.files.all": "All files",
"session.files.empty": "No files",
"session.files.binaryContent": "Binary file (content cannot be displayed)",
"session.files.viewPreview": "Preview",
"session.files.viewSource": "Source",

"session.messages.renderEarlier": "Render earlier messages",
"session.messages.loadingEarlier": "Loading earlier messages...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/es.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -630,6 +630,8 @@ export const dict = {
"session.files.all": "Todos los archivos",
"session.files.empty": "Sin archivos",
"session.files.binaryContent": "Archivo binario (el contenido no puede ser mostrado)",
"session.files.viewPreview": "Vista previa",
"session.files.viewSource": "Fuente",

"session.messages.renderEarlier": "Renderizar mensajes anteriores",
"session.messages.loadingEarlier": "Cargando mensajes anteriores...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/fr.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -581,6 +581,8 @@ export const dict = {
"session.files.all": "Tous les fichiers",
"session.files.empty": "Aucun fichier",
"session.files.binaryContent": "Fichier binaire (le contenu ne peut pas être affiché)",
"session.files.viewPreview": "Aperçu",
"session.files.viewSource": "Source",
"session.messages.renderEarlier": "Afficher les messages précédents",
"session.messages.loadingEarlier": "Chargement des messages précédents...",
"session.messages.loadEarlier": "Charger les messages précédents",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ja.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -573,6 +573,8 @@ export const dict = {
"session.files.all": "すべてのファイル",
"session.files.empty": "ファイルなし",
"session.files.binaryContent": "バイナリファイル(内容を表示できません)",
"session.files.viewPreview": "プレビュー",
"session.files.viewSource": "ソース",
"session.messages.renderEarlier": "以前のメッセージを表示",
"session.messages.loadingEarlier": "以前のメッセージを読み込み中...",
"session.messages.loadEarlier": "以前のメッセージを読み込む",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ko.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -465,6 +465,8 @@ export const dict = {
"session.files.all": "모든 파일",
"session.files.empty": "파일 없음",
"session.files.binaryContent": "바이너리 파일 (내용을 표시할 수 없음)",
"session.files.viewPreview": "미리보기",
"session.files.viewSource": "소스",
"session.messages.renderEarlier": "이전 메시지 렌더링",
"session.messages.loadingEarlier": "이전 메시지 로드 중...",
"session.messages.loadEarlier": "이전 메시지 로드",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/no.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -524,6 +524,8 @@ export const dict = {
"session.files.all": "Alle filer",
"session.files.empty": "Ingen filer",
"session.files.binaryContent": "Binær fil (innhold kan ikke vises)",
"session.files.viewPreview": "Forhåndsvisning",
"session.files.viewSource": "Kilde",

"session.messages.renderEarlier": "Vis tidligere meldinger",
"session.messages.loadingEarlier": "Laster inn tidligere meldinger...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/pl.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,6 +576,8 @@ export const dict = {
"session.files.all": "Wszystkie pliki",
"session.files.empty": "Brak plików",
"session.files.binaryContent": "Plik binarny (zawartość nie może być wyświetlona)",
"session.files.viewPreview": "Podgląd",
"session.files.viewSource": "Źródło",
"session.messages.renderEarlier": "Renderuj wcześniejsze wiadomości",
"session.messages.loadingEarlier": "Ładowanie wcześniejszych wiadomości...",
"session.messages.loadEarlier": "Załaduj wcześniejsze wiadomości",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ru.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -628,6 +628,8 @@ export const dict = {
"session.files.all": "Все файлы",
"session.files.empty": "Нет файлов",
"session.files.binaryContent": "Двоичный файл (содержимое не может быть отображено)",
"session.files.viewPreview": "Предпросмотр",
"session.files.viewSource": "Исходный код",
"session.messages.renderEarlier": "Показать предыдущие сообщения",
"session.messages.loadingEarlier": "Загрузка предыдущих сообщений...",
"session.messages.loadEarlier": "Загрузить предыдущие сообщения",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/th.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -624,6 +624,8 @@ export const dict = {
"session.files.empty": "ไม่มีไฟล์",
"session.files.all": "ไฟล์ทั้งหมด",
"session.files.binaryContent": "ไฟล์ไบนารี (ไม่สามารถแสดงเนื้อหาได้)",
"session.files.viewPreview": "ดูตัวอย่าง",
"session.files.viewSource": "ซอร์สโค้ด",

"session.messages.renderEarlier": "แสดงข้อความก่อนหน้า",
"session.messages.loadingEarlier": "กำลังโหลดข้อความก่อนหน้า...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/tr.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -634,6 +634,8 @@ export const dict = {
"session.files.all": "Tüm dosyalar",
"session.files.empty": "Dosya yok",
"session.files.binaryContent": "İkili dosya (içerik görüntülenemiyor)",
"session.files.viewPreview": "Önizleme",
"session.files.viewSource": "Kaynak",

"session.messages.renderEarlier": "Önceki mesajları göster",
"session.messages.loadingEarlier": "Önceki mesajlar yükleniyor...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/zh.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -624,6 +624,8 @@ export const dict = {
"session.files.all": "所有文件",
"session.files.empty": "无文件",
"session.files.binaryContent": "二进制文件(无法显示内容)",
"session.files.viewPreview": "预览",
"session.files.viewSource": "源代码",
"session.messages.renderEarlier": "显示更早的消息",
"session.messages.loadingEarlier": "正在加载更早的消息...",
"session.messages.loadEarlier": "加载更早的消息",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/zht.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -619,6 +619,8 @@ export const dict = {
"session.files.all": "所有檔案",
"session.files.empty": "沒有檔案",
"session.files.binaryContent": "二進位檔案(無法顯示內容)",
"session.files.viewPreview": "預覽",
"session.files.viewSource": "原始碼",
"session.messages.renderEarlier": "顯示更早的訊息",
"session.messages.loadingEarlier": "正在載入更早的訊息...",
"session.messages.loadEarlier": "載入更早的訊息",
Expand Down
100 changes: 99 additions & 1 deletion packages/app/src/pages/session/file-tabs.tsx
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { createEffect, createMemo, createSignal, Match, on, onCleanup, Switch } from "solid-js"
import { createEffect, createMemo, createSignal, Match, on, onCleanup, Show, Switch } from "solid-js"
import { createStore } from "solid-js/store"
import { Dynamic } from "solid-js/web"
import { makeEventListener } from "@solid-primitives/event-listener"
Expand DownExpand Up@@ -211,6 +211,73 @@ export function FileTabContent(props: { tab: string }) {
view,
})

const isMarkdown = createMemo(() => {
const p = path()
return p ? /\.(?:md|markdown)$/i.test(p) : false
})
const [preview, setPreview] = createSignal(true)

let mermaidContainer: HTMLDivElement | undefined

const setupMermaidContainer = (el: HTMLDivElement) => {
mermaidContainer = el
}

createEffect(
on(
() => [mermaidContainer, preview(), contents()] as const,
([container, isPreview]) => {
if (typeof window === "undefined") return
if (!container || !isPreview) return
if (!isMarkdown()) return

const renderMermaid = () => {
mermaid.initialize({ startOnLoad: false })

const preBlocks = container.querySelectorAll("pre.shiki")
if (preBlocks.length === 0) return

preBlocks.forEach((pre) => {
if (!(pre instanceof HTMLPreElement)) return

const code = pre.querySelector("code")
if (!code) return

const lines = code.querySelectorAll(".line")
const text = Array.from(lines).map((line) => line.textContent).join("\n")

const mermaidKeywords =
/\b(graph|flowchart|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|journey|gitGraph|mindmap|requirement|timeline|zenuml)\b|->>|-->>|Note\b|loop\b|alt\b|opt\b\par\b/i.test(
text,
)
if (!mermaidKeywords) return

const div = document.createElement("div")
div.className = "mermaid"
div.textContent = text

pre.replaceWith(div)
})

const blocks = container.querySelectorAll(".mermaid")
if (blocks.length === 0) return

mermaid.run({ nodes: Array.from(blocks) as HTMLElement[] }).catch(() => {})
}

const tryRender = () => {
renderMermaid()
if (container.querySelectorAll(".mermaid").length === 0) {
setTimeout(tryRender, 100)
}
}

setTimeout(tryRender, 0)
},
{ defer: true },
),
)

const selectionPreview = (source: string, selection: FileSelection) => {
return previewSelectedLines(source, {
start: selection.startLine,
Expand DownExpand Up@@ -359,11 +426,21 @@ export function FileTabContent(props: { tab: string }) {
path,
() => {
commentsUi.note.reset()
setPreview(true)
},
{ defer: true },
),
)

createEffect(() => {
const focus = comments.focus()
const p = path()
if (!focus || !p) return
if (focus.file !== p) return
if (activeFileTab() !== props.tab) return
if (preview()) setPreview(false)
})

createEffect(() => {
const focus = comments.focus()
const p = path()
Expand DownExpand Up@@ -442,7 +519,28 @@ export function FileTabContent(props: { tab: string }) {
return (
<Tabs.Content value={props.tab} class="mt-3 relative h-full">
<ScrollView class="h-full" viewportRef={scrollSync.setViewport} onScroll={scrollSync.handleScroll as any}>
<Show when={state()?.loaded && isMarkdown() && state()?.content?.type !== "binary"}>
<div class="sticky top-0 z-10 flex items-center gap-1 bg-background-base px-4 py-1.5 border-b border-border-base">
<button
class={"px-2 py-0.5 rounded text-sm " + (preview() ? "bg-surface-base-active text-text-base" : "text-text-weak hover:text-text-base")}
onClick={() => setPreview(true)}
>
{language.t("session.files.viewPreview")}
</button>
<button
class={"px-2 py-0.5 rounded text-sm " + (!preview() ? "bg-surface-base-active text-text-base" : "text-text-weak hover:text-text-base")}
onClick={() => setPreview(false)}
>
{language.t("session.files.viewSource")}
</button>
</div>
</Show>
<Switch>
<Match when={state()?.loaded && isMarkdown() && preview() && state()?.content?.type !== "binary"}>
<div ref={setupMermaidContainer} class="px-6 py-4 pb-40">
<Markdown text={contents()} cacheKey={cacheKey()} />
</div>
</Match>
<Match when={state()?.loaded}>{renderFile(contents())}</Match>
<Match when={state()?.loading}>
<div class="px-6 py-4 text-text-weak">{language.t("common.loading")}...</div>
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); feat(app): add markdown preview with mermaid diagram support by Kiruno-lz · Pull Request #23688 · anomalyco/opencode · GitHub
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions bun.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -71,6 +71,7 @@
"luxon": "3.6.1",
"marked": "17.0.1",
"marked-shiki": "1.2.1",
"mermaid": "11.4.1",
"remend": "1.3.0",
"@playwright/test": "1.59.1",
"semver": "7.7.4",
Expand Down
1 change: 1 addition & 0 deletions packages/app/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -84,6 +84,7 @@
"luxon": "catalog:",
"marked": "catalog:",
"marked-shiki": "catalog:",
"mermaid": "catalog:",
"remeda": "catalog:",
"shiki": "catalog:",
"solid-js": "catalog:",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ar.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -571,6 +571,8 @@ export const dict = {
"session.files.all": "كل الملفات",
"session.files.empty": "لا توجد ملفات",
"session.files.binaryContent": "ملف ثنائي (لا يمكن عرض المحتوى)",
"session.files.viewPreview": "معاينة",
"session.files.viewSource": "مصدر",
"session.messages.renderEarlier": "عرض الرسائل السابقة",
"session.messages.loadingEarlier": "جارٍ تحميل الرسائل السابقة...",
"session.messages.loadEarlier": "تحميل الرسائل السابقة",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/br.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,6 +576,8 @@ export const dict = {
"session.files.all": "Todos os arquivos",
"session.files.empty": "Nenhum arquivo",
"session.files.binaryContent": "Arquivo binário (conteúdo não pode ser exibido)",
"session.files.viewPreview": "Pré-visualização",
"session.files.viewSource": "Código-fonte",
"session.messages.renderEarlier": "Renderizar mensagens anteriores",
"session.messages.loadingEarlier": "Carregando mensagens anteriores...",
"session.messages.loadEarlier": "Carregar mensagens anteriores",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/bs.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -629,6 +629,8 @@ export const dict = {
"session.files.all": "Sve datoteke",
"session.files.empty": "Nema datoteka",
"session.files.binaryContent": "Binarna datoteka (sadržaj se ne može prikazati)",
"session.files.viewPreview": "Pregled",
"session.files.viewSource": "Izvor",

"session.messages.renderEarlier": "Prikaži ranije poruke",
"session.messages.loadingEarlier": "Učitavanje ranijih poruka...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/da.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -625,6 +625,8 @@ export const dict = {
"session.files.all": "Alle filer",
"session.files.empty": "Ingen filer",
"session.files.binaryContent": "Binær fil (indhold kan ikke vises)",
"session.files.viewPreview": "Forhåndsvisning",
"session.files.viewSource": "Kilde",
"session.messages.renderEarlier": "Vis tidligere beskeder",
"session.messages.loadingEarlier": "Indlæser tidligere beskeder...",
"session.messages.loadEarlier": "Indlæs tidligere beskeder",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/de.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -585,6 +585,8 @@ export const dict = {
"session.files.all": "Alle Dateien",
"session.files.empty": "Keine Dateien",
"session.files.binaryContent": "Binärdatei (Inhalt kann nicht angezeigt werden)",
"session.files.viewPreview": "Vorschau",
"session.files.viewSource": "Quelle",
"session.messages.renderEarlier": "Frühere Nachrichten rendern",
"session.messages.loadingEarlier": "Lade frühere Nachrichten...",
"session.messages.loadEarlier": "Frühere Nachrichten laden",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/en.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -651,6 +651,8 @@ export const dict = {
"session.files.all": "All files",
"session.files.empty": "No files",
"session.files.binaryContent": "Binary file (content cannot be displayed)",
"session.files.viewPreview": "Preview",
"session.files.viewSource": "Source",

"session.messages.renderEarlier": "Render earlier messages",
"session.messages.loadingEarlier": "Loading earlier messages...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/es.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -630,6 +630,8 @@ export const dict = {
"session.files.all": "Todos los archivos",
"session.files.empty": "Sin archivos",
"session.files.binaryContent": "Archivo binario (el contenido no puede ser mostrado)",
"session.files.viewPreview": "Vista previa",
"session.files.viewSource": "Fuente",

"session.messages.renderEarlier": "Renderizar mensajes anteriores",
"session.messages.loadingEarlier": "Cargando mensajes anteriores...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/fr.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -581,6 +581,8 @@ export const dict = {
"session.files.all": "Tous les fichiers",
"session.files.empty": "Aucun fichier",
"session.files.binaryContent": "Fichier binaire (le contenu ne peut pas être affiché)",
"session.files.viewPreview": "Aperçu",
"session.files.viewSource": "Source",
"session.messages.renderEarlier": "Afficher les messages précédents",
"session.messages.loadingEarlier": "Chargement des messages précédents...",
"session.messages.loadEarlier": "Charger les messages précédents",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ja.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -573,6 +573,8 @@ export const dict = {
"session.files.all": "すべてのファイル",
"session.files.empty": "ファイルなし",
"session.files.binaryContent": "バイナリファイル(内容を表示できません)",
"session.files.viewPreview": "プレビュー",
"session.files.viewSource": "ソース",
"session.messages.renderEarlier": "以前のメッセージを表示",
"session.messages.loadingEarlier": "以前のメッセージを読み込み中...",
"session.messages.loadEarlier": "以前のメッセージを読み込む",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ko.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -465,6 +465,8 @@ export const dict = {
"session.files.all": "모든 파일",
"session.files.empty": "파일 없음",
"session.files.binaryContent": "바이너리 파일 (내용을 표시할 수 없음)",
"session.files.viewPreview": "미리보기",
"session.files.viewSource": "소스",
"session.messages.renderEarlier": "이전 메시지 렌더링",
"session.messages.loadingEarlier": "이전 메시지 로드 중...",
"session.messages.loadEarlier": "이전 메시지 로드",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/no.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -524,6 +524,8 @@ export const dict = {
"session.files.all": "Alle filer",
"session.files.empty": "Ingen filer",
"session.files.binaryContent": "Binær fil (innhold kan ikke vises)",
"session.files.viewPreview": "Forhåndsvisning",
"session.files.viewSource": "Kilde",

"session.messages.renderEarlier": "Vis tidligere meldinger",
"session.messages.loadingEarlier": "Laster inn tidligere meldinger...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/pl.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -576,6 +576,8 @@ export const dict = {
"session.files.all": "Wszystkie pliki",
"session.files.empty": "Brak plików",
"session.files.binaryContent": "Plik binarny (zawartość nie może być wyświetlona)",
"session.files.viewPreview": "Podgląd",
"session.files.viewSource": "Źródło",
"session.messages.renderEarlier": "Renderuj wcześniejsze wiadomości",
"session.messages.loadingEarlier": "Ładowanie wcześniejszych wiadomości...",
"session.messages.loadEarlier": "Załaduj wcześniejsze wiadomości",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/ru.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -628,6 +628,8 @@ export const dict = {
"session.files.all": "Все файлы",
"session.files.empty": "Нет файлов",
"session.files.binaryContent": "Двоичный файл (содержимое не может быть отображено)",
"session.files.viewPreview": "Предпросмотр",
"session.files.viewSource": "Исходный код",
"session.messages.renderEarlier": "Показать предыдущие сообщения",
"session.messages.loadingEarlier": "Загрузка предыдущих сообщений...",
"session.messages.loadEarlier": "Загрузить предыдущие сообщения",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/th.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -624,6 +624,8 @@ export const dict = {
"session.files.empty": "ไม่มีไฟล์",
"session.files.all": "ไฟล์ทั้งหมด",
"session.files.binaryContent": "ไฟล์ไบนารี (ไม่สามารถแสดงเนื้อหาได้)",
"session.files.viewPreview": "ดูตัวอย่าง",
"session.files.viewSource": "ซอร์สโค้ด",

"session.messages.renderEarlier": "แสดงข้อความก่อนหน้า",
"session.messages.loadingEarlier": "กำลังโหลดข้อความก่อนหน้า...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/tr.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -634,6 +634,8 @@ export const dict = {
"session.files.all": "Tüm dosyalar",
"session.files.empty": "Dosya yok",
"session.files.binaryContent": "İkili dosya (içerik görüntülenemiyor)",
"session.files.viewPreview": "Önizleme",
"session.files.viewSource": "Kaynak",

"session.messages.renderEarlier": "Önceki mesajları göster",
"session.messages.loadingEarlier": "Önceki mesajlar yükleniyor...",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/zh.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -624,6 +624,8 @@ export const dict = {
"session.files.all": "所有文件",
"session.files.empty": "无文件",
"session.files.binaryContent": "二进制文件(无法显示内容)",
"session.files.viewPreview": "预览",
"session.files.viewSource": "源代码",
"session.messages.renderEarlier": "显示更早的消息",
"session.messages.loadingEarlier": "正在加载更早的消息...",
"session.messages.loadEarlier": "加载更早的消息",
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/i18n/zht.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -619,6 +619,8 @@ export const dict = {
"session.files.all": "所有檔案",
"session.files.empty": "沒有檔案",
"session.files.binaryContent": "二進位檔案(無法顯示內容)",
"session.files.viewPreview": "預覽",
"session.files.viewSource": "原始碼",
"session.messages.renderEarlier": "顯示更早的訊息",
"session.messages.loadingEarlier": "正在載入更早的訊息...",
"session.messages.loadEarlier": "載入更早的訊息",
Expand Down
100 changes: 99 additions & 1 deletion packages/app/src/pages/session/file-tabs.tsx
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
import { createEffect, createMemo, createSignal, Match, on, onCleanup, Switch } from "solid-js"
import { createEffect, createMemo, createSignal, Match, on, onCleanup, Show, Switch } from "solid-js"
import { createStore } from "solid-js/store"
import { Dynamic } from "solid-js/web"
import { makeEventListener } from "@solid-primitives/event-listener"
Expand DownExpand Up@@ -211,6 +211,73 @@ export function FileTabContent(props: { tab: string }) {
view,
})

const isMarkdown = createMemo(() => {
const p = path()
return p ? /\.(?:md|markdown)$/i.test(p) : false
})
const [preview, setPreview] = createSignal(true)

let mermaidContainer: HTMLDivElement | undefined

const setupMermaidContainer = (el: HTMLDivElement) => {
mermaidContainer = el
}

createEffect(
on(
() => [mermaidContainer, preview(), contents()] as const,
([container, isPreview]) => {
if (typeof window === "undefined") return
if (!container || !isPreview) return
if (!isMarkdown()) return

const renderMermaid = () => {
mermaid.initialize({ startOnLoad: false })

const preBlocks = container.querySelectorAll("pre.shiki")
if (preBlocks.length === 0) return

preBlocks.forEach((pre) => {
if (!(pre instanceof HTMLPreElement)) return

const code = pre.querySelector("code")
if (!code) return

const lines = code.querySelectorAll(".line")
const text = Array.from(lines).map((line) => line.textContent).join("\n")

const mermaidKeywords =
/\b(graph|flowchart|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|journey|gitGraph|mindmap|requirement|timeline|zenuml)\b|->>|-->>|Note\b|loop\b|alt\b|opt\b\par\b/i.test(
text,
)
if (!mermaidKeywords) return

const div = document.createElement("div")
div.className = "mermaid"
div.textContent = text

pre.replaceWith(div)
})

const blocks = container.querySelectorAll(".mermaid")
if (blocks.length === 0) return

mermaid.run({ nodes: Array.from(blocks) as HTMLElement[] }).catch(() => {})
}

const tryRender = () => {
renderMermaid()
if (container.querySelectorAll(".mermaid").length === 0) {
setTimeout(tryRender, 100)
}
}

setTimeout(tryRender, 0)
},
{ defer: true },
),
)

const selectionPreview = (source: string, selection: FileSelection) => {
return previewSelectedLines(source, {
start: selection.startLine,
Expand DownExpand Up@@ -359,11 +426,21 @@ export function FileTabContent(props: { tab: string }) {
path,
() => {
commentsUi.note.reset()
setPreview(true)
},
{ defer: true },
),
)

createEffect(() => {
const focus = comments.focus()
const p = path()
if (!focus || !p) return
if (focus.file !== p) return
if (activeFileTab() !== props.tab) return
if (preview()) setPreview(false)
})

createEffect(() => {
const focus = comments.focus()
const p = path()
Expand DownExpand Up@@ -442,7 +519,28 @@ export function FileTabContent(props: { tab: string }) {
return (
<Tabs.Content value={props.tab} class="mt-3 relative h-full">
<ScrollView class="h-full" viewportRef={scrollSync.setViewport} onScroll={scrollSync.handleScroll as any}>
<Show when={state()?.loaded && isMarkdown() && state()?.content?.type !== "binary"}>
<div class="sticky top-0 z-10 flex items-center gap-1 bg-background-base px-4 py-1.5 border-b border-border-base">
<button
class={"px-2 py-0.5 rounded text-sm " + (preview() ? "bg-surface-base-active text-text-base" : "text-text-weak hover:text-text-base")}
onClick={() => setPreview(true)}
>
{language.t("session.files.viewPreview")}
</button>
<button
class={"px-2 py-0.5 rounded text-sm " + (!preview() ? "bg-surface-base-active text-text-base" : "text-text-weak hover:text-text-base")}
onClick={() => setPreview(false)}
>
{language.t("session.files.viewSource")}
</button>
</div>
</Show>
<Switch>
<Match when={state()?.loaded && isMarkdown() && preview() && state()?.content?.type !== "binary"}>
<div ref={setupMermaidContainer} class="px-6 py-4 pb-40">
<Markdown text={contents()} cacheKey={cacheKey()} />
</div>
</Match>
<Match when={state()?.loaded}>{renderFile(contents())}</Match>
<Match when={state()?.loading}>
<div class="px-6 py-4 text-text-weak">{language.t("common.loading")}...</div>
Expand Down
Loading