forked from sveltejs/svelte-hmr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
svelte-hooks.js
268 lines (238 loc) · 8.03 KB
/
svelte-hooks.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
/**
* Emulates forthcoming HMR hooks in Svelte.
*
* All references to private component state ($$) are now isolated in this
* module.
*/
import {
current_component,
get_current_component,
set_current_component,
} from 'svelte/internal'
const captureState = cmp => {
// sanity check: propper behaviour here is to crash noisily so that
// user knows that they're looking at something broken
if (!cmp) {
throw new Error('Missing component')
}
if (!cmp.$$) {
throw new Error('Invalid component')
}
const {
$$: { callbacks, bound, ctx },
} = cmp
const state = cmp.$capture_state()
// capturing current value of props (or we'll recreate the component with the
// initial prop values, that may have changed -- and would not be reflected in
// options.props)
const props = Object.assign({}, cmp.$$.props)
Object.keys(cmp.$$.props).forEach(prop => {
props[prop] = ctx[props[prop]]
})
return { ctx, callbacks, bound, state, props }
}
// restoreState
//
// It is too late to restore context at this point because component instance
// function has already been called (and so context has already been read).
// Instead, we rely on setting current_component to the same value it has when
// the component was first rendered -- which fix support for context, and is
// also generally more respectful of normal operation.
//
const restoreState = (cmp, restore) => {
if (!restore) {
return
}
const { callbacks, bound } = restore
if (callbacks) {
cmp.$$.callbacks = callbacks
}
if (bound) {
cmp.$$.bound = bound
}
// props, props.$$slots are restored at component creation (works
// better -- well, at all actually)
}
const get_current_component_safe = () => {
// NOTE relying on dynamic bindings (current_component) makes us dependent on
// bundler config (and apparently it does not work in demo-svelte-nollup)
try {
// unfortunately, unlike current_component, get_current_component() can
// crash in the normal path (when there is really no parent)
return get_current_component()
} catch (err) {
// ... so we need to consider that this error means that there is no parent
//
// that makes us tightly coupled to the error message but, at least, we
// won't mute an unexpected error, which is quite a horrible thing to do
if (err.message === 'Function called outside component initialization') {
// who knows...
return current_component
} else {
throw err
}
}
}
export const createProxiedComponent = (
Component,
initialOptions,
{ allowLiveBinding, onInstance, onMount, onDestroy }
) => {
let cmp
let options = initialOptions
const isCurrent = _cmp => cmp === _cmp
const assignOptions = (target, anchor, restore, preserveLocalState) => {
const props = Object.assign({}, options.props)
// Filtering props to avoid "unexpected prop" warning
// NOTE this is based on props present in initial options, but it should
// always works, because props that are passed from the parent can't
// change without a code change to the parent itself -- hence, the
// child component will be fully recreated, and initial options should
// always represent props that are currnetly passed by the parent
if (options.props && restore.props) {
for (const prop of Object.keys(options.props)) {
if (restore.props.hasOwnProperty(prop)) {
props[prop] = restore.props[prop]
}
}
}
if (preserveLocalState && restore.state) {
if (Array.isArray(preserveLocalState)) {
// form ['a', 'b'] => preserve only 'a' and 'b'
props.$$inject = {}
for (const key of preserveLocalState) {
props.$$inject[key] = restore.state[key]
}
} else {
props.$$inject = restore.state
}
} else {
delete props.$$inject
}
options = Object.assign({}, initialOptions, {
target,
anchor,
props,
hydrate: false,
})
}
const instrument = targetCmp => {
const createComponent = (Component, restore, previousCmp) => {
set_current_component(parentComponent || previousCmp)
const comp = new Component(options)
restoreState(comp, restore)
instrument(comp)
return comp
}
targetCmp.$$.on_before_hmr = []
targetCmp.$$.on_hmr = []
// `conservative: true` means we want to be sure that the new component has
// actually been successfuly created before destroying the old instance.
// This could be useful for preventing runtime errors in component init to
// bring down the whole HMR. Unfortunately the implementation bellow is
// broken (FIXME), but that remains an interesting target for when HMR hooks
// will actually land in Svelte itself.
//
// The goal would be to render an error inplace in case of error, to avoid
// losing the navigation stack (especially annoying in native, that is not
// based on URL navigation, so we lose the current page on each error).
//
targetCmp.$replace = (
Component,
{
target = options.target,
anchor = options.anchor,
preserveLocalState,
conservative = false,
}
) => {
const restore = captureState(targetCmp)
assignOptions(target, anchor, restore, preserveLocalState)
const callbacks = cmp.$$.on_hmr
const afterCallbacks = callbacks.map(fn => fn(cmp)).filter(Boolean)
const previous = cmp
if (conservative) {
try {
const next = createComponent(Component, restore, previous)
// prevents on_destroy from firing on non-final cmp instance
cmp = null
previous.$destroy()
cmp = next
} catch (err) {
cmp = previous
throw err
}
} else {
// prevents on_destroy from firing on non-final cmp instance
cmp = null
if (previous) {
// previous can be null if last constructor has crashed
previous.$destroy()
}
cmp = createComponent(Component, restore, cmp)
}
cmp.$$.hmr_cmp = cmp
for (const fn of afterCallbacks) {
fn(cmp)
}
cmp.$$.on_hmr = callbacks
return cmp
}
// NOTE onMount must provide target & anchor (for us to be able to determinate
// actual DOM insertion point)
//
// And also, to support keyed list, it needs to be called each time the
// component is moved (same as $$.fragment.m)
if (onMount) {
const m = targetCmp.$$.fragment.m
targetCmp.$$.fragment.m = (...args) => {
const result = m(...args)
onMount(...args)
return result
}
}
// NOTE onDestroy must be called even if the call doesn't pass through the
// component's $destroy method (that we can hook onto by ourselves, since
// it's public API) -- this happens a lot in svelte's internals, that
// manipulates cmp.$$.fragment directly, often binding to fragment.d,
// for example
if (onDestroy) {
targetCmp.$$.on_destroy.push(() => {
if (isCurrent(targetCmp)) {
onDestroy()
}
})
}
if (onInstance) {
onInstance(targetCmp)
}
// Svelte 3 creates and mount components from their constructor if
// options.target is present.
//
// This means that at this point, the component's `fragment.c` and,
// most notably, `fragment.m` will already have been called _from inside
// createComponent_. That is: before we have a chance to hook on it.
//
// Proxy's constructor
// -> createComponent
// -> component constructor
// -> component.$$.fragment.c(...) (or l, if hydrate:true)
// -> component.$$.fragment.m(...)
//
// -> you are here <-
//
if (onMount) {
const { target, anchor } = options
if (target) {
onMount(target, anchor)
}
}
}
const parentComponent = allowLiveBinding
? current_component
: get_current_component_safe()
cmp = new Component(options)
cmp.$$.hmr_cmp = cmp
instrument(cmp)
return cmp
}