Skip to content

Commit

Permalink
fix: renderComponent, add renderSnippet, and some other Svelte fi…
Browse files Browse the repository at this point in the history
…x-ups (#5888)

* update render-compnent and use dynamic component instead of snippet rendering in FlexRender

* fix linting error (import order)

* added renderSnippet example

* move svelte snippet example and update svelte dependencies

* update deps

* ci: apply automated fixes

* add doc for svelte renderSnippet

* Fix typo in snippet

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
  • Loading branch information
walker-tx and autofix-ci[bot] authored Jan 27, 2025
1 parent 495f0ed commit 1661fcf
Show file tree
Hide file tree
Showing 27 changed files with 2,758 additions and 1,408 deletions.
18 changes: 16 additions & 2 deletions docs/framework/svelte/svelte-table.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,22 @@ Takes an `options` object and returns a table.
A Svelte component for rendering cell/header/footer templates with dynamic values.

FlexRender supports any type of renderable content supported by Svelte:

- Scalar data types such as numbers, strings, etc.
- Svelte components (when wrapped with `renderComponent`)
- Svelte snippets (when wrapped with `renderSnippet`)

Example:

```svelte
<script lang="ts">
import {
import {
type ColumnDef,
FlexRender,
createTable,
getCoreRowModel,
renderComponent
renderComponent,
renderSnippet
} from '@tanstack/svelte-table'
import { StatusTag } from '$lib/components/status-tag.svelte'
import type { Person } from './types'
Expand All @@ -60,6 +63,11 @@ Example:
/* Renders a Svelte component */
accessorKey: 'status',
cell: (info) => renderComponent(StatusTag, { value: info.getValue() })
},
{
/* Renders a Svelte component */
accessorKey: 'email',
cell: (info) => renderSnippet(mailtoLink, info.getValue())
}
]
Expand All @@ -70,6 +78,12 @@ Example:
})
</script>
{#snippet mailtoLink(email: string)}
<a href="mailto:{email}">
{email}
</a>
{/snippet}
<table>
<tbody>
{#each table.getRowModel().rows as row}
Expand Down
8 changes: 8 additions & 0 deletions examples/svelte/basic-snippets/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
node_modules
.DS_Store
dist
dist-ssr
*.local

src/**/*.d.ts
src/**/*.map
6 changes: 6 additions & 0 deletions examples/svelte/basic-snippets/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Example

To run this example:

- `npm install` or `yarn`
- `npm run start` or `yarn start`
14 changes: 14 additions & 0 deletions examples/svelte/basic-snippets/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
<script type="module" src="https://cdn.skypack.dev/twind/shim"></script>
</head>

<body>
<div id="root"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
23 changes: 23 additions & 0 deletions examples/svelte/basic-snippets/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "tanstack-table-example-svelte-basic-snippets",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview",
"test:types": "svelte-check --tsconfig ./tsconfig.json",
"lint": "eslint ./src"
},
"devDependencies": {
"@rollup/plugin-replace": "^6.0.1",
"@sveltejs/vite-plugin-svelte": "^4.0.4",
"@tanstack/svelte-table": "^9.0.0-alpha.10",
"@tsconfig/svelte": "^5.0.4",
"svelte": "^5.19.3",
"svelte-check": "^4.1.4",
"typescript": "5.6.3",
"vite": "^5.4.11"
}
}
152 changes: 152 additions & 0 deletions examples/svelte/basic-snippets/src/App.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
<script lang="ts">
import {
createTableHelper,
FlexRender,
renderSnippet,
} from '@tanstack/svelte-table'
import { capitalized, countup, spectrum } from './snippets.svelte'
import './index.css'
/**
* This `svelte-table` example demonstrates the following:
* - Creating a basic table with no additional features (sorting, filtering,
* grouping, etc),
* - Creating and using a `table helper`,
* - Defining columns with custom headers, cells, and footers using the table
* helper, and
* - Rendering a table with the instance APIs.
*/
// 1. Define what the shape of your data will be for each row
type Person = {
firstName: string
lastName: string
age: number
visits: number
status: string
progress: number
}
// 2. Create some dummy data with a stable reference (this could be an API
// response stored in a rune).
const data: Person[] = [
{
firstName: 'tanner',
lastName: 'linsley',
age: 24,
visits: 100,
status: 'In Relationship',
progress: 50,
},
{
firstName: 'tandy',
lastName: 'miller',
age: 40,
visits: 40,
status: 'Single',
progress: 80,
},
{
firstName: 'joe',
lastName: 'dirte',
age: 45,
visits: 20,
status: 'Complicated',
progress: 10,
},
]
// 3. New in V9! Tell the table which features and row models we want to use.
// In this case, this will be a basic table with no additional features
const tableHelper = createTableHelper({
_features: {},
// 3a. `_rowModels` defines client-side row models. `Core` row model is now
// included by default, but you can still override it here.
_rowModels: {},
// 3b. Optionally, set the `TData` type. Omit TData is this table helper
// will be used to create multiple tables with different data types.
TData: {} as Person,
})
// 4. For convenience, destructure the desired utilities from `tableHelper`
const { columnHelper, createTable } = tableHelper
// 5. Define the columns for your table with a stable reference (in this case,
// defined statically).
const columns = columnHelper.columns([
columnHelper.accessor('firstName', {
header: 'First Name',
// 5a. Use the `renderSnippet` utility to render the snippet in the cell.
cell: (info) => renderSnippet(capitalized, info.getValue()),
}),
columnHelper.accessor('lastName', {
header: 'Last Name',
cell: (info) => renderSnippet(capitalized, info.getValue()),
}),
columnHelper.accessor('age', {
header: 'Age',
cell: (info) => renderSnippet(countup, info.getValue()),
}),
columnHelper.accessor('visits', {
header: 'Visits',
cell: (info) => renderSnippet(countup, info.getValue()),
}),
columnHelper.accessor('status', {
header: 'Status',
}),
columnHelper.accessor('progress', {
header: 'Profile Progress',
cell(info) {
return renderSnippet(spectrum, {
value: info.getValue(),
min: 0,
max: 100,
})
},
}),
])
// 6. Create the table instance with columns and data. Features and row
// models are already defined in the `tableHelper` object that
// `createTable` was destructured from.
const table = createTable({
columns,
data,
})
</script>

<!-- 7. Render the table in markup using the Instance APIs. -->
<div class="p-2">
<table>
<thead>
{#each table.getHeaderGroups() as headerGroup}
<tr>
{#each headerGroup.headers as header}
<th>
{#if !header.isPlaceholder}
<FlexRender
content={header.column.columnDef.header}
context={header.getContext()}
/>
{/if}
</th>
{/each}
</tr>
{/each}
</thead>
<tbody>
{#each table.getRowModel().rows as row}
<tr>
{#each row.getAllCells() as cell}
<td>
<FlexRender
content={cell.column.columnDef.cell}
context={cell.getContext()}
/>
</td>
{/each}
</tr>
{/each}
</tbody>
</table>
</div>
19 changes: 19 additions & 0 deletions examples/svelte/basic-snippets/src/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
html {
font-family: sans-serif;
font-size: 14px;
}

table {
border: 1px solid lightgray;
}

tbody {
border-bottom: 1px solid lightgray;
}

th {
border-bottom: 1px solid lightgray;
border-right: 1px solid lightgray;
padding: 2px 4px;
font-weight: normal;
}
9 changes: 9 additions & 0 deletions examples/svelte/basic-snippets/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// @ts-ignore - Svelte type definitions are not properly recognized
import { mount } from 'svelte'
import App from './App.svelte'

const app = mount(App, {
target: document.getElementById('root')!,
})

export default app
55 changes: 55 additions & 0 deletions examples/svelte/basic-snippets/src/snippets.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<script module lang="ts">
import { createRawSnippet } from 'svelte'
export { capitalized, spectrum, countup }
function getColor(value: number, min: number, max: number) {
console.log(value, min, max)
const ratio = (value - min) / (max - min)
console.log(value - min, max - min, ratio)
const hue = Math.floor(120 * ratio) // 0 (red) to 120 (green)
return `hsl(${hue}, 100%, 50%)`
}
type SpectrumParams = {
value: number
min: number
max: number
}
const countup = createRawSnippet<[value: number]>((value) => {
return {
render() {
return `<p>0</p>`
},
setup(element) {
let count = 0
const interval = setInterval(() => {
count++
element.textContent = `${count}`
if (count === value()) {
clearInterval(interval)
}
}, 1000 / value())
return () => {
clearInterval(interval)
}
},
}
})
</script>

{#snippet capitalized(value: string)}
<p class="text-capitalize">{value}</p>
{/snippet}

{#snippet spectrum({ value, min, max }: SpectrumParams)}
<div
class="text-center font-semibold"
style="background-color: {getColor(value, min, max)}"
>
{value}
</div>
{/snippet}
5 changes: 5 additions & 0 deletions examples/svelte/basic-snippets/svelte.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'

export default {
preprocess: vitePreprocess(),
}
17 changes: 17 additions & 0 deletions examples/svelte/basic-snippets/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"extends": "@tsconfig/svelte/tsconfig.json",
"compilerOptions": {
"target": "esnext",
"useDefineForClassFields": true,
"module": "esnext",
"resolveJsonModule": true,
"allowJs": true,
"checkJs": true,
"isolatedModules": true
},
"include": [
"../basic-snippets/src/**/*.ts",
"../basic-snippets/src/**/*.js",
"../basic-snippets/src/**/*.svelte"
]
}
17 changes: 17 additions & 0 deletions examples/svelte/basic-snippets/vite.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import rollupReplace from '@rollup/plugin-replace'

// https://vitejs.dev/config/
export default defineConfig({
plugins: [
rollupReplace({
preventAssignment: true,
values: {
__DEV__: JSON.stringify(true),
'process.env.NODE_ENV': JSON.stringify('development'),
},
}),
svelte(),
],
})
4 changes: 2 additions & 2 deletions examples/svelte/basic-table-helper/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
"@sveltejs/vite-plugin-svelte": "^4.0.4",
"@tanstack/svelte-table": "^9.0.0-alpha.10",
"@tsconfig/svelte": "^5.0.4",
"svelte": "^5.8.1",
"svelte-check": "^4.1.1",
"svelte": "^5.19.3",
"svelte-check": "^4.1.4",
"typescript": "5.6.3",
"vite": "^5.4.11"
}
Expand Down
Loading

0 comments on commit 1661fcf

Please sign in to comment.