diff --git a/.changeset/README.md b/.changeset/README.md new file mode 100644 index 000000000000..e5b6d8d6a67a --- /dev/null +++ b/.changeset/README.md @@ -0,0 +1,8 @@ +# Changesets + +Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works +with multi-package repos, or single-package repos to help you version and publish your code. You can +find the full documentation for it [in our repository](https://github.com/changesets/changesets) + +We have a quick list of common questions to get you started engaging with this project in +[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) diff --git a/.changeset/chatty-apples-flash.md b/.changeset/chatty-apples-flash.md new file mode 100644 index 000000000000..fc689a003c17 --- /dev/null +++ b/.changeset/chatty-apples-flash.md @@ -0,0 +1,5 @@ +--- +'svelte': patch +--- + +chore: default params for html blocks diff --git a/.changeset/config.json b/.changeset/config.json new file mode 100644 index 000000000000..b56077a9220c --- /dev/null +++ b/.changeset/config.json @@ -0,0 +1,11 @@ +{ + "$schema": "https://unpkg.com/@changesets/config@2.3.0/schema.json", + "changelog": ["@svitejs/changesets-changelog-github-compact", { "repo": "sveltejs/svelte" }], + "commit": false, + "fixed": [], + "linked": [], + "access": "public", + "baseBranch": "main", + "bumpVersionsWithWorkspaceProtocolOnly": true, + "ignore": ["!(@sveltejs/*|svelte)"] +} diff --git a/.changeset/strong-pianos-promise.md b/.changeset/strong-pianos-promise.md new file mode 100644 index 000000000000..f5214c7dcb9d --- /dev/null +++ b/.changeset/strong-pianos-promise.md @@ -0,0 +1,5 @@ +--- +'svelte': patch +--- + +fix: Throw on unrendered snippets in `dev` diff --git a/.changeset/sweet-adults-complain.md b/.changeset/sweet-adults-complain.md new file mode 100644 index 000000000000..429b034b3d6f --- /dev/null +++ b/.changeset/sweet-adults-complain.md @@ -0,0 +1,5 @@ +--- +'svelte': patch +--- + +fix: avoid unnecessary read version increments diff --git a/.editorconfig b/.editorconfig index ed2a319d5843..2f52d9993f71 100644 --- a/.editorconfig +++ b/.editorconfig @@ -11,6 +11,5 @@ trim_trailing_whitespace = true [test/**/expected.css] insert_final_newline = false -[{package.json,.travis.yml,.eslintrc.json}] +[package.json] indent_style = space -indent_size = 2 diff --git a/.eslintignore b/.eslintignore deleted file mode 100644 index 4a113378ce2c..000000000000 --- a/.eslintignore +++ /dev/null @@ -1,7 +0,0 @@ -src/shared -shared.js -store.js -test/test.js -test/setup.js -**/_actual.js -**/expected.js \ No newline at end of file diff --git a/.eslintrc.json b/.eslintrc.json deleted file mode 100644 index 340b9a0e1216..000000000000 --- a/.eslintrc.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "root": true, - "rules": { - "indent": [ 2, "tab", { "SwitchCase": 1 } ], - "semi": [ 2, "always" ], - "keyword-spacing": [ 2, { "before": true, "after": true } ], - "space-before-blocks": [ 2, "always" ], - "no-mixed-spaces-and-tabs": [ 2, "smart-tabs" ], - "no-cond-assign": 0, - "no-unused-vars": 2, - "object-shorthand": [ 2, "always" ], - "no-const-assign": 2, - "no-class-assign": 2, - "no-this-before-super": 2, - "no-var": 2, - "no-unreachable": 2, - "valid-typeof": 2, - "quote-props": [ 2, "as-needed" ], - "one-var": [ 2, "never" ], - "prefer-arrow-callback": 2, - "prefer-const": [ 2, { "destructuring": "all" } ], - "arrow-spacing": 2, - "no-inner-declarations": 0 - }, - "env": { - "es6": true, - "browser": true, - "node": true, - "mocha": true - }, - "extends": [ - "eslint:recommended", - "plugin:import/errors", - "plugin:import/warnings" - ], - "plugins": [ - "html" - ], - "parserOptions": { - "ecmaVersion": 6, - "sourceType": "module" - }, - "settings": { - "import/core-modules": [ "svelte" ] - } -} diff --git a/.flowconfig b/.flowconfig deleted file mode 100644 index 2ed2b0c713bf..000000000000 --- a/.flowconfig +++ /dev/null @@ -1,9 +0,0 @@ -[ignore] -/dist/.* - -[include] - -[libs] - -[options] -strip_root=true diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000000..a299a4435ae8 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +/site/** -linguist-detectable +/test/**/samples/** -linguist-detectable +/**/*.svelte linguist-detectable diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 000000000000..d632634540e5 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +open_collective: svelte diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 5e43e5ca1dbe..220af118345e 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,21 +1,28 @@ - +- _Repeatable steps to reproduce the issue_ + +## Thanks for being part of Svelte! diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 000000000000..2e484e5ca26d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,50 @@ +name: "\U0001F41E Bug report" +description: Report an issue with Svelte +labels: ['triage: bug'] +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to fill out this bug report! + - type: textarea + id: bug-description + attributes: + label: Describe the bug + description: A clear and concise description of what the bug is. If you intend to submit a PR for this issue, tell us in the description. Thanks! + placeholder: Bug description + validations: + required: true + - type: textarea + id: reproduction + attributes: + label: Reproduction + description: Please provide a link to a repo or REPL that can reproduce the problem you ran into. If a report is vague (e.g. just a generic error message) and has no reproduction, it will receive a "need reproduction" label. If no reproduction is provided within a reasonable time-frame, the issue will be closed. + placeholder: Reproduction + validations: + required: true + - type: textarea + id: logs + attributes: + label: Logs + description: 'Please include browser console and server logs around the time this bug occurred. Optional if provided reproduction. Please try not to insert an image but copy paste the log text.' + render: shell + - type: textarea + id: system-info + attributes: + label: System Info + description: Output of `npx envinfo --system --npmPackages svelte,rollup,webpack --binaries --browsers` + render: shell + placeholder: System, Binaries, Browsers + validations: + required: true + - type: dropdown + id: severity + attributes: + label: Severity + description: Select the severity of this issue + options: + - annoyance + - blocking an upgrade + - blocking all usage of svelte + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 000000000000..ee3e5a41b982 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Discord Chat + url: https://svelte.dev/chat + about: Ask questions and discuss with other Svelte users in real time. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 000000000000..d79e8b2e21f3 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,35 @@ +name: 'Feature Request' +description: Request a new Svelte feature +labels: [enhancement] +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to request this feature! If your feature request is complex or substantial enough to warrant in-depth discussion, maintainers may close the issue and ask you to open an [RFC](https://github.com/sveltejs/rfcs). + - type: textarea + id: problem + attributes: + label: Describe the problem + description: Please provide a clear and concise description the problem this feature would solve. The more information you can provide here, the better. + placeholder: I'm always frustrated when... + validations: + required: true + - type: textarea + id: solution + attributes: + label: Describe the proposed solution + description: Please provide a clear and concise description of what you would like to happen. + placeholder: I would like to see... + validations: + required: true + - type: dropdown + id: importance + attributes: + label: Importance + description: How important is this feature to you? + options: + - nice to have + - would make my life easier + - i cannot use svelte without it + validations: + required: true diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index d2882acf4ac2..aa5f9732b6d3 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,7 +1,11 @@ - +- [ ] It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs +- [ ] Prefix your PR title with `feat:`, `fix:`, `chore:`, or `docs:`. +- [ ] This message body should clearly illustrate what problems it solves. +- [ ] Ideally, include a test that fails without this PR but passes with it. +- [ ] If this PR changes code within `packages/svelte/src`, add a changeset (`npx changeset`). + +### Tests and linting + +- [ ] Run the tests with `pnpm test` and lint the project with `pnpm lint` diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000000..cf73a1f6cb02 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,79 @@ +name: CI +on: + push: + branches: [main] + pull_request: +permissions: + contents: read # to fetch code (actions/checkout) + +env: + # We only install Chromium manually + PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: '1' + +jobs: + Tests: + permissions: {} + runs-on: ${{ matrix.os }} + timeout-minutes: 15 + strategy: + matrix: + include: + - node-version: 18 + os: windows-latest + - node-version: 18 + os: macOS-latest + - node-version: 18 + os: ubuntu-latest + - node-version: 20 + os: ubuntu-latest + - node-version: 22 + os: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + cache: pnpm + - run: pnpm install --frozen-lockfile + - run: pnpm playwright install chromium + - run: pnpm test + env: + CI: true + Lint: + permissions: {} + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: 18 + cache: pnpm + - name: install + run: pnpm install --frozen-lockfile + - name: type check + run: pnpm check + - name: lint + if: (${{ success() }} || ${{ failure() }}) # ensures this step runs even if previous steps fail (avoids multiple runs uncovering different issues at different steps) + run: pnpm lint + - name: build and check generated types + if: (${{ success() }} || ${{ failure() }}) # ensures this step runs even if previous steps fail + run: pnpm build && { [ "`git status --porcelain=v1`" == "" ] || (echo "Generated types have changed — please regenerate types locally with `cd packages/svelte && pnpm generate:types` and commit the changes after you have reviewed them"; git diff; exit 1); } + Benchmarks: + permissions: {} + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: 18 + cache: pnpm + - run: pnpm install --frozen-lockfile + - run: pnpm bench + env: + CI: true diff --git a/.github/workflows/ecosystem-ci-trigger.yml b/.github/workflows/ecosystem-ci-trigger.yml new file mode 100644 index 000000000000..71df3242e8f1 --- /dev/null +++ b/.github/workflows/ecosystem-ci-trigger.yml @@ -0,0 +1,94 @@ +name: ecosystem-ci trigger + +on: + issue_comment: + types: [created] + +jobs: + trigger: + runs-on: ubuntu-latest + if: github.repository == 'sveltejs/svelte' && github.event.issue.pull_request && startsWith(github.event.comment.body, '/ecosystem-ci run') + steps: + - uses: GitHubSecurityLab/actions-permissions/monitor@v1 + - uses: actions/github-script@v6 + with: + script: | + const user = context.payload.sender.login + console.log(`Validate user: ${user}`) + + let hasTriagePermission = false + try { + const { data } = await github.rest.repos.getCollaboratorPermissionLevel({ + owner: context.repo.owner, + repo: context.repo.repo, + username: user, + }); + hasTriagePermission = data.user.permissions.triage + } catch (e) { + console.warn(e) + } + + if (hasTriagePermission) { + console.log('Allowed') + await github.rest.reactions.createForIssueComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: context.payload.comment.id, + content: '+1', + }) + } else { + console.log('Not allowed') + await github.rest.reactions.createForIssueComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: context.payload.comment.id, + content: '-1', + }) + throw new Error('not allowed') + } + - uses: actions/github-script@v6 + id: get-pr-data + with: + script: | + console.log(`Get PR info: ${context.repo.owner}/${context.repo.repo}#${context.issue.number}`) + const { data: pr } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.issue.number + }) + return { + num: context.issue.number, + branchName: pr.head.ref, + repo: pr.head.repo.full_name + } + - id: generate-token + uses: tibdex/github-app-token@b62528385c34dbc9f38e5f4225ac829252d1ea92 #keep pinned for security reasons, currently 1.8.0 + with: + app_id: ${{ secrets.ECOSYSTEM_CI_GITHUB_APP_ID }} + private_key: ${{ secrets.ECOSYSTEM_CI_GITHUB_APP_PRIVATE_KEY }} + repository: '${{ github.repository_owner }}/svelte-ecosystem-ci' + - uses: actions/github-script@v6 + id: trigger + env: + COMMENT: ${{ github.event.comment.body }} + with: + github-token: ${{ steps.generate-token.outputs.token }} + result-encoding: string + script: | + const comment = process.env.COMMENT.trim() + const prData = ${{ steps.get-pr-data.outputs.result }} + + const suite = comment.split('\n')[0].replace(/^\/ecosystem-ci run/, '').trim() + + await github.rest.actions.createWorkflowDispatch({ + owner: context.repo.owner, + repo: 'svelte-ecosystem-ci', + workflow_id: 'ecosystem-ci-from-pr.yml', + ref: 'main', + inputs: { + prNumber: '' + prData.num, + branchName: prData.branchName, + repo: prData.repo, + suite: suite === '' ? '-' : suite + } + }) diff --git a/.github/workflows/pkg.pr.new-comment.yml b/.github/workflows/pkg.pr.new-comment.yml new file mode 100644 index 000000000000..3f1fca5a0bea --- /dev/null +++ b/.github/workflows/pkg.pr.new-comment.yml @@ -0,0 +1,116 @@ +name: Update pkg.pr.new comment + +on: + workflow_run: + workflows: ['Publish Any Commit'] + types: + - completed + +permissions: + pull-requests: write + +jobs: + build: + name: 'Update comment' + runs-on: ubuntu-latest + steps: + - uses: GitHubSecurityLab/actions-permissions/monitor@v1 + - name: Download artifact + uses: actions/download-artifact@v4 + with: + name: output + github-token: ${{ secrets.GITHUB_TOKEN }} + run-id: ${{ github.event.workflow_run.id }} + + - run: ls -R . + - name: 'Post or update comment' + uses: actions/github-script@v6 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const fs = require('fs'); + const output = JSON.parse(fs.readFileSync('output.json', 'utf8')); + + const bot_comment_identifier = ``; + + const body = (number) => `${bot_comment_identifier} + + [Playground](https://svelte.dev/playground?version=pr-${number}) + + \`\`\` + ${output.packages.map((p) => `pnpm add https://pkg.pr.new/${p.name}@${number}`).join('\n')} + \`\`\` + `; + + async function find_bot_comment(issue_number) { + if (!issue_number) return null; + const comments = await github.rest.issues.listComments({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issue_number, + }); + return comments.data.find((comment) => + comment.body.includes(bot_comment_identifier) + ); + } + + async function create_or_update_comment(issue_number) { + if (!issue_number) { + console.log('No issue number provided. Cannot post or update comment.'); + return; + } + + const existing_comment = await find_bot_comment(issue_number); + if (existing_comment) { + await github.rest.issues.updateComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: existing_comment.id, + body: body(issue_number), + }); + } else { + await github.rest.issues.createComment({ + issue_number: issue_number, + owner: context.repo.owner, + repo: context.repo.repo, + body: body(issue_number), + }); + } + } + + async function log_publish_info() { + const svelte_package = output.packages.find(p => p.name === 'svelte'); + const svelte_sha = svelte_package.url.replace(/^.+@([^@]+)$/, '$1'); + console.log('\n' + '='.repeat(50)); + console.log('Publish Information'); + console.log('='.repeat(50)); + console.log('\nPublished Packages:'); + console.log(output.packages.map((p) => `${p.name} - pnpm add https://pkg.pr.new/${p.name}@${p.url.replace(/^.+@([^@]+)$/, '$1')}`).join('\n')); + if(svelte_sha){ + console.log('\nPlayground URL:'); + console.log(`\nhttps://svelte.dev/playground?version=commit-${svelte_sha}`) + } + console.log('\n' + '='.repeat(50)); + } + + if (output.event_name === 'pull_request') { + if (output.number) { + await create_or_update_comment(output.number); + } + } else if (output.event_name === 'push') { + const pull_requests = await github.rest.pulls.list({ + owner: context.repo.owner, + repo: context.repo.repo, + state: 'open', + head: `${context.repo.owner}:${output.ref.replace('refs/heads/', '')}`, + }); + + if (pull_requests.data.length > 0) { + await create_or_update_comment(pull_requests.data[0].number); + } else { + console.log( + 'No open pull request found for this push. Logging publish information to console:' + ); + await log_publish_info(); + } + } diff --git a/.github/workflows/pkg.pr.new.yml b/.github/workflows/pkg.pr.new.yml new file mode 100644 index 000000000000..b1ba217e5a0f --- /dev/null +++ b/.github/workflows/pkg.pr.new.yml @@ -0,0 +1,42 @@ +name: Publish Any Commit +on: [push, pull_request] + +jobs: + build: + permissions: {} + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22.x + cache: pnpm + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Build + run: pnpm build + + - run: pnpx pkg-pr-new publish --comment=off --json output.json --compact --no-template './packages/svelte' + - name: Add metadata to output + uses: actions/github-script@v6 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const fs = require('fs'); + const output = JSON.parse(fs.readFileSync('output.json', 'utf8')); + output.number = context.issue.number; + output.event_name = context.eventName; + output.ref = context.ref; + fs.writeFileSync('output.json', JSON.stringify(output), 'utf8'); + - name: Upload output + uses: actions/upload-artifact@v4 + with: + name: output + path: ./output.json + + - run: ls -R . diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 000000000000..6debe5662a88 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,48 @@ +name: Release + +on: + push: + branches: + - main + +permissions: {} +jobs: + release: + # prevents this action from running on forks + if: github.repository == 'sveltejs/svelte' + permissions: + contents: write # to create release (changesets/action) + id-token: write # OpenID Connect token needed for provenance + pull-requests: write # to create pull request (changesets/action) + name: Release + runs-on: ubuntu-latest + steps: + - uses: GitHubSecurityLab/actions-permissions/monitor@v1 + - name: Checkout Repo + uses: actions/checkout@v4 + with: + # This makes Actions fetch all Git history so that Changesets can generate changelogs with the correct commits + fetch-depth: 0 + - uses: pnpm/action-setup@v4 + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 18.x + cache: pnpm + + - name: Install + run: pnpm install --frozen-lockfile + + - name: Build + run: pnpm build && { [ "`git status --porcelain=v1`" == "" ] || (echo "Generated types have changed — please regenerate types locally with `cd packages/svelte && pnpm generate:types` and commit the changes after you have reviewed them"; git diff; exit 1); } + + - name: Create Release Pull Request or Publish to npm + id: changesets + uses: changesets/action@v1 + with: + version: pnpm changeset:version + publish: pnpm changeset:publish + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + NPM_CONFIG_PROVENANCE: true + NPM_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/.gitignore b/.gitignore index 472328464c87..d50343766485 100644 --- a/.gitignore +++ b/.gitignore @@ -1,19 +1,26 @@ +# Dependency directories +node_modules/ + +# IDE related +.idea + +# Test coverage +coverage +*.lcov + +# Optional eslint cache +.eslintcache + +# dotenv environment variables file +.env +.env.test + +# build output +.vercel + +# OS-specific .DS_Store -.nyc_output -node_modules -/cli/ -/compiler/ -/ssr/ -/shared.js -/scratch/ -/coverage/ -/coverage.lcov/ -/test/cli/samples/*/actual -/test/sourcemaps/samples/*/output.js -/test/sourcemaps/samples/*/output.js.map -/test/sourcemaps/samples/*/output.css -/test/sourcemaps/samples/*/output.css.map -/src/compile/shared.ts -/store.umd.js -/yarn-error.log -_actual*.* \ No newline at end of file + +tmp + +benchmarking/compare/.results diff --git a/.npmrc b/.npmrc new file mode 100644 index 000000000000..33484750d05a --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +playwright_skip_browser_download=1 \ No newline at end of file diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 000000000000..d5c124353c37 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,47 @@ +documentation/docs/ + +packages/**/dist/*.js +packages/**/build/*.js +packages/**/npm/**/* +packages/**/config/*.js + +# packages/svelte +packages/svelte/messages/**/*.md +packages/svelte/src/compiler/errors.js +packages/svelte/src/compiler/warnings.js +packages/svelte/src/internal/client/errors.js +packages/svelte/src/internal/client/warnings.js +packages/svelte/src/internal/shared/errors.js +packages/svelte/src/internal/shared/warnings.js +packages/svelte/src/internal/server/errors.js +packages/svelte/tests/migrate/samples/*/output.svelte +packages/svelte/tests/**/*.svelte +packages/svelte/tests/**/_expected* +packages/svelte/tests/**/_actual* +packages/svelte/tests/**/expected* +packages/svelte/tests/**/_output +packages/svelte/tests/**/shards/*.test.js +packages/svelte/tests/hydration/samples/*/_expected.html +packages/svelte/tests/hydration/samples/*/_override.html +packages/svelte/types +packages/svelte/compiler/index.js +playgrounds/sandbox/input/**.svelte +playgrounds/sandbox/output + +# sites/svelte.dev +sites/svelte.dev/static/svelte-app.json +sites/svelte.dev/scripts/svelte-app/ +sites/svelte.dev/src/routes/_components/Supporters/contributors.jpg +sites/svelte.dev/src/routes/_components/Supporters/contributors.js +sites/svelte.dev/src/routes/_components/Supporters/donors.jpg +sites/svelte.dev/src/routes/_components/Supporters/donors.js +sites/svelte.dev/src/lib/generated + +**/node_modules +**/.svelte-kit +**/.vercel +.github/CODEOWNERS +.prettierignore +.changeset +pnpm-lock.yaml +pnpm-workspace.yaml diff --git a/.prettierrc b/.prettierrc index 81451039faf5..c4fd5d9f2f73 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,3 +1,28 @@ -useTabs: true -singleQuote: true -trailingComma: es5 +{ + "useTabs": true, + "singleQuote": true, + "trailingComma": "none", + "printWidth": 100, + "plugins": ["prettier-plugin-svelte"], + "overrides": [ + { + "files": ["*.svelte"], + "options": { + "bracketSameLine": false + } + }, + { + "files": ["README.md", "packages/*/README.md", "**/package.json"], + "options": { + "useTabs": false, + "tabWidth": 2 + } + }, + { + "files": ["sites/svelte-5-preview/src/routes/docs/content/**/*.md"], + "options": { + "printWidth": 60 + } + } + ] +} diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index de91162ece95..000000000000 --- a/.travis.yml +++ /dev/null @@ -1,20 +0,0 @@ -language: node_js -node_js: - - "6" - - "node" - -env: - global: - - BUILD_TIMEOUT=20000 - -addons: - apt: - packages: - - xvfb - -install: - - export DISPLAY=':99.0' - - Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & - - npm ci || npm install - -after_success: npm run codecov diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 000000000000..142965ada292 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,14 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "type": "node", + "request": "launch", + "name": "Run sandbox", + "program": "${workspaceFolder}/playgrounds/sandbox/run.js", + "env": { + "NODE_OPTIONS": "--stack-trace-limit=10000" + } + } + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000000..21a2a11c84e3 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,6 @@ +{ + "search.exclude": { + "sites/svelte-5-preview/static/*": true + }, + "typescript.tsdk": "node_modules/typescript/lib" +} diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index 811d9f42742c..000000000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,1391 +0,0 @@ -# Svelte changelog - -## 2.15.3 - -* Don't mutate AST - -## 2.15.2 - -* Expose `stats.props` ([#1837](https://github.com/sveltejs/svelte/issues/1837)) - -## 2.15.1 - -* Don't throw missing store error when store is declared in component ([#1828](https://github.com/sveltejs/svelte/issues/1828)) - -## 2.15.0 - -* Event modifiers ([#1088](https://github.com/sveltejs/svelte/issues/1088)) -* Wheel and touch events are passive by default ([#1088](https://github.com/sveltejs/svelte/issues/1088)) -* Add `` tag ([#1484](https://github.com/sveltejs/svelte/issues/1484)) -* Include binding values in server-rendered HTML ([#1205](https://github.com/sveltejs/svelte/issues/1205)) -* Remove attributes when value is undefined/null ([#1434](https://github.com/sveltejs/svelte/issues/1434)) -* Initialise window scroll from component data ([#938](https://github.com/sveltejs/svelte/issues/938)) -* Remove references to unused properties in generated code ([#1187](https://github.com/sveltejs/svelte/issues/1187)) -* Add TypeScript definitions for store ([#1207](https://github.com/sveltejs/svelte/issues/1207)) -* Better error for missing store ([#1807](https://github.com/sveltejs/svelte/issues/1807)) - -## 2.14.3 - -* Account for directive dependencies ([#1793](https://github.com/sveltejs/svelte/issues/1793)) -* Detach each block iterations in each blocks with no update method ([#1795](https://github.com/sveltejs/svelte/issues/1795)) - -## 2.14.2 - -* Fix issue with nested `{#if}` blocks ([#1780](https://github.com/sveltejs/svelte/issues/1780)) - -## 2.14.1 - -* Fix block insertion order regression ([#1778](https://github.com/sveltejs/svelte/issues/1778)) -* Fix blocks inside `` ([#1774](https://github.com/sveltejs/svelte/issues/1774)) -* Better attribute parsing ([#1772](https://github.com/sveltejs/svelte/issues/1772)) -* Fix parse errors inside directives ([#1788](https://github.com/sveltejs/svelte/issues/1788)) - - -## 2.14.0 - -* Refactor internals ([#1678](https://github.com/sveltejs/svelte/issues/1678)) -* Deprecate `onerror` option ([#1745](https://github.com/sveltejs/svelte/issues/1745)) -* Handle edge cases where `destroy` is called before `mount` ([#1653](https://github.com/sveltejs/svelte/pull/1653)) -* Make `scroll` binding more efficient ([#1579](https://github.com/sveltejs/svelte/pull/1770)) -* Make 'readonly property' store error more informative ([#1761](https://github.com/sveltejs/svelte/pull/1761)) - -## 2.13.5 - -* Fix missing dependencies in shorthand class directives ([#1739](https://github.com/sveltejs/svelte/issues/1739)) - -## 2.13.4 - -* Support dynamic `import()` in template expressions - -## 2.13.3 - -* Fix bug with keyed each blocks and nested components ([#1706](https://github.com/sveltejs/svelte/issues/1706)) - -## 2.13.2 - -* Coalesce simultaneous store/component updates ([#1520](https://github.com/sveltejs/svelte/issues/1520)) -* Fix nested transitions preventing each block item removal ([#1617](https://github.com/sveltejs/svelte/issues/1617)) -* Add `class` directive shorthand and encapsulate styles ([#1695](https://github.com/sveltejs/svelte/pull/1695)) -* Prevent erroneous updates of bound inputs ([#1699](https://github.com/sveltejs/svelte/issues/1699)) - -## 2.13.1 - -* Coerce second argument to `toggleClass` ([#1685](https://github.com/sveltejs/svelte/issues/1685)) - -## 2.13.0 - -* Add `class` directive ([#890](https://github.com/sveltejs/svelte/issues/890)) -* Remove sourcemaps from npm package ([#1690](https://github.com/sveltejs/svelte/pull/1690)) - -## 2.12.1 - -* Allow actions to take any expression ([#1676](https://github.com/sveltejs/svelte/issues/1676)) -* Run transitions in component context ([#1675](https://github.com/sveltejs/svelte/issues/1675)) -* Correctly set select value on mount ([#1666](https://github.com/sveltejs/svelte/issues/1666)) -* Support `{@debug}` in SSR ([#1659](https://github.com/sveltejs/svelte/issues/1659)) -* Don't treat ` ` as empty whitespace ([#1658](https://github.com/sveltejs/svelte/issues/1658)) -* Fix outros for if blocks with no else ([#1688](https://github.com/sveltejs/svelte/pull/1688)) -* Set `style.cssText` in spread attributes ([#1684](https://github.com/sveltejs/svelte/pull/1684)) - - -## 2.12.0 - -* Initialise actions on mount rather than hydrate ([#1653](https://github.com/sveltejs/svelte/pull/1653)) -* Allow non-existent components to be destroyed ([#1677](https://github.com/sveltejs/svelte/pull/1677)) -* Pass AMD ID from CLI correctly ([#1672](https://github.com/sveltejs/svelte/pull/1672)) -* Minor AST tweaks ([#1673](https://github.com/sveltejs/svelte/pull/1673), [#1674](https://github.com/sveltejs/svelte/pull/1674)) -* Reduce code duplication in component initialisation ([#1670](https://github.com/sveltejs/svelte/pull/1670)) - - -## 2.11.0 - -* Add `--shared` CLI option ([#1649](https://github.com/sveltejs/svelte/pull/1649)) -* Run first `onstate` *before* fragment is rendered ([#1522](https://github.com/sveltejs/svelte/issues/1522)) -* Exclude current computed prop from state object ([#1544](https://github.com/sveltejs/svelte/issues/1544)) - - -## 2.10.1 - -* Add sourcemaps to `{@debug}` tags ([#1647](https://github.com/sveltejs/svelte/pull/1647)) - -## 2.10.0 - -* Add a `{@debug}` tag, for inspecting values in templates in dev mode ([#1635](https://github.com/sveltejs/svelte/issues/1635)) -* Fix dimension bindings in iOS ([#1642](https://github.com/sveltejs/svelte/pull/1642)) - -## 2.9.11 - -* Pass props to custom elements rather than setting attributes, where appropriate ([#875](https://github.com/sveltejs/svelte/issues/875)) -* Handle whitespace in lists consistently between SSR and DOM renderers ([#1637](https://github.com/sveltejs/svelte/pull/1637)) -* Improve error for invalid `ref` names ([#1613](https://github.com/sveltejs/svelte/issues/1613)) - -## 2.9.10 - -* Handle `null` consistently in tags ([#1598](https://github.com/sveltejs/svelte/issues/1598)) -* Support object rest in computed properties ([#1540](https://github.com/sveltejs/svelte/issues/1540)) -* Always update dynamic components when expression changes ([#1621](https://github.com/sveltejs/svelte/issues/1621)) -* Encapsulate local styles inside global styles ([#1618](https://github.com/sveltejs/svelte/issues/1618)) - -## 2.9.9 - -* Fix attribute name regex ([#1623](https://github.com/sveltejs/svelte/pull/1623)) - -## 2.9.8 - -* Sanitize spread attributes in SSR — fixes vulnerability CVE-2018-6341 ([#1623](https://github.com/sveltejs/svelte/pull/1623)) - -## 2.9.7 - -* Allow `` ([#1608](https://github.com/sveltejs/svelte/issues/1608)) -* Ensure child window exists before removing listener in `addResizeHandler` ([#1600](https://github.com/sveltejs/svelte/issues/1600)) -* Handle transitions in `else` block ([#1589](https://github.com/sveltejs/svelte/issues/1589)) - -## 2.9.6 - -* Provide more useful error if SSR component attempts to render non-SSR component ([#1605](https://github.com/sveltejs/svelte/issues/1605)) - -## 2.9.5 - -* Null out refs to dynamic components ([#1596](https://github.com/sveltejs/svelte/issues/1596)) - -## 2.9.4 - -* Make identifier optional for `then` and `catch` blocks ([#1507](https://github.com/sveltejs/svelte/issues/1507)) -* Group outros correctly ([#1575](https://github.com/sveltejs/svelte/issues/1575)) - -## 2.9.3 - -* Fix bug when an each block contains transitions but its else branch does not ([#1559](https://github.com/sveltejs/svelte/issues/1559)) -* If an event handler throws an exception, don't block all future calls to that handler ([#1573](https://github.com/sveltejs/svelte/issues/1573)) - -## 2.9.2 - -* Fix conflict when using multiple if-else blocks, some of which use outros and some of which do not ([#1580](https://github.com/sveltejs/svelte/issues/1580)) -* Fix some cases where `.innerHTML` was being used to create child elements when it shouldn't ([#1581](https://github.com/sveltejs/svelte/issues/1581)) - -## 2.9.1 - -* Use `template.content` instead of `template` where appropriate ([#1571](https://github.com/sveltejs/svelte/issues/1571)) - -## 2.9.0 - -* Play outro transitions on `` if `nestedTransitions` is true ([#1568](https://github.com/sveltejs/svelte/issues/1568)) -* Allow illegal identifiers to be component prop names, for e.g. spreading `data-foo` props ([#887](https://github.com/sveltejs/svelte/issues/887)) -* Abort transition when node is detached ([#1561](https://github.com/sveltejs/svelte/issues/1561)) -* Only include `transitionManager` when necessary ([#1514](https://github.com/sveltejs/svelte/issues/1514)) - -## 2.8.1 - -* Fix prefixed animation name replacement ([#1556](https://github.com/sveltejs/svelte/pull/1556)) - -## 2.8.0 - -* Correctly set store on nested components (to parent store, not root store) ([#1538](https://github.com/sveltejs/svelte/issues/1538)) - -## 2.7.2 - -* Prevent unnecessary remounts ([#1527](https://github.com/sveltejs/svelte/issues/1527)) -* Allow `refs.*` as callee ([#1526](https://github.com/sveltejs/svelte/pull/1526)) -* Handle empty lists when outroing ([#1532](https://github.com/sveltejs/svelte/issues/1532)) - -## 2.7.1 - -* Fix spread props with multiple dependencies ([#1515](https://github.com/sveltejs/svelte/issues/1515)) - -## 2.7.0 - -* Add `__svelte_meta` object to elements in dev mode, containing source info ([#1499](https://github.com/sveltejs/svelte/issues/1499)) -* Fix `bind:online` in dev mode ([#1502](https://github.com/sveltejs/svelte/issues/1502)) -* Update v1 warnings/errors ([#1508](https://github.com/sveltejs/svelte/pull/1508)) -* Transform prefixed keyframes ([#1504](https://github.com/sveltejs/svelte/issues/1504)) - -## 2.6.6 - -* Fix nested transition bug ([#1497](https://github.com/sveltejs/svelte/issues/1497)) - -## 2.6.5 - -* Handle cases where only some `if` block branches have outros ([#1492](https://github.com/sveltejs/svelte/issues/1492)) - -## 2.6.4 - -* Web worker support ([#1487](https://github.com/sveltejs/svelte/issues/1487)) -* Update dynamic component bindings when component changes ([#1489](https://github.com/sveltejs/svelte/issues/1489)) - -## 2.6.3 - -* Nested transitions respect `skipIntroByDefault` ([#1460](https://github.com/sveltejs/svelte/issues/1460)) -* Always create outro for top-level block ([#1470](https://github.com/sveltejs/svelte/issues/1470)) - -## 2.6.2 - -* Fix spread+bindings on dynamic components ([#1433](https://github.com/sveltejs/svelte/issues/1433)) -* Abort in-progress animations, if a new one starts ([#1458](https://github.com/sveltejs/svelte/issues/1458)) -* Allow animations to be parameterised ([#1462](https://github.com/sveltejs/svelte/issues/1462)) - -## 2.6.1 - -* Absolutely position outroing animated nodes ([#1457](https://github.com/sveltejs/svelte/pull/1457)) - -## 2.6.0 - -* Add `animate` directive ([#1454](https://github.com/sveltejs/svelte/pull/1454)) -* Add `skipIntroByDefault` compiler option and `intro: true` init option ([#1448](https://github.com/sveltejs/svelte/pull/1448)) -* Add `nestedTransitions` compiler option ([#1451](https://github.com/sveltejs/svelte/pull/1451)) -* Component outros, if `nestedTransitions` is true ([#1211](https://github.com/sveltejs/svelte/issues/1211)) -* Allow transition functions to return a function, for inter-transition coordination ([#1453](https://github.com/sveltejs/svelte/pull/1453)) -* Pass `1 - t` as second argument to transition functions ([#1452](https://github.com/sveltejs/svelte/pull/1452)) - -## 2.5.1 - -* Add new ARIA attributes ([#1436](https://github.com/sveltejs/svelte/pull/1436)) -* Add `Promise` to whitelisted globals ([#1441](https://github.com/sveltejs/svelte/issues/1441)) -* Allow spaces around reserved keyword attributes ([#1445](https://github.com/sveltejs/svelte/issues/1445)) - -## 2.5.0 - -* Support transitions in `await` blocks ([#956](https://github.com/sveltejs/svelte/issues/956)) -* Abort outros if block is recreated ([#1425](https://github.com/sveltejs/svelte/issues/1425)) -* Wait until transitions have completed before removing styles ([#648](https://github.com/sveltejs/svelte/issues/648)) -* Support event shorthand on dynamic components ([#1427](https://github.com/sveltejs/svelte/pull/1427)) -* Various codegen improvements ([#1419](https://github.com/sveltejs/svelte/pull/1419), [#1421](https://github.com/sveltejs/svelte/pull/1421), [#1422](https://github.com/sveltejs/svelte/pull/1422), [#1424](https://github.com/sveltejs/svelte/pull/1424)) -* Correctly handle `await` blocks with no dynamic content ([#1417](https://github.com/sveltejs/svelte/issues/1417)) -* Allow spread props on elements with static attribute tests ([#1429](https://github.com/sveltejs/svelte/pull/1429)) - - -## 2.4.4 - -* Declare missing variable in Store ([#1415](https://github.com/sveltejs/svelte/issues/1415)) -* ALways declare spread levels ([#1413](https://github.com/sveltejs/svelte/issues/1413)) - -## 2.4.3 - -* `ref` directives prevent HTMLified content ([#1407](https://github.com/sveltejs/svelte/issues/1407)) -* Store computed properties update components immediately upon declaration ([#1327](https://github.com/sveltejs/svelte/issues/1327)) - -## 2.4.2 - -* Evaluate `each` key in child scope ([#1397](https://github.com/sveltejs/svelte/issues/1397)) -* Prevent false negatives and positives when detecting cyclical computed store properties ([#1399](https://github.com/sveltejs/svelte/issues/1399)) -* Only update dynamic component props ([#1394](https://github.com/sveltejs/svelte/issues/1394)) - -## 2.4.1 - -* Fix DOM event context ([#1390](https://github.com/sveltejs/svelte/issues/1390)) - -## 2.4.0 - -* Integrate CLI ([#1360](https://github.com/sveltejs/svelte/issues/1360)) -* Allow arbitrary destructuring for each block items, with binding ([#1385](https://github.com/sveltejs/svelte/pull/1385)) -* Each block keys can use arbitrary expressions ([#703](https://github.com/sveltejs/svelte/issues/703)) -* `bind:offsetWidth`, `bind:offsetHeight`, `bind:clientWidth` and `bind:clientHeight` ([#984](https://github.com/sveltejs/svelte/issues/984)) -* Leaner generated code for `each` blocks ([#1287](https://github.com/sveltejs/svelte/issues/1287)) - - -## 2.3.0 - -* Allow computed properties to have entire state object as dependency ([#1303](https://github.com/sveltejs/svelte/issues/1303)) -* Fix `stats` when `options.generate` is `false` ([#1368](https://github.com/sveltejs/svelte/issues/1368)) -* Assign custom methods to custom elements ([#1369](https://github.com/sveltejs/svelte/issues/1369)) -* Fix `this` value in custom event handlers ([#1297](https://github.com/sveltejs/svelte/issues/1297)) -* Re-evaluate `each` values lazily ([#1286](https://github.com/sveltejs/svelte/issues/1286)) -* Preserve outer context in `await` blocks ([#1251](https://github.com/sveltejs/svelte/issues/1251)) - -## 2.2.0 - -* Internal refactoring ([#1367](https://github.com/sveltejs/svelte/pull/1367)) - -## 2.1.1 - -* Report initial `changed` based on state, not expected props ([#1356](https://github.com/sveltejs/svelte/issues/1356)) -* Set state to empty object, not null, on destroy ([#1354](https://github.com/sveltejs/svelte/issues/1354)) -* Prevent stale state in component event handlers ([#1353](https://github.com/sveltejs/svelte/issues/1353)) - -## 2.1.0 - -* Allow shorthand imports ([#1038](https://github.com/sveltejs/svelte/issues/1038)) -* Update spread props inside each blocks ([#1337](https://github.com/sveltejs/svelte/issues/1337)) - -## 2.0.0 - -*See [the blog post](https://svelte.technology/blog/version-2) for information on how to upgrade your apps* - -* New template syntax ([#1318](https://github.com/sveltejs/svelte/issues/1318)) -* Emit ES2015 code, not ES5 ([#1348](https://github.com/sveltejs/svelte/pull/1348)) -* Add `onstate` and `onupdate` hooks, remove `component.observe` method ([#1197](https://github.com/sveltejs/svelte/issues/1197)) -* Use destructuring syntax for computed properties ([#1069](https://github.com/sveltejs/svelte/issues/1069) -* Change signature of `svelte.compile` ([#1298](https://github.com/sveltejs/svelte/pull/1298)) -* Remove `validate` and `Stylesheet` from public API ([#1348](https://github.com/sveltejs/svelte/pull/1348)) -* Don't typecast numeric attributes ([#657](https://github.com/sveltejs/svelte/issues/657)) -* Always compile with `Store` support, and cascading disabled ([#1348](https://github.com/sveltejs/svelte/pull/1348)) -* Remove unused `hash` property from AST ([#1348](https://github.com/sveltejs/svelte/pull/1348)) -* Rename `loc` property to `start` in warnings and errors ([#1348](https://github.com/sveltejs/svelte/pull/1348)) - -## 1.64.1 - -* Fix computed properties in SSR renderer ([#1349](https://github.com/sveltejs/svelte/issues/1349)) - -## 1.64.0 - -* Deprecate passing a string argument to `component.get` ([#1347](https://github.com/sveltejs/svelte/pull/1347)) - -## 1.63.1 - -* Allow `observe` method to be overwritten - -## 1.63.0 - -* Add `onstate` and `onupdate` lifecycle hooks and deprecate `component.observe` ([#1197](https://github.com/sveltejs/svelte/issues/1197)) -* Add `on` and `fire` to `Store`, deprecate `onchange` and `observe` ([#1344](https://github.com/sveltejs/svelte/pull/1344)) -* Require computed properties to have destructured argument in v2 mode ([#1069](https://github.com/sveltejs/svelte/issues/1069)) - -## 1.62.0 - -* Add a `code` field to errors and warnings ([#474](https://github.com/sveltejs/svelte/issues/474)) -* When using v2 syntax, do not use interpolation in non-root ` +``` + +...into lean, tightly optimized JavaScript. + +You can use it to build anything on the web, from standalone components to ambitious full stack apps (using Svelte's companion application framework, [SvelteKit](../kit)) and everything in between. + +These pages serve as reference documentation. If you're new to Svelte, we recommend starting with the [interactive tutorial](/tutorial) and coming back here when you have questions. + +You can also try Svelte online in the [playground](/playground) or, if you need a more fully-featured environment, on [StackBlitz](https://sveltekit.new). diff --git a/documentation/docs/01-introduction/02-getting-started.md b/documentation/docs/01-introduction/02-getting-started.md new file mode 100644 index 000000000000..c7351729ff17 --- /dev/null +++ b/documentation/docs/01-introduction/02-getting-started.md @@ -0,0 +1,32 @@ +--- +title: Getting started +--- + +We recommend using [SvelteKit](../kit), which lets you [build almost anything](../kit/project-types). It's the official application framework from the Svelte team and powered by [Vite](https://vite.dev/). Create a new project with: + +```bash +npx sv create myapp +cd myapp +npm install +npm run dev +``` + +Don't worry if you don't know Svelte yet! You can ignore all the nice features SvelteKit brings on top for now and dive into it later. + +## Alternatives to SvelteKit + +You can also use Svelte directly with Vite by running `npm create vite@latest` and selecting the `svelte` option. With this, `npm run build` will generate HTML, JS, and CSS files inside the `dist` directory using [vite-plugin-svelte](https://github.com/sveltejs/vite-plugin-svelte). In most cases, you will probably need to [choose a routing library](faq#Is-there-a-router) as well. + +>[!NOTE] Vite is often used in standalone mode to build [single page apps (SPAs)](../kit/glossary#SPA), which you can also [build with SvelteKit](../kit/single-page-apps). + +There are also plugins for [Rollup](https://github.com/sveltejs/rollup-plugin-svelte), [Webpack](https://github.com/sveltejs/svelte-loader) [and a few others](https://sveltesociety.dev/packages?category=build-plugins), but we recommend Vite. + +## Editor tooling + +The Svelte team maintains a [VS Code extension](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode), and there are integrations with various other [editors](https://sveltesociety.dev/resources#editor-support) and tools as well. + +You can also check your code from the command line using [sv check](https://github.com/sveltejs/cli). + +## Getting help + +Don't be shy about asking for help in the [Discord chatroom](/chat)! You can also find answers on [Stack Overflow](https://stackoverflow.com/questions/tagged/svelte). diff --git a/documentation/docs/01-introduction/03-svelte-files.md b/documentation/docs/01-introduction/03-svelte-files.md new file mode 100644 index 000000000000..cd98652370f3 --- /dev/null +++ b/documentation/docs/01-introduction/03-svelte-files.md @@ -0,0 +1,71 @@ +--- +title: .svelte files +--- + +Components are the building blocks of Svelte applications. They are written into `.svelte` files, using a superset of HTML. + +All three sections — script, styles and markup — are optional. + + +```svelte +/// file: MyComponent.svelte + + + + + + + +``` + +## ` + + +``` + +You can `export` bindings from this block, and they will become exports of the compiled module. You cannot `export default`, since the default export is the component itself. + +> [!NOTE] If you are using TypeScript and import such exports from a `module` block into a `.ts` file, make sure to have your editor setup so that TypeScript knows about them. This is the case for our VS Code extension and the IntelliJ plugin, but in other cases you might need to setup our [TypeScript editor plugin](https://www.npmjs.com/package/typescript-svelte-plugin). + +> [!LEGACY] +> In Svelte 4, this script tag was created using ` + + +``` + +Unlike other frameworks you may have encountered, there is no API for interacting with state — `count` is just a number, rather than an object or a function, and you can update it like you would update any other variable. + +### Deep state + +If `$state` is used with an array or a simple object, the result is a deeply reactive _state proxy_. [Proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) allow Svelte to run code when you read or write properties, including via methods like `array.push(...)`, triggering granular updates. + +> [!NOTE] Classes like `Set` and `Map` will not be proxied, but Svelte provides reactive implementations for various built-ins like these that can be imported from [`svelte/reactivity`](./svelte-reactivity). + +State is proxified recursively until Svelte finds something other than an array or simple object. In a case like this... + +```js +let todos = $state([ + { + done: false, + text: 'add more todos' + } +]); +``` + +...modifying an individual todo's property will trigger updates to anything in your UI that depends on that specific property: + +```js +let todos = [{ done: false, text: 'add more todos' }]; +// ---cut--- +todos[0].done = !todos[0].done; +``` + +If you push a new object to the array, it will also be proxified: + +```js +let todos = [{ done: false, text: 'add more todos' }]; +// ---cut--- +todos.push({ + done: false, + text: 'eat lunch' +}); +``` + +> [!NOTE] When you update properties of proxies, the original object is _not_ mutated. + +Note that if you destructure a reactive value, the references are not reactive — as in normal JavaScript, they are evaluated at the point of destructuring: + +```js +let todos = [{ done: false, text: 'add more todos' }]; +// ---cut--- +let { done, text } = todos[0]; + +// this will not affect the value of `done` +todos[0].done = !todos[0].done; +``` + +### Classes + +You can also use `$state` in class fields (whether public or private): + +```js +// @errors: 7006 2554 +class Todo { + done = $state(false); + text = $state(); + + constructor(text) { + this.text = text; + } + + reset() { + this.text = ''; + this.done = false; + } +} +``` + +> [!NOTE] The compiler transforms `done` and `text` into `get`/`set` methods on the class prototype referencing private fields. This means the properties are not enumerable. + +When calling methods in JavaScript, the value of [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) matters. This won't work, because `this` inside the `reset` method will be the ` +``` + +You can either use an inline function... + +```svelte + +``` + +...or use an arrow function in the class definition: + +```js +// @errors: 7006 2554 +class Todo { + done = $state(false); + text = $state(); + + constructor(text) { + this.text = text; + } + + +++reset = () => {+++ + this.text = ''; + this.done = false; + } +} +``` + +## `$state.raw` + +In cases where you don't want objects and arrays to be deeply reactive you can use `$state.raw`. + +State declared with `$state.raw` cannot be mutated; it can only be _reassigned_. In other words, rather than assigning to a property of an object, or using an array method like `push`, replace the object or array altogether if you'd like to update it: + +```js +let person = $state.raw({ + name: 'Heraclitus', + age: 49 +}); + +// this will have no effect +person.age += 1; + +// this will work, because we're creating a new person +person = { + name: 'Heraclitus', + age: 50 +}; +``` + +This can improve performance with large arrays and objects that you weren't planning to mutate anyway, since it avoids the cost of making them reactive. Note that raw state can _contain_ reactive state (for example, a raw array of reactive objects). + +## `$state.snapshot` + +To take a static snapshot of a deeply reactive `$state` proxy, use `$state.snapshot`: + +```svelte + +``` + +This is handy when you want to pass some state to an external library or API that doesn't expect a proxy, such as `structuredClone`. + +## Passing state into functions + +JavaScript is a _pass-by-value_ language — when you call a function, the arguments are the _values_ rather than the _variables_. In other words: + +```js +/// file: index.js +// @filename: index.js +// ---cut--- +/** + * @param {number} a + * @param {number} b + */ +function add(a, b) { + return a + b; +} + +let a = 1; +let b = 2; +let total = add(a, b); +console.log(total); // 3 + +a = 3; +b = 4; +console.log(total); // still 3! +``` + +If `add` wanted to have access to the _current_ values of `a` and `b`, and to return the current `total` value, you would need to use functions instead: + +```js +/// file: index.js +// @filename: index.js +// ---cut--- +/** + * @param {() => number} getA + * @param {() => number} getB + */ +function add(+++getA, getB+++) { + return +++() => getA() + getB()+++; +} + +let a = 1; +let b = 2; +let total = add+++(() => a, () => b)+++; +console.log(+++total()+++); // 3 + +a = 3; +b = 4; +console.log(+++total()+++); // 7 +``` + +State in Svelte is no different — when you reference something declared with the `$state` rune... + +```js +let a = +++$state(1)+++; +let b = +++$state(2)+++; +``` + +...you're accessing its _current value_. + +Note that 'functions' is broad — it encompasses properties of proxies and [`get`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get)/[`set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) properties... + +```js +/// file: index.js +// @filename: index.js +// ---cut--- +/** + * @param {{ a: number, b: number }} input + */ +function add(input) { + return { + get value() { + return input.a + input.b; + } + }; +} + +let input = $state({ a: 1, b: 2 }); +let total = add(input); +console.log(total.value); // 3 + +input.a = 3; +input.b = 4; +console.log(total.value); // 7 +``` + +...though if you find yourself writing code like that, consider using [classes](#Classes) instead. + +## Passing state across modules + +You can declare state in `.svelte.js` and `.svelte.ts` files, but you can only _export_ that state if it's not directly reassigned. In other words you can't do this: + +```js +/// file: state.svelte.js +export let count = $state(0); + +export function increment() { + count += 1; +} +``` + +That's because every reference to `count` is transformed by the Svelte compiler — the code above is roughly equivalent to this: + +```js +/// file: state.svelte.js (compiler output) +// @filename: index.ts +interface Signal { + value: T; +} + +interface Svelte { + state(value?: T): Signal; + get(source: Signal): T; + set(source: Signal, value: T): void; +} +declare const $: Svelte; +// ---cut--- +export let count = $.state(0); + +export function increment() { + $.set(count, $.get(count) + 1); +} +``` + +> [!NOTE] You can see the code Svelte generates by clicking the 'JS Output' tab in the [playground](/playground). + +Since the compiler only operates on one file at a time, if another file imports `count` Svelte doesn't know that it needs to wrap each reference in `$.get` and `$.set`: + +```js +// @filename: state.svelte.js +export let count = 0; + +// @filename: index.js +// ---cut--- +import { count } from './state.svelte.js'; + +console.log(typeof count); // 'object', not 'number' +``` + +This leaves you with two options for sharing state between modules — either don't reassign it... + +```js +// This is allowed — since we're updating +// `counter.count` rather than `counter`, +// Svelte doesn't wrap it in `$.state` +export const counter = $state({ + count: 0 +}); + +export function increment() { + counter.count += 1; +} +``` + +...or don't directly export it: + +```js +let count = $state(0); + +export function getCount() { + return count; +} + +export function increment() { + count += 1; +} +``` diff --git a/documentation/docs/02-runes/03-$derived.md b/documentation/docs/02-runes/03-$derived.md new file mode 100644 index 000000000000..2464aa929550 --- /dev/null +++ b/documentation/docs/02-runes/03-$derived.md @@ -0,0 +1,112 @@ +--- +title: $derived +--- + +Derived state is declared with the `$derived` rune: + +```svelte + + + + +

{count} doubled is {doubled}

+``` + +The expression inside `$derived(...)` should be free of side-effects. Svelte will disallow state changes (e.g. `count++`) inside derived expressions. + +As with `$state`, you can mark class fields as `$derived`. + +> [!NOTE] Code in Svelte components is only executed once at creation. Without the `$derived` rune, `doubled` would maintain its original value even when `count` changes. + +## `$derived.by` + +Sometimes you need to create complex derivations that don't fit inside a short expression. In these cases, you can use `$derived.by` which accepts a function as its argument. + +```svelte + + + +``` + +In essence, `$derived(expression)` is equivalent to `$derived.by(() => expression)`. + +## Understanding dependencies + +Anything read synchronously inside the `$derived` expression (or `$derived.by` function body) is considered a _dependency_ of the derived state. When the state changes, the derived will be marked as _dirty_ and recalculated when it is next read. + +To exempt a piece of state from being treated as a dependency, use [`untrack`](svelte#untrack). + +## Overriding derived values + +Derived expressions are recalculated when their dependencies change, but you can temporarily override their values by reassigning them (unless they are declared with `const`). This can be useful for things like _optimistic UI_, where a value is derived from the 'source of truth' (such as data from your server) but you'd like to show immediate feedback to the user: + +```svelte + + + +``` + +> [!NOTE] Prior to Svelte 5.25, deriveds were read-only. + +## Deriveds and reactivity + +Unlike `$state`, which converts objects and arrays to [deeply reactive proxies]($state#Deep-state), `$derived` values are left as-is. For example, [in a case like this](/playground/untitled#H4sIAAAAAAAAE4VU22rjMBD9lUHd3aaQi9PdstS1A3t5XvpQ2Ic4D7I1iUUV2UjjNMX431eS7TRdSosxgjMzZ45mjt0yzffIYibvy0ojFJWqDKCQVBk2ZVup0LJ43TJ6rn2aBxw-FP2o67k9oCKP5dziW3hRaUJNjoYltjCyplWmM1JIIAn3FlL4ZIkTTtYez6jtj4w8WwyXv9GiIXiQxLVs9pfTMR7EuoSLIuLFbX7Z4930bZo_nBrD1bs834tlfvsBz9_SyX6PZXu9XaL4gOWn4sXjeyzftv4ZWfyxubpzxzg6LfD4MrooxELEosKCUPigQCMPKCZh0OtQE1iSxcsmdHuBvCiHZXALLXiN08EL3RRkaJ_kDVGle0HcSD5TPEeVtj67O4Nrg9aiSNtBY5oODJkrL5QsHtN2cgXp6nSJMWzpWWGasdlsGEMbzi5jPr5KFr0Ep7pdeM2-TCelCddIhDxAobi1jqF3cMaC1RKp64bAW9iFAmXGIHfd4wNXDabtOLN53w8W53VvJoZLh7xk4Rr3CoL-UNoLhWHrT1JQGcM17u96oES5K-kc2XOzkzqGCKL5De79OUTyyrg1zgwXsrEx3ESfx4Bz0M5UjVMHB24mw9SuXtXFoN13fYKOM1tyUT3FbvbWmSWCZX2Er-41u5xPoml45svRahl9Wb9aasbINJixDZwcPTbyTLZSUsAvrg_cPuCR7s782_WU8343Y72Qtlb8OYatwuOQvuN13M_hJKNfxann1v1U_B1KZ_D_mzhzhz24fw85CSz2irtN9w9HshBK7AQAAA==)... + +```svelte +let items = $state([...]); + +let index = $state(0); +let selected = $derived(items[index]); +``` + +...you can change (or `bind:` to) properties of `selected` and it will affect the underlying `items` array. If `items` was _not_ deeply reactive, mutating `selected` would have no effect. + +## Update propagation + +Svelte uses something called _push-pull reactivity_ — when state is updated, everything that depends on the state (whether directly or indirectly) is immediately notified of the change (the 'push'), but derived values are not re-evaluated until they are actually read (the 'pull'). + +If the new value of a derived is referentially identical to its previous value, downstream updates will be skipped. In other words, Svelte will only update the text inside the button when `large` changes, not when `count` changes, even though `large` depends on `count`: + +```svelte + + + +``` diff --git a/documentation/docs/02-runes/04-$effect.md b/documentation/docs/02-runes/04-$effect.md new file mode 100644 index 000000000000..46ea9b81e92e --- /dev/null +++ b/documentation/docs/02-runes/04-$effect.md @@ -0,0 +1,330 @@ +--- +title: $effect +--- + +Effects are functions that run when state updates, and can be used for things like calling third-party libraries, drawing on `` elements, or making network requests. They only run in the browser, not during server-side rendering. + +Generally speaking, you should _not_ update state inside effects, as it will make code more convoluted and will often lead to never-ending update cycles. If you find yourself doing so, see [when not to use `$effect`](#When-not-to-use-$effect) to learn about alternative approaches. + +You can create an effect with the `$effect` rune ([demo](/playground/untitled#H4sIAAAAAAAAE31S246bMBD9lZF3pSRSAqTVvrCAVPUP2sdSKY4ZwJJjkD0hSVH-vbINuWxXfQH5zMyZc2ZmZLVUaFn6a2R06ZGlHmBrpvnBvb71fWQHVOSwPbf4GS46TajJspRlVhjZU1HqkhQSWPkHIYdXS5xw-Zas3ueI6FRn7qHFS11_xSRZhIxbFtcDtw7SJb1iXaOg5XIFeQGjzyPRaevYNOGZIJ8qogbpe8CWiy_VzEpTXiQUcvPDkSVrSNZz1UlW1N5eLcqmpdXUvaQ4BmqlhZNUCgxuzFHDqUWNAxrYeUM76AzsnOsdiJbrBp_71lKpn3RRbii-4P3f-IMsRxS-wcDV_bL4PmSdBa2wl7pKnbp8DMgVvJm8ZNskKRkEM_OzyOKQFkgqOYBQ3Nq89Ns0nbIl81vMFN-jKoLMTOr-SOBOJS-Z8f5Y6D1wdcR8dFqvEBdetK-PHwj-z-cH8oHPY54wRJ8Ys7iSQ3Bg3VA9azQbmC9k35kKzYa6PoVtfwbbKVnBixBiGn7Pq0rqJoUtHiCZwAM3jdTPWCVtr_glhVrhecIa3vuksJ_b7TqFs4DPyriSjd5IwoNNQaAmNI-ESfR2p8zimzvN1swdCkvJHPH6-_oX8o1SgcIDAAA=)): + +```svelte + + + +``` + +When Svelte runs an effect function, it tracks which pieces of state (and derived state) are accessed (unless accessed inside [`untrack`](svelte#untrack)), and re-runs the function when that state later changes. + +> [!NOTE] If you're having difficulty understanding why your `$effect` is rerunning or is not running see [understanding dependencies](#Understanding-dependencies). Effects are triggered differently than the `$:` blocks you may be used to if coming from Svelte 4. + +### Understanding lifecycle + +Your effects run after the component has been mounted to the DOM, and in a [microtask](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) after state changes. Re-runs are batched (i.e. changing `color` and `size` in the same moment won't cause two separate runs), and happen after any DOM updates have been applied. + +You can use `$effect` anywhere, not just at the top level of a component, as long as it is called while a parent effect is running. + +> [!NOTE] Svelte uses effects internally to represent logic and expressions in your template — this is how `

hello {name}!

` updates when `name` changes. + +An effect can return a _teardown function_ which will run immediately before the effect re-runs ([demo](/playground/untitled#H4sIAAAAAAAAE42SQVODMBCF_8pOxkPRKq3HCsx49K4n64xpskjGkDDJ0tph-O8uINo6HjxB3u7HvrehE07WKDbiyZEhi1osRWksRrF57gQdm6E2CKx_dd43zU3co6VB28mIf-nKO0JH_BmRRRVMQ8XWbXkAgfKtI8jhIpIkXKySu7lSG2tNRGZ1_GlYr1ZTD3ddYFmiosUigbyAbpC2lKbwWJkIB8ZhhxBQBWRSw6FCh3sM8GrYTthL-wqqku4N44TyqEgwF3lmRHr4Op0PGXoH31c5rO8mqV-eOZ49bikgtcHBL55tmhIkEMqg_cFB2TpFxjtg703we6NRL8HQFCS07oSUCZi6Rm04lz1yytIHBKoQpo1w6Gsm4gmyS8b8Y5PydeMdX8gwS2Ok4I-ov5NZtvQde95GMsccn_1wzNKfu3RZtS66cSl9lvL7qO1aIk7knbJGvefdtIOzi73M4bYvovUHDFk6AcX_0HRESxnpBOW_jfCDxIZCi_1L_wm4xGQ60wIAAA==)). + +```svelte + + +

{count}

+ + + +``` + +Teardown functions also run when the effect is destroyed, which happens when its parent is destroyed (for example, a component is unmounted) or the parent effect re-runs. + +### Understanding dependencies + +`$effect` automatically picks up any reactive values (`$state`, `$derived`, `$props`) that are _synchronously_ read inside its function body (including indirectly, via function calls) and registers them as dependencies. When those dependencies change, the `$effect` schedules a re-run. + +If `$state` and `$derived` are used directly inside the `$effect` (for example, during creation of a [reactive class](https://svelte.dev/docs/svelte/$state#Classes)), those values will _not_ be treated as dependencies. + +Values that are read _asynchronously_ — after an `await` or inside a `setTimeout`, for example — will not be tracked. Here, the canvas will be repainted when `color` changes, but not when `size` changes ([demo](/playground/untitled#H4sIAAAAAAAAE31T246bMBD9lZF3pWSlBEirfaEQqdo_2PatVIpjBrDkGGQPJGnEv1e2IZfVal-wfHzmzJyZ4cIqqdCy9M-F0blDlnqArZjmB3f72XWRHVCRw_bc4me4aDWhJstSlllhZEfbQhekkMDKfwg5PFvihMvX5OXH_CJa1Zrb0-Kpqr5jkiwC48rieuDWQbqgZ6wqFLRcvkC-hYvnkWi1dWqa8ESQTxFRjfQWsOXiWzmr0sSLhEJu3p1YsoJkNUcdZUnN9dagrBu6FVRQHAM10sJRKgUG16bXcGxQ44AGdt7SDkTDdY02iqLHnJVU6hedlWuIp94JW6Tf8oBt_8GdTxlF0b4n0C35ZLBzXb3mmYn3ae6cOW74zj0YVzDNYXRHFt9mprNgHfZSl6mzml8CMoLvTV6wTZIUDEJv5us2iwMtiJRyAKG4tXnhl8O0yhbML0Wm-B7VNlSSSd31BG7z8oIZZ6dgIffAVY_5xdU9Qrz1Bnx8fCfwtZ7v8Qc9j3nB8PqgmMWlHIID6-bkVaPZwDySfWtKNGtquxQ23Qlsq2QJT0KIqb8dL0up6xQ2eIBkAg_c1FI_YqW0neLnFCqFpwmreedJYT7XX8FVOBfwWRhXstZrSXiwKQjUhOZeMIleb5JZfHWn2Yq5pWEpmR7Hv-N_wEqT8hEEAAA=)): + +```ts +// @filename: index.ts +declare let canvas: { + width: number; + height: number; + getContext(type: '2d', options?: CanvasRenderingContext2DSettings): CanvasRenderingContext2D; +}; +declare let color: string; +declare let size: number; + +// ---cut--- +$effect(() => { + const context = canvas.getContext('2d'); + context.clearRect(0, 0, canvas.width, canvas.height); + + // this will re-run whenever `color` changes... + context.fillStyle = color; + + setTimeout(() => { + // ...but not when `size` changes + context.fillRect(0, 0, size, size); + }, 0); +}); +``` + +An effect only reruns when the object it reads changes, not when a property inside it changes. (If you want to observe changes _inside_ an object at dev time, you can use [`$inspect`]($inspect).) + +```svelte + + + + +

{state.value} doubled is {derived.value}

+``` + +An effect only depends on the values that it read the last time it ran. This has interesting implications for effects that have conditional code. + +For instance, if `condition` is `true` in the code snippet below, the code inside the `if` block will run and `color` will be evaluated. As such, changes to either `condition` or `color` [will cause the effect to re-run](/playground/untitled#H4sIAAAAAAAAE21RQW6DMBD8ytaNBJHaJFLViwNIVZ8RcnBgXVk1xsILTYT4e20TQg89IOPZ2fHM7siMaJBx9tmaWpFqjQNlAKXEihx7YVJpdIyfRkY3G4gB8Pi97cPanRtQU8AuwuF_eNUaQuPlOMtc1SlLRWlKUo1tOwJflUikQHZtA0klzCDc64Imx0ANn8bInV1CDhtHgjClrsftcSXotluLybOUb3g4JJHhOZs5WZpuIS9gjNqkJKQP5e2ClrR4SMdZ13E4xZ8zTPOTJU2A2uE_PQ9COCI926_hTVarIU4hu_REPlBrKq2q73ycrf1N-vS4TMUsulaVg3EtR8H9rFgsg8uUsT1B2F9eshigZHBRpuaD0D3mY8Qm2BfB5N2YyRzdNEYVDy0Ja-WsFjcOUuP1HvFLWA6H3XuHTUSmmDV2--0TXonxsKbp7G9C6R__NONS-MFNvxj_d6mBAgAA). + +Conversely, if `condition` is `false`, `color` will not be evaluated, and the effect will _only_ re-run again when `condition` changes. + +```ts +// @filename: ambient.d.ts +declare module 'canvas-confetti' { + interface ConfettiOptions { + colors: string[]; + } + + function confetti(opts?: ConfettiOptions): void; + export default confetti; +} + +// @filename: index.js +// ---cut--- +import confetti from 'canvas-confetti'; + +let condition = $state(true); +let color = $state('#ff3e00'); + +$effect(() => { + if (condition) { + confetti({ colors: [color] }); + } else { + confetti(); + } +}); +``` + +## `$effect.pre` + +In rare cases, you may need to run code _before_ the DOM updates. For this we can use the `$effect.pre` rune: + +```svelte + + +
+ {#each messages as message} +

{message}

+ {/each} +
+``` + +Apart from the timing, `$effect.pre` works exactly like `$effect`. + +## `$effect.tracking` + +The `$effect.tracking` rune is an advanced feature that tells you whether or not the code is running inside a tracking context, such as an effect or inside your template ([demo](/playground/untitled#H4sIAAAAAAAACn3PwYrCMBDG8VeZDYIt2PYeY8Dn2HrIhqkU08nQjItS-u6buAt7UDzmz8ePyaKGMWBS-nNRcmdU-hHUTpGbyuvI3KZvDFLal0v4qvtIgiSZUSb5eWSxPfWSc4oB2xDP1XYk8HHiSHkICeXKeruDDQ4Demlldv4y0rmq6z10HQwuJMxGVv4mVVXDwcJS0jP9u3knynwtoKz1vifT_Z9Jhm0WBCcOTlDD8kyspmML5qNpHg40jc3fFryJ0iWsp_UHgz3180oBAAA=)): + +```svelte + + +

in template: {$effect.tracking()}

+``` + +It is used to implement abstractions like [`createSubscriber`](/docs/svelte/svelte-reactivity#createSubscriber), which will create listeners to update reactive values but _only_ if those values are being tracked (rather than, for example, read inside an event handler). + +## `$effect.root` + +The `$effect.root` rune is an advanced feature that creates a non-tracked scope that doesn't auto-cleanup. This is useful for nested effects that you want to manually control. This rune also allows for the creation of effects outside of the component initialisation phase. + +```js +const destroy = $effect.root(() => { + $effect(() => { + // setup + }); + + return () => { + // cleanup + }; +}); + +// later... +destroy(); +``` + +## When not to use `$effect` + +In general, `$effect` is best considered something of an escape hatch — useful for things like analytics and direct DOM manipulation — rather than a tool you should use frequently. In particular, avoid using it to synchronise state. Instead of this... + +```svelte + +``` + +...do this: + +```svelte + +``` + +> [!NOTE] For things that are more complicated than a simple expression like `count * 2`, you can also use `$derived.by`. + +If you're using an effect because you want to be able to reassign the derived value (to build an optimistic UI, for example) note that [deriveds can be directly overridden]($derived#Overriding-derived-values) as of Svelte 5.25. + +You might be tempted to do something convoluted with effects to link one value to another. The following example shows two inputs for "money spent" and "money left" that are connected to each other. If you update one, the other should update accordingly. Don't use effects for this ([demo](/playground/untitled#H4sIAAAAAAAACpVRy26DMBD8FcvKgUhtoIdeHBwp31F6MGSJkBbHwksEQvx77aWQqooq9bgzOzP7mGTdIHipPiZJowOpGJAv0po2VmfnDv4OSBErjYdneHWzBJaCjcx91TWOToUtCIEE3cig0OIty44r5l1oDtjOkyFIsv3GINQ_CNYyGegd1DVUlCR7oU9iilDUcP8S8roYs9n8p2wdYNVFm4csTx872BxNCcjr5I11fdgonEkXsjP2CoUUZWMv6m6wBz2x7yxaM-iJvWeRsvSbSVeUy5i0uf8vKA78NIeJLSZWv1I8jQjLdyK4XuTSeIdmVKJGGI4LdjVOiezwDu1yG74My8PLCQaSiroe5s_5C2PHrkVGAgAA)): + +```svelte + + + + + +``` + +Instead, use `oninput` callbacks or — better still — [function bindings](bind#Function-bindings) where possible ([demo](/playground/untitled#H4sIAAAAAAAAE51SsW6DMBT8FcvqABINdOhCIFKXTt06lg4GHpElYyz8iECIf69tcIIipo6-u3f3fPZMJWuBpvRzkBXyTpKSy5rLq6YRbbgATdOfmeKkrMgCBt9GPpQ66RsItFjJNBzhVScRJBobmumq5wovhSxQABLskAmSk7ckOXtMKyM22ItGhhAk4Z0R0OwIN-tIQzd-90HVhvy2HsGNiQFCMltBgd7XoecV2xzXNV7XaEcth7ZfRv7kujnsTX2Qd7USb5rFjwZkJlgJwpWRcakG04cpOS9oz-QVCuoeInXW-RyEJL-sG0b7Wy6kZWM-u7CFxM5tdrIl9qg72vB74H-y7T2iXROHyVb0CLanp1yNk4D1A1jQ91hzrQSbUtIIGLcir0ylJDm9Q7urz42bX4UwIk2xH2D5Xf4A7SeMcMQCAAA=)): + +```svelte + + + + + +``` + +If you absolutely have to update `$state` within an effect and run into an infinite loop because you read and write to the same `$state`, use [untrack](svelte#untrack). diff --git a/documentation/docs/02-runes/05-$props.md b/documentation/docs/02-runes/05-$props.md new file mode 100644 index 000000000000..222b4831b65a --- /dev/null +++ b/documentation/docs/02-runes/05-$props.md @@ -0,0 +1,222 @@ +--- +title: $props +--- + +The inputs to a component are referred to as _props_, which is short for _properties_. You pass props to components just like you pass attributes to elements: + +```svelte + + + + +``` + +On the other side, inside `MyComponent.svelte`, we can receive props with the `$props` rune... + +```svelte + + + +

this component is {props.adjective}

+``` + +...though more commonly, you'll [_destructure_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) your props: + +```svelte + + + +

this component is {+++adjective+++}

+``` + +## Fallback values + +Destructuring allows us to declare fallback values, which are used if the parent component does not set a given prop (or the value is `undefined`): + +```js +let { adjective = 'happy' } = $props(); +``` + +> [!NOTE] Fallback values are not turned into reactive state proxies (see [Updating props](#Updating-props) for more info) + +## Renaming props + +We can also use the destructuring assignment to rename props, which is necessary if they're invalid identifiers, or a JavaScript keyword like `super`: + +```js +let { super: trouper = 'lights are gonna find me' } = $props(); +``` + +## Rest props + +Finally, we can use a _rest property_ to get, well, the rest of the props: + +```js +let { a, b, c, ...others } = $props(); +``` + +## Updating props + +References to a prop inside a component update when the prop itself updates — when `count` changes in `App.svelte`, it will also change inside `Child.svelte`. But the child component is able to temporarily override the prop value, which can be useful for unsaved ephemeral state ([demo](/playground/untitled#H4sIAAAAAAAAE6WQ0WrDMAxFf0WIQR0Wmu3VTQJln7HsIfVcZubIxlbGRvC_DzuBraN92qPula50tODZWB1RPi_IX16jLALWSOOUq6P3-_ihLWftNEZ9TVeOWBNHlNhGFYznfqCBzeRdYHh6M_YVzsFNsNs3pdpGd4eBcqPVDMrNxNDBXeSRtXioDgO1zU8ataeZ2RE4Utao924RFXQ9iHXwvoPHKpW1xY4g_Bg0cSVhKS0p560Za95612ZC02ONrD8ZJYdZp_rGQ37ff_mSP86Np2TWZaNNmdcH56P4P67K66_SXoK9pG-5dF5Z9QEAAA==)): + +```svelte + + + + + + +``` + +```svelte + + + + +``` + +While you can temporarily _reassign_ props, you should not _mutate_ props unless they are [bindable]($bindable). + +If the prop is a regular object, the mutation will have no effect ([demo](/playground/untitled#H4sIAAAAAAAAE3WQwU7DMBBEf2W1QmorQgJXk0RC3PkBwiExG9WQrC17U4Es_ztKUkQp9OjxzM7bjcjtSKjwyfKNp1aLORA4b13ADHszUED1HFE-3eyaBcy-Mw_O5eFAg8xa1wb6T9eWhVgCKiyD9sZJ3XAjZnTWCzzuzfAKvbcjbPJieR2jm_uGy-InweXqtd0baaliBG0nFgW3kBIUNWYo9CGoxE-UsgvIpw2_oc9-LmAPJBCPDJCggqvlVtvdH9puErEMlvVg9HsVtzuoaojzkKKAfRuALVDfk5ZZW0fmy05wXcFdwyktlUs-KIinljTXrRVnm7-kL9dYLVbUAQAA)): + +```svelte + + + + +``` + +```svelte + + + + +``` + +If the prop is a reactive state proxy, however, then mutations _will_ have an effect but you will see an [`ownership_invalid_mutation`](runtime-warnings#Client-warnings-ownership_invalid_mutation) warning, because the component is mutating state that does not 'belong' to it ([demo](/playground/untitled#H4sIAAAAAAAAE3WR0U7DMAxFf8VESBuiauG1WycheOEbKA9p67FA6kSNszJV-XeUZhMw2GN8r-1znUmQ7FGU4pn2UqsOes-SlSGRia3S6ET5Mgk-2OiJBZGdOh6szd0eNcdaIx3-V28NMRI7UYq1awdleVNTzaq3ZmB43CndwXYwPSzyYn4dWxermqJRI4Np3rFlqODasWRcTtAaT1zCHYSbVU3r4nsyrdPMKTUFKDYiE4yfLEoePIbsQpqfy3_nOVMuJIqg0wk1RFg7GOuWfwEbz2wIDLVatR_VtLyBagNTHFIUMCqtoZXeIfAOU1JoUJsR2IC3nWTMjt7GM4yKdyBhlAMpesvhydCC0y_i0ZagHByMh26WzUhXUUxKnpbcVnBfUwhznJnNlac7JkuIURL-2VVfwxflyrWcSQIAAA==)): + +```svelte + + + + +``` + +```svelte + + + + +``` + +The fallback value of a prop not declared with `$bindable` is left untouched — it is not turned into a reactive state proxy — meaning mutations will not cause updates ([demo](/playground/untitled#H4sIAAAAAAAAE3WQwU7DMBBEf2VkIbUVoYFraCIh7vwA4eC4G9Wta1vxpgJZ_nfkBEQp9OjxzOzTRGHlkUQlXpy9G0gq1idCL43ppDrAD84HUYheGwqieo2CP3y2Z0EU3-En79fhRIaz1slA_-nKWSbLQVRiE9SgPTetbVkfvRsYzztttugHd8RiXU6vr-jisbWb8idhN7O3bEQhmN5ZVDyMlIorcOddv_Eufq4AGmJEuG5PilEjQrnRcoV7JCTUuJlGWq7-YHYjs7NwVhmtDnVcrlA3iLmzLLGTAdaB-j736h68Oxv-JM1I0AFjoG1OzPfX023c1nhobUoT39QeKsRzS8owM8DFTG_pE6dcVl70AQAA)) + +```svelte + + + + +``` + +In summary: don't mutate props. Either use callback props to communicate changes, or — if parent and child should share the same object — use the [`$bindable`]($bindable) rune. + +## Type safety + +You can add type safety to your components by annotating your props, as you would with any other variable declaration. In TypeScript that might look like this... + +```svelte + +``` + +...while in JSDoc you can do this: + +```svelte + +``` + +You can, of course, separate the type declaration from the annotation: + +```svelte + +``` + +> [!NOTE] Interfaces for native DOM elements are provided in the `svelte/elements` module (see [Typing wrapper components](typescript#Typing-wrapper-components)) + +Adding types is recommended, as it ensures that people using your component can easily discover which props they should provide. + + +## `$props.id()` + +This rune, added in version 5.20.0, generates an ID that is unique to the current component instance. When hydrating a server-rendered component, the value will be consistent between server and client. + +This is useful for linking elements via attributes like `for` and `aria-labelledby`. + +```svelte + + +
+ + + + + +
+``` diff --git a/documentation/docs/02-runes/06-$bindable.md b/documentation/docs/02-runes/06-$bindable.md new file mode 100644 index 000000000000..c12c2bf4903e --- /dev/null +++ b/documentation/docs/02-runes/06-$bindable.md @@ -0,0 +1,54 @@ +--- +title: $bindable +--- + +Ordinarily, props go one way, from parent to child. This makes it easy to understand how data flows around your app. + +In Svelte, component props can be _bound_, which means that data can also flow _up_ from child to parent. This isn't something you should do often, but it can simplify your code if used sparingly and carefully. + +It also means that a state proxy can be _mutated_ in the child. + +> [!NOTE] Mutation is also possible with normal props, but is strongly discouraged — Svelte will warn you if it detects that a component is mutating state it does not 'own'. + +To mark a prop as bindable, we use the `$bindable` rune: + + +```svelte +/// file: FancyInput.svelte + + + + + +``` + +Now, a component that uses `` can add the [`bind:`](bind) directive ([demo](/playground/untitled#H4sIAAAAAAAAE3WQwWrDMBBEf2URBSfg2nfFMZRCoYeecqx6UJx1IyqvhLUONcb_XqSkTUOSk1az7DBvJtEai0HI90nw6FHIJIhckO7i78n7IhzQctS2OuAtvXHESByEFFVoeuO5VqTYdN71DC-amvGV_MDQ9q6DrCjP0skkWymKJxYZOgxBfyKs4SGwZlxke7TWZcuVoqo8-1P1z3lraCcP2g64nk4GM5S1osrXf0JV-lrkgvGbheR-wDm_g30V8JL-1vpOCZFogpQsEsWcemtxscyhKArfOx9gjps0Lq4hzRVfemaYfu-PoIqqwKPFY_XpaIqj4tYRP7a6M3aUkD27zjSw0RTgbZN6Z8WNs66XsEP03tBXUueUJFlelvYx_wCuI3leNwIAAA==)): + + +```svelte +/// file: App.svelte + + + +

{message}

+``` + +The parent component doesn't _have_ to use `bind:` — it can just pass a normal prop. Some parents don't want to listen to what their children have to say. + +In this case, you can specify a fallback value for when no prop is passed at all: + +```js +/// file: FancyInput.svelte +let { value = $bindable('fallback'), ...props } = $props(); +``` diff --git a/documentation/docs/02-runes/07-$inspect.md b/documentation/docs/02-runes/07-$inspect.md new file mode 100644 index 000000000000..ff3d64757b6b --- /dev/null +++ b/documentation/docs/02-runes/07-$inspect.md @@ -0,0 +1,61 @@ +--- +title: $inspect +--- + +> [!NOTE] `$inspect` only works during development. In a production build it becomes a noop. + +The `$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)): + +```svelte + + + + +``` + +## $inspect(...).with + +`$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)): + +```svelte + + + +``` + +A convenient way to find the origin of some change is to pass `console.trace` to `with`: + +```js +// @errors: 2304 +$inspect(stuff).with(console.trace); +``` + +## $inspect.trace(...) + +This 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. + +```svelte + +``` + +`$inspect.trace` takes an optional first argument which will be used as the label. diff --git a/documentation/docs/02-runes/08-$host.md b/documentation/docs/02-runes/08-$host.md new file mode 100644 index 000000000000..ba6f0a5b5b40 --- /dev/null +++ b/documentation/docs/02-runes/08-$host.md @@ -0,0 +1,37 @@ +--- +title: $host +--- + +When compiling a component as a [custom element](custom-elements), the `$host` rune provides access to the host element, allowing you to (for example) dispatch custom events ([demo](/playground/untitled#H4sIAAAAAAAAE41Ry2rDMBD8FSECtqkTt1fHFpSSL-ix7sFRNkTEXglrnTYY_3uRlDgxTaEHIfYxs7szA9-rBizPPwZOZwM89wmecqxbF70as7InaMjltrWFR3mpkQDJ8pwXVnbKkKiwItUa3RGLVtk7gTHQXRDR2lXda4CY1D0SK9nCUk0QPyfrCovsRoNFe17aQOAwGncgO2gBqRzihJXiQrEs2csYOhQ-7HgKHaLIbpRhhBG-I2eD_8ciM4KnnOCbeE5dD2P6h0Dz0-Yi_arNhPLJXBtSGi2TvSXdbpqwdsXvjuYsC1veabvvUTog2ylrapKH2G2XsMFLS4uDthQnq2t1cwKkGOGLvYU5PvaQxLsxOkPmsm97Io1Mo2yUPF6VnOZFkw1RMoopKLKAE_9gmGxyDFMwMcwN-Bx_ABXQWmOtAgAA)): + + +```svelte +/// file: Stepper.svelte + + + + + + +``` + + +```svelte +/// file: App.svelte + + + count -= 1} + onincrement={() => count += 1} +> + +

count: {count}

+``` diff --git a/documentation/docs/02-runes/index.md b/documentation/docs/02-runes/index.md new file mode 100644 index 000000000000..8ade901351fb --- /dev/null +++ b/documentation/docs/02-runes/index.md @@ -0,0 +1,3 @@ +--- +title: Runes +--- diff --git a/documentation/docs/03-template-syntax/01-basic-markup.md b/documentation/docs/03-template-syntax/01-basic-markup.md new file mode 100644 index 000000000000..fe5f8b02aae0 --- /dev/null +++ b/documentation/docs/03-template-syntax/01-basic-markup.md @@ -0,0 +1,215 @@ +--- +title: Basic markup +--- + +Markup inside a Svelte component can be thought of as HTML++. + +## Tags + +A lowercase tag, like `
`, denotes a regular HTML element. A capitalised tag or a tag that uses dot notation, such as `` or ``, indicates a _component_. + +```svelte + + +
+ +
+``` + +## Element attributes + +By default, attributes work exactly like their HTML counterparts. + +```svelte +
+ +
+``` + +As in HTML, values may be unquoted. + + +```svelte + +``` + +Attribute values can contain JavaScript expressions. + +```svelte +page {p} +``` + +Or they can _be_ JavaScript expressions. + +```svelte + +``` + +Boolean attributes are included on the element if their value is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) and excluded if it's [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy). + +All other attributes are included unless their value is [nullish](https://developer.mozilla.org/en-US/docs/Glossary/Nullish) (`null` or `undefined`). + +```svelte + +
This div has no title attribute
+``` + +> [!NOTE] Quoting a singular expression does not affect how the value is parsed, but in Svelte 6 it will cause the value to be coerced to a string: +> +> +> ```svelte +> +> ``` + +When the attribute name and value match (`name={name}`), they can be replaced with `{name}`. + +```svelte + + +``` + +## Component props + +By convention, values passed to components are referred to as _properties_ or _props_ rather than _attributes_, which are a feature of the DOM. + +As with elements, `name={name}` can be replaced with the `{name}` shorthand. + +```svelte + +``` + +_Spread attributes_ allow many attributes or properties to be passed to an element or component at once. + +An element or component can have multiple spread attributes, interspersed with regular ones. + +```svelte + +``` + +## Events + +Listening to DOM events is possible by adding attributes to the element that start with `on`. For example, to listen to the `click` event, add the `onclick` attribute to a button: + +```svelte + +``` + +Event attributes are case sensitive. `onclick` listens to the `click` event, `onClick` listens to the `Click` event, which is different. This ensures you can listen to custom events that have uppercase characters in them. + +Because events are just attributes, the same rules as for attributes apply: + +- you can use the shorthand form: `` +- you can spread them: `` + +Timing-wise, event attributes always fire after events from bindings (e.g. `oninput` always fires after an update to `bind:value`). Under the hood, some event handlers are attached directly with `addEventListener`, while others are _delegated_. + +When using `ontouchstart` and `ontouchmove` event attributes, the handlers are [passive](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#using_passive_listeners) for better performance. This greatly improves responsiveness by allowing the browser to scroll the document immediately, rather than waiting to see if the event handler calls `event.preventDefault()`. + +In the very rare cases that you need to prevent these event defaults, you should use [`on`](svelte-events#on) instead (for example inside an action). + +### Event delegation + +To reduce memory footprint and increase performance, Svelte uses a technique called event delegation. This means that for certain events — see the list below — a single event listener at the application root takes responsibility for running any handlers on the event's path. + +There are a few gotchas to be aware of: + +- when you manually dispatch an event with a delegated listener, make sure to set the `{ bubbles: true }` option or it won't reach the application root +- when using `addEventListener` directly, avoid calling `stopPropagation` or the event won't reach the application root and handlers won't be invoked. Similarly, handlers added manually inside the application root will run _before_ handlers added declaratively deeper in the DOM (with e.g. `onclick={...}`), in both capturing and bubbling phases. For these reasons it's better to use the `on` function imported from `svelte/events` rather than `addEventListener`, as it will ensure that order is preserved and `stopPropagation` is handled correctly. + +The following event handlers are delegated: + +- `beforeinput` +- `click` +- `change` +- `dblclick` +- `contextmenu` +- `focusin` +- `focusout` +- `input` +- `keydown` +- `keyup` +- `mousedown` +- `mousemove` +- `mouseout` +- `mouseover` +- `mouseup` +- `pointerdown` +- `pointermove` +- `pointerout` +- `pointerover` +- `pointerup` +- `touchend` +- `touchmove` +- `touchstart` + +## Text expressions + +A JavaScript expression can be included as text by surrounding it with curly braces. + +```svelte +{expression} +``` + +Expressions that are `null` or `undefined` will be omitted; all others are [coerced to strings](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). + +Curly braces can be included in a Svelte template by using their [HTML entity](https://developer.mozilla.org/docs/Glossary/Entity) strings: `{`, `{`, or `{` for `{` and `}`, `}`, or `}` for `}`. + +If you're using a regular expression (`RegExp`) [literal notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#literal_notation_and_constructor), you'll need to wrap it in parentheses. + + +```svelte +

Hello {name}!

+

{a} + {b} = {a + b}.

+ +
{(/^[A-Za-z ]+$/).test(value) ? x : y}
+``` + +The expression will be stringified and escaped to prevent code injections. If you want to render HTML, use the `{@html}` tag instead. + +```svelte +{@html potentiallyUnsafeHtmlString} +``` + +> [!NOTE] Make sure that you either escape the passed string or only populate it with values that are under your control in order to prevent [XSS attacks](https://owasp.org/www-community/attacks/xss/) + +## Comments + +You can use HTML comments inside components. + +```svelte +

Hello world

+``` + +Comments beginning with `svelte-ignore` disable warnings for the next block of markup. Usually, these are accessibility warnings; make sure that you're disabling them for a good reason. + +```svelte + + +``` + +You can add a special comment starting with `@component` that will show up when hovering over the component name in other files. + +````svelte + + + +
+

+ Hello, {name} +

+
+```` diff --git a/documentation/docs/03-template-syntax/02-if.md b/documentation/docs/03-template-syntax/02-if.md new file mode 100644 index 000000000000..1378733e6f29 --- /dev/null +++ b/documentation/docs/03-template-syntax/02-if.md @@ -0,0 +1,40 @@ +--- +title: {#if ...} +--- + +```svelte + +{#if expression}...{/if} +``` + +```svelte + +{#if expression}...{:else if expression}...{/if} +``` + +```svelte + +{#if expression}...{:else}...{/if} +``` + +Content that is conditionally rendered can be wrapped in an if block. + +```svelte +{#if answer === 42} +

what was the question?

+{/if} +``` + +Additional conditions can be added with `{:else if expression}`, optionally ending in an `{:else}` clause. + +```svelte +{#if porridge.temperature > 100} +

too hot!

+{:else if 80 > porridge.temperature} +

too cold!

+{:else} +

just right!

+{/if} +``` + +(Blocks don't have to wrap elements, they can also wrap text within elements.) diff --git a/documentation/docs/03-template-syntax/03-each.md b/documentation/docs/03-template-syntax/03-each.md new file mode 100644 index 000000000000..70666f6a5798 --- /dev/null +++ b/documentation/docs/03-template-syntax/03-each.md @@ -0,0 +1,114 @@ +--- +title: {#each ...} +--- + +```svelte + +{#each expression as name}...{/each} +``` + +```svelte + +{#each expression as name, index}...{/each} +``` + +Iterating over values can be done with an each block. The values in question can be arrays, array-like objects (i.e. anything with a `length` property), or iterables like `Map` and `Set` — in other words, anything that can be used with `Array.from`. + +```svelte +

Shopping list

+
    + {#each items as item} +
  • {item.name} x {item.qty}
  • + {/each} +
+``` + +An each block can also specify an _index_, equivalent to the second argument in an `array.map(...)` callback: + +```svelte +{#each items as item, i} +
  • {i + 1}: {item.name} x {item.qty}
  • +{/each} +``` + +## Keyed each blocks + +```svelte + +{#each expression as name (key)}...{/each} +``` + +```svelte + +{#each expression as name, index (key)}...{/each} +``` + +If a _key_ expression is provided — which must uniquely identify each list item — Svelte will use it to diff the list when data changes, rather than adding or removing items at the end. The key can be any object, but strings and numbers are recommended since they allow identity to persist when the objects themselves change. + +```svelte +{#each items as item (item.id)} +
  • {item.name} x {item.qty}
  • +{/each} + + +{#each items as item, i (item.id)} +
  • {i + 1}: {item.name} x {item.qty}
  • +{/each} +``` + +You can freely use destructuring and rest patterns in each blocks. + +```svelte +{#each items as { id, name, qty }, i (id)} +
  • {i + 1}: {name} x {qty}
  • +{/each} + +{#each objects as { id, ...rest }} +
  • {id}
  • +{/each} + +{#each items as [id, ...rest]} +
  • {id}
  • +{/each} +``` + +## Each blocks without an item + +```svelte + +{#each expression}...{/each} +``` + +```svelte + +{#each expression, index}...{/each} +``` + +In case you just want to render something `n` times, you can omit the `as` part ([demo](/playground/untitled#H4sIAAAAAAAAE3WR0W7CMAxFf8XKNAk0WsSeUEaRpn3Guoc0MbQiJFHiMlDVf18SOrZJ48259_jaVgZmxBEZZ28thgCNFV6xBdt1GgPj7wOji0t2EqI-wa_OleGEmpLWiID_6dIaQkMxhm1UdwKpRQhVzWSaVORJNdvWpqbhAYVsYQCNZk8thzWMC_DCHMZk3wPSThNQ088I3mghD9UwSwHwlLE5PMIzVFUFq3G7WUZ2OyUvU3JOuZU332wCXTRmtPy1NgzXZtUFp8WFw9536uWqpbIgPEaDsJBW90cTOHh0KGi2XsBq5-cT6-3nPauxXqHnsHJnCFZ3CvJVkyuCQ0mFF9TZyCQ162WGvteLKfG197Y3iv_pz_fmS68Hxt8iPBPj5HscP8YvCNX7uhYCAAA=)): + +```svelte +
    + {#each { length: 8 }, rank} + {#each { length: 8 }, file} +
    + {/each} + {/each} +
    +``` + +## Else blocks + +```svelte + +{#each expression as name}...{:else}...{/each} +``` + +An each block can also have an `{:else}` clause, which is rendered if the list is empty. + +```svelte +{#each todos as todo} +

    {todo.text}

    +{:else} +

    No tasks today!

    +{/each} +``` diff --git a/documentation/docs/03-template-syntax/04-key.md b/documentation/docs/03-template-syntax/04-key.md new file mode 100644 index 000000000000..10b6ab435824 --- /dev/null +++ b/documentation/docs/03-template-syntax/04-key.md @@ -0,0 +1,24 @@ +--- +title: {#key ...} +--- + +```svelte + +{#key expression}...{/key} +``` + +Key blocks destroy and recreate their contents when the value of an expression changes. When used around components, this will cause them to be reinstantiated and reinitialised: + +```svelte +{#key value} + +{/key} +``` + +It's also useful if you want a transition to play whenever a value changes: + +```svelte +{#key value} +
    {value}
    +{/key} +``` diff --git a/documentation/docs/03-template-syntax/05-await.md b/documentation/docs/03-template-syntax/05-await.md new file mode 100644 index 000000000000..842b3c7e325d --- /dev/null +++ b/documentation/docs/03-template-syntax/05-await.md @@ -0,0 +1,79 @@ +--- +title: {#await ...} +--- + +```svelte + +{#await expression}...{:then name}...{:catch name}...{/await} +``` + +```svelte + +{#await expression}...{:then name}...{/await} +``` + +```svelte + +{#await expression then name}...{/await} +``` + +```svelte + +{#await expression catch name}...{/await} +``` + +Await blocks allow you to branch on the three possible states of a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) — pending, fulfilled or rejected. + +```svelte +{#await promise} + +

    waiting for the promise to resolve...

    +{:then value} + +

    The value is {value}

    +{:catch error} + +

    Something went wrong: {error.message}

    +{/await} +``` + +> [!NOTE] During server-side rendering, only the pending branch will be rendered. +> +> If the provided expression is not a `Promise`, only the `:then` branch will be rendered, including during server-side rendering. + +The `catch` block can be omitted if you don't need to render anything when the promise rejects (or no error is possible). + +```svelte +{#await promise} + +

    waiting for the promise to resolve...

    +{:then value} + +

    The value is {value}

    +{/await} +``` + +If you don't care about the pending state, you can also omit the initial block. + +```svelte +{#await promise then value} +

    The value is {value}

    +{/await} +``` + +Similarly, if you only want to show the error state, you can omit the `then` block. + +```svelte +{#await promise catch error} +

    The error is {error}

    +{/await} +``` + +> [!NOTE] You can use `#await` with [`import(...)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) to render components lazily: +> +> ```svelte +> {#await import('./Component.svelte') then { default: Component }} +> +> {/await} +> ``` + diff --git a/documentation/docs/03-template-syntax/06-snippet.md b/documentation/docs/03-template-syntax/06-snippet.md new file mode 100644 index 000000000000..ab536c6e5ced --- /dev/null +++ b/documentation/docs/03-template-syntax/06-snippet.md @@ -0,0 +1,280 @@ +--- +title: {#snippet ...} +--- + +```svelte + +{#snippet name()}...{/snippet} +``` + +```svelte + +{#snippet name(param1, param2, paramN)}...{/snippet} +``` + +Snippets, and [render tags](@render), are a way to create reusable chunks of markup inside your components. Instead of writing duplicative code like [this](/playground/untitled#H4sIAAAAAAAAE5VUYW-kIBD9K8Tmsm2yXXRzvQ-s3eR-R-0HqqOQKhAZb9sz_vdDkV1t000vRmHewMx7w2AflbIGG7GnPlK8gYhFv42JthG-m9Gwf6BGcLbVXZuPSGrzVho8ZirDGpDIhldgySN5GpEMez9kaNuckY1ANJZRamRuu2ZnhEZt6a84pvs43mzD4pMsUDDi8DMkQFYCGdkvsJwblFq5uCik9bmJ4JZwUkv1eoknWigX2eGNN6aGXa6bjV8ybP-X7sM36T58SVcrIIV2xVIaA41xeD5kKqWXuqpUJEefOqVuOkL9DfBchGrzWfu0vb-RpTd3o-zBR045Ga3HfuE5BmJpKauuhbPtENlUF2sqR9jqpsPSxWsMrlngyj3VJiyYjJXb1-lMa7IWC-iSk2M5Zzh-SJjShe-siq5kpZRPs55BbSGU5YPyte4vVV_VfFXxVb10dSLf17pS2lM5HnpPxw4Zpv6x-F57p0jI3OKlVnhv5V9wPQrNYQQ9D_f6aGHlC89fq1Z3qmDkJCTCweOGF4VUFSPJvD_DhreVdA0eu8ehJJ5x91dBaBkpWm3ureCFPt3uzRv56d4kdp-2euG38XZ6dsnd3ZmPG9yRBCrzRUvi-MccOdwz3qE-fOZ7AwAhlrtTUx3c76vRhSwlFBHDtoPhefgHX3dM0PkEAAA=)... + +```svelte +{#each images as image} + {#if image.href} + +
    + {image.caption} +
    {image.caption}
    +
    +
    + {:else} +
    + {image.caption} +
    {image.caption}
    +
    + {/if} +{/each} +``` + +...you can write [this](/playground/untitled#H4sIAAAAAAAAE5VUYW-bMBD9KxbRlERKY4jWfSA02n5H6QcXDmwVbMs-lnaI_z6D7TTt1moTAnPvzvfenQ_GpBEd2CS_HxPJekjy5IfWyS7BFz0b9id0CM62ajDVjBS2MkLjqZQldoBE9KwFS-7I_YyUOPqlRGuqnKw5orY5pVpUduj3mitUln5LU3pI0_UuBp9FjTwnDr9AHETLMSeHK6xiGoWSLi9yYT034cwSRjohn17zcQPNFTs8s153sK9Uv_Yh0-5_5d7-o9zbD-UqCaRWrllSYZQxLw_HUhb0ta-y4NnJUxfUvc7QuLJSaO0a3oh2MLBZat8u-wsPnXzKQvTtVVF34xK5d69ThFmHEQ4SpzeVRediTG8rjD5vBSeN3E5JyHh6R1DQK9-iml5kjzQUN_lSgVU8DhYLx7wwjSvRkMDvTjiwF4zM1kXZ7DlF1eN3A7IG85e-zRrYEjjm0FkI4Cc7Ripm0pHOChexhcWXzreeZyRMU6Mk3ljxC9w4QH-cQZ_b3T5pjHxk1VNr1CDrnJy5QDh6XLO6FrLNSRb2l9gz0wo3S6m7HErSgLsPGMHkpDZK31jOanXeHPQz-eruLHUP0z6yTbpbrn223V70uMXNSpQSZjpL0y8hcxxpNqA6_ql3BQAxlxvfpQ_uT9GrWjQC6iRHM8D0MP0GQsIi92QEAAA=): + +```svelte +{#snippet figure(image)} +
    + {image.caption} +
    {image.caption}
    +
    +{/snippet} + +{#each images as image} + {#if image.href} + + {@render figure(image)} + + {:else} + {@render figure(image)} + {/if} +{/each} +``` + +Like function declarations, snippets can have an arbitrary number of parameters, which can have default values, and you can destructure each parameter. You cannot use rest parameters, however. + +## Snippet scope + +Snippets can be declared anywhere inside your component. They can reference values declared outside themselves, for example in the ` + +{#snippet hello(name)} +

    hello {name}! {message}!

    +{/snippet} + +{@render hello('alice')} +{@render hello('bob')} +``` + +...and they are 'visible' to everything in the same lexical scope (i.e. siblings, and children of those siblings): + +```svelte +
    + {#snippet x()} + {#snippet y()}...{/snippet} + + + {@render y()} + {/snippet} + + + {@render y()} +
    + + +{@render x()} +``` + +Snippets can reference themselves and each other ([demo](/playground/untitled#H4sIAAAAAAAAE2WPTQqDMBCFrxLiRqH1Zysi7TlqF1YnENBJSGJLCYGeo5tesUeosfYH3c2bee_jjaWMd6BpfrAU6x5oTvdS0g01V-mFPkNnYNRaDKrxGxto5FKCIaeu1kYwFkauwsoUWtZYPh_3W5FMY4U2mb3egL9kIwY0rbhgiO-sDTgjSEqSTvIDs-jiOP7i_MHuFGAL6p9BtiSbOTl0GtzCuihqE87cqtyam6WRGz_vRcsZh5bmRg3gju4Fptq_kzQBAAA=)): + +```svelte +{#snippet blastoff()} + 🚀 +{/snippet} + +{#snippet countdown(n)} + {#if n > 0} + {n}... + {@render countdown(n - 1)} + {:else} + {@render blastoff()} + {/if} +{/snippet} + +{@render countdown(10)} +``` + +## Passing snippets to components + +### Explicit props + +Within the template, snippets are values just like any other. As such, they can be passed to components as props ([demo](/playground/untitled#H4sIAAAAAAAAE3VS247aMBD9lZGpBGwDASRegonaPvQL2qdlH5zYEKvBNvbQLbL875VzAcKyj3PmzJnLGU8UOwqSkd8KJdaCk4TsZS0cyV49wYuJuQiQpGd-N2bu_ooaI1YwJ57hpVYoFDqSEepKKw3mO7VDeTTaIvxiRS1gb_URxvO0ibrS8WanIrHUyiHs7Vmigy28RmyHHmKvDMbMmFq4cQInvGSwTsBYWYoMVhCSB2rBFFPsyl0uruTlR3JZCWvlTXl1Yy_mawiR_rbZKZrellJ-5JQ0RiBUgnFhJ9OGR7HKmwVoilXeIye8DOJGfYCgRlZ3iE876TBsZPX7hPdteO75PC4QaIo8vwNPePmANQ2fMeEFHrLD7rR1jTNkW986E8C3KwfwVr8HSHOSEBT_kGRozyIkn_zQveXDL3rIfPJHtUDwzShJd_Qk3gQCbOGLsdq4yfTRJopRuin3I7nv6kL7ARRjmLdBDG3uv1mhuLA3V2mKtqNEf_oCn8p9aN-WYqH5peP4kWBl1UwJzAEPT9U7K--0fRrrWnPTXpCm1_EVdXjpNmlA8G1hPPyM1fKgMqjFHjctXGjLhZ05w0qpDhksGrybuNEHtJnCalZWsuaTlfq6nPaaBSv_HKw-K57BjzOiVj9ZKQYKzQjZodYFqydYTRN4gPhVzTDO2xnma3HsVWjaLjT8nbfwHy7Q5f2dBAAA)): + +```svelte + + +{#snippet header()} + fruit + qty + price + total +{/snippet} + +{#snippet row(d)} + {d.name} + {d.qty} + {d.price} + {d.qty * d.price} +{/snippet} + + +``` + +Think about it like passing content instead of data to a component. The concept is similar to slots in web components. + +### Implicit props + +As an authoring convenience, snippets declared directly _inside_ a component implicitly become props _on_ the component ([demo](/playground/untitled#H4sIAAAAAAAAE3VSTa_aMBD8Kyu_SkAbCA-JSzBR20N_QXt6vIMTO8SqsY29tI2s_PcqTiB8vaPHs7MzuxuIZgdBMvJLo0QlOElIJZXwJHsLBBvb_XUASc7Mb9Yu_B-hsMMK5sUzvDQahUZPMkJ96aTFfKd3KA_WOISfrFACKmcOMFmk8TWUTjY73RFLoz1C5U4SPWzhrcN2GKDrlcGEWauEnyRwxCaDdQLWyVJksII2uaMWTDPNLtzX5YX8-kgua-GcHJVXI3u5WEPb0d83O03TMZSmfRzOkG1Db7mNacOL19JagVALxoWbztq-H8U6j0SaYp2P2BGbOyQ2v8PQIFMXLKRDk177pq0zf6d8bMrzwBdd0pamyPMb-IjNEzS2f86Gz_Dwf-2F9nvNSUJQ_EOSoTuJNvngqK5v4Pas7n4-OCwlEEJcQTIMO-nSQwtb-GSdsX46e9gbRoP9yGQ11I0rEuycunu6PHx1QnPhxm3SFN15MOlYEFJZtf0dUywMbwZOeBGsrKNLYB54-1R9WNqVdki7usim6VmQphf7mnpshiQRhNAXdoOfMyX3OgMlKtz0cGEcF27uLSul3mewjPjgOOoDukxjPS9rqfh0pb-8zs6aBSt_7505aZ7B9xOi0T9YKW4UooVsr0zB1BTrWQJ3EL-oWcZ572GxFoezCk37QLe3897-B2i2U62uBAAA)): + +```svelte + +
    + {#snippet header()} + + + + + {/snippet} + + {#snippet row(d)} + + + + + {/snippet} +
    fruitqtypricetotal{d.name}{d.qty}{d.price}{d.qty * d.price}
    +``` + +### Implicit `children` snippet + +Any content inside the component tags that is _not_ a snippet declaration implicitly becomes part of the `children` snippet ([demo](/playground/untitled#H4sIAAAAAAAAE3WOQQrCMBBFrzIMggql3ddY1Du4si5sOmIwnYRkFKX07lKqglqX8_7_w2uRDw1hjlsWI5ZqTPBoLEXMdy3K3fdZDzB5Ndfep_FKVnpWHSKNce1YiCVijirqYLwUJQOYxrsgsLmIOIZjcA1M02w4n-PpomSVvTclqyEutDX6DA2pZ7_ABIVugrmEC3XJH92P55_G39GodCmWBFrQJ2PrQAwdLGHig_NxNv9xrQa1dhWIawrv1Wzeqawa8953D-8QOmaEAQAA)): + +```svelte + + +``` + +```svelte + + + + + +``` + +> [!NOTE] Note that you cannot have a prop called `children` if you also have content inside the component — for this reason, you should avoid having props with that name + +### Optional snippet props + +You can declare snippet props as being optional. You can either use optional chaining to not render anything if the snippet isn't set... + +```svelte + + +{@render children?.()} +``` + +...or use an `#if` block to render fallback content: + +```svelte + + +{#if children} + {@render children()} +{:else} + fallback content +{/if} +``` + +## Typing snippets + +Snippets implement the `Snippet` interface imported from `'svelte'`: + +```svelte + +``` + +With this change, red squigglies will appear if you try and use the component without providing a `data` prop and a `row` snippet. Notice that the type argument provided to `Snippet` is a tuple, since snippets can have multiple parameters. + +We can tighten things up further by declaring a generic, so that `data` and `row` refer to the same type: + +```svelte + +``` + +## Exporting snippets + +Snippets declared at the top level of a `.svelte` file can be exported from a ` + +{#snippet add(a, b)} + {a} + {b} = {a + b} +{/snippet} +``` + +> [!NOTE] +> This requires Svelte 5.5.0 or newer + +## Programmatic snippets + +Snippets can be created programmatically with the [`createRawSnippet`](svelte#createRawSnippet) API. This is intended for advanced use cases. + +## Snippets and slots + +In Svelte 4, content can be passed to components using [slots](legacy-slots). Snippets are more powerful and flexible, and as such slots are deprecated in Svelte 5. diff --git a/documentation/docs/03-template-syntax/07-@render.md b/documentation/docs/03-template-syntax/07-@render.md new file mode 100644 index 000000000000..ecdf5cc216fc --- /dev/null +++ b/documentation/docs/03-template-syntax/07-@render.md @@ -0,0 +1,39 @@ +--- +title: {@render ...} +--- + +To render a [snippet](snippet), use a `{@render ...}` tag. + +```svelte +{#snippet sum(a, b)} +

    {a} + {b} = {a + b}

    +{/snippet} + +{@render sum(1, 2)} +{@render sum(3, 4)} +{@render sum(5, 6)} +``` + +The expression can be an identifier like `sum`, or an arbitrary JavaScript expression: + +```svelte +{@render (cool ? coolSnippet : lameSnippet)()} +``` + +## Optional snippets + +If the snippet is potentially undefined — for example, because it's an incoming prop — then you can use optional chaining to only render it when it _is_ defined: + +```svelte +{@render children?.()} +``` + +Alternatively, use an [`{#if ...}`](if) block with an `:else` clause to render fallback content: + +```svelte +{#if children} + {@render children()} +{:else} +

    fallback content

    +{/if} +``` diff --git a/documentation/docs/03-template-syntax/08-@html.md b/documentation/docs/03-template-syntax/08-@html.md new file mode 100644 index 000000000000..30456fa666eb --- /dev/null +++ b/documentation/docs/03-template-syntax/08-@html.md @@ -0,0 +1,51 @@ +--- +title: {@html ...} +--- + +To inject raw HTML into your component, use the `{@html ...}` tag: + +```svelte +
    + {@html content} +
    +``` + +> [!NOTE] Make sure that you either escape the passed string or only populate it with values that are under your control in order to prevent [XSS attacks](https://owasp.org/www-community/attacks/xss/). Never render unsanitized content. + +The expression should be valid standalone HTML — this will not work, because `
    ` is not valid HTML: + +```svelte +{@html '
    '}content{@html '
    '} +``` + +It also will not compile Svelte code. + +## Styling + +Content rendered this way is 'invisible' to Svelte and as such will not receive [scoped styles](scoped-styles) — in other words, this will not work, and the `a` and `img` styles will be regarded as unused: + + +```svelte +
    + {@html content} +
    + + +``` + +Instead, use the `:global` modifier to target everything inside the `
    `: + + +```svelte + +``` diff --git a/documentation/docs/03-template-syntax/09-@const.md b/documentation/docs/03-template-syntax/09-@const.md new file mode 100644 index 000000000000..2a587b7a3d7c --- /dev/null +++ b/documentation/docs/03-template-syntax/09-@const.md @@ -0,0 +1,14 @@ +--- +title: {@const ...} +--- + +The `{@const ...}` tag defines a local constant. + +```svelte +{#each boxes as box} + {@const area = box.width * box.height} + {box.width} * {box.height} = {area} +{/each} +``` + +`{@const}` is only allowed as an immediate child of a block — `{#if ...}`, `{#each ...}`, `{#snippet ...}` and so on — a `` or a ``. diff --git a/documentation/docs/03-template-syntax/10-@debug.md b/documentation/docs/03-template-syntax/10-@debug.md new file mode 100644 index 000000000000..15e32dcae99f --- /dev/null +++ b/documentation/docs/03-template-syntax/10-@debug.md @@ -0,0 +1,35 @@ +--- +title: {@debug ...} +--- + +The `{@debug ...}` tag offers an alternative to `console.log(...)`. It logs the values of specific variables whenever they change, and pauses code execution if you have devtools open. + +```svelte + + +{@debug user} + +

    Hello {user.firstname}!

    +``` + +`{@debug ...}` accepts a comma-separated list of variable names (not arbitrary expressions). + +```svelte + +{@debug user} +{@debug user1, user2, user3} + + +{@debug user.firstname} +{@debug myArray[0]} +{@debug !isReady} +{@debug typeof user === 'object'} +``` + +The `{@debug}` tag without any arguments will insert a `debugger` statement that gets triggered when _any_ state changes, as opposed to the specified variables. + diff --git a/documentation/docs/03-template-syntax/11-bind.md b/documentation/docs/03-template-syntax/11-bind.md new file mode 100644 index 000000000000..c23f3b52327c --- /dev/null +++ b/documentation/docs/03-template-syntax/11-bind.md @@ -0,0 +1,364 @@ +--- +title: bind: +--- + +Data ordinarily flows down, from parent to child. The `bind:` directive allows data to flow the other way, from child to parent. + +The general syntax is `bind:property={expression}`, where `expression` is an _lvalue_ (i.e. a variable or an object property). When the expression is an identifier with the same name as the property, we can omit the expression — in other words these are equivalent: + + +```svelte + + +``` + + +Svelte creates an event listener that updates the bound value. If an element already has a listener for the same event, that listener will be fired before the bound value is updated. + +Most bindings are _two-way_, meaning that changes to the value will affect the element and vice versa. A few bindings are _readonly_, meaning that changing their value will have no effect on the element. + +## Function bindings + +You can also use `bind:property={get, set}`, where `get` and `set` are functions, allowing you to perform validation and transformation: + +```svelte + value, + (v) => value = v.toLowerCase()} +/> +``` + +In the case of readonly bindings like [dimension bindings](#Dimensions), the `get` value should be `null`: + +```svelte +
    ...
    +``` + +> [!NOTE] +> Function bindings are available in Svelte 5.9.0 and newer. + +## `` + +A `bind:value` directive on an `` element binds the input's `value` property: + + +```svelte + + + +

    {message}

    +``` + +In the case of a numeric input (`type="number"` or `type="range"`), the value will be coerced to a number ([demo](/playground/untitled#H4sIAAAAAAAAE6WPwYoCMQxAfyWEPeyiOOqx2w74Hds9pBql0IllmhGXYf5dKqwiyILsLXnwwsuI-5i4oPkaUX8yo7kCnKNQV7dNzoty4qSVBSr8jG-Poixa0KAt2z5mbb14TaxA4OCtKCm_rz4-f2m403WltrlrYhMFTtcLNkoeFGqZ8yhDF7j3CCHKzpwoDexGmqCL4jwuPUJHZ-dxVcfmyYGe5MAv-La5pbxYFf5Z9Zf_UJXb-sEMquFgJJhBmGyTW5yj8lnRaD_w9D1dAKSSj7zqAQAA)): + +```svelte + + + + + + +

    {a} + {b} = {a + b}

    +``` + +If the input is empty or invalid (in the case of `type="number"`), the value is `undefined`. + +Since 5.6.0, if an `` has a `defaultValue` and is part of a form, it will revert to that value instead of the empty string when the form is reset. Note that for the initial render the value of the binding takes precedence unless it is `null` or `undefined`. + +```svelte + + +
    + + +
    +``` + +> [!NOTE] +> Use reset buttons sparingly, and ensure that users won't accidentally click them while trying to submit the form. + +## `` + +Checkbox and radio inputs can be bound with `bind:checked`: + +```svelte + +``` + +Since 5.6.0, if an `` has a `defaultChecked` attribute and is part of a form, it will revert to that value instead of `false` when the form is reset. Note that for the initial render the value of the binding takes precedence unless it is `null` or `undefined`. + +```svelte + + +
    + + +
    +``` + +## `` + +Inputs that work together can use `bind:group`. + +```svelte + + + + + + + + + + + + +``` + +> [!NOTE] `bind:group` only works if the inputs are in the same Svelte component. + +## `` + +On `` elements with `type="file"`, you can use `bind:files` to get the [`FileList` of selected files](https://developer.mozilla.org/en-US/docs/Web/API/FileList). When you want to update the files programmatically, you always need to use a `FileList` object. Currently `FileList` objects cannot be constructed directly, so you need to create a new [`DataTransfer`](https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer) object and get `files` from there. + +```svelte + + + + + +``` + +`FileList` objects also cannot be modified, so if you want to e.g. delete a single file from the list, you need to create a new `DataTransfer` object and add the files you want to keep. + +> [!NOTE] `DataTransfer` may not be available in server-side JS runtimes. Leaving the state that is bound to `files` uninitialized prevents potential errors if components are server-side rendered. + +## `` value binding corresponds to the `value` property on the selected ` + + + + +``` + +When the value of an ` + + + +``` + +## `