Modify the content

pull/8435/head
Puru Vijay 3 years ago
parent 7cd7425472
commit ebd9567ef2

@ -1,5 +1,5 @@
--- ---
title: Component format title: .svelte files
--- ---
Components are the building blocks of Svelte applications. They are written into `.svelte` files, using a superset of HTML. Components are the building blocks of Svelte applications. They are written into `.svelte` files, using a superset of HTML.
@ -340,3 +340,134 @@ In that case, the `<style>` tag will be inserted as-is into the DOM, no scoping
</style> </style>
</div> </div>
``` ```
## Tags
A lowercase tag, like `<div>`, denotes a regular HTML element. A capitalised tag, such as `<Widget>` or `<Namespace.Widget>`, indicates a _component_.
```svelte
<script>
import Widget from './Widget.svelte';
</script>
<div>
<Widget />
</div>
```
## Attributes and props
By default, attributes work exactly like their HTML counterparts.
```svelte
<div class="foo">
<button disabled>can't touch this</button>
</div>
```
As in HTML, values may be unquoted.
```svelte
<input type="checkbox" />
```
Attribute values can contain JavaScript expressions.
```svelte
<a href="page/{p}">page {p}</a>
```
Or they can _be_ JavaScript expressions.
```svelte
<button disabled={!clickable}>...</button>
```
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
<input required={false} placeholder="This input field is not required" />
<div title={null}>This div has no title attribute</div>
```
An expression might include characters that would cause syntax highlighting to fail in regular HTML, so quoting the value is permitted. The quotes do not affect how the value is parsed:
```svelte
<button disabled={number !== 42}>...</button>
```
When the attribute name and value match (`name={name}`), they can be replaced with `{name}`.
```svelte
<!-- These are equivalent -->
<button {disabled}>...</button>
<button {disabled}>...</button>
```
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
<Widget foo={bar} answer={42} text="hello" />
```
_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
<Widget {...things} />
```
_`$$props`_ references all props that are passed to a component, including ones that are not declared with `export`. It is not generally recommended, as it is difficult for Svelte to optimise. But it can be useful in rare cases for example, when you don't know at compile time what props might be passed to a component.
```svelte
<Widget {...$$props} />
```
_`$$restProps`_ contains only the props which are _not_ declared with `export`. It can be used to pass down other unknown attributes to an element in a component. It shares the same optimisation problems as _`$$props`_, and is likewise not recommended.
```svelte
<input {...$$restProps} />
```
> The `value` attribute of an `input` element or its children `option` elements must not be set with spread attributes when using `bind:group` or `bind:checked`. Svelte needs to be able to see the element's `value` directly in the markup in these cases so that it can link it to the bound variable.
> Sometimes, the attribute order matters as Svelte sets attributes sequentially in JavaScript. For example, `<input type="range" min="0" max="1" value={0.5} step="0.1"/>`, Svelte will attempt to set the value to `1` (rounding up from 0.5 as the step by default is 1), and then set the step to `0.1`. To fix this, change it to `<input type="range" min="0" max="1" step="0.1" value={0.5}/>`.
> Another example is `<img src="..." loading="lazy" />`. Svelte will set the img `src` before making the img element `loading="lazy"`, which is probably too late. Change this to `<img loading="lazy" src="...">` to make the image lazily loaded.
## Text expressions
```svelte
{expression}
```
Text can also contain JavaScript expressions:
> 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
<h1>Hello {name}!</h1>
<p>{a} + {b} = {a + b}.</p>
<div>{/^[A-Za-z ]+$/.test(value) ? x : y}</div>
```
## Comments
You can use HTML comments inside components.
```svelte
<!-- this is a comment! --><h1>Hello world</h1>
```
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
<!-- svelte-ignore a11y-autofocus -->
<input bind:value={name} autofocus />
```

@ -1,134 +0,0 @@
---
title: Basics
---
## Tags
A lowercase tag, like `<div>`, denotes a regular HTML element. A capitalised tag, such as `<Widget>` or `<Namespace.Widget>`, indicates a _component_.
```svelte
<script>
import Widget from './Widget.svelte';
</script>
<div>
<Widget />
</div>
```
## Attributes and props
By default, attributes work exactly like their HTML counterparts.
```svelte
<div class="foo">
<button disabled>can't touch this</button>
</div>
```
As in HTML, values may be unquoted.
```svelte
<input type="checkbox" />
```
Attribute values can contain JavaScript expressions.
```svelte
<a href="page/{p}">page {p}</a>
```
Or they can _be_ JavaScript expressions.
```svelte
<button disabled={!clickable}>...</button>
```
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
<input required={false} placeholder="This input field is not required" />
<div title={null}>This div has no title attribute</div>
```
An expression might include characters that would cause syntax highlighting to fail in regular HTML, so quoting the value is permitted. The quotes do not affect how the value is parsed:
```svelte
<button disabled={number !== 42}>...</button>
```
When the attribute name and value match (`name={name}`), they can be replaced with `{name}`.
```svelte
<!-- These are equivalent -->
<button {disabled}>...</button>
<button {disabled}>...</button>
```
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
<Widget foo={bar} answer={42} text="hello" />
```
_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
<Widget {...things} />
```
_`$$props`_ references all props that are passed to a component, including ones that are not declared with `export`. It is not generally recommended, as it is difficult for Svelte to optimise. But it can be useful in rare cases for example, when you don't know at compile time what props might be passed to a component.
```svelte
<Widget {...$$props} />
```
_`$$restProps`_ contains only the props which are _not_ declared with `export`. It can be used to pass down other unknown attributes to an element in a component. It shares the same optimisation problems as _`$$props`_, and is likewise not recommended.
```svelte
<input {...$$restProps} />
```
> The `value` attribute of an `input` element or its children `option` elements must not be set with spread attributes when using `bind:group` or `bind:checked`. Svelte needs to be able to see the element's `value` directly in the markup in these cases so that it can link it to the bound variable.
> Sometimes, the attribute order matters as Svelte sets attributes sequentially in JavaScript. For example, `<input type="range" min="0" max="1" value={0.5} step="0.1"/>`, Svelte will attempt to set the value to `1` (rounding up from 0.5 as the step by default is 1), and then set the step to `0.1`. To fix this, change it to `<input type="range" min="0" max="1" step="0.1" value={0.5}/>`.
> Another example is `<img src="..." loading="lazy" />`. Svelte will set the img `src` before making the img element `loading="lazy"`, which is probably too late. Change this to `<img loading="lazy" src="...">` to make the image lazily loaded.
## Text expressions
```svelte
{expression}
```
Text can also contain JavaScript expressions:
> 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
<h1>Hello {name}!</h1>
<p>{a} + {b} = {a + b}.</p>
<div>{/^[A-Za-z ]+$/.test(value) ? x : y}</div>
```
## Comments
You can use HTML comments inside components.
```svelte
<!-- this is a comment! --><h1>Hello world</h1>
```
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
<!-- svelte-ignore a11y-autofocus -->
<input bind:value={name} autofocus />
```

@ -1,5 +1,5 @@
--- ---
title: Logic Blocks title: Logic blocks
--- ---
## {#if ...} ## {#if ...}

@ -1,5 +1,5 @@
--- ---
title: Special Tags title: Special tags
--- ---
## {@html ...} ## {@html ...}

@ -1,5 +1,5 @@
--- ---
title: Element Directives title: Element directives
--- ---
As well as attributes, elements can have _directives_, which control the element's behaviour in some way. As well as attributes, elements can have _directives_, which control the element's behaviour in some way.

@ -1,5 +1,5 @@
--- ---
title: Component Directives title: Component directives
--- ---
## on:_eventname_ ## on:_eventname_

@ -1,5 +1,5 @@
--- ---
title: 'Custom Elements API' title: 'Custom elements API'
--- ---
Svelte components can also be compiled to custom elements (aka web components) using the `customElement: true` compiler option. You should specify a tag name for the component using the `<svelte:options>` [element](/docs/special-elements#svelte-options). Svelte components can also be compiled to custom elements (aka web components) using the `customElement: true` compiler option. You should specify a tag name for the component using the `<svelte:options>` [element](/docs/special-elements#svelte-options).

@ -130,24 +130,24 @@
'accessibility-warnings-a11y-role-supports-aria-props', 'accessibility-warnings-a11y-role-supports-aria-props',
'accessibility-warnings-a11y-structure', 'accessibility-warnings-a11y-structure',
'accessibility-warnings-a11y-unknown-aria-attribute', 'accessibility-warnings-a11y-unknown-aria-attribute',
'accessibility-warnings-a11y-unknown-role' 'accessibility-warnings-a11y-unknown-role',
]; ];
/** @type {Map<RegExp, string>}*/ /** @type {Map<RegExp, string>}*/
const pages_regex_map = new Map([ const pages_regex_map = new Map([
// Basic ones // Basic ones
[/(before-we-begin|getting-started)$/i, 'introduction'], [/(before-we-begin|getting-started)$/i, 'introduction'],
[/(component-format)$/i, '$1'], [/(component-format)$/i, 'dot-svelte-files'],
[/template-syntax$/i, 'template-syntax-basics'], [/template-syntax$/i, 'dot-svelte-files'],
[/run-time$/i, 'svelte'], [/run-time$/i, 'svelte'],
[/compile-time$/i, 'svelte-compiler'], [/compile-time$/i, 'svelte-compiler'],
[/(accessibility-warnings)$/i, '$1'], [/(accessibility-warnings)$/i, '$1'],
// component-format- // component-format-
[/(component-format)-(style)$/i, '$1#$2'], [/component-format-(style)$/i, 'dot-svelte-files#$1'],
[/(component-format)-(script)$/i, '$1#$2'], [/component-format-(script)$/i, 'dot-svelte-files#$1'],
[/(component-format)-(script-context-module)$/i, '$1#$2'], [/component-format-(script-context-module)$/i, 'dot-svelte-files#$1'],
[/(component-format)-(?:script)(?:-?(.*))$/i, '$1#$2'], [/component-format-(?:script)(?:-?(.*))$/i, 'dot-svelte-files#$1'],
// template-syntax // template-syntax
[/template-syntax-((?:element|component)-directives)-?(.*)/i, '$1#$2'], [/template-syntax-((?:element|component)-directives)-?(.*)/i, '$1#$2'],
@ -156,7 +156,7 @@
[/template-syntax-(if|each|await|key)$/i, 'logic-blocks#$1'], [/template-syntax-(if|each|await|key)$/i, 'logic-blocks#$1'],
[/template-syntax-(const|debug|html)$/i, 'special-tags#$1'], [/template-syntax-(const|debug|html)$/i, 'special-tags#$1'],
// !!!! This one should stay at the bottom of `template-syntax`, or it may end up hijacking logic blocks and special tags // !!!! This one should stay at the bottom of `template-syntax`, or it may end up hijacking logic blocks and special tags
[/template-syntax-(.+)/i, 'template-syntax-basics#$1'], [/template-syntax-(.+)/i, 'dot-svelte-files#$1'],
// run-time // run-time
[/run-time-(svelte-(?:store|motion|transition|animate))-?(.*)/i, '$1#$2'], [/run-time-(svelte-(?:store|motion|transition|animate))-?(.*)/i, '$1#$2'],
@ -172,7 +172,7 @@
[/compile-time-?(.*)/i, 'svelte-compiler#$1'], [/compile-time-?(.*)/i, 'svelte-compiler#$1'],
// Accessibility warnings // Accessibility warnings
[/(accessibility-warnings)-?(.+)/i, '$1#$2'] [/(accessibility-warnings)-?(.+)/i, '$1#$2'],
]); ]);
function get_old_new_ids_map() { function get_old_new_ids_map() {

@ -1,8 +1,9 @@
<script> <script>
import { onMount } from 'svelte'; import { afterUpdate, onMount } from 'svelte';
import { afterNavigate } from '$app/navigation'; import { afterNavigate } from '$app/navigation';
import { base } from '$app/paths'; import { base } from '$app/paths';
import { page } from '$app/stores'; import { page } from '$app/stores';
import { browser } from '$app/environment';
/** @type {import('./$types').PageData['page']} */ /** @type {import('./$types').PageData['page']} */
export let details; export let details;
@ -22,9 +23,13 @@
/** @type {number[]} */ /** @type {number[]} */
let positions = []; let positions = [];
/** @type {HTMLElement} */
let containerEl;
let show_contents = false;
onMount(async () => { onMount(async () => {
await document.fonts.ready; await document.fonts.ready;
update(); update();
highlight(); highlight();
}); });
@ -37,21 +42,17 @@
function update() { function update() {
content = document.querySelector('.content'); content = document.querySelector('.content');
const { top } = content.getBoundingClientRect(); const { top } = content.getBoundingClientRect();
headings = content.querySelectorAll('h2[id]'); headings = content.querySelectorAll('h2[id]');
positions = Array.from(headings).map((heading) => { positions = Array.from(headings).map((heading) => {
const style = getComputedStyle(heading); const style = getComputedStyle(heading);
return heading.getBoundingClientRect().top - parseFloat(style.scrollMarginTop) - top; return heading.getBoundingClientRect().top - parseFloat(style.scrollMarginTop) - top;
}); });
height = window.innerHeight; height = window.innerHeight;
} }
function highlight() { function highlight() {
const { top, bottom } = content.getBoundingClientRect(); const { top, bottom } = content.getBoundingClientRect();
let i = headings.length; let i = headings.length;
while (i--) { while (i--) {
if (bottom - height < 50 || positions[i] + top < 100) { if (bottom - height < 50 || positions[i] + top < 100) {
const heading = headings[i]; const heading = headings[i];
@ -59,7 +60,6 @@
return; return;
} }
} }
hash = ''; hash = '';
} }
@ -69,7 +69,6 @@
setTimeout(() => { setTimeout(() => {
hash = url.hash; hash = url.hash;
}); });
// ...and braces // ...and braces
window.addEventListener( window.addEventListener(
'scroll', 'scroll',
@ -79,11 +78,37 @@
{ once: true } { once: true }
); );
} }
afterUpdate(() => {
// bit of a hack — prevent sidebar scrolling if
// TOC is open on mobile, or scroll came from within sidebar
if (show_contents && window.innerWidth < 832) return;
const active = containerEl.querySelector('.active');
if (active) {
const { top, bottom } = active.getBoundingClientRect();
const min = 100;
const max = window.innerHeight - 100;
if (top > max) {
containerEl.scrollBy({
top: top - max,
left: 0,
behavior: 'smooth',
});
} else if (bottom < min) {
containerEl.scrollBy({
top: bottom - min,
left: 0,
behavior: 'smooth',
});
}
}
});
</script> </script>
<svelte:window on:scroll={highlight} on:resize={update} on:hashchange={() => select($page.url)} /> <svelte:window on:scroll={highlight} on:resize={update} on:hashchange={() => select($page.url)} />
<aside class="on-this-page"> <aside class="on-this-page" bind:this={containerEl}>
<h2>On this page</h2> <h2>On this page</h2>
<nav> <nav>
<ul> <ul>
@ -101,7 +126,7 @@
position: fixed; position: fixed;
padding: var(--sk-page-padding-top) var(--sk-page-padding-side) 0 0; padding: var(--sk-page-padding-top) var(--sk-page-padding-side) 0 0;
width: min(280px, calc(var(--sidebar-width) - var(--sk-page-padding-side))); width: min(280px, calc(var(--sidebar-width) - var(--sk-page-padding-side)));
height: calc(100vh - var(--sk-nav-height)); height: calc(100vh - var(--sk-nav-height) - var(--sk-page-padding-top));
top: var(--sk-nav-height); top: var(--sk-nav-height);
left: calc(100vw - (var(--sidebar-width))); left: calc(100vw - (var(--sidebar-width)));
overflow-y: auto; overflow-y: auto;

Loading…
Cancel
Save