Create a Svelte 5 counter component with increment and decrement functionality.
Use Svelte 5's `$state` rune for reactivity. The component should have increment/decrement buttons and display the current count starting at 0.
## Test Suite
Your component must pass the following tests:
```ts
import { render, screen } from "@testing-library/svelte";
import { expect, test, describe } from "vitest";
import userEvent from "@testing-library/user-event";
import Counter from "./Component.svelte"; // Your component that is written using the ResultWrite tool
describe("Counter component", () => {
test("renders with initial count of 0", () => {
render(Counter);
// Use data-testid to get elements
const countElement = screen.getByTestId("count-value");
const decrementButton = screen.getByTestId("decrement-button");
const incrementButton = screen.getByTestId("increment-button");
// Check initial state
expect(countElement).toHaveTextContent("0");
expect(decrementButton).toBeInTheDocument();
expect(incrementButton).toBeInTheDocument();
});
test("increments the count when + button is clicked", async () => {
const user = userEvent.setup();
render(Counter);
const incrementButton = screen.getByTestId("increment-button");
const countElement = screen.getByTestId("count-value");
// Initial count should be 0
expect(countElement).toHaveTextContent("0");
// Click the increment button
await user.click(incrementButton);
// Count should now be 1
expect(countElement).toHaveTextContent("1");
});
test("decrements the count when - button is clicked", async () => {
const user = userEvent.setup();
render(Counter);
const decrementButton = screen.getByTestId("decrement-button");
const countElement = screen.getByTestId("count-value");
// Initial count should be 0
expect(countElement).toHaveTextContent("0");
// Click the decrement button
await user.click(decrementButton);
// Count should now be -1
expect(countElement).toHaveTextContent("-1");
});
test("handles multiple clicks correctly", async () => {
const user = userEvent.setup();
render(Counter);
const decrementButton = screen.getByTestId("decrement-button");
const incrementButton = screen.getByTestId("increment-button");
const countElement = screen.getByTestId("count-value");
// Increment twice
await user.click(incrementButton);
await user.click(incrementButton);
expect(countElement).toHaveTextContent("2");
// Decrement once
await user.click(decrementButton);
expect(countElement).toHaveTextContent("1");
});
});
```
IMPORTANT: When you have finished implementing the component, use the ResultWrite tool to output your final Svelte component code. Only output the component code itself, no explanations or markdown formatting.
{
"content": "<script>\n\tlet count = $state(0);\n\n\tfunction increment() {\n\t\tcount += 1;\n\t}\n\n\tfunction decrement() {\n\t\tcount -= 1;\n\t}\n</script>\n\n<button data-testid=\"decrement-button\" onclick={decrement}>\n\t-\n</button>\n\n<span data-testid=\"count-value\">{count}</span>\n\n<button data-testid=\"increment-button\" onclick={increment}>\n\t+\n</button>\n"
}
{
"success": true
}
<script>
let count = $state(0);
function increment() {
count += 1;Create a Svelte 5 number doubler component that uses the `$derived` rune.
The component should have a number input starting at 5, use `$derived` to calculate the doubled value, and include a button to increment the number.
## Test Suite
Your component must pass the following tests:
```ts
import { render, screen } from "@testing-library/svelte";
import { expect, test, describe } from "vitest";
import userEvent from "@testing-library/user-event";
import NumberDoubler from "./Component.svelte";
describe("NumberDoubler component", () => {
test("renders with initial state", () => {
render(NumberDoubler);
expect(screen.getByTestId("number-value")).toHaveTextContent("Number: 5");
expect(screen.getByTestId("doubled-value")).toHaveTextContent("Doubled: 10");
});
test("updates doubled value when number increments", async () => {
const user = userEvent.setup();
render(NumberDoubler);
await user.click(screen.getByTestId("increment-button"));
expect(screen.getByTestId("number-value")).toHaveTextContent("Number: 6");
expect(screen.getByTestId("doubled-value")).toHaveTextContent("Doubled: 12");
// Click again
await user.click(screen.getByTestId("increment-button"));
expect(screen.getByTestId("number-value")).toHaveTextContent("Number: 7");
expect(screen.getByTestId("doubled-value")).toHaveTextContent("Doubled: 14");
});
});
```
IMPORTANT: When you have finished implementing the component, use the ResultWrite tool to output your final Svelte component code. Only output the component code itself, no explanations or markdown formatting.
{
"code": "<script>\n\tlet number = $state(5);\n\tlet doubled = $derived(number * 2);\n\t\n\tfunction increment() {\n\t\tnumber += 1;\n\t}\n</script>\n\n<div>\n\t<p data-testid=\"number-value\">Number: {number}</p>\n\t<p data-testid=\"doubled-value\">Doubled: {doubled}</p>\n\t<button data-testid=\"increment-button\" onclick={increment}>\n\t\tIncrement\n\t</button>\n</div>",
"desired_svelte_version": "5",
"filename": "Component.svelte"
}
{
"content": [
{
"type": "text",
"text": "{\"issues\":[],\"suggestions\":[],\"require_another_tool_call_after_fixing\":false}"
}
],
"isError": false,
"structuredContent": {
"issues": [],
"suggestions": [],
"require_another_tool_call_after_fixing": false
}
}
{
"content": "<script>\n\tlet number = $state(5);\n\tlet doubled = $derived(number * 2);\n\t\n\tfunction increment() {\n\t\tnumber += 1;\n\t}\n</script>\n\n<div>\n\t<p data-testid=\"number-value\">Number: {number}</p>\n\t<p data-testid=\"doubled-value\">Doubled: {doubled}</p>\n\t<button data-testid=\"increment-button\" onclick={increment}>\n\t\tIncrement\n\t</button>\n</div>"
}
{
"success": true,
"message": "All 2 tests passed!",
"passed": 2,
"failed": 0,
"total": 2,
"duration": 757,
"validationFailed": false,
"validation": {
"valid": true,
"errors": []
}
}
{
"content": "<script>\n\tlet number = $state(5);\n\tlet doubled = $derived(number * 2);\n\t\n\tfunction increment() {\n\t\tnumber += 1;\n\t}\n</script>\n\n<div>\n\t<p data-testid=\"number-value\">Number: {number}</p>\n\t<p data-testid=\"doubled-value\">Doubled: {doubled}</p>\n\t<button data-testid=\"increment-button\" onclick={increment}>\n\t\tIncrement\n\t</button>\n</div>"
}
{
"success": true
}
<script>
let number = $state(5);
let doubled = $derived(number * 2);
function increment() {Create a Svelte 5 text analyzer component that uses the `$derived.by` rune for complex derivations.
The component should have a text input field and use `$derived.by` to calculate word count, character count, and whether the text is considered "long" (more than 15 words). Include a clear button to reset the text.
## Test Suite
Your component must pass the following tests:
```ts
import { render, screen } from "@testing-library/svelte";
import { expect, test, describe } from "vitest";
import userEvent from "@testing-library/user-event";
import TextAnalyzer from "./Component.svelte";
describe("TextAnalyzer component", () => {
test("renders with initial state", () => {
render(TextAnalyzer);
expect(screen.getByTestId("word-count")).toHaveTextContent("Words: 0");
expect(screen.getByTestId("char-count")).toHaveTextContent("Characters: 0");
expect(screen.getByTestId("length-indicator")).toHaveTextContent("Status: Short text");
});
test("updates counts when text is entered", async () => {
const user = userEvent.setup();
render(TextAnalyzer);
const input = screen.getByTestId("text-input");
// Enter a short text
await user.type(input, "Hello world");
expect(screen.getByTestId("word-count")).toHaveTextContent("Words: 2");
expect(screen.getByTestId("char-count")).toHaveTextContent("Characters: 11");
expect(screen.getByTestId("length-indicator")).toHaveTextContent("Status: Short text");
// Clear and enter a longer text
await user.clear(input);
await user.type(
input,
"This is a much longer text that should have more than fifteen words so that we can test the long text indicator functionality properly",
);
expect(screen.getByTestId("word-count")).toHaveTextContent("Words: 24");
expect(screen.getByTestId("char-count")).toHaveTextContent("Characters: 134");
expect(screen.getByTestId("length-indicator")).toHaveTextContent("Status: Long text");
});
test("clear button resets the text", async () => {
const user = userEvent.setup();
render(TextAnalyzer);
const input = screen.getByTestId("text-input");
const clearButton = screen.getByTestId("clear-button");
// Enter some text
await user.type(input, "Hello world");
// Verify counts
expect(screen.getByTestId("word-count")).toHaveTextContent("Words: 2");
// Click the clear button
await user.click(clearButton);
// Verify everything is reset
expect(screen.getByTestId("word-count")).toHaveTextContent("Words: 0");
expect(screen.getByTestId("char-count")).toHaveTextContent("Characters: 0");
expect(screen.getByTestId("length-indicator")).toHaveTextContent("Status: Short text");
expect(input).toHaveValue("");
});
});
```
IMPORTANT: When you have finished implementing the component, use the ResultWrite tool to output your final Svelte component code. Only output the component code itself, no explanations or markdown formatting.
{
"code": "<script>\n\tlet text = $state(\"\");\n\t\n\tlet wordCount = $derived.by(() => {\n\t\tconst trimmed = text.trim();\n\t\tif (trimmed === \"\") {\n\t\t\treturn 0;\n\t\t}\n\t\tconst words = trimmed.split(/\\s+/);\n\t\treturn words.length;\n\t});\n\t\n\tlet charCount = $derived.by(() => {\n\t\treturn text.length;\n\t});\n\t\n\tlet isLongText = $derived.by(() => {\n\t\treturn wordCount > 15;\n\t});\n\t\n\tfunction handleClear() {\n\t\ttext = \"\";\n\t}\n</script>\n\n<div class=\"analyzer\">\n\t<textarea\n\t\tdata-testid=\"text-input\"\n\t\tbind:value={text}\n\t\tplaceholder=\"Enter text to analyze...\"\n\t></textarea>\n\t\n\t<div class=\"stats\">\n\t\t<p data-testid=\"word-count\">Words: {wordCount}</p>\n\t\t<p data-testid=\"char-count\">Characters: {charCount}</p>\n\t\t<p data-testid=\"length-indicator\">Status: {isLongText ? 'Long text' : 'Short text'}</p>\n\t</div>\n\t\n\t<button data-testid=\"clear-button\" onclick={handleClear}>\n\t\tClear\n\t</button>\n</div>\n\n<style>\n\t.analyzer {\n\t\tdisplay: flex;\n\t\tflex-direction: column;\n\t\tgap: 1rem;\n\t\tmax-width: 500px;\n\t\tmargin: 0 auto;\n\t\tpadding: 1rem;\n\t}\n\t\n\ttextarea {\n\t\twidth: 100%;\n\t\tmin-height: 150px;\n\t\tpadding: 0.75rem;\n\t\tfont-size: 1rem;\n\t\tfont-family: inherit;\n\t\tresize: vertical;\n\t\tborder: 1px solid #ccc;\n\t\tborder-radius: 4px;\n\t}\n\t\n\ttextarea:focus {\n\t\toutline: none;\n\t\tborder-color: #4a90d9;\n\t\tbox-shadow: 0 0 0 2px rgba(74, 144, 217, 0.2);\n\t}\n\t\n\t.stats {\n\t\tdisplay: flex;\n\t\tflex-direction: column;\n\t\tgap: 0.25rem;\n\t\tpadding: 0.5rem;\n\t\tbackground-color: #f5f5f5;\n\t\tborder-radius: 4px;\n\t}\n\t\n\t.stats p {\n\t\tmargin: 0;\n\t\tfont-size: 0.9rem;\n\t}\n\t\n\tbutton {\n\t\talign-self: flex-end;\n\t\tpadding: 0.5rem 1rem;\n\t\tfont-size: 0.9rem;\n\t\tbackground-color: #4a90d9;\n\t\tcolor: white;\n\t\tborder: none;\n\t\tborder-radius: 4px;\n\t\tcursor: pointer;\n\t\ttransition: background-color 0.2s;\n\t}\n\t\n\tbutton:hover {\n\t\tbackground-color: #357abd;\n\t}\n\t\n\tbutton:active {\n\t\tbackground-color: #2d6aa3;\n\t}\n</style>\n",
"desired_svelte_version": "5",
"filename": "TextAnalyzer.svelte"
}
{
"content": [
{
"type": "text",
"text": "{\"issues\":[],\"suggestions\":[],\"require_another_tool_call_after_fixing\":false}"
}
],
"isError": false,
"structuredContent": {
"issues": [],
"suggestions": [],
"require_another_tool_call_after_fixing": false
}
}
{
"content": "<script>\n\tlet text = $state(\"\");\n\t\n\tlet wordCount = $derived.by(() => {\n\t\tconst trimmed = text.trim();\n\t\tif (trimmed === \"\") {\n\t\t\treturn 0;\n\t\t}\n\t\tconst words = trimmed.split(/\\s+/);\n\t\treturn words.length;\n\t});\n\t\n\tlet charCount = $derived.by(() => {\n\t\treturn text.length;\n\t});\n\t\n\tlet isLongText = $derived.by(() => {\n\t\treturn wordCount > 15;\n\t});\n\t\n\tfunction handleClear() {\n\t\ttext = \"\";\n\t}\n</script>\n\n<div class=\"analyzer\">\n\t<textarea\n\t\tdata-testid=\"text-input\"\n\t\tbind:value={text}\n\t\tplaceholder=\"Enter text to analyze...\"\n\t></textarea>\n\t\n\t<div class=\"stats\">\n\t\t<p data-testid=\"word-count\">Words: {wordCount}</p>\n\t\t<p data-testid=\"char-count\">Characters: {charCount}</p>\n\t\t<p data-testid=\"length-indicator\">Status: {isLongText ? 'Long text' : 'Short text'}</p>\n\t</div>\n\t\n\t<button data-testid=\"clear-button\" onclick={handleClear}>\n\t\tClear\n\t</button>\n</div>\n\n<style>\n\t.analyzer {\n\t\tdisplay: flex;\n\t\tflex-direction: column;\n\t\tgap: 1rem;\n\t\tmax-width: 500px;\n\t\tmargin: 0 auto;\n\t\tpadding: 1rem;\n\t}\n\t\n\ttextarea {\n\t\twidth: 100%;\n\t\tmin-height: 150px;\n\t\tpadding: 0.75rem;\n\t\tfont-size: 1rem;\n\t\tfont-family: inherit;\n\t\tresize: vertical;\n\t\tborder: 1px solid #ccc;\n\t\tborder-radius: 4px;\n\t}\n\t\n\ttextarea:focus {\n\t\toutline: none;\n\t\tborder-color: #4a90d9;\n\t\tbox-shadow: 0 0 0 2px rgba(74, 144, 217, 0.2);\n\t}\n\t\n\t.stats {\n\t\tdisplay: flex;\n\t\tflex-direction: column;\n\t\tgap: 0.25rem;\n\t\tpadding: 0.5rem;\n\t\tbackground-color: #f5f5f5;\n\t\tborder-radius: 4px;\n\t}\n\t\n\t.stats p {\n\t\tmargin: 0;\n\t\tfont-size: 0.9rem;\n\t}\n\t\n\tbutton {\n\t\talign-self: flex-end;\n\t\tpadding: 0.5rem 1rem;\n\t\tfont-size: 0.9rem;\n\t\tbackground-color: #4a90d9;\n\t\tcolor: white;\n\t\tborder: none;\n\t\tborder-radius: 4px;\n\t\tcursor: pointer;\n\t\ttransition: background-color 0.2s;\n\t}\n\t\n\tbutton:hover {\n\t\tbackground-color: #357abd;\n\t}\n\t\n\tbutton:active {\n\t\tbackground-color: #2d6aa3;\n\t}\n</style>\n"
}
{
"success": true,
"message": "All 3 tests passed!",
"passed": 3,
"failed": 0,
"total": 3,
"duration": 1034,
"validationFailed": false,
"validation": {
"valid": true,
"errors": []
}
}
{
"content": "<script>\n\tlet text = $state(\"\");\n\t\n\tlet wordCount = $derived.by(() => {\n\t\tconst trimmed = text.trim();\n\t\tif (trimmed === \"\") {\n\t\t\treturn 0;\n\t\t}\n\t\tconst words = trimmed.split(/\\s+/);\n\t\treturn words.length;\n\t});\n\t\n\tlet charCount = $derived.by(() => {\n\t\treturn text.length;\n\t});\n\t\n\tlet isLongText = $derived.by(() => {\n\t\treturn wordCount > 15;\n\t});\n\t\n\tfunction handleClear() {\n\t\ttext = \"\";\n\t}\n</script>\n\n<div class=\"analyzer\">\n\t<textarea\n\t\tdata-testid=\"text-input\"\n\t\tbind:value={text}\n\t\tplaceholder=\"Enter text to analyze...\"\n\t></textarea>\n\t\n\t<div class=\"stats\">\n\t\t<p data-testid=\"word-count\">Words: {wordCount}</p>\n\t\t<p data-testid=\"char-count\">Characters: {charCount}</p>\n\t\t<p data-testid=\"length-indicator\">Status: {isLongText ? 'Long text' : 'Short text'}</p>\n\t</div>\n\t\n\t<button data-testid=\"clear-button\" onclick={handleClear}>\n\t\tClear\n\t</button>\n</div>\n\n<style>\n\t.analyzer {\n\t\tdisplay: flex;\n\t\tflex-direction: column;\n\t\tgap: 1rem;\n\t\tmax-width: 500px;\n\t\tmargin: 0 auto;\n\t\tpadding: 1rem;\n\t}\n\t\n\ttextarea {\n\t\twidth: 100%;\n\t\tmin-height: 150px;\n\t\tpadding: 0.75rem;\n\t\tfont-size: 1rem;\n\t\tfont-family: inherit;\n\t\tresize: vertical;\n\t\tborder: 1px solid #ccc;\n\t\tborder-radius: 4px;\n\t}\n\t\n\ttextarea:focus {\n\t\toutline: none;\n\t\tborder-color: #4a90d9;\n\t\tbox-shadow: 0 0 0 2px rgba(74, 144, 217, 0.2);\n\t}\n\t\n\t.stats {\n\t\tdisplay: flex;\n\t\tflex-direction: column;\n\t\tgap: 0.25rem;\n\t\tpadding: 0.5rem;\n\t\tbackground-color: #f5f5f5;\n\t\tborder-radius: 4px;\n\t}\n\t\n\t.stats p {\n\t\tmargin: 0;\n\t\tfont-size: 0.9rem;\n\t}\n\t\n\tbutton {\n\t\talign-self: flex-end;\n\t\tpadding: 0.5rem 1rem;\n\t\tfont-size: 0.9rem;\n\t\tbackground-color: #4a90d9;\n\t\tcolor: white;\n\t\tborder: none;\n\t\tborder-radius: 4px;\n\t\tcursor: pointer;\n\t\ttransition: background-color 0.2s;\n\t}\n\t\n\tbutton:hover {\n\t\tbackground-color: #357abd;\n\t}\n\t\n\tbutton:active {\n\t\tbackground-color: #2d6aa3;\n\t}\n</style>\n"
}
{
"success": true
}
<script>
let text = $state("");
let wordCount = $derived.by(() => {
const trimmed = text.trim();Create a Svelte 5 character list component that uses the `{#each}` block.
The component should display a hardcoded list of 3 Seinfeld characters (Jerry, Elaine, Kramer) and include a button to add George to the list.
## Test Suite
Your component must pass the following tests:
```ts
import { render, screen } from "@testing-library/svelte";
import { expect, test, describe } from "vitest";
import userEvent from "@testing-library/user-event";
import CharacterList from "./Component.svelte";
describe("CharacterList component", () => {
test("renders all characters initially", () => {
render(CharacterList);
const characterElements = screen.getAllByTestId("character");
expect(characterElements.length).toBe(3);
expect(characterElements[0]).toHaveTextContent("Jerry");
expect(characterElements[1]).toHaveTextContent("Elaine");
expect(characterElements[2]).toHaveTextContent("Kramer");
});
test("adds George to the list when button clicked", async () => {
const user = userEvent.setup();
render(CharacterList);
// Initial check
let characterElements = screen.getAllByTestId("character");
expect(characterElements.length).toBe(3);
// Click the button to add George
await user.click(screen.getByTestId("add-george-button"));
// Get updated elements
characterElements = screen.getAllByTestId("character");
// Check that George was added
expect(characterElements.length).toBe(4);
expect(characterElements[3]).toHaveTextContent("George");
// Verify original characters are still there
expect(characterElements[0]).toHaveTextContent("Jerry");
expect(characterElements[1]).toHaveTextContent("Elaine");
expect(characterElements[2]).toHaveTextContent("Kramer");
});
});
```
IMPORTANT: When you have finished implementing the component, use the ResultWrite tool to output your final Svelte component code. Only output the component code itself, no explanations or markdown formatting.
{
"code": "<script>\n\tlet characters = $state([\"Jerry\", \"Elaine\", \"Kramer\"]);\n\t\n\tfunction addGeorge() {\n\t\tcharacters = [...characters, \"George\"];\n\t}\n</script>\n\n<ul>\n\t{#each characters as character (character)}\n\t\t<li data-testid=\"character\">{character}</li>\n\t{/each}\n</ul>\n\n<button data-testid=\"add-george-button\" onclick={addGeorge}>\n\tAdd George\n</button>\n",
"desired_svelte_version": "5",
"filename": "CharacterList.svelte"
}
{
"content": [
{
"type": "text",
"text": "{\"issues\":[],\"suggestions\":[],\"require_another_tool_call_after_fixing\":false}"
}
],
"isError": false,
"structuredContent": {
"issues": [],
"suggestions": [],
"require_another_tool_call_after_fixing": false
}
}
{
"content": "<script>\n\tlet characters = $state([\"Jerry\", \"Elaine\", \"Kramer\"]);\n\t\n\tfunction addGeorge() {\n\t\tcharacters = [...characters, \"George\"];\n\t}\n</script>\n\n<ul>\n\t{#each characters as character (character)}\n\t\t<li data-testid=\"character\">{character}</li>\n\t{/each}\n</ul>\n\n<button data-testid=\"add-george-button\" onclick={addGeorge}>\n\tAdd George\n</button>\n"
}
{
"success": true
}
<script>
let characters = $state(["Jerry", "Elaine", "Kramer"]);
function addGeorge() {
characters = [...characters, "George"];Create a Svelte 5 number doubler component that uses the `$effect` rune.
The component should have a number input starting at 5, use `$effect` to calculate the doubled value whenever the number changes, and include a button to increment the number.
## Test Suite
Your component must pass the following tests:
```ts
import { render, screen } from "@testing-library/svelte";
import { expect, test, describe } from "vitest";
import userEvent from "@testing-library/user-event";
import NumberDoubler from "./Component.svelte";
describe("NumberDoubler component", () => {
test("renders with initial state", () => {
render(NumberDoubler);
expect(screen.getByTestId("number-value")).toHaveTextContent("Number: 5");
expect(screen.getByTestId("doubled-value")).toHaveTextContent("Doubled: 10");
});
test("updates doubled value when number increments", async () => {
const user = userEvent.setup();
render(NumberDoubler);
await user.click(screen.getByTestId("increment-button"));
expect(screen.getByTestId("number-value")).toHaveTextContent("Number: 6");
expect(screen.getByTestId("doubled-value")).toHaveTextContent("Doubled: 12");
// Click again
await user.click(screen.getByTestId("increment-button"));
expect(screen.getByTestId("number-value")).toHaveTextContent("Number: 7");
expect(screen.getByTestId("doubled-value")).toHaveTextContent("Doubled: 14");
});
});
```
IMPORTANT: When you have finished implementing the component, use the ResultWrite tool to output your final Svelte component code. Only output the component code itself, no explanations or markdown formatting.
{
"code": "<script>\n\tlet number = $state(5);\n\tlet doubled = $state(10);\n\t\n\t$effect(() => {\n\t\tdoubled = number * 2;\n\t});\n\t\n\tfunction increment() {\n\t\tnumber += 1;\n\t}\n</script>\n\n<div>\n\t<p data-testid=\"number-value\">Number: {number}</p>\n\t<p data-testid=\"doubled-value\">Doubled: {doubled}</p>\n\t<button data-testid=\"increment-button\" onclick={increment}>Increment</button>\n</div>",
"desired_svelte_version": "5",
"filename": "Component.svelte"
}
{
"content": [
{
"type": "text",
"text": "{\"issues\":[],\"suggestions\":[\"The stateful variable \\\"doubled\\\" is assigned inside an $effect which is generally consider a malpractice. Consider using $derived if possible.\",\"Prefer using writable $derived instead of $state and $effect at line 3, column 6\"],\"require_another_tool_call_after_fixing\":true}"
}
],
"isError": false,
"structuredContent": {
"issues": [],
"suggestions": [
"The stateful variable \"doubled\" is assigned inside an $effect which is generally consider a malpractice. Consider using $derived if possible.",
"Prefer using writable $derived instead of $state and $effect at line 3, column 6"
],
"require_another_tool_call_after_fixing": true
}
}
{
"content": "<script>\n\tlet number = $state(5);\n\tlet doubled = $state(10);\n\t\n\t$effect(() => {\n\t\tdoubled = number * 2;\n\t});\n\t\n\tfunction increment() {\n\t\tnumber += 1;\n\t}\n</script>\n\n<div>\n\t<p data-testid=\"number-value\">Number: {number}</p>\n\t<p data-testid=\"doubled-value\">Doubled: {doubled}</p>\n\t<button data-testid=\"increment-button\" onclick={increment}>Increment</button>\n</div>"
}
{
"success": true,
"message": "All 2 tests passed!",
"passed": 2,
"failed": 0,
"total": 2,
"duration": 736,
"validationFailed": false,
"validation": {
"valid": true,
"errors": []
}
}
{
"content": "<script>\n\tlet number = $state(5);\n\tlet doubled = $state(10);\n\t\n\t$effect(() => {\n\t\tdoubled = number * 2;\n\t});\n\t\n\tfunction increment() {\n\t\tnumber += 1;\n\t}\n</script>\n\n<div>\n\t<p data-testid=\"number-value\">Number: {number}</p>\n\t<p data-testid=\"doubled-value\">Doubled: {doubled}</p>\n\t<button data-testid=\"increment-button\" onclick={increment}>Increment</button>\n</div>"
}
{
"success": true
}
<script>
let number = $state(5);
let doubled = $state(10);
$effect(() => {Create a simple Svelte 5 component that displays "Hello, World!" with styling.
The text should be blue, centered, and have a small margin around it.
## Test Suite
Your component must pass the following tests:
```ts
import { render, screen } from "@testing-library/svelte";
import { expect, test, describe } from "vitest";
import HelloWorld from "./Component.svelte"; // Path to the generated component
describe("HelloWorld component", () => {
test("renders with Hello, World! text", () => {
render(HelloWorld);
// Get the greeting element
const greetingElement = screen.getByTestId("greeting");
// Check that it contains the correct text
expect(greetingElement).toHaveTextContent("Hello, World!");
});
test("has the correct styling class", () => {
render(HelloWorld);
// Get the greeting element
const greetingElement = screen.getByTestId("greeting");
// Check that it has the greeting class
expect(greetingElement).toHaveClass("greeting");
});
});
```
IMPORTANT: When you have finished implementing the component, use the ResultWrite tool to output your final Svelte component code. Only output the component code itself, no explanations or markdown formatting.
{
"code": "<div class=\"greeting\" data-testid=\"greeting\">Hello, World!</div>\n\n<style>\n .greeting {\n color: blue;\n text-align: center;\n margin: 10px;\n }\n</style>",
"desired_svelte_version": "5",
"filename": "Component.svelte"
}
{
"content": [
{
"type": "text",
"text": "{\"issues\":[],\"suggestions\":[],\"require_another_tool_call_after_fixing\":false}"
}
],
"isError": false,
"structuredContent": {
"issues": [],
"suggestions": [],
"require_another_tool_call_after_fixing": false
}
}
{
"content": "<div class=\"greeting\" data-testid=\"greeting\">Hello, World!</div>\n\n<style>\n .greeting {\n color: blue;\n text-align: center;\n margin: 10px;\n }\n</style>"
}
{
"success": true
}
<div class="greeting" data-testid="greeting">Hello, World!</div>
<style>
.greeting {
color: blue;Create a Svelte 5 component that uses the `$inspect` rune to log and track state changes.
The component should have a text input starting with "Hello world", use basic `$inspect` to log the value, implement `$inspect(...).with` to track updates with a custom callback, and use `$inspect.trace()` inside an effect. Display the input value and character count.
## Test Suite
Your component must pass the following tests:
```ts
import { render, screen } from "@testing-library/svelte";
import { expect, test, describe, vi } from "vitest";
import userEvent from "@testing-library/user-event";
import InspectDemo from "./Component.svelte";
// Helper function to check text content with or without quotes
const expectCurrentTextToBe = (element: HTMLElement, expectedText: string) => {
const textContent = element.textContent || "";
const withQuotes = `Current text: "${expectedText}"`;
const withoutQuotes = `Current text: ${expectedText}`;
const hasWithQuotes = textContent.includes(withQuotes);
const hasWithoutQuotes = textContent.includes(withoutQuotes);
expect(hasWithQuotes || hasWithoutQuotes).toBe(true);
if (!hasWithQuotes && !hasWithoutQuotes) {
throw new Error(
`Expected element to contain either "${withQuotes}" or "${withoutQuotes}", but got "${textContent}"`,
);
}
};
// Helper function to get all console output as a single string
const getAllConsoleOutput = (consoleSpy: any) => {
return consoleSpy.mock.calls.map((call: any[]) => call.join(" ")).join("\n");
};
describe("InspectDemo component", () => {
test("renders with initial state", () => {
render(InspectDemo);
// Check initial text value and character count
expectCurrentTextToBe(screen.getByTestId("text-value"), "Hello world");
expect(screen.getByTestId("char-count")).toHaveTextContent("Character count: 11");
});
test("updates text value and character count when input changes", async () => {
const user = userEvent.setup();
// Mock console.log to verify $inspect functionality
const consoleSpy = vi.spyOn(console, "log");
render(InspectDemo);
// Update the input field
const input = screen.getByTestId("text-input");
await user.clear(input);
await user.type(input, "Testing $inspect");
// Check if displayed text updated
expectCurrentTextToBe(screen.getByTestId("text-value"), "Testing $inspect");
// Check if character count updated
expect(screen.getByTestId("char-count")).toHaveTextContent("Character count: 16");
// Verify $inspect features are being used (console.log was called)
// This proves $inspect, $inspect.with, and $inspect.trace are working
expect(consoleSpy).toHaveBeenCalled();
// Verify standard $inspect output is present
const output = getAllConsoleOutput(consoleSpy);
expect(output).toContain("init"); // Basic $inspect always logs init event
expect(output).toContain("update"); // Should have update events from typing
// Restore original console.log
consoleSpy.mockRestore();
});
test("handles special characters correctly", async () => {
const user = userEvent.setup();
const consoleSpy = vi.spyOn(console, "log");
render(InspectDemo);
// Update with special characters
const input = screen.getByTestId("text-input");
await user.clear(input);
await user.type(input, "!@#$%^&*()");
// Check if displayed text updated
expectCurrentTextToBe(screen.getByTestId("text-value"), "!@#$%^&*()");
// Check if character count is correct
expect(screen.getByTestId("char-count")).toHaveTextContent("Character count: 10");
// Verify $inspect features are working
expect(consoleSpy).toHaveBeenCalled();
// Verify standard $inspect output is present
const output = getAllConsoleOutput(consoleSpy);
expect(output).toContain("init"); // Basic $inspect always logs init event
expect(output).toContain("update"); // Should have update events from typing
consoleSpy.mockRestore();
});
test("handles empty input correctly", async () => {
const user = userEvent.setup();
const consoleSpy = vi.spyOn(console, "log");
render(InspectDemo);
// Clear the input
const input = screen.getByTestId("text-input");
await user.clear(input);
// Check if displayed text is empty
expectCurrentTextToBe(screen.getByTestId("text-value"), "");
// Check if character count is zero
expect(screen.getByTestId("char-count")).toHaveTextContent("Character count: 0");
// Verify $inspect features are working
expect(consoleSpy).toHaveBeenCalled();
// Verify standard $inspect output is present
const output = getAllConsoleOutput(consoleSpy);
expect(output).toContain("init"); // Basic $inspect always logs init event
expect(output).toContain("update"); // Should have update events from clearing input
consoleSpy.mockRestore();
});
});
```
IMPORTANT: When you have finished implementing the component, use the ResultWrite tool to output your final Svelte component code. Only output the component code itself, no explanations or markdown formatting.
{}
{
"content": [
{
"type": "text",
"text": "List of available Svelte documentation sections with their intended use cases. The \"use_cases\" field describes WHEN each section would be useful - analyze these carefully to determine which sections match the user's query:\n\n- title: Overview, use_cases: project setup, creating new svelte apps, scaffolding, cli tools, initializing projects, path: cli/overview\n- title: Frequently asked questions, use_cases: project setup, initializing new svelte projects, troubleshooting cli installation, package manager configuration, path: cli/faq\n- title: sv create, use_cases: project setup, starting new sveltekit app, initializing project, creating from playground, choosing project template, path: cli/sv-create\n- title: sv add, use_cases: project setup, adding features to existing projects, integrating tools, testing setup, styling setup, authentication, database setup, deployment adapters, path: cli/sv-add\n- title: sv check, use_cases: code quality, ci/cd pipelines, error checking, typescript projects, pre-commit hooks, finding unused css, accessibility auditing, production builds, path: cli/sv-check\n- title: sv migrate, use_cases: migration, upgrading svelte versions, upgrading sveltekit versions, modernizing codebase, svelte 3 to 4, svelte 4 to 5, sveltekit 1 to 2, adopting runes, refactoring deprecated apis, path: cli/sv-migrate\n- title: devtools-json, use_cases: development setup, chrome devtools integration, browser-based editing, local development workflow, debugging setup, path: cli/devtools-json\n- title: drizzle, use_cases: database setup, sql queries, orm integration, data modeling, postgresql, mysql, sqlite, server-side data access, database migrations, type-safe queries, path: cli/drizzle\n- title: eslint, use_cases: code quality, linting, error detection, project setup, code standards, team collaboration, typescript projects, path: cli/eslint\n- title: lucia, use_cases: authentication, login systems, user management, registration pages, session handling, auth setup, path: cli/lucia\n- title: mcp, use_cases: use title and path to estimate use case, path: cli/mcp\n- title: mdsvex, use_cases: blog, content sites, markdown rendering, documentation sites, technical writing, cms integration, article pages, path: cli/mdsvex\n- title: paraglide, use_cases: internationalization, multi-language sites, i18n, translation, localization, language switching, global apps, multilingual content, path: cli/paraglide\n- title: playwright, use_cases: browser testing, e2e testing, integration testing, test automation, quality assurance, ci/cd pipelines, testing user flows, path: cli/playwright\n- title: prettier, use_cases: code formatting, project setup, code style consistency, team collaboration, linting configuration, path: cli/prettier\n- title: storybook, use_cases: component development, design systems, ui library, isolated component testing, documentation, visual testing, component showcase, path: cli/storybook\n- title: sveltekit-adapter, use_cases: deployment, production builds, hosting setup, choosing deployment platform, configuring adapters, static site generation, node server, vercel, cloudflare, netlify, path: cli/sveltekit-adapter\n- title: tailwindcss, use_cases: project setup, styling, css framework, rapid prototyping, utility-first css, design systems, responsive design, adding tailwind to svelte, path: cli/tailwind\n- title: vitest, use_cases: testing, unit tests, component testing, test setup, quality assurance, ci/cd pipelines, test-driven development, path: cli/vitest\n- title: Introduction, use_cases: learning sveltekit, project setup, understanding framework basics, choosing between svelte and sveltekit, getting started with full-stack apps, path: kit/introduction\n- title: Creating a project, use_cases: project setup, starting new sveltekit app, initial development environment, first-time sveltekit users, scaffolding projects, path: kit/creating-a-project\n- title: Project types, use_cases: deployment, project setup, choosing adapters, ssg, spa, ssr, serverless, mobile apps, desktop apps, pwa, offline apps, browser extensions, separate backend, docker containers, path: kit/project-types\n- title: Project structure, use_cases: project setup, understanding file structure, organizing code, starting new project, learning sveltekit basics, path: kit/project-structure\n- title: Web standards, use_cases: always, any sveltekit project, data fetching, forms, api routes, server-side rendering, deployment to various platforms, path: kit/web-standards\n- title: Routing, use_cases: routing, navigation, multi-page apps, project setup, file structure, api endpoints, data loading, layouts, error pages, always, path: kit/routing\n- title: Loading data, use_cases: data fetching, api calls, database queries, dynamic routes, page initialization, loading states, authentication checks, ssr data, form data, content rendering, path: kit/load\n- title: Form actions, use_cases: forms, user input, data submission, authentication, login systems, user registration, progressive enhancement, validation errors, path: kit/form-actions\n- title: Page options, use_cases: prerendering static sites, ssr configuration, spa setup, client-side rendering control, url trailing slash handling, adapter deployment config, build optimization, path: kit/page-options\n- title: State management, use_cases: sveltekit, server-side rendering, ssr, state management, authentication, data persistence, load functions, context api, navigation, component lifecycle, path: kit/state-management\n- title: Remote functions, use_cases: data fetching, server-side logic, database queries, type-safe client-server communication, forms, user input, mutations, authentication, crud operations, optimistic updates, path: kit/remote-functions\n- title: Building your app, use_cases: production builds, deployment preparation, build process optimization, adapter configuration, preview before deployment, path: kit/building-your-app\n- title: Adapters, use_cases: deployment, production builds, hosting setup, choosing deployment platform, configuring adapters, path: kit/adapters\n- title: Zero-config deployments, use_cases: deployment, production builds, hosting setup, choosing deployment platform, ci/cd configuration, path: kit/adapter-auto\n- title: Node servers, use_cases: deployment, production builds, node.js hosting, custom server setup, environment configuration, reverse proxy setup, docker deployment, systemd services, path: kit/adapter-node\n- title: Static site generation, use_cases: static site generation, ssg, prerendering, deployment, github pages, spa mode, blogs, documentation sites, marketing sites, path: kit/adapter-static\n- title: Single-page apps, use_cases: spa mode, single-page apps, client-only rendering, static hosting, mobile app wrappers, no server-side logic, adapter-static setup, fallback pages, path: kit/single-page-apps\n- title: Cloudflare, use_cases: deployment, cloudflare workers, cloudflare pages, hosting setup, production builds, serverless deployment, edge computing, path: kit/adapter-cloudflare\n- title: Cloudflare Workers, use_cases: deploying to cloudflare workers, cloudflare workers sites deployment, legacy cloudflare adapter, wrangler configuration, cloudflare platform bindings, path: kit/adapter-cloudflare-workers\n- title: Netlify, use_cases: deployment, netlify hosting, production builds, serverless functions, edge functions, static site hosting, path: kit/adapter-netlify\n- title: Vercel, use_cases: deployment, vercel hosting, production builds, serverless functions, edge functions, isr, image optimization, environment variables, path: kit/adapter-vercel\n- title: Writing adapters, use_cases: custom deployment, building adapters, unsupported platforms, adapter development, custom hosting environments, path: kit/writing-adapters\n- title: Advanced routing, use_cases: advanced routing, dynamic routes, file viewers, nested paths, custom 404 pages, url validation, route parameters, multi-level navigation, path: kit/advanced-routing\n- title: Hooks, use_cases: authentication, logging, error tracking, request interception, api proxying, custom routing, internationalization, database initialization, middleware logic, session management, path: kit/hooks\n- title: Errors, use_cases: error handling, custom error pages, 404 pages, api error responses, production error logging, error tracking, type-safe errors, path: kit/errors\n- title: Link options, use_cases: routing, navigation, multi-page apps, performance optimization, link preloading, forms with get method, search functionality, focus management, scroll behavior, path: kit/link-options\n- title: Service workers, use_cases: offline support, pwa, caching strategies, performance optimization, precaching assets, network resilience, progressive web apps, path: kit/service-workers\n- title: Server-only modules, use_cases: api keys, environment variables, sensitive data protection, backend security, preventing data leaks, server-side code isolation, path: kit/server-only-modules\n- title: Snapshots, use_cases: forms, user input, preserving form data, multi-step forms, navigation state, preventing data loss, textarea content, input fields, comment systems, surveys, path: kit/snapshots\n- title: Shallow routing, use_cases: modals, dialogs, image galleries, overlays, history-driven ui, mobile-friendly navigation, photo viewers, lightboxes, drawer menus, path: kit/shallow-routing\n- title: Observability, use_cases: performance monitoring, debugging, observability, tracing requests, production diagnostics, analyzing slow requests, finding bottlenecks, monitoring server-side operations, path: kit/observability\n- title: Packaging, use_cases: building component libraries, publishing npm packages, creating reusable svelte components, library development, package distribution, path: kit/packaging\n- title: Auth, use_cases: authentication, login systems, user management, session handling, jwt tokens, protected routes, user credentials, authorization checks, path: kit/auth\n- title: Performance, use_cases: performance optimization, slow loading pages, production deployment, debugging performance issues, reducing bundle size, improving load times, path: kit/performance\n- title: Icons, use_cases: icons, ui components, styling, css frameworks, tailwind, unocss, performance optimization, dependency management, path: kit/icons\n- title: Images, use_cases: image optimization, responsive images, performance, hero images, product photos, galleries, cms integration, cdn setup, asset management, path: kit/images\n- title: Accessibility, use_cases: always, any sveltekit project, screen reader support, keyboard navigation, multi-page apps, client-side routing, internationalization, multilingual sites, path: kit/accessibility\n- title: SEO, use_cases: seo optimization, search engine ranking, content sites, blogs, marketing sites, public-facing apps, sitemaps, amp pages, meta tags, performance optimization, path: kit/seo\n- title: Frequently asked questions, use_cases: troubleshooting package imports, library compatibility issues, client-side code execution, external api integration, middleware setup, database configuration, view transitions, yarn configuration, path: kit/faq\n- title: Integrations, use_cases: project setup, css preprocessors, postcss, scss, sass, less, stylus, typescript setup, adding integrations, tailwind, testing, auth, linting, formatting, path: kit/integrations\n- title: Breakpoint Debugging, use_cases: debugging, breakpoints, development workflow, troubleshooting issues, vscode setup, ide configuration, inspecting code execution, path: kit/debugging\n- title: Migrating to SvelteKit v2, use_cases: migration, upgrading from sveltekit 1 to 2, breaking changes, version updates, path: kit/migrating-to-sveltekit-2\n- title: Migrating from Sapper, use_cases: migrating from sapper, upgrading legacy projects, sapper to sveltekit conversion, project modernization, path: kit/migrating\n- title: Additional resources, use_cases: troubleshooting, getting help, finding examples, learning sveltekit, project templates, common issues, community support, path: kit/additional-resources\n- title: Glossary, use_cases: rendering strategies, performance optimization, deployment configuration, seo requirements, static sites, spas, server-side rendering, prerendering, edge deployment, pwa development, path: kit/glossary\n- title: @sveltejs/kit, use_cases: forms, form actions, server-side validation, form submission, error handling, redirects, json responses, http errors, server utilities, path: kit/@sveltejs-kit\n- title: @sveltejs/kit/hooks, use_cases: middleware, request processing, authentication chains, logging, multiple hooks, request/response transformation, path: kit/@sveltejs-kit-hooks\n- title: @sveltejs/kit/node/polyfills, use_cases: node.js environments, custom servers, non-standard runtimes, ssr setup, web api compatibility, polyfill requirements, path: kit/@sveltejs-kit-node-polyfills\n- title: @sveltejs/kit/node, use_cases: node.js adapter, custom server setup, http integration, streaming files, node deployment, server-side rendering with node, path: kit/@sveltejs-kit-node\n- title: @sveltejs/kit/vite, use_cases: project setup, vite configuration, initial sveltekit setup, build tooling, path: kit/@sveltejs-kit-vite\n- title: $app/environment, use_cases: always, conditional logic, client-side code, server-side code, build-time logic, prerendering, development vs production, environment detection, path: kit/$app-environment\n- title: $app/forms, use_cases: forms, user input, data submission, progressive enhancement, custom form handling, form validation, path: kit/$app-forms\n- title: $app/navigation, use_cases: routing, navigation, multi-page apps, programmatic navigation, data reloading, preloading, shallow routing, navigation lifecycle, scroll handling, view transitions, path: kit/$app-navigation\n- title: $app/paths, use_cases: static assets, images, fonts, public files, base path configuration, subdirectory deployment, cdn setup, asset urls, links, navigation, path: kit/$app-paths\n- title: $app/server, use_cases: remote functions, server-side logic, data fetching, form handling, api endpoints, client-server communication, prerendering, file reading, batch queries, path: kit/$app-server\n- title: $app/state, use_cases: routing, navigation, multi-page apps, loading states, url parameters, form handling, error states, version updates, page metadata, shallow routing, path: kit/$app-state\n- title: $app/stores, use_cases: legacy projects, sveltekit pre-2.12, migration from stores to runes, maintaining older codebases, accessing page data, navigation state, app version updates, path: kit/$app-stores\n- title: $app/types, use_cases: routing, navigation, type safety, route parameters, dynamic routes, link generation, pathname validation, multi-page apps, path: kit/$app-types\n- title: $env/dynamic/private, use_cases: api keys, secrets management, server-side config, environment variables, backend logic, deployment-specific settings, private data handling, path: kit/$env-dynamic-private\n- title: $env/dynamic/public, use_cases: environment variables, client-side config, runtime configuration, public api keys, deployment-specific settings, multi-environment apps, path: kit/$env-dynamic-public\n- title: $env/static/private, use_cases: server-side api keys, backend secrets, database credentials, private configuration, build-time optimization, server endpoints, authentication tokens, path: kit/$env-static-private\n- title: $env/static/public, use_cases: environment variables, public config, client-side data, api endpoints, build-time configuration, public constants, path: kit/$env-static-public\n- title: $lib, use_cases: project setup, component organization, importing shared components, reusable ui elements, code structure, path: kit/$lib\n- title: $service-worker, use_cases: offline support, pwa, service workers, caching strategies, progressive web apps, offline-first apps, path: kit/$service-worker\n- title: Configuration, use_cases: project setup, configuration, adapters, deployment, build settings, environment variables, routing customization, prerendering, csp security, csrf protection, path configuration, typescript setup, path: kit/configuration\n- title: Command Line Interface, use_cases: project setup, typescript configuration, generated types, ./$types imports, initial project configuration, path: kit/cli\n- title: Types, use_cases: typescript, type safety, route parameters, api endpoints, load functions, form actions, generated types, jsconfig setup, path: kit/types\n- title: Overview, use_cases: use title and path to estimate use case, path: mcp/overview\n- title: Local setup, use_cases: use title and path to estimate use case, path: mcp/local-setup\n- title: Remote setup, use_cases: use title and path to estimate use case, path: mcp/remote-setup\n- title: Tools, use_cases: use title and path to estimate use case, path: mcp/tools\n- title: Resources, use_cases: use title and path to estimate use case, path: mcp/resources\n- title: Prompts, use_cases: use title and path to estimate use case, path: mcp/prompts\n- title: Overview, use_cases: always, any svelte project, getting started, learning svelte, introduction, project setup, understanding framework basics, path: svelte/overview\n- title: Getting started, use_cases: project setup, starting new svelte project, initial installation, choosing between sveltekit and vite, editor configuration, path: svelte/getting-started\n- title: .svelte files, use_cases: always, any svelte project, component creation, project setup, learning svelte basics, path: svelte/svelte-files\n- title: .svelte.js and .svelte.ts files, use_cases: shared reactive state, reusable reactive logic, state management across components, global stores, custom reactive utilities, path: svelte/svelte-js-files\n- title: What are runes?, use_cases: always, any svelte 5 project, understanding core syntax, learning svelte 5, migration from svelte 4, path: svelte/what-are-runes\n- title: $state, use_cases: always, any svelte project, core reactivity, state management, counters, forms, todo apps, interactive ui, data updates, class-based components, path: svelte/$state\n- title: $derived, use_cases: always, any svelte project, computed values, reactive calculations, derived data, transforming state, dependent values, path: svelte/$derived\n- title: $effect, use_cases: canvas drawing, third-party library integration, dom manipulation, side effects, intervals, timers, network requests, analytics tracking, path: svelte/$effect\n- title: $props, use_cases: always, any svelte project, passing data to components, component communication, reusable components, component props, path: svelte/$props\n- title: $bindable, use_cases: forms, user input, two-way data binding, custom input components, parent-child communication, reusable form fields, path: svelte/$bindable\n- title: $inspect, use_cases: debugging, development, tracking state changes, reactive state monitoring, troubleshooting reactivity issues, path: svelte/$inspect\n- title: $host, use_cases: custom elements, web components, dispatching custom events, component library, framework-agnostic components, path: svelte/$host\n- title: Basic markup, use_cases: always, any svelte project, basic markup, html templating, component structure, attributes, events, props, text rendering, path: svelte/basic-markup\n- title: {#if ...}, use_cases: always, conditional rendering, showing/hiding content, dynamic ui, user permissions, loading states, error handling, form validation, path: svelte/if\n- title: {#each ...}, use_cases: always, lists, arrays, iteration, product listings, todos, tables, grids, dynamic content, shopping carts, user lists, comments, feeds, path: svelte/each\n- title: {#key ...}, use_cases: animations, transitions, component reinitialization, forcing component remount, value-based ui updates, resetting component state, path: svelte/key\n- title: {#await ...}, use_cases: async data fetching, api calls, loading states, promises, error handling, lazy loading components, dynamic imports, path: svelte/await\n- title: {#snippet ...}, use_cases: reusable markup, component composition, passing content to components, table rows, list items, conditional rendering, reducing duplication, path: svelte/snippet\n- title: {@render ...}, use_cases: reusable ui patterns, component composition, conditional rendering, fallback content, layout components, slot alternatives, template reuse, path: svelte/@render\n- title: {@html ...}, use_cases: rendering html strings, cms content, rich text editors, markdown to html, blog posts, wysiwyg output, sanitized html injection, dynamic html content, path: svelte/@html\n- title: {@attach ...}, use_cases: tooltips, popovers, dom manipulation, third-party libraries, canvas drawing, element lifecycle, interactive ui, custom directives, wrapper components, path: svelte/@attach\n- title: {@const ...}, use_cases: computed values in loops, derived calculations in blocks, local variables in each iterations, complex list rendering, path: svelte/@const\n- title: {@debug ...}, use_cases: debugging, development, troubleshooting, tracking state changes, monitoring variables, reactive data inspection, path: svelte/@debug\n- title: bind:, use_cases: forms, user input, two-way data binding, interactive ui, media players, file uploads, checkboxes, radio buttons, select dropdowns, contenteditable, dimension tracking, path: svelte/bind\n- title: use:, use_cases: custom directives, dom manipulation, third-party library integration, tooltips, click outside, gestures, focus management, element lifecycle hooks, path: svelte/use\n- title: transition:, use_cases: animations, interactive ui, modals, dropdowns, notifications, conditional content, show/hide elements, smooth state changes, path: svelte/transition\n- title: in: and out:, use_cases: animation, transitions, interactive ui, conditional rendering, independent enter/exit effects, modals, tooltips, notifications, path: svelte/in-and-out\n- title: animate:, use_cases: sortable lists, drag and drop, reorderable items, todo lists, kanban boards, playlist editors, priority queues, animated list reordering, path: svelte/animate\n- title: style:, use_cases: dynamic styling, conditional styles, theming, dark mode, responsive design, interactive ui, component styling, path: svelte/style\n- title: class, use_cases: always, conditional styling, dynamic classes, tailwind css, component styling, reusable components, responsive design, path: svelte/class\n- title: await, use_cases: async data fetching, loading states, server-side rendering, awaiting promises in components, async validation, concurrent data loading, path: svelte/await-expressions\n- title: Scoped styles, use_cases: always, styling components, scoped css, component-specific styles, preventing style conflicts, animations, keyframes, path: svelte/scoped-styles\n- title: Global styles, use_cases: global styles, third-party libraries, css resets, animations, styling body/html, overriding component styles, shared keyframes, base styles, path: svelte/global-styles\n- title: Custom properties, use_cases: theming, custom styling, reusable components, design systems, dynamic colors, component libraries, ui customization, path: svelte/custom-properties\n- title: Nested <style> elements, use_cases: component styling, scoped styles, dynamic styles, conditional styling, nested style tags, custom styling logic, path: svelte/nested-style-elements\n- title: <svelte:boundary>, use_cases: error handling, async data loading, loading states, error recovery, flaky components, error reporting, resilient ui, path: svelte/svelte-boundary\n- title: <svelte:window>, use_cases: keyboard shortcuts, scroll tracking, window resize handling, responsive layouts, online/offline detection, viewport dimensions, global event listeners, path: svelte/svelte-window\n- title: <svelte:document>, use_cases: document events, visibility tracking, fullscreen detection, pointer lock, focus management, document-level interactions, path: svelte/svelte-document\n- title: <svelte:body>, use_cases: mouse tracking, hover effects, cursor interactions, global body events, drag and drop, custom cursors, interactive backgrounds, body-level actions, path: svelte/svelte-body\n- title: <svelte:head>, use_cases: seo optimization, page titles, meta tags, social media sharing, dynamic head content, multi-page apps, blog posts, product pages, path: svelte/svelte-head\n- title: <svelte:element>, use_cases: dynamic content, cms integration, user-generated content, configurable ui, runtime element selection, flexible components, path: svelte/svelte-element\n- title: <svelte:options>, use_cases: migration, custom elements, web components, legacy mode compatibility, runes mode setup, svg components, mathml components, css injection control, path: svelte/svelte-options\n- title: Stores, use_cases: shared state, cross-component data, reactive values, async data streams, manual control over updates, rxjs integration, extracting logic, path: svelte/stores\n- title: Context, use_cases: shared state, avoiding prop drilling, component communication, theme providers, user context, authentication state, configuration sharing, deeply nested components, path: svelte/context\n- title: Lifecycle hooks, use_cases: component initialization, cleanup tasks, timers, subscriptions, dom measurements, chat windows, autoscroll features, migration from svelte 4, path: svelte/lifecycle-hooks\n- title: Imperative component API, use_cases: project setup, client-side rendering, server-side rendering, ssr, hydration, testing, programmatic component creation, tooltips, dynamic mounting, path: svelte/imperative-component-api\n- title: Hydratable data, use_cases: use title and path to estimate use case, path: svelte/hydratable\n- title: Testing, use_cases: testing, quality assurance, unit tests, integration tests, component tests, e2e tests, vitest setup, playwright setup, test automation, path: svelte/testing\n- title: TypeScript, use_cases: typescript setup, type safety, component props typing, generic components, wrapper components, dom type augmentation, project configuration, path: svelte/typescript\n- title: Custom elements, use_cases: web components, custom elements, component library, design system, framework-agnostic components, embedding svelte in non-svelte apps, shadow dom, path: svelte/custom-elements\n- title: Svelte 4 migration guide, use_cases: upgrading svelte 3 to 4, version migration, updating dependencies, breaking changes, legacy project maintenance, path: svelte/v4-migration-guide\n- title: Svelte 5 migration guide, use_cases: migrating from svelte 4 to 5, upgrading projects, learning svelte 5 syntax changes, runes migration, event handler updates, path: svelte/v5-migration-guide\n- title: Frequently asked questions, use_cases: getting started, learning svelte, beginner setup, project initialization, vs code setup, formatting, testing, routing, mobile apps, troubleshooting, community support, path: svelte/faq\n- title: svelte, use_cases: migration from svelte 4 to 5, upgrading legacy code, component lifecycle hooks, context api, mounting components, event dispatchers, typescript component types, path: svelte/svelte\n- title: svelte/action, use_cases: typescript types, actions, use directive, dom manipulation, element lifecycle, custom behaviors, third-party library integration, path: svelte/svelte-action\n- title: svelte/animate, use_cases: animated lists, sortable items, drag and drop, reordering elements, todo lists, kanban boards, playlist management, smooth position transitions, path: svelte/svelte-animate\n- title: svelte/attachments, use_cases: library development, component libraries, programmatic element manipulation, migrating from actions to attachments, spreading props onto elements, path: svelte/svelte-attachments\n- title: svelte/compiler, use_cases: build tools, custom compilers, ast manipulation, preprocessors, code transformation, migration scripts, syntax analysis, bundler plugins, dev tools, path: svelte/svelte-compiler\n- title: svelte/easing, use_cases: animations, transitions, custom easing, smooth motion, interactive ui, modals, dropdowns, carousels, page transitions, scroll effects, path: svelte/svelte-easing\n- title: svelte/events, use_cases: window events, document events, global event listeners, event delegation, programmatic event handling, cleanup functions, media queries, path: svelte/svelte-events\n- title: svelte/legacy, use_cases: migration from svelte 4 to svelte 5, upgrading legacy code, event modifiers, class components, imperative component instantiation, path: svelte/svelte-legacy\n- title: svelte/motion, use_cases: animation, smooth transitions, interactive ui, sliders, counters, physics-based motion, drag gestures, accessibility, reduced motion, path: svelte/svelte-motion\n- title: svelte/reactivity/window, use_cases: responsive design, viewport tracking, scroll effects, window resize handling, online/offline detection, zoom level tracking, path: svelte/svelte-reactivity-window\n- title: svelte/reactivity, use_cases: reactive data structures, state management with maps/sets, game boards, selection tracking, url manipulation, query params, real-time clocks, media queries, responsive design, path: svelte/svelte-reactivity\n- title: svelte/server, use_cases: server-side rendering, ssr, static site generation, seo optimization, initial page load, pre-rendering, node.js server, custom server setup, path: svelte/svelte-server\n- title: svelte/store, use_cases: state management, shared data, reactive stores, cross-component communication, global state, computed values, data synchronization, legacy svelte projects, path: svelte/svelte-store\n- title: svelte/transition, use_cases: animations, transitions, interactive ui, modals, dropdowns, tooltips, notifications, svg animations, list animations, page transitions, path: svelte/svelte-transition\n- title: Compiler errors, use_cases: animation, transitions, keyed each blocks, list animations, path: svelte/compiler-errors\n- title: Compiler warnings, use_cases: accessibility, a11y compliance, wcag standards, screen readers, keyboard navigation, aria attributes, semantic html, interactive elements, path: svelte/compiler-warnings\n- title: Runtime errors, use_cases: debugging errors, error handling, troubleshooting runtime issues, migration to svelte 5, component binding, effects and reactivity, path: svelte/runtime-errors\n- title: Runtime warnings, use_cases: debugging state proxies, console logging reactive values, inspecting state changes, development troubleshooting, path: svelte/runtime-warnings\n- title: Overview, use_cases: migrating from svelte 3/4 to svelte 5, maintaining legacy components, understanding deprecated features, gradual upgrade process, path: svelte/legacy-overview\n- title: Reactive let/var declarations, use_cases: migration, legacy svelte projects, upgrading from svelte 4, understanding old reactivity, maintaining existing code, learning runes differences, path: svelte/legacy-let\n- title: Reactive $: statements, use_cases: legacy mode, migration from svelte 4, reactive statements, computed values, derived state, side effects, path: svelte/legacy-reactive-assignments\n- title: export let, use_cases: legacy mode, migration from svelte 4, maintaining older projects, component props without runes, exporting component methods, renaming reserved word props, path: svelte/legacy-export-let\n- title: $$props and $$restProps, use_cases: legacy mode migration, component wrappers, prop forwarding, button components, reusable ui components, spreading props to child elements, path: svelte/legacy-$$props-and-$$restProps\n- title: on:, use_cases: legacy mode, event handling, button clicks, forms, user interactions, component communication, event forwarding, event modifiers, path: svelte/legacy-on\n- title: <slot>, use_cases: legacy mode, migrating from svelte 4, component composition, reusable components, passing content to components, modals, layouts, wrappers, path: svelte/legacy-slots\n- title: $$slots, use_cases: legacy mode, conditional slot rendering, optional content sections, checking if slots provided, migrating from legacy to runes, path: svelte/legacy-$$slots\n- title: <svelte:fragment>, use_cases: named slots, component composition, layout systems, avoiding wrapper divs, legacy svelte projects, slot content organization, path: svelte/legacy-svelte-fragment\n- title: <svelte:component>, use_cases: dynamic components, component switching, conditional rendering, legacy mode migration, tabbed interfaces, multi-step forms, path: svelte/legacy-svelte-component\n- title: <svelte:self>, use_cases: recursive components, tree structures, nested menus, file explorers, comment threads, hierarchical data, path: svelte/legacy-svelte-self\n- title: Imperative component API, use_cases: migration from svelte 3/4 to 5, legacy component api, maintaining old projects, understanding deprecated patterns, path: svelte/legacy-component-api\n\nCarefully analyze the use_cases field for each section to identify which documentation is relevant for the user's specific query. The use_cases contain keywords for project types, features, components, and development stages. After identifying relevant sections, use the get-documentation tool with ALL relevant section titles or paths at once (can pass multiple sections as an array)."
}
],
"isError": false
}
{
"section": "[\"svelte/$inspect\"]"
}
{
"content": [
{
"type": "text",
"text": "## $inspect\n\n> [!NOTE] `$inspect` only works during development. In a production build it becomes a noop.\n\nThe `$inspect` rune is roughly equivalent to `console.log`, with the exception that it will re-run whenever its argument changes. `$inspect` tracks reactive state deeply, meaning that updating something inside an object or array using fine-grained reactivity will cause it to re-fire ([demo](/playground/untitled#H4sIAAAAAAAACkWQ0YqDQAxFfyUMhSotdZ-tCvu431AXtGOqQ2NmmMm0LOK_r7Utfby5JzeXTOpiCIPKT5PidkSVq2_n1F7Jn3uIcEMSXHSw0evHpAjaGydVzbUQCmgbWaCETZBWMPlKj29nxBDaHj_edkAiu12JhdkYDg61JGvE_s2nR8gyuBuiJZuDJTyQ7eE-IEOzog1YD80Lb0APLfdYc5F9qnFxjiKWwbImo6_llKRQVs-2u91c_bD2OCJLkT3JZasw7KLA2XCX31qKWE6vIzNk1fKE0XbmYrBTufiI8-_8D2cUWBA_AQAA)):\n\n```svelte\n<script>\n\tlet count = $state(0);\n\tlet message = $state('hello');\n\n\t$inspect(count, message); // will console.log when `count` or `message` change\n</script>\n\n<button onclick={() => count++}>Increment</button>\n<input bind:value={message} />\n```\n\nOn updates, a stack trace will be printed, making it easy to find the origin of a state change (unless you're in the playground, due to technical limitations).\n\n## $inspect(...).with\n\n`$inspect` returns a property `with`, which you can invoke with a callback, which will then be invoked instead of `console.log`. The first argument to the callback is either `\"init\"` or `\"update\"`; subsequent arguments are the values passed to `$inspect` ([demo](/playground/untitled#H4sIAAAAAAAACkVQ24qDMBD9lSEUqlTqPlsj7ON-w7pQG8c2VCchmVSK-O-bKMs-DefKYRYx6BG9qL4XQd2EohKf1opC8Nsm4F84MkbsTXAqMbVXTltuWmp5RAZlAjFIOHjuGLOP_BKVqB00eYuKs82Qn2fNjyxLtcWeyUE2sCRry3qATQIpJRyD7WPVMf9TW-7xFu53dBcoSzAOrsqQNyOe2XUKr0Xi5kcMvdDB2wSYO-I9vKazplV1-T-d6ltgNgSG1KjVUy7ZtmdbdjqtzRcphxMS1-XubOITJtPrQWMvKnYB15_1F7KKadA_AQAA)):\n\n```svelte\n<script>\n\tlet count = $state(0);\n\n\t$inspect(count).with((type, count) => {\n\t\tif (type === 'update') {\n\t\t\tdebugger; // or `console.trace`, or whatever you want\n\t\t}\n\t});\n</script>\n\n<button onclick={() => count++}>Increment</button>\n```\n\n## $inspect.trace(...)\n\nThis rune, added in 5.14, causes the surrounding function to be _traced_ in development. Any time the function re-runs as part of an [effect]($effect) or a [derived]($derived), information will be printed to the console about which pieces of reactive state caused the effect to fire.\n\n```svelte\n<script>\n\timport { doSomeWork } from './elsewhere';\n\n\t$effect(() => {\n\t\t+++// $inspect.trace must be the first statement of a function body+++\n\t\t+++$inspect.trace();+++\n\t\tdoSomeWork();\n\t});\n</script>\n```\n\n`$inspect.trace` takes an optional first argument which will be used as the label."
}
],
"isError": false
}
{
"content": "<script>\n\tlet text = $state(\"Hello world\");\n\n\t// Basic $inspect to log the value on changes\n\t$inspect(text);\n\n\t// $inspect(...).with for custom callback tracking updates\n\t$inspect(text).with((type, value) => {\n\t\tif (type === 'init') {\n\t\t\tconsole.log('Text initialized:', value);\n\t\t} else if (type === 'update') {\n\t\t\tconsole.log('Text updated:', value);\n\t\t}\n\t});\n\n\t// $inspect.trace() inside an effect\n\t$effect(() => {\n\t\t$inspect.trace('Text effect trace');\n\t\t// Effect body - the trace will show which reactive state caused this effect to run\n\t});\n\n\t// Character count derived from text\n\tlet charCount = $derived(text.length);\n</script>\n\n<input \n\tbind:value={text} \n\tdata-testid=\"text-input\"\n/>\n\n<p data-testid=\"text-value\">Current text: \"{text}\"</p>\n<p data-testid=\"char-count\">Character count: {charCount}</p>\n"
}
{
"success": true
}
<script>
let text = $state("Hello world");
// Basic $inspect to log the value on changes
$inspect(text);Create a Svelte 5 component that uses the `$props` rune to accept component properties.
The component should accept props for `name` (default "World"), `count` (default 0), and `showDetails` (default false). Display the name in a heading, show the count with an increment button, and conditionally display details when `showDetails` is true.
## Test Suite
Your component must pass the following tests:
```ts
import { render, screen } from "@testing-library/svelte";
import { expect, test, describe } from "vitest";
import userEvent from "@testing-library/user-event";
import PropsDemo from "./Component.svelte"; // Path to the generated component
describe("PropsDemo component", () => {
test("renders with default props", () => {
render(PropsDemo);
// Check default values
const nameDisplay = screen.getByTestId("name-display");
const countDisplay = screen.getByTestId("count-display");
expect(nameDisplay).toHaveTextContent("World");
// Just check for the number 0 without requiring "Count: " prefix
expect(countDisplay.textContent).toMatch(/0/);
// Details should not be visible by default
expect(screen.queryByTestId("details")).not.toBeInTheDocument();
});
test("renders with custom props", () => {
render(PropsDemo, {
props: { name: "Svelte", count: 5, showDetails: true },
});
// Check custom values
const nameDisplay = screen.getByTestId("name-display");
const countDisplay = screen.getByTestId("count-display");
const details = screen.getByTestId("details");
expect(nameDisplay).toHaveTextContent("Svelte");
// Just check for the number 5 without requiring specific text before it
expect(countDisplay.textContent).toMatch(/5/);
expect(details).toBeInTheDocument();
// Check for values without requiring specific text format
expect(details.textContent).toMatch(/Svelte/);
expect(details.textContent).toMatch(/5/);
expect(details.textContent).toMatch(/true/i); // case insensitive match for "true"
});
test("increment button increases count", async () => {
const user = userEvent.setup();
render(PropsDemo, { props: { count: 10 } });
const incrementButton = screen.getByTestId("increment-button");
const countDisplay = screen.getByTestId("count-display");
// Initial count should be 10, without requiring "Count: " prefix
expect(countDisplay.textContent).toMatch(/10/);
// Click the increment button
await user.click(incrementButton);
// Count should now be 11, without requiring "Count: " prefix
expect(countDisplay.textContent).toMatch(/11/);
});
test("conditional rendering works correctly", () => {
// First render without details
const { unmount } = render(PropsDemo, { props: { showDetails: false } });
expect(screen.queryByTestId("details")).not.toBeInTheDocument();
// Unmount and render again with details
unmount();
render(PropsDemo, { props: { showDetails: true } });
expect(screen.getByTestId("details")).toBeInTheDocument();
});
});
```
IMPORTANT: When you have finished implementing the component, use the ResultWrite tool to output your final Svelte component code. Only output the component code itself, no explanations or markdown formatting.
{
"content": "<script>\n\tlet { name = \"World\", count = 0, showDetails = false } = $props();\n\t\n\tlet currentCount = $state(count);\n\t\n\tfunction increment() {\n\t\tcurrentCount += 1;\n\t}\n</script>\n\n<h1 data-testid=\"name-display\">{name}</h1>\n\n<div>\n\t<span data-testid=\"count-display\">{currentCount}</span>\n\t<button data-testid=\"increment-button\" onclick={increment}>Increment</button>\n</div>\n\n{#if showDetails}\n\t<div data-testid=\"details\">\n\t\t<p>Name: {name}</p>\n\t\t<p>Count: {currentCount}</p>\n\t\t<p>Show Details: {showDetails}</p>\n\t</div>\n{/if}"
}
{
"success": true
}
<script>
let { name = "World", count = 0, showDetails = false } = $props();
let currentCount = $state(count);
Create a Svelte 5 book list component that uses snippets to render each title.
The component should display a list of book titles using a snippet to render each title. Use a hardcoded array of 3 books with appropriate syntax for Svelte 5 Snippets.
## Test Suite
Your component must pass the following tests:
```ts
import { render, screen } from "@testing-library/svelte";
import { expect, test, describe } from "vitest";
import BookList from "./Component.svelte";
describe("Simple Snippet component", () => {
test("renders the correct number of book titles", () => {
render(BookList);
const bookItems = screen.getAllByTestId("book-item");
expect(bookItems.length).toBe(3);
const bookTitles = screen.getAllByTestId("book-title");
expect(bookTitles.length).toBe(3);
});
test("displays correct book titles", () => {
render(BookList);
const bookTitles = screen.getAllByTestId("book-title");
expect(bookTitles[0]).toHaveTextContent("The Lord of the Rings");
expect(bookTitles[1]).toHaveTextContent("To Kill a Mockingbird");
expect(bookTitles[2]).toHaveTextContent("1984");
});
test("has the correct structure for each book item", () => {
render(BookList);
const bookItems = screen.getAllByTestId("book-item");
bookItems.forEach((item) => {
expect(item.tagName).toBe("LI");
const title = item.querySelector('[data-testid="book-title"]');
expect(title).toBeInTheDocument();
expect(title?.tagName).toBe("SPAN");
});
});
});
```
IMPORTANT: When you have finished implementing the component, use the ResultWrite tool to output your final Svelte component code. Only output the component code itself, no explanations or markdown formatting.
{
"content": "<script>\n\tlet books = [\n\t\t\"The Lord of the Rings\",\n\t\t\"To Kill a Mockingbird\",\n\t\t\"1984\"\n\t];\n\n\t{#snippet bookItem(title)}\n\t\t<li data-testid=\"book-item\">\n\t\t\t<span data-testid=\"book-title\">{title}</span>\n\t\t</li>\n\t{/snippet}\n</script>\n\n<ul>\n\t{#each books as book}\n\t\t{@render bookItem(book)}\n\t{/each}\n</ul>"
}
{
"success": true
}
<script>
let books = [
"The Lord of the Rings",
"To Kill a Mockingbird",
"1984"