-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathExpandableCode.tsx
More file actions
92 lines (86 loc) · 2.39 KB
/
ExpandableCode.tsx
File metadata and controls
92 lines (86 loc) · 2.39 KB
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
'use client';
import {ActionButton} from '@react-spectrum/s2';
import {flushSync} from 'react-dom';
import React, {CSSProperties, ReactNode, useRef, useState} from 'react';
import {style} from '@react-spectrum/s2/style' with {type: 'macro'};
const example = style({
font: 'code-lg',
maxHeight: {
default: '[6lh]',
isExpanded: 800
},
overflow: {
default: 'clip',
isExpanded: 'auto'
},
position: 'relative',
width: 'full',
borderBottomRadius: 'xl',
'--import-display': {
type: 'display',
value: {
default: 'none',
isExpanded: 'inline'
}
},
'--code-padding-end': {
type: 'paddingEnd',
value: {
default: 16,
isExpanded: 64 // Extra space for the toolbar
}
}
});
const expandWrapper = style({
position: {
default: 'absolute',
isExpanded: 'static'
},
bottom: 0,
insetX: 0,
display: 'flex',
justifyContent: 'center',
paddingY: 8
});
export function ExpandableCode({children, hasHighlightedLine}: {children: ReactNode, hasHighlightedLine?: boolean}) {
let [isExpanded, setExpanded] = useState(false);
let ref = useRef<HTMLDivElement | null>(null);
let mask: string | undefined;
let padding: string | undefined;
if (!isExpanded) {
if (hasHighlightedLine) {
// mask the top, bottom, and right sides
mask = 'linear-gradient(transparent, white 25% 50%, transparent), linear-gradient(to right, white 0% 85%, transparent)';
padding = '0px';
} else {
// only mask the bottom and right
mask = 'linear-gradient(white 0% 50%, transparent), linear-gradient(to right, white 0% 85%, transparent)';
}
}
return (
<div ref={ref} className={example({isExpanded})}>
<div style={{maskImage: mask, maskComposite: 'intersect', maxHeight: isExpanded ? undefined : 'inherit', '--code-padding-y': padding} as CSSProperties}>
{children}
</div>
<div className={expandWrapper({isExpanded})}>
<ActionButton
onPress={() => {
viewTransition(() => {
setExpanded(!isExpanded);
ref.current?.scrollTo(0, 0);
});
}}>
{isExpanded ? 'Collapse code' : 'Expand code'}
</ActionButton>
</div>
</div>
);
}
function viewTransition(cb) {
if ('startViewTransition' in document) {
// @ts-ignore
document.startViewTransition(() => flushSync(() => cb()));
} else {
cb();
}
}