forked from getsentry/develop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
77 lines (70 loc) · 1.82 KB
/
utils.ts
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
import { useEffect, useCallback, useRef } from "react";
type ClickOutsideCallback = (event: MouseEvent) => void;
export function useOnClickOutside<T>(
ref: React.RefObject<T>,
handler: ClickOutsideCallback
) {
useEffect(() => {
const cb = (event: MouseEvent) => {
// TODO(dcramer): fix any type here
if (!ref.current || !(ref.current as any).contains(event.target)) {
handler(event);
}
};
document.addEventListener("click", cb);
return () => {
document.removeEventListener("click", cb);
};
}, [ref, handler]);
}
type RefCallback<T> = (node: HTMLElement, old: T) => void;
export function useRefWithCallback<T>(
callback: RefCallback<T>
): [React.MutableRefObject<T>, (node: any) => void] {
const ref = useRef<T>();
const setRef = useCallback(
node => {
const old = ref.current;
ref.current = node;
callback(node, old);
},
[callback]
);
return [ref, setRef];
}
export const sortBy = (arr: any[], comp: (any) => any): any[] => {
return arr.sort((a, b) => {
const aComp = comp(a);
const bComp = comp(b);
if (aComp < bComp) {
return -1;
}
if (aComp > bComp) {
return 1;
}
return 0;
});
};
type Page = {
context: {
title?: string;
sidebar_title?: string;
sidebar_order?: number;
};
};
export const sortPages = (
arr: any,
extractor: (any) => Page = n => n
): any[] => {
return arr.sort((a, b) => {
a = extractor(a);
b = extractor(b);
const aso = a.context.sidebar_order >= 0 ? a.context.sidebar_order : 10;
const bso = b.context.sidebar_order >= 0 ? b.context.sidebar_order : 10;
if (aso > bso) return 1;
else if (bso > aso) return -1;
return (a.context.sidebar_title || a.context.title).localeCompare(
b.context.sidebar_title || b.context.title
);
});
};