-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathFigspec.tsx
243 lines (202 loc) · 5.45 KB
/
Figspec.tsx
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
/** @jsx jsx */
import type {
FileResponse,
FileNodesResponse,
FileImageResponse,
Node,
} from "figma-js";
import { FC, Fragment, useEffect, useMemo, useState } from "react";
import {
FigspecFileViewer,
FigspecFileViewerProps,
FigspecFrameViewer,
FigspecFrameViewerProps,
} from "@figspec/react";
import { Placeholder } from "@storybook/components";
import { css, jsx } from "@storybook/theming";
import { FigspecConfig } from "../../config";
import { figmaURLPattern } from "./Figma";
const fullscreen = css`
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
`;
type RenderItem =
| {
type: "file";
props: Pick<
FigspecFileViewerProps,
"documentNode" | "renderedImages" | "link"
>;
}
| {
type: "frame";
props: Pick<FigspecFrameViewerProps, "nodes" | "renderedImage" | "link">;
};
type Remote<T, E = Error> =
| {
state: "fetched";
value: T;
}
| {
state: "failed";
error: E;
}
| {
state: "loading";
};
function unwrapJson<T>(res: Response): Promise<T> {
return res.status !== 200
? Promise.reject(res.statusText)
: (res.json() as Promise<T>);
}
/**
* Safely get Figma API access token.
*/
function getAccessToken(cfg: FigspecConfig): string | null {
if (cfg.accessToken) {
return cfg.accessToken;
}
try {
return process.env.STORYBOOK_FIGMA_ACCESS_TOKEN ?? null;
} catch (err) {
// The only case here is no DefinePlugin entry for `process.env` nor
// `process.env.STORYBOOK_FIGMA_ACCESS_TOKEN`. We can safely ignore this.
return null;
}
}
interface Props {
config: FigspecConfig;
}
export const Figspec: FC<Props> = ({ config }) => {
const [state, setState] = useState<Remote<RenderItem, string>>({
state: "loading",
});
const fetchDetails = async (signal: AbortSignal) => {
setState({ state: "loading" });
try {
const match = config.url.match(figmaURLPattern);
if (!match) {
throw new Error(config.url + " is not a valid Figma URL.");
}
const [, , fileKey] = match;
const url = new URL(config.url);
const nodeId = url.searchParams.get("node-id");
const accessToken = getAccessToken(config);
if (!accessToken) {
throw new Error("Personal Access Token is required.");
}
const headers = {
"X-FIGMA-TOKEN": accessToken,
};
const nodeUrl = new URL(`https://api.figma.com/v1/files/${fileKey}`);
const imageUrl = new URL(`https://api.figma.com/v1/images/${fileKey}`);
imageUrl.searchParams.set("format", "svg");
if (!nodeId) {
const documentNode = await fetch(nodeUrl.href, {
headers,
signal,
}).then((resp) => unwrapJson<FileResponse>(resp));
const frames = listAllFrames(documentNode.document);
imageUrl.searchParams.set(
"ids",
frames.map((frame) => frame.id).join(","),
);
const images = await fetch(imageUrl.href, {
headers,
signal,
}).then((resp) => unwrapJson<FileImageResponse>(resp));
setState({
state: "fetched",
value: {
type: "file",
props: {
documentNode,
renderedImages: images.images,
link: config.url,
},
},
});
return;
}
nodeUrl.pathname += "/nodes";
nodeUrl.searchParams.set("ids", nodeId);
imageUrl.searchParams.set("ids", nodeId);
const [nodes, images] = await Promise.all([
fetch(nodeUrl.href, {
headers,
signal,
}).then((resp) => unwrapJson<FileNodesResponse>(resp)),
fetch(imageUrl.href, { headers, signal }).then((resp) =>
unwrapJson<FileImageResponse>(resp),
),
]);
setState({
state: "fetched",
value: {
type: "frame",
props: {
nodes,
renderedImage: Object.values<string>(images.images)[0],
link: config.url,
},
},
});
} catch (err) {
if (err instanceof DOMException && err.code === DOMException.ABORT_ERR) {
return;
}
console.error(err);
setState({
state: "failed",
error: err instanceof Error ? err.message : String(err),
});
}
};
useEffect(() => {
let fulfilled = false;
const fulfil = () => {
fulfilled = true;
};
const ac = new AbortController();
fetchDetails(ac.signal).then(fulfil, fulfil);
return () => {
if (!fulfilled) {
ac.abort();
}
};
}, [config.url]);
switch (state.state) {
case "loading":
return (
<Placeholder>
<Fragment>Loading Figma file...</Fragment>
</Placeholder>
);
case "failed":
return (
<Placeholder>
<Fragment>Failed to load Figma file</Fragment>
<Fragment>{state.error}</Fragment>
</Placeholder>
);
case "fetched":
return state.value.type === "file" ? (
<FigspecFileViewer css={fullscreen} {...state.value.props} />
) : (
<FigspecFrameViewer css={fullscreen} {...state.value.props} />
);
}
};
export default Figspec;
function listAllFrames(node: Node): Node[] {
if ("absoluteBoundingBox" in node) {
return [node];
}
if (!node.children || node.children.length === 0) {
return [];
}
return node.children.map(listAllFrames).reduce((a, b) => a.concat(b), []);
}