Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow passing in context in constructor #6032

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Svelte changelog

## Unreleased

* Allow root-level context to be passed to the component constructor ([#6032](https://github.com/sveltejs/svelte/pull/6032))

## 3.36.0

* Add `this: void` typing to store functions ([#6094](https://github.com/sveltejs/svelte/pull/6094))
Expand Down
27 changes: 27 additions & 0 deletions site/content/docs/03-run-time.md
Original file line number Diff line number Diff line change
Expand Up @@ -904,6 +904,7 @@ The following initialisation options can be provided:
| `target` | **none** | An `HTMLElement` to render to. This option is required
| `anchor` | `null` | A child of `target` to render the component immediately before
| `props` | `{}` | An object of properties to supply to the component
| `context` | `new Map()` | A `Map` of root-level context key-value pairs to supply to the component
| `hydrate` | `false` | See below
| `intro` | `false` | If `true`, will play transitions on initial render, rather than waiting for subsequent state changes

Expand Down Expand Up @@ -1081,3 +1082,29 @@ const { head, html, css } = App.render({
answer: 42
});
```

---

The `.render()` method accepts the following parameters:

| parameter | default | description |
| --- | --- | --- |
| `props` | `{}` | An object of properties to supply to the component
| `options` | `{}` | An object of options

The `options` object takes in the following options:

| option | default | description |
| --- | --- | --- |
| `context` | `new Map()` | A `Map` of root-level context key-value pairs to supply to the component

```js
const { head, html, css } = App.render(
// props
{ answer: 42 },
// options
{
context: new Map([['context-key', 'context-value']])
}
);
```
2 changes: 1 addition & 1 deletion src/runtime/internal/Component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export function init(component, options, instance, create_fragment, not_equal, p
on_disconnect: [],
before_update: [],
after_update: [],
context: new Map(parent_component ? parent_component.$$.context : []),
context: new Map(parent_component ? parent_component.$$.context : options.context || []),

// everything else
callbacks: blank_object(),
Expand Down
8 changes: 4 additions & 4 deletions src/runtime/internal/ssr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,12 @@ export function debug(file, line, column, values) {
let on_destroy;

export function create_ssr_component(fn) {
function $$render(result, props, bindings, slots) {
function $$render(result, props, bindings, slots, context) {
const parent_component = current_component;

const $$ = {
on_destroy,
context: new Map(parent_component ? parent_component.$$.context : []),
context: new Map(parent_component ? parent_component.$$.context : context || []),

// these will be immediately discarded
on_mount: [],
Expand All @@ -97,7 +97,7 @@ export function create_ssr_component(fn) {
}

return {
render: (props = {}, options = {}) => {
render: (props = {}, { $$slots = {}, context = new Map() } = {}) => {
on_destroy = [];

const result: {
Expand All @@ -109,7 +109,7 @@ export function create_ssr_component(fn) {
}>;
} = { title: '', head: '', css: new Set() };

const html = $$render(result, props, {}, options);
const html = $$render(result, props, {}, $$slots, context);

run_all(on_destroy);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<script>
import { getContext } from 'svelte';

const value = getContext('key');
const fn = getContext('fn');
</script>

<div>{value}</div>
<button on:click={() => fn('hello world')} />
32 changes: 32 additions & 0 deletions test/runtime/samples/constructor-pass-context/_config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
export default {
async test({ assert, target, window }) {
const Component = require('./Component.svelte').default;

const called = [];
const component = new Component({
target,
context: new Map([
['key', 'svelte'],
['fn', (value) => called.push(value)]
])
});
assert.htmlEqual(target.innerHTML, '<div>svelte</div><button></button>');

const button = target.querySelector('button');
await button.dispatchEvent(new window.MouseEvent('click'));

assert.deepEqual(called, ['hello world']);

component.$destroy();
},
test_ssr({ assert }) {
const Component = require('./Component.svelte').default;

const called = [];
const { html } = Component.render(undefined, { context: new Map([
['key', 'svelte'],
['fn', (value) => called.push(value)]
]) });
assert.htmlEqual(html, '<div>svelte</div><button></button>');
}
};
Empty file.
5 changes: 5 additions & 0 deletions test/server-side-rendering/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
shouldUpdateExpected,
mkdirp
} from '../helpers';
import { set_current_component } from '../../internal';

function tryToReadFile(file) {
try {
Expand Down Expand Up @@ -127,6 +128,8 @@ describe('ssr', () => {
showOutput(dir, { generate: 'ssr', format: 'cjs' });
err.stack += `\n\ncmd-click: ${path.relative(process.cwd(), dir)}/main.svelte`;
throw err;
} finally {
set_current_component(null);
}
});
});
Expand Down Expand Up @@ -223,6 +226,8 @@ describe('ssr', () => {
showOutput(cwd, compileOptions);
throw err;
}
} finally {
set_current_component(null);
}
});
});
Expand Down