- give autocompletion for types and more precise event types for html elements
- allow to pass other kinds of event target nodes, like window
closes#12027fixes#12045
We need to ensure that if derived a depends on derived b, and a is reconnecting to the dependency graph, that if b was updated more recently than a, a also updates.
Fixes#11988Fixes#12044
* fix: ensure bound input content is resumed on hydration
* fix: ensure bound input content is resumed on hydration
* Update packages/svelte/src/internal/client/dom/elements/bindings/input.js
Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
* fix: ensure bound input content is resumed on hydration
* fix: ensure bound input content is resumed on hydration
* Update packages/svelte/src/internal/client/dom/elements/bindings/input.js
Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
* add test
* add test
* add test
* add test
* Update packages/svelte/src/internal/client/dom/elements/bindings/input.js
Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
* add test
* add test
* newlines between multi-line blocks, let the code breathe
---------
Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
Co-authored-by: Rich Harris <rich.harris@vercel.com>
In a handful of places, we're using effect(...) to defer work that only needs to happen once (like autofocusing an element). This is overkill. There is a much cheaper and simpler way that already exists in the codebase — queue_micro_task.
It feels like we could probably use it in more places, but when I tried it causes some tests to fail, likely because of subtle timing issues that don't apply to the things changed in this PR.
* fix: create sources for initial values of Set
* fix: create sources lazily on Set
* fix: avoid creating sources if sizes are the same
* chore: add test for size of Set
* create iterator lazily
* tidy up test
* oops
---------
Co-authored-by: Rich Harris <rich.harris@vercel.com>
When an event listener is removed right before it would be fired, adding a new listener comes too late for the browser and the event is swallowed.
The fix is to tweak the spread attributes function to keep using the same object for updates so that we can wrap the event listener to invoke it like `attributes[key](evt)` instead.
No test because it seems impossible to reproduce in testing environments.
Fixes#11903
* docs: make legacy.componentApi more visible
People didn't know that this exists, so we should make it more visible through having it be part of the error message, and calling it out in the docs with more details
* clarify
* flesh out message, put error behind a function
* make it work with HMR
* fix
* fix
* this makes it work. i don't fully understand why
* changeset
* changeset
* Delete .changeset/twelve-foxes-press.md
---------
Co-authored-by: Rich Harris <rich.harris@vercel.com>
The current type narrows the binding type to `""` by default, which means "no bindings on this component". While this is the common case, it makes it very cumbersome to use the `Component` type because legacy components are of type `string` and as soon as you have bindings, the type is something like `"foo" | "bar"` which _also_ is not assignable to `""` which is semantically wrong, because you should be able to assign a component that can have bindings to a type that accepts none.
The pragmatic solution is to change the binding type to allow `string`, which means someone theoretically could use bindings with a component that doesn't have bindings:
```svelte
<script>
let component: Component<{ prop: boolean }> = IAcceptNoBindings;
</script>
<!-- allowed but should be a type error -->
<svelte:component this={component} bind:prop={foo} />
```
But this is a) rare anyway and b) can be caught at runtime
This came up in comments of #11775
* fix: append start/end info to more tags
We should add them everywhere we can
Related https://github.com/sveltejs/language-tools/pull/2385
* changeset
---------
Co-authored-by: Rich Harris <rich.harris@vercel.com>
Also remove create_block function in favor of calling visit which in turn calls the fragment visitor, to ensure scope is updated correctly
Fixes#11450
---------
Co-authored-by: Rich Harris <rich.harris@vercel.com>
Both `<svelte:element this="div">` and `<svelte:element this={"div"}>` were backported as `tag: "div"` for the old AST. That's wrong because the latter should result in `tag: { type: 'Literal', .. }`. Fixing this makes all the tests in prettier-plugin-svelte pass with Svelte 5.
Also cleaned up a bit of code in the parser.
* fix: populate `this.#sources` when constructing reactive map
* populate sources in first #read_all
* use increment helper
* use numbers instead of symbols
* make forEach work
* feat: bind `activeElement` and `pointerLockElement` in `<svelte:document>`
* add test, use focusin/focusout rather than focus/blur
---------
Co-authored-by: Rich Harris <rich.harris@vercel.com>
* fix: silence `state_referenced_locally` when state is exported
* chore: add changesets
* chore: use `some`
* fix
* better
* we don't need a whole new test for this
* Update .changeset/few-zoos-own.md
* prettier
* tidy up the test a bit since we're in here
---------
Co-authored-by: Rich Harris <rich.harris@vercel.com>
Co-authored-by: Rich Harris <hello@rich-harris.dev>
* fix: keep default values of props a proxy after reassignment
* fix: make this work for non bindable props too
* chore: more comprehensive test
* chore: cast away
* chore: better variable name and check
* chore: fix lint
Closes#11727.
This PR aims to tackle issues around our reactive Map/Set implementations. Notably:
- We now store the values on the backing Map/Set, allowing for much better introspection in console/dev tools
- We no longer store the values inside the source signals, instead we use Symbols and booleans only as markers
There's one limitation around `.has(x)` when `x` is not in the Map/Set yet - it's not fine-grained. Making it so could create too much memory pressure when e.g. iterating a big list of items with few of them being in the set (`has` returns `false` most of the time).
When a proxy is reassigned, we call `$.proxy` again. There are cases where there's a component context set but the reassignment actually happens for variable that is ownerless within shared state or somewhere else. In that case we get false positives right now. The inverse is also true where reassigning can delete owners (because no component context exists) and result in false negatives. The fix is to pass the previous value in to copy over the owners from it.
Fixes#11525
Fixes#11817.
It turns out that we weren't fully handling the disconnection of derived signals from the reactivity graph – resulting in cases where they could leak memory because they were not being removed from their dependency reactions array. However, removing ourselves from this array meant that any future changes might mean we need to reconnect the derived to the graph again – so we have to do some additional bookkeeping to make this work. Thankfully, we already have versioning because of unowned deriveds, we can use the versions to understand if the owned derived signal is dirty after being connected to the reactivity graph again – something we couldn't do in early permutations of the signal architecture – and likely why we hadn't addressed this in the same sense.
If a property is mutated, the assumption is that it is deeply reactive. In those cases, the fallback value should be proxified so that it also is deeply reactive.
fixes#11425
- the previous assumption was wrong: browser don't fire a scroll event initially when the scroll isn't smooth
- the previous logic wasn't using the "is scrolling now" logic which meant the render effect fired immediately after, causing smooth scrolling to start too late to be overridden
adjusted the comment and reused the scroll handler function to guard against the race condition
fixes#11623
In Svelte 3 and 4, components were classes under the hood, and the base class was `SvelteComponent`. This class was also used in language tools to properly type check the template code.
In Svelte 5, components are functions. To give people a way to extend them programmatically, it would be good to expose the actual shape of components. This is why this PR introduces a new `Component` type.
For backwards compatibility reasons, we can't just get rid of the old class-based types. We also need to ensure that language tools can work with both the new and old types: There are many libraries out there that provide `d.ts` files with type definitions written using the class types - these should not error.
That's why there's an accompagning language tools PR (https://github.com/sveltejs/language-tools/pull/2380) that's doing the heavy lifting: Instead of generating classes, it now generates a constant and an interfaces and uses Typescript's declaration merging feature to provide both so we can declare a component export as being both a class and a function. That ensures that people can still instantiate them with `new` (which they can do if they use the `legacy.componentApi` compiler option), and it also ensure we don't need to adjust any other code generation mechanisms in language tools yet - from a language tools perspective, classes are still the norm. But through exposing the default export as being _also_ callable as a function we can in a future Svelte version, where classes/the Svelte 4 syntax are removed completely, seamlessly switch over to using functions in the code generation, too, and the `d.ts` files generated up until that point will support it because of the dual shape. This way we have both backwards and forwards compatibility.
* breaking: disallow string literal values in `<svelte:element this="...">`
* note breaking change
* Update sites/svelte-5-preview/src/routes/docs/content/03-appendix/02-breaking-changes.md
Co-authored-by: Jeremiasz Major <jrh.mjr@gmail.com>
* prettier
* make invalid `<svelte:element this>` a warning instead of an error (#11641)
* make it a warning instead of an error
* format
---------
Co-authored-by: Jeremiasz Major <jrh.mjr@gmail.com>
In the case of an invalid child element, we already get information about the parent and the child, but in other cases where a mismatch could occur you're pretty much on your own.
This adds a bit more context to hydration_mismatch warnings — 'The error occurred near ...'
* feat: add rootDir option and set __svelte_meta.file like in svelte4
* Update packages/svelte/src/compiler/validate-options.js
* update tests
* centralise logic
* fix
* note to self
* Apply suggestions from code review
* lint
* one dollar towards the windows backslash bugfix foundation please
---------
Co-authored-by: Rich Harris <rich.harris@vercel.com>
Co-authored-by: Simon Holthausen <simon.holthausen@vercel.com>
* feat: add $state.is rune
* fix type
* tweak docs
* may as well update the test case to match the docs
---------
Co-authored-by: Rich Harris <rich.harris@vercel.com>
* chore: improve SSR invalid element error message
* move push_element and pop_element into new dev.js file
* pass location info, remove unnecessary if (DEV) block
* use full filename, basename is not very helpful. also, current_component is guaranteed to not be null
* current_element is guaranteed to not be null in pop_element
* tweaks
* remove message prefix - redundant when filenames are included
* add line/column
* make message more concise
* reduce indirection
* only print message once
* update test
---------
Co-authored-by: Rich Harris <rich.harris@vercel.com>
* fix: adjust heuristics for effect_update_depth_exceeded
* fix: adjust heuristics for effect_update_depth_exceeded
* fix: further adjust heuristics for effect_update_depth_exceeded
In edge cases it may happen that set_attributes is re-run before the effect is executed. In that case the render effect which initiates this re-run will destroy the inner effect and it will never run. But because next and prev may have the same keys, the event would not get added again and it would get lost. We prevent this by using a root effect.
The added test case doesn't fail for some reason without this fix, but it does fail when you test it out manually, so I still added it.
Found through https://github.com/sveltejs/svelte/issues/10359#issuecomment-2101167524
* fix: make `$effect.active()` true when updating deriveds
* WIP
* this seems to work?
* prevent effects being created in unowned deriveds
* update test
* fix issue
---------
Co-authored-by: Dominic Gannaway <dg@domgan.com>
* fix: use snippet as parent element of snippets childrens in validator
* Update packages/svelte/src/compiler/phases/2-analyze/validation.js
* Update .changeset/wet-pears-remain.md
---------
Co-authored-by: Rich Harris <hello@rich-harris.dev>
* fix: use acceptExports to support partial hmr
* fix: add condition to only use acceptExports when it is available
* fix: update test snapshot
* fix: format
* Fixed: bind:scroll resets scroll state
* failing test
* bail if value is undefined
* changeset
---------
Co-authored-by: Rich Harris <rich.harris@vercel.com>
Deriveds where under certain conditions not detected as dirty correctly. The reason is that a transitive check_dirtiness call could update the flag of a derived, even if the condition doesn't ulimately result to true. That's why the check for "is now dirty" needs to be moved out of the inner if block.
Fixes#11481
This may also fix a yet undetected overfiring bug in the "is unowned" case because the previous inner "is now dirty?" check didn't take unowned into account.
fixes#11483
We need to keep track of the component function similar to how we keep track of the component context, so that effects etc have the correct one associated
Ownership validation had a false positive when rendering a component as slotted content of another component. To fix this, #11401 did set the current component context to the context the snippet was declared in, not to the context it is rendered in. This was flawed because it means that component context was altered in a way that setContext/getContext failed because the parent chain was incorrect. This fixes that by introducing a separate global (dev time only) which tracks the component function the ownership needs.
fixes#11429
Instead of using types that declare whether or not a type is bindable directly as part of the property, we're introducing a new for-types-only field to `SvelteComponent`: `$$bindings`, which is typed as the keys of the properties that are bindable (string by default, i.e. everything's bindable; for backwards compat). language-tools can then produce code that assigns to this property which results in an error we can display if the binding is invalid
closes#11356
* fix: handle reassignment of `$$props` and `$$restProps`
Some libraries assign to properties of `$$props` and `$$restProps`. These were previously resulting in an error but are now handled properly
https://github.com/sveltejs/svelte/issues/10359#issuecomment-2080067464
* $$props is coarse grained on updates, so we can simplify this
* fix
* fix comment
When spreading attributes, the setters of the element are checked. If they contain the key in question, it's set via that setter. For certain setters on certain elements this didn't work because the element prototype was not HTMLElement, rather a descendant of that (for example HTMLDivElement), which meant that only the setters of the descendant, not the superclass were taken into account. This fixes that by walking up the prototype chain until we find the Element prototype.
fixes#11179
* feat: leave view transition pseudo selectors untouched
view transition pseude selectors are global-like, i.e. they shouldn't be scoped or treated as unused.
In the process of adding support for this, is_root and is_host were consolidated into is_global_like because their usage locations didn't need any differentiation between them (same for the new view transition treatment)
closes#9127
* regenerate types
previously a reaction could be marked as DIRTY and subsequently as MAYBE_DIRTY before running, resulting in false negatives. Ensure that DIRTY flag can never be lowered to MAYBE_DIRTY
fixes#11363
Provides a migration function, exported as `migrate` from `svelte/compiler`, which tries its best to automatically migrate towards runes, render tags (instead of slots) and event attributes (instead of event handlers)
The preview REPL was updated with a migrate button so people can try it out in the playground.
closes#9239
* feat: only inject push/init/pop when necessary - closes#11297
* regenerate
* differentiate between safe/unsafe
* only inject $$props when necessary
* more
* fix
* simplify
* handle store subscriptions
* fix: mark `accessors` and `immutable` as deprecated
* add warnings for deprecated <svelte:options> attributes
* disable accessors in runes mode
* update tests
* tidy up
* the hell?
* regenerate types
* if I would get a dollar for every windows bug I fix I would be a millionaire by now
* return instance _and_ props in runes mode, move flushSync into shared code, don't set accessors in runes mode
* goddammit
* note breaking change
* fix
* regenerate messages
* Revert "return instance _and_ props in runes mode, move flushSync into shared code, don't set accessors in runes mode"
This reverts commit a47827e57d.
* pass instance to tests
---------
Co-authored-by: Simon Holthausen <simon.holthausen@vercel.com>
This is a typings PR and the companion PR to sveltejs/language-tools#2336
It introduces two new types:
- Binding: Marks a property as being bound (i.e. you must do bind:x)
- Bindable: Marks a property as being able to be bound (i.e. you can do bind:x)
Language tools then uses this generate code accordingly which then generates type errors.
All the other type gymnastics are there to ensure that you don't interact with these bindable types when using mount or hydrate or ComponentProps<MyComponent>, i.e. these two types should be mostly opaque for day-to-day users.
For backwards-compatibility, all properties are automatically wrapped with Bindable, which means existing type definition files will continue to work from a types perspective. Language tools opts into strict bindability by providing its own constructor definition for all generated classes in runes mode which omits the "wrap everything with bindable" behavior.
* breaking: disallow binding to component exports in runes mode
Svelte 4 allowed you to have `export const foo = ..` in component A and then do `<A bind:foo />`. This is confusing because it's not clear whether the binding is for a property or an export, and we have to sanitize rest props from the export bindings.
This PR therefore introduces a breaking change in runes mode: You cannot bind to these exports anymore. Instead use `<A bind:this={a} />` and then do `a.foo` - makes things easier to reason about.
* Update sites/svelte-5-preview/src/routes/docs/content/03-appendix/02-breaking-changes.md
Co-authored-by: Rich Harris <rich.harris@vercel.com>
* tweak messages
* fix tests
* use component.name
* oops
---------
Co-authored-by: Rich Harris <rich.harris@vercel.com>
* fix: run event attributes after binding event listeners
By running the event listener logic inside an effect on the first run we guarantee that they're attached after binding listeners. Fixes#11138.
* give arrow functions stable id, better code gen
* optimise normal function expressions too (rare but valid!)
---------
Co-authored-by: Rich Harris <rich.harris@vercel.com>
* Revert "fix: take outroing elements out of the flow when animating siblings (#11208)"
This reverts commit c44234dc2f.
* fix: measure elements before taking siblings out of the flow
* lint
* add changeset back
* changeset
* fix: fall back to component namespace when not statically determinable
In #10006 we added more elaborate mechanisms to determine which namespace a given element is in. For `<svelte:element>` we added a "can't know at compile time" case and introduced a limited heuristic into the runtime.
This doesn't work for a few reasons:
- we're checking the parent's namespace to determine the current namespace, but the element itself could be the one that _changes_ the namespace
- as mentioned in the previous comment already, on the first render we can't do any parent analysis
- it does not take into account the static component namespace
The last point is the crucial one: In Svelte 4, we're falling back to the component namespace if we can't know statically - e.g. if someone added `<svelte:options namespace="svg">` then `<svelte:element>` should fall back to that namespace instead.
We were not doing that up until now, which introduced a regression. Fixing this also means getting rid of the (flawed) "can't know statically" heuristic.
Fixes#10858, though for a complete solution we likely need some way to tell `<svelte:element>` the namespace at runtime through a special attribute. Maybe we can use `xmlns` for that like we do in the static case
* support dynamic svelte:element namespace through xmlns attribute
* fix
* feat: allow $inspect reactivity map, set, date
* feat: inspect map without adding new data source
* feat: add inspect
* feat: define inspect on dev mode only
* fix: lint error
Ownership was not widened when assigning a sub state to a different top level state. The set of owners for the state was zero because the owner was on the original parent, but that one was reset to null because it's now the top level of a different state. That meant that there was no owner but also no parent to check for the owner, which is an invalid combination resulting in a nullpointer (and also potentially false positive warnings in other situations).
fixes#11204
* breaking: warn/error on old syntax in runes mode
- warn on slots and event handlers in runes mode
- error on `<slot>` + `{@render ...}` tag usage in same component
closes#9416
* render tag + slot could occur in legacy mode as well, error there, too
* rename metadata.o to metadata.owners, tweak check_ownership implementation
* track parent relationships
* update
* changeset
* adjust test to reflect new semantics
* prevent component using bind: with object it does not own
* failing test
* fix#11060
* add explanatory comment
* don't accidentally narrow global ownership, fix has_owner method
* widen ownership if assigning different state proxies to one another
* don't set owners to null when parent exists
* fix
* only recurse into POJOs
* handle cycles on context
---------
Co-authored-by: Simon Holthausen <simon.holthausen@vercel.com>
Co-authored-by: Dominic Gannaway <dg@domgan.com>
- don't call fallback values eagerly, only when it's actually needed. Avoids potential unwanted side effects
- use derived_safe_equals to memoize results of destructured snippet/each context values with default values to ensure they're only recalculated when their dependencies change. Avoids unstable default values getting called multiple times yielding different results. Use derived_safe_equals to ensure new values are always set, even when mutated. fixes#11143
* added raw elements set
* added test
* added changeset
* moved raw text elements to constands and made array
* moved to correct constants
* fix test
* fix constants formatting
* feat: hot module reloading support for Svelte 5
* fix lockfile
* tweaks
* types
* lint
* lint
* tweaks
* add hmr flag
* tweak
* tweaks
* move HMR logic into its own module
* simplify
* tidy up types
* fix test
* lint
* need some indirection here or references break
* prevent transitions during HMR update
---------
Co-authored-by: Rich Harris <rich.harris@vercel.com>
* fix: loosen proxy signal creation heuristics
* tighten up test
* update comment
* no need to create a source outside an effect here, because it can't result in a reference
* preserve reference to props.$$events
---------
Co-authored-by: Rich Harris <rich.harris@vercel.com>
- take into account that template could consist of a single script tag, for which querySelectorAll('script') would yield false negatives
- add test to ensure that we don't execute script tags inside `@html` tags next to static script tags
fixes#11082
Previously, ownership widening/removal was only done if the immediate object that was encountered was state. This isn't always the case. It also didn't take into account classes with state on it (which turn into getters). This change takes both these cases into account and now always traverses the given object deeply.
fixes#11060
- don't throw a dev time error when binding to an export (fixes#11008)
- remove bindings that are for component exports
- throw an error when using a component export with the same name as a property