/
directives.js
414 lines (379 loc) · 11 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
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
/**
* External dependencies
*/
import {
useContext,
useMemo,
useEffect,
useRef,
useLayoutEffect,
} from 'preact/hooks';
import { deepSignal, peek } from 'deepsignal';
/**
* Internal dependencies
*/
import { createPortal } from './portals';
import { useSignalEffect } from './utils';
import { directive } from './hooks';
import { SlotProvider, Slot, Fill } from './slots';
import { navigate } from './router';
const isObject = ( item ) =>
item && typeof item === 'object' && ! Array.isArray( item );
const mergeDeepSignals = ( target, source, overwrite ) => {
for ( const k in source ) {
if ( isObject( peek( target, k ) ) && isObject( peek( source, k ) ) ) {
mergeDeepSignals(
target[ `$${ k }` ].peek(),
source[ `$${ k }` ].peek(),
overwrite
);
} else if ( overwrite || typeof peek( target, k ) === 'undefined' ) {
target[ `$${ k }` ] = source[ `$${ k }` ];
}
}
};
export default () => {
// data-wp-context
directive(
'context',
( {
directives: { context },
props: { children },
context: inheritedContext,
} ) => {
const { Provider } = inheritedContext;
const inheritedValue = useContext( inheritedContext );
const currentValue = useRef( deepSignal( {} ) );
const passedValues = context.map( ( { value } ) => value );
currentValue.current = useMemo( () => {
const newValue = context
.map( ( c ) => deepSignal( { [ c.namespace ]: c.value } ) )
.reduceRight( mergeDeepSignals );
mergeDeepSignals( newValue, inheritedValue );
mergeDeepSignals( currentValue.current, newValue, true );
return currentValue.current;
}, [ inheritedValue, ...passedValues ] );
return (
<Provider value={ currentValue.current }>{ children }</Provider>
);
},
{ priority: 5 }
);
// data-wp-body
directive( 'body', ( { props: { children } } ) => {
return createPortal( children, document.body );
} );
// data-wp-watch--[name]
directive( 'watch', ( { directives: { watch }, evaluate } ) => {
watch.forEach( ( entry ) => {
useSignalEffect( () => evaluate( entry ) );
} );
} );
// data-wp-init--[name]
directive( 'init', ( { directives: { init }, evaluate } ) => {
init.forEach( ( entry ) => {
useEffect( () => evaluate( entry ), [] );
} );
} );
// data-wp-on--[event]
directive( 'on', ( { directives: { on }, element, evaluate } ) => {
on.forEach( ( entry ) => {
element.props[ `on${ entry.suffix }` ] = ( event ) => {
evaluate( entry, event );
};
} );
} );
// data-wp-class--[classname]
directive(
'class',
( { directives: { class: className }, element, evaluate } ) => {
className
.filter( ( { suffix } ) => suffix !== 'default' )
.forEach( ( entry ) => {
const name = entry.suffix;
const result = evaluate( entry, { className: name } );
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 );
}
}, [] );
} );
}
);
const newRule =
/(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g;
const ruleClean = /\/\*[^]*?\*\/| +/g;
const ruleNewline = /\n+/g;
const empty = ' ';
/**
* Convert a css style string into a object.
*
* Made by Cristian Bote (@cristianbote) for Goober.
* https://unpkg.com/browse/goober@2.1.13/src/core/astish.js
*
* @param {string} val CSS string.
* @return {Object} CSS object.
*/
const cssStringToObject = ( val ) => {
const tree = [ {} ];
let block, left;
while ( ( block = newRule.exec( val.replace( ruleClean, '' ) ) ) ) {
if ( block[ 4 ] ) {
tree.shift();
} else if ( block[ 3 ] ) {
left = block[ 3 ].replace( ruleNewline, empty ).trim();
tree.unshift( ( tree[ 0 ][ left ] = tree[ 0 ][ left ] || {} ) );
} else {
tree[ 0 ][ block[ 1 ] ] = block[ 2 ]
.replace( ruleNewline, empty )
.trim();
}
}
return tree[ 0 ];
};
// data-wp-style--[style-key]
directive( 'style', ( { directives: { style }, element, evaluate } ) => {
style
.filter( ( { suffix } ) => suffix !== 'default' )
.forEach( ( entry ) => {
const key = entry.suffix;
const result = evaluate( entry, { key } );
element.props.style = element.props.style || {};
if ( typeof element.props.style === 'string' )
element.props.style = cssStringToObject(
element.props.style
);
if ( ! result ) delete element.props.style[ key ];
else element.props.style[ key ] = result;
useEffect( () => {
// This seems necessary because Preact doesn't change the styles 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.style.removeProperty( key );
} else {
element.ref.current.style[ key ] = result;
}
}, [] );
} );
} );
// data-wp-bind--[attribute]
directive( 'bind', ( { directives: { bind }, element, evaluate } ) => {
bind.filter( ( { suffix } ) => suffix !== 'default' ).forEach(
( entry ) => {
const attribute = entry.suffix;
const result = evaluate( entry );
element.props[ attribute ] = result;
// Preact doesn't handle the `role` attribute properly, as it doesn't remove it when `null`.
// We need this workaround until the following issue is solved:
// https://github.com/preactjs/preact/issues/4136
useLayoutEffect( () => {
if (
attribute === 'role' &&
( result === null || result === undefined )
) {
element.ref.current.removeAttribute( attribute );
}
}, [ 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( () => {
const el = element.ref.current;
// We set the value directly to the corresponding
// HTMLElement instance property excluding the following
// special cases.
// We follow Preact's logic: https://github.com/preactjs/preact/blob/ea49f7a0f9d1ff2c98c0bdd66aa0cbc583055246/src/diff/props.js#L110-L129
if (
attribute !== 'width' &&
attribute !== 'height' &&
attribute !== 'href' &&
attribute !== 'list' &&
attribute !== 'form' &&
// Default value in browsers is `-1` and an empty string is
// cast to `0` instead
attribute !== 'tabIndex' &&
attribute !== 'download' &&
attribute !== 'rowSpan' &&
attribute !== 'colSpan' &&
attribute !== 'role' &&
attribute in el
) {
try {
el[ attribute ] =
result === null || result === undefined
? ''
: result;
return;
} catch ( err ) {}
}
// 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 !== null &&
result !== undefined &&
( result !== false || attribute[ 4 ] === '-' )
) {
el.setAttribute( attribute, result );
} else {
el.removeAttribute( attribute );
}
}, [] );
}
);
} );
// data-wp-navigation-link
directive(
'navigation-link',
( {
directives: { 'navigation-link': navigationLink },
props: { href },
element,
} ) => {
const { value: link } = navigationLink.find(
( { suffix } ) => suffix === 'default'
);
useEffect( () => {
// Prefetch the page if it is in the directive options.
if ( link?.prefetch ) {
// prefetch( href );
}
} );
// Don't do anything if it's falsy.
if ( 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-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 }, element, evaluate } ) => {
const entry = text.find( ( { suffix } ) => suffix === 'default' );
element.props.children = evaluate( entry );
} );
// data-wp-slot
directive(
'slot',
( { directives: { slot }, props: { children }, element } ) => {
const { value } = slot.find(
( { suffix } ) => suffix === 'default'
);
const name = typeof value === 'string' ? value : value.name;
const position = value.position || 'children';
if ( position === 'before' ) {
return (
<>
<Slot name={ name } />
{ children }
</>
);
}
if ( position === 'after' ) {
return (
<>
{ children }
<Slot name={ name } />
</>
);
}
if ( position === 'replace' ) {
return <Slot name={ name }>{ children }</Slot>;
}
if ( position === 'children' ) {
element.props.children = (
<Slot name={ name }>{ element.props.children }</Slot>
);
}
},
{ priority: 4 }
);
// data-wp-fill
directive(
'fill',
( { directives: { fill }, props: { children }, evaluate } ) => {
const entry = fill.find( ( { suffix } ) => suffix === 'default' );
const slot = evaluate( entry );
return <Fill slot={ slot }>{ children }</Fill>;
},
{ priority: 4 }
);
// data-wp-slot-provider
directive(
'slot-provider',
( { props: { children } } ) => (
<SlotProvider>{ children }</SlotProvider>
),
{ priority: 4 }
);
const InfiniteScroll = ( {
elementType: Type,
pageId,
children,
...props
} ) => {
const { current: pages } = useRef( new Map() );
if ( ! pages.has( pageId ) ) pages.set( pageId, children );
return <Type { ...props }>{ [ ...pages.values() ] }</Type>;
};
directive(
'infinite-scroll',
( { directives: { 'infinite-scroll': isr }, element } ) => {
const { value } = isr.find( ( e ) => e.suffix === 'default' );
element.props.elementType = element.type;
element.props.pageId = value;
element.type = InfiniteScroll;
}
);
};