Remove: Docs in Posts

This commit is contained in:
John
2024-12-28 05:33:19 -05:00
parent eae691aa8c
commit 1f1b51edcf
6 changed files with 0 additions and 1457 deletions

View File

@@ -1,64 +0,0 @@
---
title: Getting Started with SvelteKit
description: How to get started with SvelteKit
aliases: SvelteKit for Beginners
date: '2024-11-01'
updated:
tags:
- getting-started
- sveltekit
---
SvelteKit is a framework for building web applications of all sizes, with a beautiful development experience and flexible filesystem-based routing.
## Why SvelteKit?
- Zero-config setup
- Filesystem-based routing
- Server-side rendering
- Hot module replacement
```shell
npx sv create my-app
cd my-app
npm install
```
**Install SkeletonUI**
```
npm i -D @skeletonlabs/skeleton@next @skeletonlabs/skeleton-svelte@next
```
**Configure Tailwind CSS**
``` ts
import type { Config } from 'tailwindcss';
import { skeleton, contentPath } from '@skeletonlabs/skeleton/plugin';
import * as themes from '@skeletonlabs/skeleton/themes';
export default {
content: [
'./src/**/*.{html,js,svelte,ts}',
contentPath(import.meta.url, 'svelte')
],
theme: {
extend: {},
},
plugins: [
skeleton({
// NOTE: each theme included will be added to your CSS bundle
themes: [ themes.cerberus, themes.rose ]
})
]
} satisfies Config
```
**Start the dev server**
```bash
npm run dev
```
Read more at https://svelte.dev, https://next.skeleton.dev/docs/get-started/installation/sveltekit, and https://www.skeleton.dev/docs/introduction

View File

@@ -1,734 +0,0 @@
---
title: mdsvex - svelte in markdown
description: mdsvex is a markdown preprocessor for svelte
date: 2024-12-18
tags: ["svelte", "markdown", "mdsvex"]
---
"They said it was free..."
URL Source: https://mdsvex.pngwn.io/docs
mdsvex is a markdown preprocessor for [Svelte](https://svelte.dev/) components. Basically [MDX](https://mdxjs.com/) for Svelte.
This preprocessor allows you to use Svelte components in your markdown, or markdown in your Svelte components.
mdsvex supports all Svelte syntax and _almost_ all markdown syntax. See [limitations](https://mdsvex.pngwn.io/docs/#limitations) for more information.
You can do this:
```svelte
<script>
import { Chart } from "../components/Chart.svelte";
</script>
# Heres a chart
The chart is rendered inside our MDsveX document.
<Chart />
```
It uses [unified](https://unifiedjs.com/), [remark](https://github.com/remarkjs) and [rehype](https://github.com/rehypejs/rehype) and you can use any [remark plugins](https://github.com/remarkjs/remark/blob/main/doc/plugins.md#list-of-plugins) or [rehype plugins](https://github.com/rehypejs/rehype/blob/main/doc/plugins.md#list-of-plugins) to enhance your experience.
[Try it](https://mdsvex.pngwn.io/playground)
Install it
----------
Install it as a dev-dependency.
With `npm`:
```bash
npm i --save-dev mdsvex
```
With `yarn`:
```bash
yarn add --dev mdsvex
```
Use it
------
There are two named exports from `mdsvex` that can be used to transform mdsvex documents, `mdsvex` and `compile`. `mdsvex` is a Svelte preprocessor and is the preferred way to use this library. The `compile` function is useful when you wish to compile mdsvex documents to Svelte components directly, without hooking into the Svelte compiler.
### `mdsvex`
The `mdsvex` preprocessor function is a named import from the `mdsvex` module. Add it as a preprocessor to your rollup or webpack config, and tell the Svelte plugin or loader to also handle `.svx` files.
With rollup and `rollup-plugin-svelte`:
```ts
import { mdsvex } from "mdsvex";
export default {
...boring_config_stuff,
plugins: [
svelte({
// these are the defaults. If you want to add more extensions, see https://mdsvex.pngwn.io/docs#extensions
extensions: [".svelte", ".svx"],
preprocess: mdsvex()
})
]
};
```
With webpack and `svelte-loader`:
```ts
const { mdsvex } = require('mdsvex')
// add ".svx" to the extensions array
const extensions = ['.mjs', '.js', '.json', '.svelte', '.html', '.svx'];
module.exports = {
...boring_config_stuff,
resolve: { alias, extensions, mainFields },
module: {
rules: [
{
// tell svelte-loader to handle svx files as well
test: /.(svelte|html|svx)$/,
use: {
loader: 'svelte-loader',
options: {
...svelte_options,
preprocess: mdsvex()
}
}
}
]
}
};
```
If you want to use mdsvex without a bundler because you are your own person, then you can use `svelte.preprocess` directly:
```ts
const svelte = require('svelte/compiler');
const { mdsvex } = require('mdsvex');
// This will give you a valid svelte component
const preprocessed = await svelte.preprocess(
source,
mdsvex(mdsvex_opts)
);
// Now you can compile it if you wish
const compiled = svelte.compile(
preprocessed,
compiler_options
);
```
> If you dont like the `.svx` file extension, fear not, it is easily customised.
### `compile`
This option performs a very similar task to the preprocessor but it can be used directly, without needing to hook into the Svelte compiler, either directly or via a bundler. The compile option will transform valid mdsvex code into valid svelte code, but it will perform no further actions such as resolving imports.
It supports all of the same options as the preprocessor although the function signature is slightly different. The first argument should be the mdsvex source code you wish to compile, the second argument is an object of options.
```svelte
import { compile } from 'mdsvex';
const transformed_code = await compile(`
<script>
import Chart from './Chart.svelte';
</script>
# Hello friends
<Chart />
`,
mdsvexOptions
);
```
In addition to the standard mdsvex options, the options object can also take an optional `filename` property which will be passed to mdsvex. There is no significant advantage to doing this but this provided filename may be used for error reporting in the future. The extension you give to this filename must match one of the extensions provided in the options (defaults to `['.svx']`).
Options
-------
The preprocessor function accepts an object of options, that allow you to customise your experience. The options are global to all parsed files.
```ts
interface MdsvexOptions {
extensions: string[];
smartypants: boolean | smartypantsOptions;
layout: string | { [name: string]: string };
remarkPlugins: Array<plugin> | Array<[plugin, plugin_options]>;
rehypePlugins: Array<plugin> | Array<[plugin, plugin_options]>;
highlight: { highlighter: Function, alias: { [alias]: lang } };
frontmatter: { parse: Function; marker: string };
}
```
### `extensions`
```ts
extensions: string[] = [".svx"];
```
The `extensions` option allows you to set custom file extensions for files written in mdsvex; the default value is `['.svx']`. Whatever value you choose here must be passed to the `extensions` field of `rollup-plugin-svelte` or `svelte-loader`. If you do not change the default, you must still pass the extension name to the plugin or loader config.
```ts
export default {
...config,
plugins: [
svelte({
extensions: [".svelte", ".custom"],
preprocess: mdsvex({
extensions: [".custom"]
})
})
]
};
```
To import markdown files as components, add `.md` to both the Svelte compiler and `mdsvex` extensions:
```js
// svelte.config.js
import { mdsvex } from 'mdsvex'
export default {
extensions: ['.svelte', '.svx', '.md'],
preprocess: mdsvex({ extensions: ['.svx', '.md'] }),
}
```
If you use TypeScript, you should also declare an ambient module:
```ts
declare module '*.md' {
import type { SvelteComponent } from 'svelte'
export default class Comp extends SvelteComponent{}
export const metadata: Record<string, unknown>
}
```
Then you can do:
```svelte
<script>
import Readme from '../readme.md'
</script>
<Readme />
```
### `smartypants`
```ts
smartypants: boolean | {
quotes: boolean = true;
ellipses: boolean = true;
backticks: boolean | 'all' = true;
dashes: boolean | 'oldschool' | 'inverted' = true;
} = true;
```
The `smartypants` option transforms ASCII punctuation into fancy typographic punctuation HTML entities.
It turns stuff like:
```
"They said it was free..."
```
into:
> “They said it was free…”
Notice the beautiful punctuation. It does other nice things.
`smartypants` can be either a `boolean` (pass `false` to disable it) or an options object (defaults to `true`). The possible options are as follows.
```
quotes: boolean = true;
```
Converts straight double and single quotes to smart double or single quotes.
* `"words"` **becomes**: “words”
* `'words'` **becomes** words
```
ellipses: boolean = true;
```
Converts triple-dot characters (with or without spaces) into a single Unicode ellipsis character.
* `words...` **becomes** words…
```
backticks: boolean | 'all' = true;
```
When `true`, converts double back-ticks into an opening double quote, and double straight single quotes into a closing double quote.
* ` ``words''` **becomes** “words”
When `'all'` it also converts single back-ticks into a single opening quote, and a single straight quote into a closing single, smart quote.
Note: Quotes can not be `true` when backticks is `'all'`;
```
dashes: boolean | 'oldschool' | 'inverted' = true;
```
When `true`, converts two dashes into an em-dash character.
* `--` **becomes**
When `'oldschool'`, converts two dashes into an en-dash, and three dashes into an em-dash.
* `--` **becomes**
* `---` **becomes**
When `'inverted'`, converts two dashes into an em-dash, and three dashes into an en-dash.
* `--` **becomes**
* `---` **becomes**
### `layout`
```
layout: string | Array<string | RegExp, string>;
```
The `layout` option allows you to provide a custom layout component that will wrap your mdsvex file like so:
```
<Layout>
<MdsvexDocument />
<Layout>
```
> Layout components receive all frontmatter values as props, which should provide a great deal of flexibility when designing your layouts.
You can provide a `string`, which should be the path to your layout component. An absolute path is preferred but mdsvex tries to resolve relative paths based upon the current working directory.
```
import { join } from "path";
const path_to_layout = join(__dirname, "./src/Layout.svelte");
mdsvex({
layout: path_to_layout
});
```
In some cases you may want different layouts for different types of document, to address this you may pass an object of named layouts instead. Each key should be a name for your layout, the value should be a path as described above. A fallback layout, or default, can be passed using `_` (underscore) as a key name.
```
mdsvex({
layout: {
blog: "./path/to/blog/layout.svelte",
article: "./path/to/article/layout.svelte",
_: "./path/to/fallback/layout.svelte"
}
});
```
```
remarkPlugins: Array<plugin> | Array<[plugin, plugin_options]>;
rehypePlugins: Array<plugin> | Array<[plugin, plugin_options]>;
```
mdsvex has a simple pipeline. Your source file is first parsed into a Markdown AST (MDAST), this is where remark plugins would run. Then it is converted into an HTML AST (HAST), this is where rehype plugins would be run. After this it is converted (stringified) into a valid Svelte component ready to be compiled.
[remark](https://github.com/remarkjs) and [rehype](https://github.com/rehypejs/rehype) have a vibrant plugin ecosystem and mdsvex allows you to pass any [remark plugins](https://github.com/remarkjs/remark/blob/main/doc/plugins.md#list-of-plugins) or [rehype plugins](https://github.com/rehypejs/rehype/blob/main/doc/plugins.md#list-of-plugins) as options, which will run on the remark and rehype ASTs at the correct point in the pipeline.
These options take an array. If you do not wish to pass any options to a plugin then you can simply pass an array of plugins like so:
```
import containers from "remark-containers";
import github from "remark-github";
mdsvex({
remarkPlugins: [containers, github]
});
```
If you _do_ wish to pass options to your plugins then those array items should be an array of `[plugin, options]`, like so:
```
import containers from "remark-containers";
import github from "remark-github";
mdsvex({
remarkPlugins: [
[containers, container_opts],
[github, github_opts]
]
});
```
You can mix and match as needed, only providing an array when options are needed:
```
import containers from "remark-containers";
import github from "remark-github";
mdsvex({
remarkPlugins: [
[containers, container_opts],
github,
another_plugin,
[yet_another_plugin, more_options]
]
});
```
While these examples use `remarkPlugins`, the `rehypePlugins` option works in exactly the same way. You are free to use one or both of these options as you wish.
Remark plugins work on the Markdown AST (MDAST) produced by remark, rehype plugins work on the HTML AST (HAST) produced by rehype and it is possible to write your own custom plugins if the existing ones do not satisfy your needs!
### `highlight`
```
highlight: {
highlighter: (code: string, lang: string) => string | Promise<string>
alias: { [lang : string]: string }
};
```
Without any configuration, mdsvex will automatically highlight the syntax of over 100 languages using [PrismJS](https://prismjs.com/), you simply need to add the language name to the fenced code block and import the CSS file for a Prism theme of your choosing. See [here for available options](https://github.com/PrismJS/prism-themes). Languages are loaded on-demand and cached for later use, this feature does not unnecessarily load all languages for highlighting purposes.
Custom aliases for language names can be defined via the `alias` property of the highlight option. This property takes an object of key-value pairs: the key should be the alias you wish to define, the value should be the language you wish to assign it to.
```
mdsvex({
highlight: {
alias: { yavascript: "javascript" }
}
})
```
If you wish to handle syntax-highlighting yourself, you can provide a custom highlight function via the `highlighter` property. The function will receive two arguments, the `code` to be highlighted and the `lang` defined in the fenced code-block, both are strings. You can use this information to highlight as you wish. The function should return a string of highlighted code.
You can disable syntax highlighting by passing a function that does nothing:
```
function highlighter(code, lang) {
return `<pre><code>${code}</code></pre>`;
}
mdsvex({
highlight: {
highlighter
}
})
```
### `frontmatter`
```
frontmatter: { parse: Function, marker: string };
```
By default mdsvex supports yaml frontmatter, this is defined by enclosing the YAML in three hyphens (`---`). If you want to use a custom language or marker for frontmatter then you can use the `frontmatter` option.
`frontmatter` should be an object that can contain a `marker` and a `parse` property.
```
marker: string = '-';
```
The marker option defines the fence for your frontmatter. This defaults to `-` which corresponds to the standard triple-hyphen syntax (`---`) that you would normally use to define frontmatter. You can pass in a custom string to change this behaviour:
```
mdsvex({
frontmatter: {
marker: "+"
}
});
```
Now you can use `+++` to mark frontmatter. Setting _only_ the marker will keep the default frontmatter parser which only supports YAML.
```
parse: (frontmatter, message) => Object | undefined
```
The `parse` property accepts a function which allows you to provide a custom parser for frontmatter. This is useful if you want to use a different language in your frontmatter.
The parse function gets the raw frontmatter as the first argument and a `messages` array as the second.
If parsing is successful, the function should return the parsed frontmatter (as an object of key-value pairs), if there is a problem the function should return `undefined` or `false` . Any parsing errors or warnings should be pushed into the `messages` array which will be printed to the console when mdsvex has finished parsing. If you would prefer to throw an error, you are free to do so but it will interrupt the parsing process.
In the following example, we will modify the frontmatter handling so we can write our frontmatter in TOML with a triple-`+` fence.
```
mdsvex({
marker: "+",
parse(frontmatter, messages) {
try {
return toml.parse(frontmatter);
} catch (e) {
messages.push(
"Parsing error on line " +
e.line +
", column " +
e.column +
": " +
e.message
);
}
}
});
```
Now we will be able to write TOML frontmatter:
```
+++
title = "TOML Example"
[owner]
name = "some name"
dob = 1879-05-27T07:32:00-08:00
+++
```
Layouts
-------
Layouts are one of the more powerful features available in mdsvex and allow for a great deal of flexibility. At their simplest a layout is just a component that wraps an mdsvex document. Providing a string as the layout option will enable this behaviour:
```
mdsvex({
layout: "./path/to/layout.svelte"
});
```
Layouts receive all values defined in frontmatter as props:
```
<Layout {...props} >
<!-- mdsvex content here -->
</Layout>
```
You can then use these values in your layout however you wish, a typical use might be to define some fancy formatting for headings, authors, and dates. Although you could do all kinds of wonderful things. You just need to make sure you provide a default `slot` so the mdsvex content can be passed into your layout and rendered.
```
<script>
export let title;
export let author;
export let date;
</script>
<h1>{ title }</h1>
<p class="date">on: { date }</p>
<p class="date">by: { author }</p>
<slot>
<!-- the mdsvex content will be slotted in here -->
</slot>
```
### Named Layouts
In some cases you may want different layouts for different types of document. To address this you can pass an object of named layouts instead. Each key should be a name for your layout, the value should be the path to that layout file. A fallback layout, or default, can be passed using `_` (underscore) as a key name.
```
mdsvex({
layout: {
blog: "./path/to/blog/layout.svelte",
article: "./path/to/article/layout.svelte",
_: "./path/to/fallback/layout.svelte"
}
});
```
If you pass an object of named layouts, you can decide which layout to use on a file-by-file basis by declaring it in the frontmatter. For example, if you wanted to force a document to be wrapped with the `blog` layout you would do the following:
```
---
layout: blog
---
```
If you are using named layouts and do not have a layout field in the frontmatter then mdsvex will try to pick the correct one based on the folder a file is stored in. Take the following folder structure:
```
.
├── blog
│ └── my-blog-post.svx
└── article
└── my-article.svx
```
If there is a layout named `blog` and `article` then documents in the `blog` folder will use the `blog` layout, articles in the `articles` folder will use the `article` layout. mdsvex will try to check both singular and pluralised names, as you may have named a folder `events` but the matching layout could be named `event`, however, having the same folder and layout name will make this process more reliable. The current working directory is removed from the path when checking for matches but nested folders can still cause problems if there are conflicts. Shallow folder structures and unique folder and layout names will prevent these kinds of collisions.
If there is no matching layout then the fallback layout (`_`) will be applied, if there is no fallback then no layout will be applied.
### disabling layouts
If you are using layouts but wish to disable them for a specific component, then you can set the `layout` field to `false` to prevent the application of a layout.
```
---
layout: false
---
```
### Custom Components
Layouts also allow you to provide custom components to any mdsvex file they are applied to. Custom components replace the elements that markdown would normally generate.
```
# Title
Some text
- a
- short
- list
```
Would normally compile to:
```
<h1>Title</h1>
<p>Some text</p>
<ul>
<li>a</li>
<li>short</li>
<li>list</li>
</ul>
```
Custom components allow you to replace these elements with components. You can define components by exporting named exports from the `context="module"` script of your Layout file:
```
<script context="module">
import { h1, p, li } from './components.js';
export { h1, p, li };
</script>
```
The named exports must be named after the actual element you want to replace (`p`, `blockquote`, etc.), the value must be the component you wish to replace them with. This makes certain named exports protected API, make sure you dont use html names as export names for other values. Named exports whose names do not correspond to an HTML element will be ignored, so feel free to continue using them for other purposes as well. As these are named exports it is possible for the bundler to treeshake unused custom components, even if they are exported.
The above custom components would generate:
```
<script>
import * as Components from './Layout.svelte';
</script>
<Components.h1>Title</Components.h1>
<Components.p>Some text</Components.p>
<ul>
<Components.li>a</Components.li>
<Components.li>short</Components.li>
<Components.li>list</Components.li>
</ul>
```
Notice that the `ul` is left intact: elements are replaced _after_ the markdown is parsed to HTML. This allows greater flexibility, for example, when using custom components to customise lists, tables or other markdown that compiles to a combination of different HTML elements.
You may also receive attributes of the normal HTML component. For example, to render a custom `<img>` tag you could do:
```
<script>
export let src;
</script>
<img src={src} />
```
Frontmatter
-----------
YAML frontmatter is a common convention in blog posts and mdsvex supports it out of the box. If you want to use a custom language or marker for frontmatter than you can use the [`frontmatter`](https://mdsvex.pngwn.io/docs#frontmatter) option to modify the default behaviour.
Mdsvex integrates well with frontmatter providing additional flexibility when authoring documents.
All variables defined in frontmatter are available directly in the component, exactly as you wrote them:
```
---
title: My lovely article
author: Dr. Fabuloso the Fabulous
---
# {title} by {author}
Some amazing content.
```
Additionally, all of these variables are exported as a single object named `metadata` from the `context="module"` script, so they can easily be imported in javascript:
```
<script context="module">
export let metadata = {
title: "My lovely article",
author: "Dr. Fabuloso the Fabulous"
};
</script>
```
Due to how `context="module"` scripts work, this metadata can be imported like this:
```
import { metadata } from "./some-mdsvex-file.svx";
```
Frontmatter also interacts with layouts, you can find more details in the [Layout section](https://mdsvex.pngwn.io/docs#layouts).
Integrations
------------
### With shiki
You can use shiki for highlighting rather than prism by leveraging the `highlighter` option:
```ts
import { mdsvex, escapeSvelte } from 'mdsvex';
import { createHighlighter } from 'shiki';
const theme = 'github-dark';
const highlighter = await createHighlighter({
themes: [theme],
langs: ['javascript', 'typescript']
});
/** @type {import('mdsvex').MdsvexOptions} */
const mdsvexOptions = {
highlight: {
highlighter: async (code, lang = 'text') => {
const html = escapeSvelte(highlighter.codeToHtml(code, { lang, theme }));
return `{@html \`${html}\` }`;
}
},
}
```
Limitations
-----------
### Indentation
In markdown you can begin a code block by indenting 4 spaces. This doesnt work in mdsvex as indentation is common with XML-based languages. Indenting 4 spaces will do nothing.
In general you have a lot more flexibility when it comes to indenting code in mdsvex than you do in markdown because of the above change, however, you need to be very careful when indenting fenced code blocks. By which I mean, dont do it.
The following code block will break in a way that is both very bad and quite unexpected:
```js
```js
console.log('Hello, World!')
```
```
The solution is to not do this. When working with fenced code blocks, do not indent them. This isnt an issue that can really be worked around, even if the parser did make assumptions about what you meant. Because code blocks are designed to respect whitespace, any fix would simply result in a different but equally frustrating failure. Dont indent code blocks.

View File

@@ -1,232 +0,0 @@
---
title: SkeletonUI
aliases: [Getting Started with SkeletonUI]
description: A comprehensive UI toolkit for SvelteKit
tags:
- svelte
- styling
- skeletonui
- CSS
date: 2023-01-17
updated: 2024-12-08
---
SkeletonUI is a comprehensive UI toolkit that integrates seamlessly with SvelteKit and Tailwind CSS, enabling developers to build adaptive and accessible web interfaces efficiently.
SkeletonUI offers a comprehensive suite of components to enhance your Svelte applications. Below is a categorized list of these components, presented in Svelte syntax:
```
<!-- Layout Components -->
<AppShell />
<AppBar />
<Sidebar />
<Footer />
<!-- Navigation Components -->
<NavMenu />
<Breadcrumbs />
<Tabs />
<Pagination />
<!-- Form Components -->
<Button />
<Input />
<Select />
<Textarea />
<Checkbox />
<Radio />
<Switch />
<Slider />
<FileUpload />
<!-- Data Display Components -->
<Card />
<Avatar />
<Badge />
<Chip />
<Divider />
<Table />
<List />
<Accordion />
<ProgressBar />
<Rating />
<Tag />
<!-- Feedback Components -->
<Alert />
<Modal />
<Toast />
<Popover />
<Tooltip />
<!-- Media Components -->
<Image />
<Video />
<Icon />
<!-- Utility Components -->
<Spinner />
<SkeletonLoader />
<Placeholder />
```
For detailed information on each component, including their properties and usage examples, please refer to the official SkeletonUI documentation.
___
Below is an expanded cheat sheet to assist you in leveraging SkeletonUI within your SvelteKit projects.
**1\. Installation**
To set up SkeletonUI in a new SvelteKit project, follow these steps:
- **Create a new SvelteKit project**:
```
npx sv create my-skeleton-app
cd my-skeleton-app
npm install
```
- **Install SkeletonUI packages**:
```
npm install -D @skeletonlabs/skeleton@next @skeletonlabs/skeleton-svelte@next
```
- **Configure Tailwind CSS**:
In your `tailwind.config.js` file, add the following:
```
import { skeleton, contentPath } from '@skeletonlabs/skeleton/plugin';
import * as themes from '@skeletonlabs/skeleton/themes';
export default {
content: [
'./src/**/*.{html,js,svelte,ts}',
contentPath(import.meta.url, 'svelte')
],
theme: {
extend: {},
},
plugins: [
skeleton({
themes: [themes.cerberus, themes.rose]
})
]
};
```
- **Set the active theme**:
In your `src/app.html`, set the `data-theme` attribute on the `<body>` tag:
```
<body data-theme="cerberus">
<!-- Your content -->
</body>
```
For detailed installation instructions, refer to the official SkeletonUI documentation.
**2\. Components**
SkeletonUI offers a variety of pre-designed components to accelerate your development process. Here's how to use some of them:
- **Button**:
```
<script>
import { Button } from '@skeletonlabs/skeleton-svelte';
</script>
<Button on:click={handleClick}>Click Me</Button>
```
- **Card**:
```
<script>
import { Card } from '@skeletonlabs/skeleton-svelte';
</script>
<Card>
<h2>Card Title</h2>
<p>Card content goes here.</p>
</Card>
```
- **Form Input**:
```
<script>
import { Input } from '@skeletonlabs/skeleton-svelte';
let inputValue = '';
</script>
<Input bind:value={inputValue} placeholder="Enter text" />
```
For a comprehensive list of components and their usage, consult the SkeletonUI components documentation.
**3. Theming**
SkeletonUI's theming system allows for extensive customization:
- **Applying a Theme**:
Set the desired theme in your `tailwind.config.js` and `app.html` as shown in the installation steps above.
- **Switching Themes Dynamically**:
To enable dynamic theme switching, you can modify the `data-theme` attribute programmatically:
```
<script>
function switchTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
}
</script>
<button on:click={() => switchTheme('rose')}>Switch to Rose Theme</button>
```
- **Customizing Themes**:
You can create custom themes by defining your own color palettes and settings in the `tailwind.config.js` file.
For more information on theming, refer to the SkeletonUI theming guide.
**4. Utilities**
SkeletonUI provides several utility functions and actions to enhance your SvelteKit application:
- **Table of Contents**:
Automatically generate a table of contents based on page headings:
```
<script>
import { TableOfContents, tocCrawler } from '@skeletonlabs/skeleton-svelte';
</script>
<div use:tocCrawler>
<TableOfContents />
<!-- Your content with headings -->
</div>
```
- **Transitions and Animations**:
Utilize built-in transitions for smooth animations:
```
<script>
import { fade } from '@skeletonlabs/skeleton-svelte';
let visible = true;
</script>
{#if visible}
<div transition:fade>
Fading content
</div>
{/if}
```
For a full list of utilities and their usage, explore the SkeletonUI utilities documentation.
This cheat sheet provides a foundational overview to help you start integrating SkeletonUI into your SvelteKit projects. For more detailed information and advanced features, please refer to the official SkeletonUI documentation.
https://www.skeleton.dev/docs/introduction

View File

@@ -1,278 +0,0 @@
---
title: JSON to Markdown
aliases: [Delete this file]
description: Delete this file
date: 2024-01-17
tags: [Delete this file]
author: me
---
1 min read
SvelteKit offers powerful tools for rendering Markdown content from JSON responses, with mdsvex emerging as a popular solution for seamlessly integrating Markdown processing into Svelte applications.
## Streaming JSON to Markdown
To render Markdown content from streaming JSON in a SvelteKit application, you can combine SvelteKit's server-side rendering (SSR) capabilities with tools like mdsvex or svelte-markdown. This approach ensures that dynamic data fetched from APIs can be transformed into rich, interactive content.
Heres how you can handle streaming JSON and convert it into Markdown:
Fetch the Streaming JSON: Use SvelteKit's load function to fetch the API data. If the API streams JSON, ensure you parse it incrementally using the ReadableStream interface in JavaScript.
Parse and Extract Markdown: Once you receive the JSON chunks, extract the Markdown strings from the relevant fields. For example:
```
const response = await fetch('https://api.example.com/stream');
const reader = response.body.getReader();
let markdownContent = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
markdownContent += new TextDecoder().decode(value);
}
```
Render Markdown with mdsvex or svelte-markdown:
Using mdsvex: Compile the Markdown string into HTML at runtime. Mdsvex provides a compile function for this purpose.
```
import { compile } from 'mdsvex';
const { code } = await compile(markdownContent);
```
You can then inject this compiled HTML into your Svelte component.
Using svelte-markdown: This library directly renders Markdown strings as Svelte components, making it ideal for runtime rendering3. Install it with:
```
npm install svelte-markdown
```
Then use it in your component:
```
import Markdown from 'svelte-markdown';
let markdownContent = '# Example Heading\nThis is some text.';
{markdownContent}
```
Optimize Streaming: If the JSON contains large amounts of data, consider rendering partial content as it arrives. SvelteKit's support for streaming responses allows you to send initial HTML while continuing to process and append additional content45.
This method is particularly useful for applications that rely on real-time data or external content sources like headless CMSs or GitHub repositories. By leveraging tools like mdsvex and svelte-markdown, you can transform raw JSON data into visually engaging Markdown content without sacrificing performance or interactivity678.
dev.to favicon
stackoverflow.com favicon
npmjs.com favicon
8 sources
## Using mdsvex for Markdown
Mdsvex is a powerful preprocessor that extends Svelte's capabilities to seamlessly integrate Markdown content into SvelteKit applications1. It allows developers to write Markdown files that can contain Svelte components, effectively blending the simplicity of Markdown with the dynamic features of Svelte2.
To set up mdsvex in a SvelteKit project:
Install mdsvex and its dependencies:
text
npm install mdsvex
Configure mdsvex in your svelte.config.js file:
```
import { mdsvex } from 'mdsvex';
const config = {
extensions: ['.svelte', '.md'],
preprocess: [
mdsvex({
extensions: ['.md']
})
]
};
```
This configuration allows you to use .md files as Svelte components3.
Mdsvex offers several advantages for handling Markdown in SvelteKit:
It supports frontmatter, allowing you to include metadata at the top of your Markdown files4.
You can use Svelte components directly within your Markdown content, enabling interactive elements2.
Code highlighting is built-in, making it easy to display formatted code snippets2.
For dynamic content, such as Markdown stored in a database or fetched from an API, you can use mdsvex to render Markdown strings at runtime:
```
import { compile } from 'mdsvex';
const markdownString = '# Hello, World!';
const { code } = await compile(markdownString);
```
This approach allows you to process Markdown content on-the-fly, which is particularly useful when working with content management systems or external data sources5.
By leveraging mdsvex, SvelteKit developers can create rich, interactive content experiences that combine the ease of writing in Markdown with the power of Svelte components, making it an excellent choice for blogs, documentation sites, and content-heavy applications6.
## More Markdown Integration Examples
Dynamic Markdown Rendering: For scenarios where Markdown content is dynamically fetched from an external API, you can use the marked library to parse the Markdown into HTML directly within a Svelte component. This approach is simple and effective for runtime rendering:
```
import { marked } from 'marked';
let markdownContent = '';
async function fetchMarkdown() {
const response = await fetch('https://api.example.com/markdown');
markdownContent = await response.text();
}
$: htmlContent = marked(markdownContent);
Loading...
{@html htmlContent}
```
This method ensures that even dynamically loaded Markdown content is rendered efficiently, making it ideal for live data scenarios12.
Markdown with Frontmatter: Mdsvex supports frontmatter, which allows you to embed metadata in your Markdown files. This is particularly useful for blogs or documentation sites. For example:
```
---
title: "My Blog Post"
date: "2024-01-01"
tags: ["svelte", "markdown"]
---
```
# Welcome to My Blog
This is a post about integrating Markdown with SvelteKit.
You can access this metadata in your Svelte components, enabling features like dynamic page titles or tag-based filtering34.
Interactive Charts in Markdown: Combine the power of Markdown with Svelte's interactivity by embedding components like charts. For instance, using Mdsvex, you can include a chart directly in your Markdown file:
```
# Sales Data
```
Here, Chart is a Svelte component that renders a chart using libraries like Chart.js or D3.js. This approach makes it easy to create visually rich content while keeping the simplicity of Markdown56.
Custom Styling for Markdown Content: To apply consistent styles to your rendered Markdown, wrap it in a container with scoped CSS. For example:
```
.markdown-content h1 {
color: blue;
}
.markdown-content p {
font-size: 1.2rem;
}
```
This ensures your Markdown content adheres to your application's design system without affecting other parts of the UI12.
Pagination for Large Markdown Files: If you're dealing with extensive Markdown content, split it into smaller sections and implement pagination. For example, store each section in an array and render only the current page:
```
let currentPage = 0;
const markdownPages = [
'# Page 1\nThis is the first page.',
'# Page 2\nThis is the second page.',
'# Page 3\nThis is the third page.'
];
Previous
Next
{@html marked(markdownPages[currentPage])}
```
This approach improves performance and user experience by loading content incrementally72.
## Interactive Markdown Examples
Building on the previous examples, let's explore some more advanced techniques for integrating Markdown in SvelteKit applications:
Syntax Highlighting: Enhance code blocks in your Markdown content with syntax highlighting using libraries like Prism.js. Here's how you can set it up with mdsvex:
```
import { mdsvex } from 'mdsvex';
import prism from 'prismjs';
const config = {
extensions: ['.svelte', '.md'],
preprocess: [
mdsvex({
highlight: {
highlighter: (code, lang) => {
return `${prism.highlight(code, prism.languages[lang], lang)}`;
}
}
})
]
};
```
This configuration will automatically apply syntax highlighting to code blocks in your Markdown files1.
Custom Components for Markdown Elements: Create custom Svelte components to replace standard Markdown elements. For instance, you can create a custom Image component for enhanced image handling:
```
export let src;
export let alt;
```
Then, configure mdsvex to use this component:
```
import Image from './Image.svelte';
const config = {
extensions: ['.svelte', '.md'],
preprocess: [
mdsvex({
layout: {
_: './src/layouts/DefaultLayout.svelte'
},
remarkPlugins: [],
rehypePlugins: [],
components: {
img: Image
}
})
]
};
```
This setup allows you to add lazy loading, responsive images, or other custom behaviors to all images in your Markdown content2.
Table of Contents Generation: Automatically generate a table of contents for your Markdown files using remark plugins:
```
import { mdsvex } from 'mdsvex';
import remarkToc from 'remark-toc';
const config = {
extensions: ['.svelte', '.md'],
preprocess: [
mdsvex({
remarkPlugins: [
[remarkToc, { tight: true }]
]
})
]
};
```
This configuration will automatically generate a table of contents based on the headings in your Markdown files3.
Live Markdown Editor: Create an interactive Markdown editor with real-time preview:
```
import { marked } from 'marked';
let markdownInput = '# Live Markdown Editor\n\nStart typing...';
$: htmlOutput = marked(markdownInput);
{@html htmlOutput}
```
This component allows users to input Markdown and see the rendered HTML output in real-time, which can be useful for comment systems or content management interfaces4
.
These examples demonstrate the flexibility and power of integrating Markdown with SvelteKit, enabling developers to create rich, interactive content experiences tailored to their specific needs.

View File

@@ -1,149 +0,0 @@
---
title: Svelte
description: sveltekit stuff.
aliases: this is just a temp file
date: 2024-12-18
images:
tags:
- tag1
- tag2
---
Can I import images from `static` to be used in Metadata? People have thought about this and it's better to keep images for posts in the Obsidian Vault. Check out Bramses opinionated vault. [Bramses-Highly-Opinioinated-Vault](https://github.com/bramses/bramses-highly-opinionated-vault-2023)
URL Source: https://svelte.dev/docs/kit/link-options
Markdown Content:
In SvelteKit, `<a>` elements (rather than framework-specific `<Link>` components) are used to navigate between the routes of your app. If the user clicks on a link whose `href` is owned by the app (as opposed to, say, a link to an external site) then SvelteKit will navigate to the new page by importing its code and then calling any `load` functions it needs to fetch data.
You can customise the behaviour of links with `data-sveltekit-*` attributes. These can be applied to the `<a>` itself, or to a parent element.
These options also apply to `<form>` elements with [`method="GET"`](https://svelte.dev/docs/kit/form-actions#GET-vs-POST).
[data-sveltekit-preload-data](https://svelte.dev/docs/kit/link-options#data-sveltekit-preload-data)
---------------------------------------------------------------------------------------------------
Before the browser registers that the user has clicked on a link, we can detect that theyve hovered the mouse over it (on desktop) or that a `touchstart` or `mousedown` event was triggered. In both cases, we can make an educated guess that a `click` event is coming.
SvelteKit can use this information to get a head start on importing the code and fetching the pages data, which can give us an extra couple of hundred milliseconds — the difference between a user interface that feels laggy and one that feels snappy.
We can control this behaviour with the `data-sveltekit-preload-data` attribute, which can have one of two values:
* `"hover"` means that preloading will start if the mouse comes to a rest over a link. On mobile, preloading begins on `touchstart`
* `"tap"` means that preloading will start as soon as a `touchstart` or `mousedown` event is registered
The default project template has a `data-sveltekit-preload-data="hover"` attribute applied to the `<body>` element in `src/app.html`, meaning that every link is preloaded on hover by default:
```svelte
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
```
Sometimes, calling `load` when the user hovers over a link might be undesirable, either because its likely to result in false positives (a click neednt follow a hover) or because data is updating very quickly and a delay could mean staleness.
In these cases, you can specify the `"tap"` value, which causes SvelteKit to call `load` only when the user taps or clicks on a link:
```svelte
<a data-sveltekit-preload-data="tap" href="/stonks">
Get current stonk values
</a>
```
> You can also programmatically invoke `preloadData` from `$app/navigation`.
Data will never be preloaded if the user has chosen reduced data usage, meaning [`navigator.connection.saveData`](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/saveData) is `true`.
[data-sveltekit-preload-code](https://svelte.dev/docs/kit/link-options#data-sveltekit-preload-code)
---------------------------------------------------------------------------------------------------
Even in cases where you dont want to preload _data_ for a link, it can be beneficial to preload the _code_. The `data-sveltekit-preload-code` attribute works similarly to `data-sveltekit-preload-data`, except that it can take one of four values, in decreasing eagerness:
* `"eager"` means that links will be preloaded straight away
* `"viewport"` means that links will be preloaded once they enter the viewport
* `"hover"` - as above, except that only code is preloaded
* `"tap"` - as above, except that only code is preloaded
Note that `viewport` and `eager` only apply to links that are present in the DOM immediately following navigation — if a link is added later (in an `{#if ...}` block, for example) it will not be preloaded until triggered by `hover` or `tap`. This is to avoid performance pitfalls resulting from aggressively observing the DOM for changes.
> Since preloading code is a prerequisite for preloading data, this attribute will only have an effect if it specifies a more eager value than any `data-sveltekit-preload-data` attribute that is present.
As with `data-sveltekit-preload-data`, this attribute will be ignored if the user has chosen reduced data usage.
data-sveltekit-reload[etst](https://svelte.dev/docs/kit/link-options#data-sveltekit-reload)
---------------------------------------------------------------------------------------------------
Occasionally, we need to tell SvelteKit not to handle a link, but allow the browser to handle it. Adding a `data-sveltekit-reload` attribute to a link...
```svelte
<a data-sveltekit-reload href="/path">Path</a>
```
...will cause a full-page navigation when the link is clicked.
Links with a `rel="external"` attribute will receive the same treatment. In addition, they will be ignored during [prerendering](https://svelte.dev/docs/kit/page-options#prerender).
[data-sveltekit-replacestate](https://svelte.dev/docs/kit/link-options#data-sveltekit-replacestate)
---------------------------------------------------------------------------------------------------
Sometimes you dont want navigation to create a new entry in the browsers session history. Adding a `data-sveltekit-replacestate` attribute to a link...
```svelte
<a data-sveltekit-replacestate href="/path">Path</a>
```
...will replace the current `history` entry rather than creating a new one with `pushState` when the link is clicked.
data-sveltekit-keepfocus[sveltekit-keepfocus](https://svelte.dev/docs/kit/link-options#data-sveltekit-keepfocus)
---------------------------------------------------------------------------------------------
Sometimes you dont want [focus to be reset](https://svelte.dev/docs/kit/accessibility#Focus-management) after navigation. For example, maybe you have a search form that submits as the user is typing, and you want to keep focus on the text input. Adding a `data-sveltekit-keepfocus` attribute to it...
```svelte
<form data-sveltekit-keepfocus>
<input type="text" name="query">
</form>
```
...will cause the currently focused element to retain focus after navigation. In general, avoid using this attribute on links, since the focused element would be the `<a>` tag (and not a previously focused element) and screen reader and other assistive technology users often expect focus to be moved after a navigation. You should also only use this attribute on elements that still exist after navigation. If the element no longer exists, the users focus will be lost, making for a confusing experience for assistive technology users.
When navigating to internal links, SvelteKit mirrors the browsers default navigation behaviour: it will change the scroll position to 0,0 so that the user is at the very top left of the page (unless the link includes a `#hash`, in which case it will scroll to the element with a matching ID).
In certain cases, you may wish to disable this behaviour. Adding a `data-sveltekit-noscroll` attribute to a link...
```svelte
<a href="path" data-sveltekit-noscroll ally="Path">Path</a>
```
...will prevent scrolling after the link is clicked.
[Disabling options](https://svelte.dev/docs/kit/link-options#Disabling-options)
-------------------------------------------------------------------------------
To disable any of these options inside an element where they have been enabled, use the `"false"` value:
```svelte
<div data-sveltekit-preload-data>
<!-- these links will be preloaded -->
<a href="/a">a</a>
<a href="/b">b</a>
<a href="/c">c</a>
<div data-sveltekit-preload-data="false">
<!-- these links will NOT be preloaded -->
<a href="/d">d</a>
<a href="/e">e</a>
<a href="/f">f</a>
</div>
</div>
```
To apply an attribute to an element conditionally, do this:
```svelte
<div data-sveltekit-preload-data={condition ? 'hover' : false}>
```