1
- import { useEffect , useRef , useMemo } from "preact/hooks " ;
2
- import { signal } from "@ preact/signals " ;
1
+ import { signal , useSignalEffect , useSignal as useSignalOriginal } from "@ preact/signals " ;
2
+ import { useEffect , useRef , useMemo , useCallback } from "preact/hooks " ;
3
3
4
4
import {
5
5
createRef as createRefOriginal ,
@@ -31,16 +31,32 @@ export const bracketAccess = (array, index, just, nothing) => {
31
31
}
32
32
} ;
33
33
34
- // This sets the references to an element or component. The current
34
+ // These set the references to an element or component. The current
35
35
// value is always a `Maybe`
36
- export const setRef = ( value , just , nothing ) => ( element ) => {
36
+ export const setTestRef = ( signal , just , nothing ) => ( element ) => {
37
+ let current ;
37
38
if ( element === null ) {
38
- value . current = new nothing ( ) ;
39
+ current = new nothing ( ) ;
39
40
} else {
40
- value . current = new just ( element ) ;
41
+ current = new just ( element ) ;
41
42
}
43
+
44
+ if ( signal ) {
45
+ if ( ! compare ( signal . peek ( ) , current ) ) {
46
+ signal . value = current
47
+ }
48
+ }
49
+ }
50
+
51
+ export const setRef = ( signal , just , nothing ) => {
52
+ return useCallback ( ( element ) => {
53
+ setTestRef ( signal , just , nothing ) ( element )
54
+ } , [ ] )
42
55
} ;
43
56
57
+ // The normal useSignal.
58
+ export const useRefSignal = useSignalOriginal ;
59
+
44
60
// A version of `useSignal` which subscribes to the signal by default (like a
45
61
// state) since we want to re-render every time the signal changes.
46
62
export const useSignal = ( value ) => {
@@ -49,13 +65,6 @@ export const useSignal = (value) => {
49
65
return item ;
50
66
} ;
51
67
52
- // A version of `createRef` with a default value.
53
- export const createRef = ( value ) => {
54
- const ref = createRefOriginal ( ) ;
55
- ref . current = value ;
56
- return ref ;
57
- } ;
58
-
59
68
// A hook to replace the `componentDidUpdate` function.
60
69
export const useDidUpdate = ( callback ) => {
61
70
const hasMount = useRef ( false ) ;
@@ -131,3 +140,26 @@ export const load = async (path) => {
131
140
export const isThruthy = ( value , just , ok ) => {
132
141
return value instanceof ok || value instanceof just
133
142
} ;
143
+
144
+ // Returns a signal for tracking the size of an entity.
145
+ export const useDimensions = ( ref , get , empty ) => {
146
+ const signal = useSignal ( empty ( ) ) ;
147
+
148
+ // Initial setup...
149
+ useSignalEffect ( ( ) => {
150
+ const observer = new ResizeObserver ( ( ) => {
151
+ signal . value = ref . value && ref . value . _0 ? get ( ref . value . _0 ) : empty ( ) ;
152
+ } ) ;
153
+
154
+ if ( ref . value && ref . value . _0 ) {
155
+ observer . observe ( ref . value . _0 ) ;
156
+ }
157
+
158
+ return ( ) => {
159
+ signal . value = empty ( ) ;
160
+ observer . disconnect ( ) ;
161
+ } ;
162
+ } ) ;
163
+
164
+ return signal ;
165
+ }
0 commit comments