Skip to content

Commit a0fda48

Browse files
committed
add mock state.ts
1 parent 1abc1a5 commit a0fda48

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import { getContext, setContext } from 'svelte';
2+
import { state } from 'svelte/reactivity';
3+
4+
function createMockedStateValue<T>(contextName: string, defaultValue?: T) {
5+
let value = state.raw(getContext(contextName) ?? defaultValue);
6+
7+
return {
8+
get current() {
9+
return value;
10+
},
11+
set current(newValue: T) {
12+
value = newValue;
13+
setContext(contextName, newValue);
14+
}
15+
};
16+
}
17+
18+
function createPageState() {
19+
const contextValue = getContext('page-state-ctx') ?? {
20+
url: new URL('http://localhost:6006'),
21+
params: {},
22+
route: {
23+
id: '/'
24+
},
25+
status: 200,
26+
error: null,
27+
data: {},
28+
form: undefined,
29+
state: {}
30+
};
31+
32+
return state.raw(contextValue);
33+
}
34+
35+
function createNavigatingState() {
36+
const contextValue = getContext('navigating-state-ctx') ?? null;
37+
return state.raw(contextValue);
38+
}
39+
40+
function createUpdatedState() {
41+
const updatedValue = createMockedStateValue('updated-state-ctx', false);
42+
43+
return {
44+
get current() {
45+
return updatedValue.current;
46+
},
47+
check: async () => {
48+
const event = new CustomEvent('storybook:updated-check');
49+
window.dispatchEvent(event);
50+
return false;
51+
}
52+
};
53+
}
54+
55+
export const page = createPageState();
56+
export const navigating = createNavigatingState();
57+
export const updated = createUpdatedState();
58+
59+
export function setPageState(value: any) {
60+
setContext('page-state-ctx', value);
61+
}
62+
63+
export function setNavigatingState(value: any) {
64+
setContext('navigating-state-ctx', value);
65+
}
66+
67+
export function setUpdatedState(value: boolean) {
68+
setContext('updated-state-ctx', value);
69+
}

code/frameworks/sveltekit/src/plugins/mock-sveltekit-stores.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ export function mockSveltekitStores() {
88
alias: {
99
'$app/forms': '@storybook/sveltekit/internal/mocks/app/forms',
1010
'$app/navigation': '@storybook/sveltekit/internal/mocks/app/navigation',
11+
'$app/state': '@storybook/sveltekit/internal/mocks/app/state',
1112
'$app/stores': '@storybook/sveltekit/internal/mocks/app/stores',
1213
},
1314
},

0 commit comments

Comments
 (0)