diff --git a/site/content/docs/03-run-time.md b/site/content/docs/03-run-time.md index da65ac2488..d7bf3757df 100644 --- a/site/content/docs/03-run-time.md +++ b/site/content/docs/03-run-time.md @@ -200,6 +200,24 @@ Checks whether a given `key` has been set in the context of a parent component. ``` +#### `getAllContexts` + +```js +contexts: Map = getAllContexts() +``` + +--- + +Retrieves the whole context map that belongs to the closest parent component. Must be called during component initialisation. Useful, for example, if you programmatically create a component and want to pass the existing context to it. + +```sv + +``` + #### `createEventDispatcher` ```js diff --git a/src/runtime/index.ts b/src/runtime/index.ts index b3451ed5cb..8e12f9f0ee 100644 --- a/src/runtime/index.ts +++ b/src/runtime/index.ts @@ -7,6 +7,7 @@ export { afterUpdate, setContext, getContext, + getAllContexts, hasContext, tick, createEventDispatcher, diff --git a/src/runtime/internal/lifecycle.ts b/src/runtime/internal/lifecycle.ts index a84bcc689b..bb3df3d295 100644 --- a/src/runtime/internal/lifecycle.ts +++ b/src/runtime/internal/lifecycle.ts @@ -54,6 +54,10 @@ export function getContext(key): T { return get_current_component().$$.context.get(key); } +export function getAllContexts = Map>(): T { + return get_current_component().$$.context; +} + export function hasContext(key): boolean { return get_current_component().$$.context.has(key); } diff --git a/src/runtime/ssr.ts b/src/runtime/ssr.ts index c75bb30349..69fe841e5c 100644 --- a/src/runtime/ssr.ts +++ b/src/runtime/ssr.ts @@ -1,6 +1,7 @@ export { setContext, getContext, + getAllContexts, hasContext, tick, createEventDispatcher, diff --git a/test/runtime/samples/context-api-d/Leaf.svelte b/test/runtime/samples/context-api-d/Leaf.svelte new file mode 100644 index 0000000000..02b6b26e00 --- /dev/null +++ b/test/runtime/samples/context-api-d/Leaf.svelte @@ -0,0 +1,9 @@ + + +{#each [...context.keys()] as key} +
{key}: {context.get(key)}
+{/each} diff --git a/test/runtime/samples/context-api-d/Nested.svelte b/test/runtime/samples/context-api-d/Nested.svelte new file mode 100644 index 0000000000..e8a7e083c3 --- /dev/null +++ b/test/runtime/samples/context-api-d/Nested.svelte @@ -0,0 +1,8 @@ + + + \ No newline at end of file diff --git a/test/runtime/samples/context-api-d/_config.js b/test/runtime/samples/context-api-d/_config.js new file mode 100644 index 0000000000..a5b0769f8b --- /dev/null +++ b/test/runtime/samples/context-api-d/_config.js @@ -0,0 +1,7 @@ +export default { + html: ` +
a: 1
+
b: 2
+
c: 3
+ ` +}; diff --git a/test/runtime/samples/context-api-d/main.svelte b/test/runtime/samples/context-api-d/main.svelte new file mode 100644 index 0000000000..82d1021574 --- /dev/null +++ b/test/runtime/samples/context-api-d/main.svelte @@ -0,0 +1,8 @@ + + + + +