2021-02-01 19:51:22 +01:00
|
|
|
<script>
|
2021-02-05 17:16:41 +01:00
|
|
|
import { getContext, setContext, onMount } from "svelte"
|
|
|
|
import { datasourceStore, createContextStore } from "../store"
|
|
|
|
import { ActionTypes } from "../constants"
|
|
|
|
import { generate } from "shortid"
|
2021-02-01 19:51:22 +01:00
|
|
|
|
|
|
|
export let data
|
|
|
|
export let actions
|
2021-02-05 12:44:33 +01:00
|
|
|
export let key
|
2021-02-01 19:51:22 +01:00
|
|
|
|
|
|
|
// Clone and create new data context for this component tree
|
|
|
|
const context = getContext("context")
|
|
|
|
const component = getContext("component")
|
|
|
|
const newContext = createContextStore($context)
|
|
|
|
setContext("context", newContext)
|
2021-02-05 12:44:33 +01:00
|
|
|
$: providerKey = key || $component.id
|
2021-02-01 19:51:22 +01:00
|
|
|
|
2021-02-05 17:16:41 +01:00
|
|
|
// Instance ID is unique to each instance of a provider
|
|
|
|
let instanceId
|
|
|
|
|
2021-02-01 19:51:22 +01:00
|
|
|
// Add data context
|
2021-02-05 13:54:36 +01:00
|
|
|
$: data !== undefined && newContext.actions.provideData(providerKey, data)
|
2021-02-01 19:51:22 +01:00
|
|
|
|
|
|
|
// Add actions context
|
|
|
|
$: {
|
2021-02-05 17:16:41 +01:00
|
|
|
if (instanceId) {
|
|
|
|
actions?.forEach(({ type, callback, metadata }) => {
|
|
|
|
newContext.actions.provideAction(providerKey, type, callback)
|
|
|
|
|
|
|
|
// Register any "refresh datasource" actions with a singleton store
|
|
|
|
// so we can easily refresh data at all levels for any datasource
|
|
|
|
if (type === ActionTypes.RefreshDatasource) {
|
|
|
|
const { datasource } = metadata || {}
|
|
|
|
datasourceStore.actions.registerDatasource(
|
|
|
|
datasource,
|
|
|
|
instanceId,
|
|
|
|
callback
|
|
|
|
)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2021-02-01 19:51:22 +01:00
|
|
|
}
|
2021-02-05 17:16:41 +01:00
|
|
|
|
|
|
|
onMount(() => {
|
|
|
|
// Generate a permanent unique ID for this component and use it to register
|
|
|
|
// any datasource actions
|
|
|
|
instanceId = generate()
|
|
|
|
|
|
|
|
// Unregister all datasource instances when unmounting this provider
|
|
|
|
return () => datasourceStore.actions.unregisterInstance(instanceId)
|
|
|
|
})
|
2021-02-01 19:51:22 +01:00
|
|
|
</script>
|
|
|
|
|
|
|
|
<slot />
|