feat(ui): code blocks and chat messages from shadcn-vue's code-block, message and bubble

This commit is contained in:
sam committed 2026-10-19 02:22:42 +11:00
1 parent d876c150eb
commit 63adbc71ef
67 files changed
+1770 -310

No files matched your search

+38
View File
@@ -0,0 +1,38 @@
<script setup lang="ts">
import { cn } from "@/lib/utils";
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockLine,
CodeBlockToken,
useHighlightedCode,
} from "@/components/ui/code-block";
/**
* Code or a payload with a copy button that appears on hover or focus. The
* text is shown verbatim and wrapped: stored payloads are mostly long unbroken
* tokens (URLs, hashes, base64), which must not push the panel past its edge.
* A language the highlighter does not know renders plain.
*/
const props = defineProps<{ code: string; lang?: string; class?: string }>();
const lines = useHighlightedCode(
() => props.code,
() => props.lang || "text",
);
</script>
<template>
<CodeBlock :class="cn('bg-muted', props.class)">
<CodeBlockActions>
<CodeBlockCopyButton :value="code" />
</CodeBlockActions>
<CodeBlockContent wrap class="max-h-[60vh] pe-10 text-xs">
<CodeBlockLine v-for="(line, index) in lines" :key="index">
<CodeBlockToken v-for="(token, i) in line" :key="i" :token="token" />
</CodeBlockLine>
</CodeBlockContent>
</CodeBlock>
</template>
-28
View File
@@ -1,28 +0,0 @@
<script setup lang="ts">
/**
* Inline JSON content with syntax highlighting, or the text verbatim when it
* is not JSON. Every source character survives either way: highlighting adds
* colour spans, never removes or rewrites text. Callers own the surrounding
* <pre> and its classes (borders, max height, wrap behaviour differ per
* surface); this renders only the content.
*/
import { computed } from "vue";
import { tokenClass, tokenizeJson } from "@/lib/json-tokens";
const props = defineProps<{ text: string }>();
const tokens = computed(() => tokenizeJson(props.text));
</script>
<template>
<template v-if="tokens">
<span
v-for="(token, i) in tokens"
:key="i"
:class="tokenClass(token.kind)"
>{{ token.text }}</span
>
</template>
<template v-else>{{ props.text }}</template>
</template>
+2 -10
View File
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed } from "vue";
import HighlightedJson from "@/base/HighlightedJson.vue";
import CodeView from "@/base/CodeView.vue";
import { prettyPrint } from "./capture-payload";
/**
@@ -20,15 +20,7 @@ const text = computed(() => prettyPrint(props.raw));
>
{{ label }}
</h3>
<!--
Wrap rather than scroll sideways: a captured payload is mostly long
unbroken tokens (URLs, hashes, base64), and one of those on a single line
would push the panel's contents past its edge instead of being read.
-->
<p v-if="!text" class="text-sm text-fg-muted">(empty)</p>
<pre
v-else
class="rounded-sm border border-border-strong bg-muted p-3 font-mono text-xs whitespace-pre-wrap wrap-break-word"
><HighlightedJson :text="text" /></pre>
<CodeView v-else :code="text" lang="json" />
</section>
</template>
+34 -31
View File
@@ -1,5 +1,7 @@
<script setup lang="ts">
import { cn } from "@/lib/utils";
import { Bubble, BubbleContent } from "@/components/ui/bubble";
import { CodeBlockCopyButton } from "@/components/ui/code-block";
import { Message, MessageContent, MessageFooter } from "@/components/ui/message";
import ChatAttachment from "./ChatAttachment.vue";
import ChatMarkdown from "./ChatMarkdown.vue";
import ChatToolCall from "./ChatToolCall.vue";
@@ -9,7 +11,8 @@ import type { ChatMedia, ChatToolCall as ToolCall } from "./state";
* One message, from either side of the conversation. There is no speaker
* label: which side of the panel it sits on, and its fill, are what say who is
* talking. A trailing action arrives through the slot, so the retry the
* transcript offers belongs to the bubble rather than beside it.
* transcript offers belongs to the bubble rather than beside it. A finished
* reply carries a copy action beneath it.
*/
withDefaults(
defineProps<{
@@ -26,33 +29,33 @@ withDefaults(
</script>
<template>
<div class="flex" :class="assistant ? 'justify-start' : 'justify-end'">
<div
:class="
cn(
'max-w-[min(78ch,92%)] rounded-[0.85rem] px-3.5 py-2.5 text-sm leading-normal [overflow-wrap:anywhere]',
assistant ? 'bg-muted' : 'bg-primary/15',
)
"
>
<div v-if="assistant && tools.length" class="mb-2 grid gap-0.5 text-xs">
<ChatToolCall
v-for="(tool, i) in tools"
:key="i"
:tool="tool"
:streaming="streaming"
/>
</div>
<div v-if="media.length" class="mb-2 flex flex-wrap gap-1.5">
<ChatAttachment
v-for="(attachment, i) in media"
:key="i"
:attachment="attachment"
/>
</div>
<ChatMarkdown v-if="assistant" :text="text" />
<div v-else class="whitespace-pre-wrap">{{ text }}</div>
<slot />
</div>
</div>
<Message :align="assistant ? 'start' : 'end'">
<MessageContent>
<Bubble :variant="assistant ? 'muted' : 'tinted'" class="max-w-[min(78ch,92%)]">
<BubbleContent class="[overflow-wrap:anywhere]">
<div v-if="assistant && tools.length" class="mb-2 grid gap-0.5 text-xs">
<ChatToolCall
v-for="(tool, i) in tools"
:key="i"
:tool="tool"
:streaming="streaming"
/>
</div>
<div v-if="media.length" class="mb-2 flex flex-wrap gap-1.5">
<ChatAttachment
v-for="(attachment, i) in media"
:key="i"
:attachment="attachment"
/>
</div>
<ChatMarkdown v-if="assistant" :text="text" />
<div v-else class="whitespace-pre-wrap">{{ text }}</div>
<slot />
</BubbleContent>
</Bubble>
<MessageFooter v-if="assistant && !streaming && text" class="px-0">
<CodeBlockCopyButton :value="text" />
</MessageFooter>
</MessageContent>
</Message>
</template>
+2 -4
View File
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { computed } from "vue";
import CodeView from "@/base/CodeView.vue";
import ChatInline from "./ChatInline.vue";
import { parseMarkdown } from "./markdown";
@@ -18,10 +19,7 @@ const blocks = computed(() => parseMarkdown(props.text));
<template>
<div class="[overflow-wrap:anywhere]">
<template v-for="(block, i) in blocks" :key="i">
<pre
v-if="block.kind === 'pre'"
class="my-2 overflow-auto rounded-md border border-border bg-background/60 p-3"
><code class="font-mono text-[0.85em]">{{ block.code }}</code></pre>
<CodeView v-if="block.kind === 'pre'" :code="block.code" :lang="block.lang" class="my-2" />
<table
v-else-if="block.kind === 'table'"
+5 -3
View File
@@ -21,7 +21,7 @@ export type ChatInline =
export type ChatBlock =
| { kind: "p" | "h1" | "h2" | "h3" | "blockquote"; inline: ChatInline[] }
| { kind: "ul" | "ol"; items: ChatInline[][] }
| { kind: "pre"; code: string }
| { kind: "pre"; code: string; lang: string }
| { kind: "table"; head: ChatInline[][]; rows: ChatInline[][][] };
const INLINE =
@@ -67,6 +67,7 @@ export function parseMarkdown(text: string | null | undefined): ChatBlock[] {
let paragraph: string[] = [];
let list: { tag: "ul" | "ol"; items: string[] } | null = null;
let code: string[] | null = null;
let lang = "";
const flushParagraph = () => {
if (paragraph.length) {
@@ -89,10 +90,11 @@ export function parseMarkdown(text: string | null | undefined): ChatBlock[] {
flushParagraph();
flushList();
if (code) {
blocks.push({ kind: "pre", code: code.join("\n") });
blocks.push({ kind: "pre", code: code.join("\n"), lang });
code = null;
} else {
code = [];
lang = line.slice(3).trim().split(/\s/)[0];
}
continue;
}
@@ -167,7 +169,7 @@ export function parseMarkdown(text: string | null | undefined): ChatBlock[] {
}
flushParagraph();
flushList();
if (code) blocks.push({ kind: "pre", code: code.join("\n") });
if (code) blocks.push({ kind: "pre", code: code.join("\n"), lang });
return blocks;
}
+33
View File
@@ -0,0 +1,33 @@
<script lang='ts' setup>
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import type { BubbleVariants } from '.'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { bubbleVariants } from '.'
interface Props extends PrimitiveProps {
variant?: BubbleVariants['variant']
align?: 'start' | 'end'
class?: HTMLAttributes['class']
}
const props = withDefaults(defineProps<Props>(), {
variant: 'default',
align: 'start',
as: 'div',
})
</script>
<template>
<Primitive
data-slot="bubble"
:data-variant="variant"
:data-align="align"
:as="as"
:as-child="asChild"
:class="cn(bubbleVariants({ variant }), props.class)"
>
<slot />
</Primitive>
</template>
@@ -0,0 +1,28 @@
<script lang='ts' setup>
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
interface Props extends PrimitiveProps {
class?: HTMLAttributes['class']
}
const props = withDefaults(defineProps<Props>(), {
as: 'div',
})
</script>
<template>
<Primitive
data-slot="bubble-content"
:as="as"
:as-child="asChild"
:class="cn(
'rounded-xl border border-transparent px-3 py-2 text-sm leading-relaxed [button,a]:outline-none [button,a]:focus-visible:border-ring [button,a]:focus-visible:ring-3 [button,a]:focus-visible:ring-ring/50 group-data-[align=end]/bubble:self-end w-fit max-w-full min-w-0 overflow-hidden wrap-break-word [button]:text-left [button,a]:transition-colors',
props.class,
)"
>
<slot />
</Primitive>
</template>
@@ -0,0 +1,25 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
interface Props extends PrimitiveProps {
class?: HTMLAttributes['class']
}
const props = withDefaults(defineProps<Props>(), {
as: 'div',
})
</script>
<template>
<Primitive
data-slot="bubble-group"
:as="as"
:as-child="asChild"
:class="cn('gap-2 flex min-w-0 flex-col', props.class)"
>
<slot />
</Primitive>
</template>
@@ -0,0 +1,33 @@
<script lang='ts' setup>
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import type { BubbleReactionsVariants } from '.'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { bubbleReactionsVariants } from '.'
interface Props extends PrimitiveProps {
side?: BubbleReactionsVariants['side']
align?: BubbleReactionsVariants['align']
class?: HTMLAttributes['class']
}
const props = withDefaults(defineProps<Props>(), {
side: 'bottom',
align: 'end',
as: 'div',
})
</script>
<template>
<Primitive
data-slot="bubble-reactions"
:data-side="side"
:data-align="align"
:as="as"
:as-child="asChild"
:class="cn(bubbleReactionsVariants({ side, align }), props.class)"
>
<slot />
</Primitive>
</template>
+49
View File
@@ -0,0 +1,49 @@
import type { VariantProps } from 'class-variance-authority'
import { cva } from 'class-variance-authority'
export { default as Bubble } from './Bubble.vue'
export { default as BubbleContent } from './BubbleContent.vue'
export { default as BubbleGroup } from './BubbleGroup.vue'
export { default as BubbleReactions } from './BubbleReactions.vue'
export const bubbleVariants = cva(
'gap-1 data-[align=end]:self-end max-w-[80%] data-[variant=ghost]:max-w-full group-data-[align=end]/message:self-end group/bubble relative flex w-fit min-w-0 flex-col',
{
variants: {
variant: {
default: '*:data-[slot=bubble-content]:bg-primary *:data-[slot=bubble-content]:text-primary-foreground [&>[data-slot=bubble-content]:is(button,a):hover]:bg-primary/80',
secondary: '*:data-[slot=bubble-content]:bg-secondary *:data-[slot=bubble-content]:text-secondary-foreground [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)]',
muted: '*:data-[slot=bubble-content]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[color-mix(in_oklch,var(--muted),var(--foreground)_5%)]',
tinted: '*:data-[slot=bubble-content]:bg-[oklch(from_var(--primary)_0.93_calc(c*0.4)_h)] dark:*:data-[slot=bubble-content]:bg-[oklch(from_var(--primary)_0.3_calc(c*0.4)_h)] *:data-[slot=bubble-content]:text-foreground [&>[data-slot=bubble-content]:is(button,a):hover]:bg-[oklch(from_var(--primary)_0.88_calc(c*0.5)_h)] dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-[oklch(from_var(--primary)_0.35_calc(c*0.5)_h)]',
outline: '*:data-[slot=bubble-content]:bg-background *:data-[slot=bubble-content]:border-border [&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:text-foreground dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-input/30',
ghost: '*:data-[slot=bubble-content]:rounded-none *:data-[slot=bubble-content]:bg-transparent *:data-[slot=bubble-content]:p-0 [&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted [&>[data-slot=bubble-content]:is(button,a):hover]:text-foreground dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-muted/50 border-none',
destructive: '*:data-[slot=bubble-content]:bg-destructive/10 dark:*:data-[slot=bubble-content]:bg-destructive/20 *:data-[slot=bubble-content]:text-destructive [&>[data-slot=bubble-content]:is(button,a):hover]:bg-destructive/20 dark:[&>[data-slot=bubble-content]:is(button,a):hover]:bg-destructive/30',
},
},
defaultVariants: {
variant: 'default',
},
},
)
export type BubbleVariants = VariantProps<typeof bubbleVariants>
export const bubbleReactionsVariants = cva(
'rounded-full ring-3 ring-card bg-muted shrink-0 gap-1 px-1.5 py-0.5 has-[button]:p-0 text-sm absolute z-10 flex w-fit items-center justify-center',
{
variants: {
side: {
top: 'top-0 -translate-y-3/4',
bottom: 'bottom-0 translate-y-3/4',
},
align: {
start: 'left-3',
end: 'right-3',
},
},
defaultVariants: {
side: 'bottom',
align: 'end',
},
},
)
export type BubbleReactionsVariants = VariantProps<typeof bubbleReactionsVariants>
@@ -0,0 +1,26 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import type { CodeBlockVariants } from '.'
import { cn } from '@/lib/utils'
import { codeBlockVariants } from '.'
const props = withDefaults(defineProps<{
variant?: CodeBlockVariants['variant']
size?: 'default' | 'sm'
class?: HTMLAttributes['class']
}>(), {
variant: 'default',
size: 'default',
})
</script>
<template>
<div
data-slot="code-block"
:data-variant="variant"
:data-size="size"
:class="cn(codeBlockVariants({ variant }), props.class)"
>
<slot />
</div>
</template>
@@ -0,0 +1,20 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<div
data-slot="code-block-actions"
:class="cn(
'-my-1 -me-1.5 gap-1 [[data-slot=code-block]>&]:m-0 [[data-slot=code-block]>&]:top-2 [[data-slot=code-block]>&]:end-2 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:top-1.5 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:end-1.5 [[data-slot=code-block]>&]:*:[button]:bg-background [[data-slot=code-block]>&]:*:[button]:ring-1 [[data-slot=code-block]>&]:*:[button]:ring-foreground/10 ms-auto flex shrink-0 items-center [[data-slot=code-block]>&]:absolute [[data-slot=code-block]>&]:z-10 [[data-slot=code-block]>&]:opacity-0 [[data-slot=code-block]>&]:transition-opacity [[data-slot=code-block]>&]:group-focus-within/code-block:opacity-100 [[data-slot=code-block]>&]:group-hover/code-block:opacity-100 [[data-slot=code-block]>&]:pointer-coarse:opacity-100',
props.class,
)"
>
<slot />
</div>
</template>
@@ -0,0 +1,80 @@
<script setup lang="ts">
import type { HTMLAttributes, VNode } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
import { Comment, Fragment, Text, useSlots } from 'vue'
import CodeBlockLine from './CodeBlockLine.vue'
const props = withDefaults(defineProps<{
wrap?: boolean
lineNumbers?: boolean
startLine?: number
class?: HTMLAttributes['class']
}>(), {
wrap: false,
lineNumbers: false,
startLine: 1,
})
const slots = useSlots()
// Plain text content, or null when the slot renders elements.
function getText(nodes: VNode[]): string | null {
let text = ''
for (const node of nodes) {
if (node.type === Comment)
continue
if (node.type === Text) {
text += node.children as string
}
else if (node.type === Fragment && Array.isArray(node.children)) {
const nested = getText(node.children as VNode[])
if (nested === null)
return null
text += nested
}
else {
return null
}
}
return text
}
function getLines() {
if (!props.lineNumbers)
return null
const text = getText(slots.default?.() ?? [])
return text === null ? null : text.replace(/\n$/, '').split('\n')
}
</script>
<template>
<Primitive
as="pre"
data-slot="code-block-content"
:data-wrap="wrap || undefined"
:data-numbered="lineNumbers || undefined"
dir="ltr"
tabindex="0"
:style="{ counterReset: `line ${startLine - 1}` }"
:class="cn(
'px-3 py-3 leading-relaxed group-has-data-[slot=code-block-header]/code-block:pt-2 group-has-data-[slot=code-block-footer]/code-block:pb-2 group-data-[size=sm]/code-block:px-2.5 group-data-[size=sm]/code-block:py-2.5 group-data-[size=sm]/code-block:group-has-data-[slot=code-block-header]/code-block:pt-1.5 min-h-0 min-w-0 scroll-fade-x scrollbar-thin overflow-auto text-start font-mono outline-none data-wrap:scroll-fade-y data-wrap:wrap-break-word data-wrap:whitespace-pre-wrap',
props.class,
)"
>
<Primitive
as="code"
data-slot="code-block-code"
class="grid min-h-lh min-w-max content-start in-data-numbered:grid-cols-[auto_1fr] in-data-wrap:min-w-0"
>
<template v-for="(lines, i) in [getLines()]" :key="i">
<template v-if="lines">
<CodeBlockLine v-for="(line, index) in lines" :key="index">
{{ line }}
</CodeBlockLine>
</template>
<slot v-else />
</template>
</Primitive>
</Primitive>
</template>
@@ -0,0 +1,44 @@
<script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import type { ButtonVariants } from '@/components/ui/button'
import { CheckIcon, CopyIcon } from '@lucide/vue'
import { useClipboard } from '@vueuse/core'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
defineOptions({ inheritAttrs: false })
const props = withDefaults(defineProps<PrimitiveProps & {
value: string
variant?: ButtonVariants['variant']
size?: ButtonVariants['size']
class?: HTMLAttributes['class']
}>(), {
as: 'button',
variant: 'ghost',
size: 'icon-xs',
})
const { copy, copied } = useClipboard({ copiedDuring: 2000, legacy: true })
</script>
<template>
<Button
v-bind="$attrs"
data-slot="code-block-copy-button"
:data-copied="copied || undefined"
:as="as"
:as-child="asChild"
:variant="variant"
:size="size"
:aria-label="copied ? 'Copied' : 'Copy'"
:class="cn('', props.class)"
@click="copy(props.value)"
>
<CheckIcon v-if="copied" />
<CopyIcon v-else />
</Button>
<span aria-live="polite" class="sr-only">{{ copied ? "Copied" : "" }}</span>
</template>
@@ -0,0 +1,17 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<div
data-slot="code-block-footer"
:class="cn('gap-2 px-3 pb-3 text-muted-foreground group-data-[size=sm]/code-block:px-2.5 group-data-[size=sm]/code-block:pb-2.5 flex min-w-0 shrink-0 items-center', props.class)"
>
<slot />
</div>
</template>
@@ -0,0 +1,17 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<div
data-slot="code-block-header"
:class="cn('gap-2 px-3 pt-3 text-muted-foreground group-data-[variant=destructive]/code-block:text-destructive group-data-[size=sm]/code-block:px-2.5 group-data-[size=sm]/code-block:pt-2.5 flex min-w-0 shrink-0 items-center *:has-[>[data-slot=code-block-title]]:min-w-0', props.class)"
>
<slot />
</div>
</template>
@@ -0,0 +1,41 @@
<script setup lang="ts">
import type { HTMLAttributes, VNode } from 'vue'
import type { CodeBlockLineVariants } from '.'
import { cn } from '@/lib/utils'
import { Comment, Fragment, Text, useSlots } from 'vue'
import { codeBlockLineVariants } from '.'
const props = withDefaults(defineProps<{
variant?: CodeBlockLineVariants['variant']
class?: HTMLAttributes['class']
}>(), {
variant: 'default',
})
const slots = useSlots()
function hasContent(nodes: VNode[]): boolean {
return nodes.some((node) => {
if (node.type === Comment)
return false
if (node.type === Text)
return node.children !== ''
if (node.type === Fragment)
return Array.isArray(node.children) && hasContent(node.children as VNode[])
return true
})
}
// An empty line holds a newline so copying a selection keeps blank lines.
function isEmpty() {
return !hasContent(slots.default?.() ?? [])
}
</script>
<template>
<span
data-slot="code-block-line"
:data-variant="variant"
:class="cn(codeBlockLineVariants({ variant }), props.class)"
><span data-slot="code-block-line-content" class="min-w-0"><template v-if="isEmpty()">{{ "\n" }}</template><slot v-else /></span></span>
</template>
@@ -0,0 +1,17 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<div
data-slot="code-block-title"
:class="cn('font-sans text-sm font-medium text-foreground group-data-[variant=destructive]/code-block:text-destructive *:[svg]:me-1.5 [&_svg:not([class*=\'size-\'])]:size-3.5 group-data-[size=sm]/code-block:text-xs min-w-0 truncate [&_svg]:pointer-events-none [&_svg]:inline-block [&_svg]:align-middle', props.class)"
>
<slot />
</div>
</template>
@@ -0,0 +1,11 @@
<script setup lang="ts">
import type { HighlightedToken } from './highlighter'
defineProps<{
token: HighlightedToken
}>()
</script>
<template>
<span :style="token.htmlStyle" class="text-(--shiki-light) dark:text-(--shiki-dark)">{{ token.content }}</span>
</template>
@@ -0,0 +1,118 @@
import type { GrammarState, HighlighterCore } from 'shiki/core'
import { createHighlighterCore } from 'shiki/core'
import { createJavaScriptRegexEngine } from 'shiki/engine/javascript'
export interface HighlightedToken {
content: string
htmlStyle?: Record<string, string>
}
// Add the languages you need. Each one loads the first time it is used.
const languages = {
bash: () => import('shiki/langs/shellscript.mjs'),
css: () => import('shiki/langs/css.mjs'),
diff: () => import('shiki/langs/diff.mjs'),
html: () => import('shiki/langs/html.mjs'),
javascript: () => import('shiki/langs/javascript.mjs'),
json: () => import('shiki/langs/json.mjs'),
jsx: () => import('shiki/langs/jsx.mjs'),
markdown: () => import('shiki/langs/markdown.mjs'),
python: () => import('shiki/langs/python.mjs'),
sql: () => import('shiki/langs/sql.mjs'),
tsx: () => import('shiki/langs/tsx.mjs'),
typescript: () => import('shiki/langs/typescript.mjs'),
vue: () => import('shiki/langs/vue.mjs'),
yaml: () => import('shiki/langs/yaml.mjs'),
}
const aliases: Record<string, keyof typeof languages> = {
js: 'javascript',
md: 'markdown',
py: 'python',
sh: 'bash',
shell: 'bash',
shellscript: 'bash',
ts: 'typescript',
yml: 'yaml',
zsh: 'bash',
}
let highlighter: Promise<HighlighterCore> | undefined
function getHighlighter() {
highlighter ??= createHighlighterCore({
themes: [
import('shiki/themes/github-light.mjs'),
import('shiki/themes/github-dark.mjs'),
],
langs: [],
engine: createJavaScriptRegexEngine({ forgiving: true }),
})
return highlighter
}
function getLanguage(language: string) {
const name = language.toLowerCase()
if (name === 'ansi')
return name
if (name in languages)
return name as keyof typeof languages
return aliases[name] ?? null
}
// Loads a language and returns a highlighter for it, or null for a language
// that is not listed.
export async function loadHighlighter(language: string) {
const lang = getLanguage(language)
if (!lang)
return null
const shiki = await getHighlighter()
if (lang !== 'ansi' && !shiki.getLoadedLanguages().includes(lang))
await shiki.loadLanguage(languages[lang])
return {
// Returns the tokens of each line, and the grammar state after the last
// line. Pass that state back to continue where the code left off.
highlight(code: string, state?: GrammarState) {
const tokenize = (text: string) =>
shiki.codeToTokens(text, {
lang,
themes: { light: 'github-light', dark: 'github-dark' },
defaultColor: false,
grammarState: state,
}).tokens
// ANSI has no grammar state, so each line is tokenized on its own and
// gets the same colors whether it arrives in one piece or streams.
const tokens = lang === 'ansi'
? code.split('\n').flatMap(line => tokenize(line))
: tokenize(code)
return {
lines: tokens.map(line =>
line.map((token): HighlightedToken => ({
content: token.content,
htmlStyle: token.htmlStyle as Record<string, string> | undefined,
})),
),
state: shiki.getLastGrammarState(tokens),
}
},
}
}
export type Highlighter = NonNullable<Awaited<ReturnType<typeof loadHighlighter>>>
// Returns the tokens of each line, or null for a language that is not listed.
export async function highlightCode(code: string, language: string) {
const highlighter = await loadHighlighter(language)
return highlighter ? highlighter.highlight(code).lines : null
}
+49
View File
@@ -0,0 +1,49 @@
import type { VariantProps } from 'class-variance-authority'
import { cva } from 'class-variance-authority'
export { default as CodeBlock } from './CodeBlock.vue'
export { default as CodeBlockActions } from './CodeBlockActions.vue'
export { default as CodeBlockContent } from './CodeBlockContent.vue'
export { default as CodeBlockCopyButton } from './CodeBlockCopyButton.vue'
export { default as CodeBlockFooter } from './CodeBlockFooter.vue'
export { default as CodeBlockHeader } from './CodeBlockHeader.vue'
export { default as CodeBlockLine } from './CodeBlockLine.vue'
export { default as CodeBlockTitle } from './CodeBlockTitle.vue'
export { default as CodeBlockToken } from './CodeBlockToken.vue'
export { highlightCode, loadHighlighter } from './highlighter'
export type { HighlightedToken } from './highlighter'
export { useHighlightedCode } from './useHighlightedCode'
export const codeBlockVariants = cva(
'rounded-lg text-sm data-[size=sm]:text-xs has-[>[data-slot=code-block-content]:focus-visible]:ring-3 has-[>[data-slot=code-block-content]:focus-visible]:ring-ring/50 group/code-block relative flex w-full min-w-0 flex-col overflow-hidden',
{
variants: {
variant: {
default: 'border border-input text-foreground dark:bg-input/30 has-[>[data-slot=code-block-content]:focus-visible]:border-ring',
destructive: 'border border-destructive/30 text-destructive dark:border-destructive/40',
},
},
defaultVariants: {
variant: 'default',
},
},
)
export type CodeBlockVariants = VariantProps<typeof codeBlockVariants>
export const codeBlockLineVariants = cva(
'-mx-3 px-3 in-data-numbered:gap-x-3 before:min-w-6 before:text-end before:text-muted-foreground after:start-1 after:text-muted-foreground group-data-[size=sm]/code-block:-mx-2.5 group-data-[size=sm]/code-block:px-2.5 relative block min-h-lh after:absolute after:top-0 after:select-none in-data-numbered:col-span-2 in-data-numbered:grid in-data-numbered:grid-cols-subgrid in-data-numbered:[counter-increment:line] in-data-numbered:before:content-[counter(line)] in-data-numbered:before:select-none in-data-numbered:supports-[content:counter(line)_/_\'\']:before:content-[counter(line)_/_\'\']',
{
variants: {
variant: {
default: '',
added: 'bg-muted after:content-[\'+\']',
removed: 'bg-destructive/10 after:text-destructive after:content-[\'−\']',
highlighted: 'bg-muted',
},
},
defaultVariants: {
variant: 'default',
},
},
)
export type CodeBlockLineVariants = VariantProps<typeof codeBlockLineVariants>
@@ -0,0 +1,72 @@
import type { GrammarState } from 'shiki/core'
import type { MaybeRefOrGetter } from 'vue'
import type { HighlightedToken, Highlighter } from './highlighter'
import { computed, shallowRef, toValue, watch } from 'vue'
import { loadHighlighter } from './highlighter'
export function useHighlightedCode(
value: MaybeRefOrGetter<string>,
language: MaybeRefOrGetter<string>,
) {
const highlighter = shallowRef<Highlighter | null>(null)
watch(() => toValue(language), (lang, _, onCleanup) => {
// Highlighting runs in the browser. The server renders the plain lines.
if (typeof window === 'undefined')
return
let cancelled = false
onCleanup(() => (cancelled = true))
highlighter.value = null
loadHighlighter(lang)
.then((next) => {
if (!cancelled)
highlighter.value = next
})
.catch(() => {})
}, { immediate: true })
// The complete lines, highlighted. While the code streams, only the new
// lines are tokenized, starting from the grammar state of the last one.
let done: {
highlighter: Highlighter | null
text: string
lines: HighlightedToken[][]
state?: GrammarState
} = { highlighter: null, text: '', lines: [] }
return computed<HighlightedToken[][]>(() => {
const raw = toValue(value)
// A trailing newline would render as an extra empty line.
const code = raw.endsWith('\n') ? raw.slice(0, -1) : raw
const current = highlighter.value
if (!current)
return code.split('\n').map(line => (line ? [{ content: line }] : []))
if (done.highlighter !== current || !code.startsWith(done.text))
done = { highlighter: current, text: '', lines: [] }
const end = code.lastIndexOf('\n') + 1
if (end > done.text.length) {
const result = current.highlight(
code.slice(done.text.length, end - 1),
done.state,
)
done = {
highlighter: current,
text: code.slice(0, end),
lines: [...done.lines, ...result.lines],
state: result.state,
}
}
// The last line is still being written, so it is tokenized on every change.
const tail = current.highlight(code.slice(end), done.state).lines[0] ?? []
return [...done.lines, tail]
})
}
+30
View File
@@ -0,0 +1,30 @@
<script lang='ts' setup>
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
interface Props extends PrimitiveProps {
class?: HTMLAttributes['class']
align?: 'start' | 'end'
}
const props = withDefaults(defineProps<Props>(), {
align: 'start',
as: 'div',
})
</script>
<template>
<Primitive
data-slot="message"
:data-align="align"
:as="as"
:as-child="asChild"
:class="cn(
'text-sm gap-2 group/message relative flex w-full min-w-0 data-[align=end]:flex-row-reverse',
props.class,
)"
>
<slot />
</Primitive>
</template>
@@ -0,0 +1,27 @@
<script lang='ts' setup>
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
interface Props extends PrimitiveProps {
class?: HTMLAttributes['class']
}
const props = withDefaults(defineProps<Props>(), {
as: 'div',
})
</script>
<template>
<Primitive
data-slot="message-avatar"
:as="as"
:as-child="asChild"
:class="cn(
'min-w-8 group-has-data-[slot=message-footer]/message:-translate-y-8 flex w-fit shrink-0 items-center justify-center self-end overflow-hidden rounded-full bg-muted',
props.class,
)"
>
<slot />
</Primitive>
</template>
@@ -0,0 +1,27 @@
<script lang='ts' setup>
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
interface Props extends PrimitiveProps {
class?: HTMLAttributes['class']
}
const props = withDefaults(defineProps<Props>(), {
as: 'div',
})
</script>
<template>
<Primitive
data-slot="message-content"
:as="as"
:as-child="asChild"
:class="cn(
'gap-2.5 group-data-[align=end]/message:*:data-slot:self-end flex w-full min-w-0 flex-col wrap-break-word',
props.class,
)"
>
<slot />
</Primitive>
</template>
@@ -0,0 +1,27 @@
<script lang='ts' setup>
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
interface Props extends PrimitiveProps {
class?: HTMLAttributes['class']
}
const props = withDefaults(defineProps<Props>(), {
as: 'div',
})
</script>
<template>
<Primitive
data-slot="message-footer"
:as="as"
:as-child="asChild"
:class="cn(
'text-xs font-medium text-muted-foreground px-3 group-has-data-[variant=ghost]/message:px-0 flex max-w-full min-w-0 items-center group-data-[align=end]/message:justify-end',
props.class,
)"
>
<slot />
</Primitive>
</template>
@@ -0,0 +1,27 @@
<script lang='ts' setup>
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
interface Props extends PrimitiveProps {
class?: HTMLAttributes['class']
}
const props = withDefaults(defineProps<Props>(), {
as: 'div',
})
</script>
<template>
<Primitive
data-slot="message-group"
:as="as"
:as-child="asChild"
:class="cn(
'gap-2 flex min-w-0 flex-col',
props.class,
)"
>
<slot />
</Primitive>
</template>
@@ -0,0 +1,27 @@
<script lang='ts' setup>
import type { PrimitiveProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
import { Primitive } from 'reka-ui'
interface Props extends PrimitiveProps {
class?: HTMLAttributes['class']
}
const props = withDefaults(defineProps<Props>(), {
as: 'div',
})
</script>
<template>
<Primitive
data-slot="message-header"
:as="as"
:as-child="asChild"
:class="cn(
'text-xs font-medium text-muted-foreground px-3 group-has-data-[variant=ghost]/message:px-0 flex max-w-full min-w-0 items-center',
props.class,
)"
>
<slot />
</Primitive>
</template>
+6
View File
@@ -0,0 +1,6 @@
export { default as Message } from './Message.vue'
export { default as MessageAvatar } from './MessageAvatar.vue'
export { default as MessageContent } from './MessageContent.vue'
export { default as MessageFooter } from './MessageFooter.vue'
export { default as MessageGroup } from './MessageGroup.vue'
export { default as MessageHeader } from './MessageHeader.vue'
-71
View File
@@ -1,71 +0,0 @@
/**
* JSON syntax highlighting, tokenised.
*
* Capture bodies and stored config documents are strings that are "valid JSON
* or not" — the reader's rule is: valid JSON renders with typed colour, and
* anything else renders plain, exactly as stored. There is no projection and
* no library: one pass with a JSON-aware scanner, every character of the
* source preserved verbatim in the output tokens.
*
* Keys and values are distinguished by what follows the string (a colon makes
* it a key), which is exactly how JSON itself decides.
*/
export type JsonTokenKind = "key" | "string" | "number" | "keyword" | "punct";
export interface JsonToken {
text: string;
kind: JsonTokenKind;
}
/** Matches one JSON token: a string (which may be a key), a number, a keyword. */
const SCANNER =
/("(?:\\.|[^"\\])*")(\s*:)?|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|(\btrue\b|\bfalse\b|\bnull\b)/g;
export function tokenizeJson(text: string): JsonToken[] | null {
if (!text.trim()) return null;
try {
JSON.parse(text);
} catch {
return null; // not JSON: the caller renders it plain
}
const tokens: JsonToken[] = [];
let last = 0;
for (const match of text.matchAll(SCANNER)) {
const [full, str, colon, num, keyword] = match;
const at = match.index ?? 0;
if (at > last) tokens.push({ text: text.slice(last, at), kind: "punct" });
if (str !== undefined) {
tokens.push({ text: str, kind: colon ? "key" : "string" });
if (colon) tokens.push({ text: colon, kind: "punct" });
last = at + full.length;
continue;
}
if (num !== undefined) {
tokens.push({ text: num, kind: "number" });
} else if (keyword !== undefined) {
tokens.push({ text: keyword, kind: "keyword" });
}
last = at + full.length;
}
if (last < text.length)
tokens.push({ text: text.slice(last), kind: "punct" });
return tokens;
}
/** The token's colour class, from the design tokens only. */
export function tokenClass(kind: JsonTokenKind): string {
switch (kind) {
case "key":
return "text-primary";
case "string":
return "text-ok";
case "number":
return "text-warn";
case "keyword":
return "text-info";
default:
return "text-foreground";
}
}
+5 -37
View File
@@ -1,49 +1,17 @@
<script setup lang="ts">
import { Button } from "@/components/ui/button";
import { computed } from "vue";
import CodeView from "@/base/CodeView.vue";
/**
* A JSON payload, verbatim. Two panels show one (the attempt's recorded config
* and the debug view), and both must show exactly what the daemon stored --
* no projection, no prettifying beyond indentation.
*/
import { computed, ref, watch } from "vue";
import { Check, Copy, TriangleAlert } from "@lucide/vue";
import HighlightedJson from "@/base/HighlightedJson.vue";
const props = defineProps<{ value: unknown }>();
const text = computed(() => JSON.stringify(props.value ?? {}, null, 2));
const copied = ref(false);
const copyError = ref(false);
watch(text, () => { copied.value = false; copyError.value = false; });
async function copy(): Promise<void> {
copyError.value = false;
try {
await navigator.clipboard.writeText(text.value);
copied.value = true;
} catch {
copied.value = false;
copyError.value = true;
}
}
</script>
<template>
<div class="group/json relative">
<Button
type="button"
variant="secondary"
size="icon-sm"
class="absolute top-2 right-2 z-10 opacity-0 focus-visible:opacity-100 group-hover/json:opacity-100 group-focus-within/json:opacity-100"
:aria-label="copyError ? 'Copy failed. Retry copying output' : copied ? 'Copied output' : 'Copy output'"
:title="copyError ? 'Copy failed. Retry.' : copied ? 'Copied' : 'Copy output'"
@click="copy"
>
<TriangleAlert v-if="copyError" class="size-4 text-danger" />
<Check v-else-if="copied" class="size-4" />
<Copy v-else class="size-4" />
</Button>
<span class="sr-only" role="status">{{ copyError ? 'Could not copy output.' : copied ? 'Output copied.' : '' }}</span>
<pre
class="max-h-[60vh] overflow-auto rounded-sm border border-border bg-muted p-3 font-mono text-xs leading-normal whitespace-pre-wrap break-words"
><HighlightedJson :text="text" /></pre>
</div>
<CodeView :code="text" lang="json" />
</template>