Code Block
import httpx
async def get_user(id: str):
async with httpx.AsyncClient() as client:
response = await client.get("/api/users/" + id)
response.raise_for_status()
return response.json()Installation
pnpm dlx @mielui/svelte add code-blocknpx @mielui/svelte add code-blockyarn dlx @mielui/svelte add code-blockbunx @mielui/svelte add code-blockThe component depends on highlight.js for syntax highlighting. Install it if your project doesn't have it yet:
pnpm add highlight.jsnpm i highlight.jsyarn add highlight.jsbun add highlight.jsUsage
Pass code and lang for a single snippet, or a tabs array for several languages. Bind value to read or set the active tab; it defaults to the first one.
<script lang="ts">
import { CodeBlock } from '@mielui/svelte/components/code-block';
const python = 'print("Hello")';
const javascript = "console.log('Hello');";
</script>
<CodeBlock
tabs={[
{ label: 'Python', lang: 'python', code: python },
{ label: 'JavaScript', lang: 'javascript', code: javascript }
]}
/>A single snippet is a named code region. Several snippets use tabs and tab panels. When the active tab is removed or disabled, the first enabled tab takes over, and the copy button follows it.
The built-in palette is GitHub light in light mode and GitHub dark in dark mode. For any other highlight.js theme, set theme="custom" and load its stylesheet; the component then skips its own token colors.
<script lang="ts">
import 'highlight.js/styles/github-dark.css';
import { CodeBlock } from '@mielui/svelte/components/code-block';
const code = 'const answer = 42;';
</script>
<CodeBlock {code} lang="typescript" theme="custom" />The theme's chrome.borders setting chooses single or double framing. single is the default.
Examples
Composed header
Five languages share one block, with two extra actions beside the copy button.
# Import the Pinecone library
from pinecone import Pinecone
# Initialize a Pinecone client with your API key
pc = Pinecone(api_key="YOUR_API_KEY")
# Create an index for dense vectors with integrated embedding
index_name = "quickstart-py"
pc.create_index_for_model(
name=index_name,
cloud="aws",
region="us-east-1",
embed={
"model": "llama-text-embed-v2",
"field_map": {"text": "chunk_text"},
},
)
// Import the Pinecone library
import { Pinecone } from '@pinecone-database/pinecone'
// Initialize a Pinecone client with your API key
const pc = new Pinecone({ apiKey: 'YOUR_API_KEY' });
// Create an index for dense vectors with integrated embedding
const indexName = 'quickstart-js';
await pc.createIndexForModel({
name: indexName,
cloud: 'aws',
region: 'us-east-1',
embed: {
model: 'llama-text-embed-v2',
fieldMap: { text: 'chunk_text' },
},
waitUntilReady: true,
});
// Initialize a Pinecone client with your API key
import io.pinecone.clients.Pinecone;
import org.openapitools.db_control.client.model.*;
Pinecone pc = new Pinecone.Builder("YOUR_API_KEY").build();
// Create an index for dense vectors with integrated embedding
String indexName = "quickstart-java";
pc.createIndexForModel(
indexName,
CreateIndexForModelRequest.CloudEnum.AWS,
"us-east-1",
new CreateIndexForModelRequestEmbed()
.model("llama-text-embed-v2")
.fieldMap(Map.of("text", "chunk_text")),
DeletionProtection.DISABLED,
null
);
// Initialize a Pinecone client with your API key
import "github.com/pinecone-io/go-pinecone/v3/pinecone"
pc, err := pinecone.NewClient(pinecone.NewClientParams{
ApiKey: "YOUR_API_KEY",
})
// Create an index for dense vectors with integrated embedding
indexName := "quickstart-go"
index, err := pc.CreateIndexForModel(ctx, &pinecone.CreateIndexForModelRequest{
Name: indexName,
Cloud: pinecone.Aws,
Region: "us-east-1",
Embed: pinecone.CreateIndexForModelEmbed{
Model: "llama-text-embed-v2",
FieldMap: map[string]interface{}{"text": "chunk_text"},
},
})
// Initialize a Pinecone client with your API key
using Pinecone;
var pc = new PineconeClient("YOUR_API_KEY");
// Create an index for dense vectors with integrated embedding
var indexName = "quickstart-cs";
var index = await pc.CreateIndexForModelAsync(new CreateIndexForModelRequest
{
Name = indexName,
Cloud = CreateIndexForModelRequestCloud.Aws,
Region = "us-east-1",
Embed = new CreateIndexForModelRequestEmbed
{
Model = "llama-text-embed-v2",
FieldMap = new Dictionary<string, object?> { { "text", "chunk_text" } },
},
});
Single snippet
const greet = (name: string) => {
return `Hello, ${name}!`;
};
console.log(greet('world'));Multiple languages
export async function getUser(id: string) {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error('Not found');
return res.json();
}import httpx
async def get_user(id: str):
async with httpx.AsyncClient() as client:
res = await client.get(f"/api/users/{id}")
res.raise_for_status()
return res.json()func GetUser(id string) (*User, error) {
res, err := http.Get("/api/users/" + id)
if err != nil {
return nil, err
}
defer res.Body.Close()
return decode(res.Body)
}Line numbers
1 2 3 4 5 6 7
def fib(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print([fib(i) for i in range(10)])Custom actions
Put editor or run buttons in Actions and handle their result in your application. This example edits a local query and reports a simulated result; it sends no request.
SELECT id, email, created_at
FROM users
WHERE created_at > now() - interval '7 days'
ORDER BY created_at DESC
LIMIT 50;Edit the query or run the local demonstration.
Copy placement: overlay
model = SentenceTransformer("all-MiniLM-L6-v2")
embeddings = model.encode(documents)
index.upsert(vectors=zip(ids, embeddings))Copy placement: inline
pnpm dlx @mielui/svelte add code-block Copy codeCompound API
npm install @mielui/svelte
npx @mielui/svelte add code-blockname: ci
on: [push]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm testCustom theme: stylesheet
theme="custom" disables the built-in token colors. Load a highlight.js stylesheet or supply your own hljs-* rules. This example defines One Dark and One Light token colors.
export async function getUser(id: string) {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error('Not found');
return res.json();
}Custom theme: variables
To keep the built-in palette and only shift its hues, override the --code-block-token-* variables on a wrapper. They inherit into the block per mode.
export async function getUser(id: string) {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error('Not found');
return res.json();
}Labels
Built-in text is English by default. Pass labels to CodeBlock or Root to translate or reword the code region's name and the copy button. Every key of CodeBlockLabels is optional; omitted keys keep their default.
<CodeBlock
{code}
lang="ts"
labels={{
code: 'Code',
copy: 'Copier le code',
copied: 'Copié'
}}
/>Copy button and parts
Copy copies the active snippet and shows a short confirmation. Its tooltip and accessible name come from labels.copy and labels.copied on Root, Copy code and Copied by default. Trigger is the tab for one language in a multi-language block, and disabled greys out a tab whose snippet is not ready.
Every part takes class, and the parts that wrap content render their children.
API reference
CodeBlock
Renders a high-level code block.
labelsCodeBlockLabelsOverrides the built-in text and accessible names. Every key is optional and English is the fallback.
valueBindablestringActive tab id (bindable). Defaults to the first tab.
tabsCodeBlockTab[]High-level multi-language form.
codestringSingle-snippet shorthand (ignored when
tabsis set).langstringLanguage for the single-snippet shorthand.
showLineNumbersbooleanRender a line-number gutter.
Default
falsecopyCodeBlockCopyPlacementCopy button placement: -
actionbar(default): in the header's action cluster. -overlay: pinned to the top-right of the code body. -inline: a single-line body with the copy centered on the far right.Default
'actionbar'actionsSnippet<[]>Extra buttons placed left of the built-in copy button (high-level form).
themeCodeBlockThemeSyntax paint: -
mielui(default): the built-in GitHub palette. -custom: no token colors; load anyhighlight.js/styles/*theme instead.Default
'mielui'classstringClasses added to the element.
childrenSnippet<[]>Content rendered inside.
CodeBlock.Actions
Groups code block actions.
copybooleanAppend the built-in copy button after
children.Default
trueclassstringClasses added to the element.
childrenSnippet<[]>Content rendered inside.
CodeBlock.Content
Renders a code snippet panel.
valuestringTab id this panel belongs to.
Default
'default'codeRequiredstringSource text to show.
langstringLanguage used for highlighting.
showLineNumbersbooleanShows a line number before each line.
Default
falsecopyPlacement"overlay" | "inline"Render the copy button in/over this panel (
overlayorinline).classstringClasses added to the element.
childrenSnippet<[]>Content rendered inside.
CodeBlock.Copy
Copies the active code snippet.
classstringClasses added to the element.
childrenSnippet<[]>Content rendered inside.
CodeBlock.Header
Renders the code block header.
classstringClasses added to the element.
childrenSnippet<[]>Content rendered inside.
CodeBlock.List
Groups code language tabs.
classstringClasses added to the element.
childrenSnippet<[]>Content rendered inside.
CodeBlock.Trigger
Selects a code language tab.
valueRequiredstringTab id; matches a
Contentvalue.disabledbooleanPrevents interaction and dims the control.
Default
falseclassstringClasses added to the element.
childrenSnippet<[]>Content rendered inside.
export async function getUser(id: string) { const response = await fetch('/api/users/' + id); if (!response.ok) { throw new Error('User not found'); } return response.json(); }