* 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
* fix: hydrate HTML with surrounding whitespace
* add test
* fix a few more short comments
* tidy up
* avoid magic strings
* avoid magic strings
* fix
* oops
* use server-rendered HTML as hydration test starting point
* update tests
* remove _before.html files
* remove _before_head.html files
* override output with _expected.html
* expected output for binding-input case
* remove unused files
* fix
* changeset
* feat: take form resets into account for two way bindings
When resetting a form, the value of the inputs within it get out of sync with the bound value of those inputs. This PR introduces a reset listener on the parent form to reset the value in that case
closes#2659
* slightly different approach
* tweaks, test
* this is a breaking change, strictly speaking
* bind:files
* use capture phase
* tweak wording
* use promise, explain
* breaking: apply fallback value every time in runes mode
closes#9948
* apply fallback value in setter
* encapsulate fallback logic
* we should keep this logic out of b.set, since it's very specific to accessors
* oops
---------
Co-authored-by: Rich Harris <rich.harris@vercel.com>
* fix: improve element class attribute behaviour
* Update packages/svelte/src/internal/client/dom/elements/class.js
Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
---------
Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
* follow up to 10846
* lint
* simplify
* don't update value
* rework logic, rely more on mutation observer, fix bug related to select multiple
* fix lazy select options bug
---------
Co-authored-by: Simon Holthausen <simon.holthausen@vercel.com>
Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
Co-authored-by: brunnerh <brunnerh@users.noreply.github.com>
* feat: add support for webkitdirectory DOM boolean attribute
* add to types
---------
Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
* feat: adds reactive Map class to svelte/reactivity
* add docs
* add docs
* add test case
* types
* make reactive set better
* address feedback
* fix typo
* more efficient initialisation
* this is incorrect, it would fail if given a map for example
* increase consistency (with e.g. proxy.js)
* tidy up
* Revert "more efficient initialisation"
This reverts commit 29d4a8078b.
* efficient initialization, without bugs this time
* convention
* delete make_iterable
* update changeset
* efficient initialization
* avoid generator functions
* Update sites/svelte-5-preview/src/routes/docs/content/01-api/02-runes.md
---------
Co-authored-by: Rich Harris <rich.harris@vercel.com>
Co-authored-by: Rich Harris <richard.a.harris@gmail.com>
* fix: invalidate store when mutated inside each block
fixes#10771
* Update packages/svelte/src/compiler/phases/3-transform/client/visitors/template.js
We can simplify pre effects by not doing the flush logic at all now. Instead we can move the flushing logic to the only place its needed – for beforeUpdate
* feat: add reactive Set class to svelte/reactivity
* add some type safety
* simplify, read entries lazily
* failing unit test
* fix deletions
* minor tweaks
* work around effect ordering bug
* simplify, make entries lazy
* small tweak
* use var, minor tweaks
---------
Co-authored-by: Rich Harris <rich.harris@vercel.com>
* Docs: Change all initizlisation to initialisation
* Reverted to "initialization" when asserting errors with specific message
* Reverted to "initialization" where related to specific error message
- run reactive statements only once per tick, even when they have indirect cyclic dependencies. Made possible by adding an array to the component context, which is filled with identifiers of the reactive statements, and which is cleared after all have run. Reactive statements rerunning before that will bail early if they detect they're still in the list
- part of the solution is to run all reactive statements, and then all render effects, which also fixes#10597
* fix: improve bind:this support around proxyied state
* fix: improve bind:this support around proxyied state
* fix: improve bind:this support around proxyied state
* fix: treat snippets like normal components when inferring namespace
* n
* simplify
* better desc
* slight adjustment
* feedback
Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
* feedback
Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
* skip html tag
* test
* changeset name
* cleanup
---------
Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
- widen ownership when getContext is called, part of #10649
- widen ownership when assigning one proxy to another
- skip first 4 stack trace entries and bail if first after that is not a module, hinting at a mutation encapsulated in a .svelte.js file; part of #10649
* feat: improve ssr html mismatch validation
* update types
* Update packages/svelte/src/internal/server/index.js
Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
* Update packages/svelte/src/compiler/validate-options.js
Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>
* feedback
---------
Co-authored-by: Simon H <5968653+dummdidumm@users.noreply.github.com>