This repository has been archived by the owner on Jul 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathdirectives.js
235 lines (216 loc) · 5.95 KB
/
directives.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
import { useContext, useMemo, useEffect } from 'preact/hooks';
import { deepSignal, peek } from 'deepsignal';
import { useSignalEffect } from './utils';
import { directive } from './hooks';
import { prefetch, navigate, canDoClientSideNavigation } from './router';
// Check if current page can do client-side navigation.
const clientSideNavigation = canDoClientSideNavigation(document.head);
const isObject = (item) =>
item && typeof item === 'object' && !Array.isArray(item);
const mergeDeepSignals = (target, source) => {
for (const k in source) {
if (typeof peek(target, k) === 'undefined') {
target[`$${k}`] = source[`$${k}`];
} else if (isObject(peek(target, k)) && isObject(peek(source, k))) {
mergeDeepSignals(target[`$${k}`].peek(), source[`$${k}`].peek());
}
}
};
export default () => {
// data-wp-context
directive(
'context',
({
directives: {
context: { default: context },
},
props: { children },
context: inherited,
}) => {
const { Provider } = inherited;
const inheritedValue = useContext(inherited);
const value = useMemo(() => {
const localValue = deepSignal(context);
mergeDeepSignals(localValue, inheritedValue);
return localValue;
}, [context, inheritedValue]);
return <Provider value={value}>{children}</Provider>;
},
{ priority: 5 }
);
// data-wp-effect.[name]
directive('effect', ({ directives: { effect }, context, evaluate }) => {
const contextValue = useContext(context);
Object.values(effect).forEach((path) => {
useSignalEffect(() => {
return evaluate(path, { context: contextValue });
});
});
});
// data-wp-on.[event]
directive('on', ({ directives: { on }, element, evaluate, context }) => {
const contextValue = useContext(context);
Object.entries(on).forEach(([name, path]) => {
element.props[`on${name}`] = (event) => {
evaluate(path, { event, context: contextValue });
};
});
});
// data-wp-class.[classname]
directive(
'class',
({ directives: { class: className }, element, evaluate, context }) => {
const contextValue = useContext(context);
Object.keys(className)
.filter((n) => n !== 'default')
.forEach((name) => {
const result = evaluate(className[name], {
className: name,
context: contextValue,
});
const currentClass = element.props.class || '';
const classFinder = new RegExp(
`(^|\\s)${name}(\\s|$)`,
'g'
);
if (!result)
element.props.class = currentClass
.replace(classFinder, ' ')
.trim();
else if (!classFinder.test(currentClass))
element.props.class = currentClass
? `${currentClass} ${name}`
: name;
useEffect(() => {
// This seems necessary because Preact doesn't change the class names
// on the hydration, so we have to do it manually. It doesn't need
// deps because it only needs to do it the first time.
if (!result) {
element.ref.current.classList.remove(name);
} else {
element.ref.current.classList.add(name);
}
}, []);
});
}
);
// data-wp-bind.[attribute]
directive(
'bind',
({ directives: { bind }, element, context, evaluate }) => {
const contextValue = useContext(context);
Object.entries(bind)
.filter((n) => n !== 'default')
.forEach(([attribute, path]) => {
const result = evaluate(path, {
context: contextValue,
});
element.props[attribute] = result;
// This seems necessary because Preact doesn't change the attributes
// on the hydration, so we have to do it manually. It doesn't need
// deps because it only needs to do it the first time.
useEffect(() => {
// aria- and data- attributes have no boolean representation.
// A `false` value is different from the attribute not being
// present, so we can't remove it.
// We follow Preact's logic: https://github.com/preactjs/preact/blob/ea49f7a0f9d1ff2c98c0bdd66aa0cbc583055246/src/diff/props.js#L131C24-L136
if (result === false && attribute[4] !== '-') {
element.ref.current.removeAttribute(attribute);
} else {
element.ref.current.setAttribute(
attribute,
result === true && attribute[4] !== '-'
? ''
: result
);
}
}, []);
});
}
);
// data-wp-link
directive(
'link',
({
directives: {
link: { default: link },
},
props: { href },
element,
}) => {
useEffect(() => {
// Prefetch the page if it is in the directive options.
if (clientSideNavigation && link?.prefetch) {
prefetch(href);
}
});
// Don't do anything if it's falsy.
if (clientSideNavigation && link !== false) {
element.props.onclick = async (event) => {
event.preventDefault();
// Fetch the page (or return it from cache).
await navigate(href);
// Update the scroll, depending on the option. True by default.
if (link?.scroll === 'smooth') {
window.scrollTo({
top: 0,
left: 0,
behavior: 'smooth',
});
} else if (link?.scroll !== false) {
window.scrollTo(0, 0);
}
};
}
}
);
// data-wp-show
directive(
'show',
({
directives: {
show: { default: show },
},
element,
evaluate,
context,
}) => {
const contextValue = useContext(context);
if (!evaluate(show, { context: contextValue }))
element.props.children = (
<template>{element.props.children}</template>
);
}
);
// data-wp-ignore
directive(
'ignore',
({
element: {
type: Type,
props: { innerHTML, ...rest },
},
}) => {
// Preserve the initial inner HTML.
const cached = useMemo(() => innerHTML, []);
return (
<Type dangerouslySetInnerHTML={{ __html: cached }} {...rest} />
);
}
);
// data-wp-text
directive(
'text',
({
directives: {
text: { default: text },
},
element,
evaluate,
context,
}) => {
const contextValue = useContext(context);
element.props.children = evaluate(text, { context: contextValue });
}
);
};