-
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
-
415
-
416
-
417
-
418
-
419
-
420
-
421
-
422
-
423
-
424
-
425
-
426
-
427
-
428
-
429
-
430
-
431
-
432
-
433
-
434
-
435
-
436
-
437
-
438
-
439
-
440
-
441
-
442
-
443
-
444
-
445
-
446
-
447
-
448
-
449
-
450
-
451
-
452
-
453
-
454
-
455
-
456
-
457
-
458
-
459
-
460
-
461
-
462
-
463
-
464
-
465
-
466
-
467
-
468
-
469
-
470
-
471
-
472
-
473
-
474
-
475
-
476
-
477
-
478
-
479
-
480
-
481
-
482
-
483
-
484
-
485
-
486
-
487
-
488
-
489
-
490
-
491
-
492
-
493
-
494
-
495
-
496
-
497
-
498
-
499
-
500
-
501
-
502
-
503
-
504
-
505
-
506
-
507
-
508
-
509
-
510
-
511
-
512
-
513
-
514
-
515
-
516
-
517
-
518
-
519
-
520
-
521
-
522
-
523
-
524
-
525
-
526
-
527
-
528
-
529
-
530
-
531
-
532
-
533
-
534
-
535
-
536
-
537
-
538
-
539
-
540
-
541
-
542
-
543
-
544
-
545
-
546
-
547
-
548
-
549
-
550
-
551
-
552
-
553
-
554
-
555
-
556
-
557
-
558
-
559
-
560
-
561
-
562
-
563
-
564
-
565
-
566
-
567
-
568
import type * as Figma from "figma-js";
import { LitElement, css, html, svg, TemplateResult } from "lit";
import { property } from "lit/decorators.js";
import { styleMap } from "lit/directives/style-map.js";
import { Constructor, extendStyles, SizedNode } from "./utils";
import { INodeSelectable, NodeSelectableMixin } from "./NodeSelectableMixin";
import { Positioned, PositionedMixin } from "./PositionedMixin";
import * as DistanceGuide from "./DistanceGuide";
import * as InspectorView from "./InspectorView/InspectorView";
import type { FigmaNode } from "./InspectorView/utils";
import * as ErrorMessage from "./ErrorMessage";
import * as Node from "./Node";
import * as FigmaFooter from "./Footer/Footer";
interface Margin {
top: number;
right: number;
bottom: number;
left: number;
}
export interface IViewer {
zoomMargin: number;
link: string;
/**
* A record of rendered images.
* Key is an id of the node.
* Value is an URL of the rendered image.
*/
__images: Record<string, string>;
readonly error?: string | TemplateResult | Error | null;
__updateTree(node: Figma.Node): void;
__updateEffectMargins(): void;
resetZoom(): void;
getMetadata():
| { fileName: string; timestamp: Date | string; link: string }
| undefined;
}
export const ViewerMixin = <T extends Constructor<LitElement>>(
superClass: T
): T & Constructor<IViewer & INodeSelectable & Positioned> => {
class Viewer extends NodeSelectableMixin(PositionedMixin(superClass)) {
@property({
type: Number,
attribute: "zoom-margin",
})
zoomMargin: number = 50;
@property({
type: String,
attribute: "link",
})
link: string = "";
static get styles() {
// @ts-ignore
const styles = super.styles;
return extendStyles(styles, [
css`
:host {
--default-error-bg: #fff;
--default-error-fg: #333;
--bg: var(--figspec-viewer-bg, #e5e5e5);
--z-index: var(--figspec-viewer-z-index, 0);
--error-bg: var(--figspec-viewer-error-bg, var(--default-error-bg));
--error-fg: var(--figspec-viewer-error-fg, var(--default-error-fg));
--error-color: var(--figspec-viewer-error-color, tomato);
--guide-thickness: var(--figspec-viewer-guide-thickness, 1.5px);
--guide-color: var(--figspec-viewer-guide-color, tomato);
--guide-selected-color: var(
--figspec-viewer-guide-selected-color,
dodgerblue
);
--guide-tooltip-fg: var(--figspec-viewer-guide-tooltip-fg, white);
--guide-selected-tooltip-fg: var(
--figspec-viewer-guide-selected-tooltip-fg,
white
);
--guide-tooltip-bg: var(
--figspec-viewer-guide-tooltip-bg,
var(--guide-color)
);
--guide-selected-tooltip-bg: var(
--figspec-viewer-guide-selected-tooltip-bg,
var(--guide-selected-color)
);
--guide-tooltip-font-size: var(
--figspec-viewer-guide-tooltip-font-size,
12px
);
position: relative;
display: block;
background-color: var(--bg);
user-select: none;
overflow: hidden;
z-index: var(--z-index);
}
@media (prefers-color-scheme: dark) {
:host {
--default-error-bg: #222;
--default-error-fg: #fff;
}
}
.spec-canvas-wrapper {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
flex-direction: column-reverse;
}
.canvas {
position: absolute;
top: 50%;
left: 50%;
flex: 1;
}
.rendered-image {
position: absolute;
top: 0;
left: 0;
}
.guides {
position: absolute;
overflow: visible;
stroke: var(--guide-color);
fill: var(--guide-color);
pointer-events: none;
z-index: calc(var(--z-index) + 2);
}
`,
Node.styles,
ErrorMessage.styles,
DistanceGuide.styles,
InspectorView.styles,
FigmaFooter.styles,
]);
}
get __images(): Record<string, string> {
return {};
}
// Cached values
#canvasSize?: Figma.Rect;
#effectMargins?: Record<string, Margin>;
#flattenedNodes?: readonly SizedNode[];
constructor(...args: any[]) {
super(...args);
}
deselectNode() {
this.selectedNode = null;
}
get error(): string | Error | null | TemplateResult | undefined {
if (!this.#canvasSize || !this.#flattenedNodes) {
return ErrorMessage.ErrorMessage({
title: "Error",
children:
"Please call `__updateTree/1` method with a valid parameter.",
});
}
return null;
}
render() {
if (this.error) {
if (this.error instanceof Error) {
return ErrorMessage.ErrorMessage({
title: this.error.name || "Error",
children: this.error.message,
});
}
if (typeof this.error === "string") {
return ErrorMessage.ErrorMessage({
title: "Error",
children: this.error,
});
}
return this.error;
}
const canvasSize = this.#canvasSize!;
const reverseScale = 1 / this.scale;
const guideThickness = `calc(var(--guide-thickness) * ${reverseScale})`;
const computedGuideThickness = parseFloat(
getComputedStyle(this).getPropertyValue("--guide-thickness")
);
const computedGuideTooltipFontSize = parseFloat(
getComputedStyle(this).getPropertyValue("--guide-tooltip-font-size")
);
return html`
<div class="spec-canvas-wrapper" @click=${this.deselectNode}>
<div
class="canvas"
style="
width: ${canvasSize.width}px;
height: ${canvasSize.height}px;
transform: translate(-50%, -50%) ${this.canvasTransform.join(" ")}
"
>
${Object.entries(this.__images).map(([nodeId, uri]) => {
const node = this.#getNodeById(nodeId);
if (
!node ||
!("absoluteBoundingBox" in node) ||
!this.#effectMargins?.[node.id]
) {
return null;
}
const margin = this.#effectMargins[node.id];
return html`
<img class="rendered-image" src="${uri}"
style=${styleMap({
top: `${node.absoluteBoundingBox.y - canvasSize.y}px`,
left: `${node.absoluteBoundingBox.x - canvasSize.x}px`,
marginTop: `${-margin.top}px`,
marginLeft: `${-margin.left}px`,
width:
node.absoluteBoundingBox.width +
margin.left +
margin.right +
"px",
height:
node.absoluteBoundingBox.height +
margin.top +
margin.bottom +
"px",
})}"
" />
`;
})}
${this.selectedNode &&
Node.Tooltip({
nodeSize: this.selectedNode.absoluteBoundingBox,
offsetX: -canvasSize.x,
offsetY: -canvasSize.y,
reverseScale,
})}
${svg`
<svg
class="guides"
viewBox="0 0 5 5"
width="5"
height="5"
style=${styleMap({
left: `${-canvasSize.x}px`,
top: `${-canvasSize.y}px`,
strokeWidth: guideThickness,
})}
>
${
this.selectedNode &&
Node.Outline({
node: this.selectedNode,
selected: true,
computedThickness: computedGuideThickness * reverseScale,
})
}
${this.#flattenedNodes!.map((node) => {
if (node.id === this.selectedNode?.id) {
return null;
}
return svg`
<g>
${Node.Outline({
node,
computedThickness: computedGuideThickness * reverseScale,
onClick: this.#handleNodeClick(node),
})}
${
this.selectedNode &&
DistanceGuide.Guides({
node,
distanceTo: this.selectedNode,
reverseScale,
fontSize: computedGuideTooltipFontSize,
})
}
</g>
`;
})}
</svg>
`}
</div>
${InspectorView.View({
node: this.selectedNode as FigmaNode,
onClose: this.deselectNode,
})}
${FigmaFooter.Footer(this.getMetadata())}
</div>
`;
}
// implemented in FileViewer/FrameViewer
getMetadata() {
return undefined;
}
connectedCallback() {
super.connectedCallback();
this.resetZoom();
}
updated(changedProperties: Parameters<LitElement["updated"]>[0]) {
super.updated(changedProperties);
}
__updateTree(node: Figma.Node) {
if (
!(
node.type === "CANVAS" ||
node.type === "FRAME" ||
node.type === "COMPONENT" ||
//@ts-ignore NOTE: figma-js does not implement COMPONENT_SET type (yet?)
node.type === "COMPONENT_SET"
)
) {
throw new Error(
"Cannot update node tree: Top level node MUST be one of CANVAS, FRAME, COMPONENT, or COMPONENT_SET"
);
}
this.#canvasSize =
node.type === "CANVAS" ? getCanvasSize(node) : node.absoluteBoundingBox;
this.#flattenedNodes = flattenNode(node);
// Since above properties aren't "attribute", their changes does not
// trigger an update. We need to manually request an update.
this.requestUpdate();
}
__updateEffectMargins() {
if (!this.__images) {
return;
}
const containers = Object.keys(this.__images)
.map(this.#getNodeById)
.filter((n): n is NonNullable<typeof n> => !!n);
this.#effectMargins = containers.reduce<Record<string, Margin>>(
(margin, node) => {
if (!("absoluteBoundingBox" in node)) {
return margin;
}
return {
...margin,
[node.id]: getEffectMargin(node, flattenNode(node)),
};
},
{}
);
this.requestUpdate();
}
resetZoom() {
if (this.#canvasSize) {
// Set initial zoom level based on element size
const { width, height } = this.#canvasSize;
const {
width: elementWidth,
height: elementHeight,
} = this.getBoundingClientRect();
const wDiff = elementWidth / (width + this.zoomMargin * 2);
const hDiff = elementHeight / (height + this.zoomMargin * 2);
this.scale = Math.min(wDiff, hDiff, 1);
}
}
#handleNodeClick = (node: SizedNode) => (ev: MouseEvent) => {
ev.preventDefault();
ev.stopPropagation();
this.selectedNode = node;
};
#getNodeById = (id: string): Figma.Node | null => {
return this.#flattenedNodes?.find((n) => n.id === id) ?? null;
};
}
return Viewer;
};
function getCanvasSize(node: Figma.Canvas): Figma.Rect {
const left: number[] = [];
const right: number[] = [];
const top: number[] = [];
const bottom: number[] = [];
for (const child of node.children) {
if (child.type !== "FRAME" && child.type !== "COMPONENT") {
continue;
}
const { x, y, width, height } = child.absoluteBoundingBox;
left.push(x);
right.push(x + width);
top.push(y);
bottom.push(y + height);
}
const minX = Math.min(...left);
const minY = Math.min(...top);
return {
x: minX,
y: minY,
width: Math.abs(Math.max(...right) - minX),
height: Math.abs(Math.min(...bottom) - minY),
};
}
function getEffectMargin(
container: SizedNode,
nodes: readonly SizedNode[]
): Margin {
const points = nodes.map((node) => {
if (!("effects" in node)) {
return {
top: node.absoluteBoundingBox.y,
right: node.absoluteBoundingBox.x + node.absoluteBoundingBox.width,
bottom: node.absoluteBoundingBox.y + node.absoluteBoundingBox.height,
left: node.absoluteBoundingBox.x,
};
}
const blurRadiuses = node.effects
.filter((effect) => effect.visible && effect.type === "LAYER_BLUR")
.map((effect) => effect.radius);
const shadowMargins = node.effects
.filter(
(
effect
): effect is Figma.Effect & {
offset: NonNullable<Figma.Effect["offset"]>;
} => effect.visible && effect.type === "DROP_SHADOW" && !!effect.offset
)
.map<Margin>((effect) => {
return {
left: effect.radius - effect.offset.x,
top: effect.radius - effect.offset.y,
right: effect.radius + effect.offset.x,
bottom: effect.radius + effect.offset.y,
};
});
const margin: Margin = {
top: Math.max(
0,
...blurRadiuses,
...shadowMargins.map((margin) => margin.top)
),
right: Math.max(
0,
...blurRadiuses,
...shadowMargins.map((margin) => margin.right)
),
bottom: Math.max(
0,
...blurRadiuses,
...shadowMargins.map((margin) => margin.bottom)
),
left: Math.max(
0,
...blurRadiuses,
...shadowMargins.map((margin) => margin.left)
),
};
return {
top: node.absoluteBoundingBox.y - margin.top,
right:
node.absoluteBoundingBox.x +
node.absoluteBoundingBox.width +
margin.right,
bottom:
node.absoluteBoundingBox.y +
node.absoluteBoundingBox.height +
margin.bottom,
left: node.absoluteBoundingBox.x - margin.left,
};
});
const bounds = {
top: Math.min(...points.map((p) => p.top)),
right: Math.max(...points.map((p) => p.right)),
bottom: Math.max(...points.map((p) => p.bottom)),
left: Math.min(...points.map((p) => p.left)),
};
return {
top: container.absoluteBoundingBox.y - bounds.top,
right:
bounds.right -
container.absoluteBoundingBox.x -
container.absoluteBoundingBox.width,
bottom:
bounds.bottom -
container.absoluteBoundingBox.y -
container.absoluteBoundingBox.height,
left: container.absoluteBoundingBox.x - bounds.left,
};
}
function flattenNode(
node: Figma.Node,
depth: number = 0
): readonly (SizedNode & {
depth: number;
})[] {
if (!("absoluteBoundingBox" in node)) {
return node.children.map((child) => flattenNode(child, depth + 1)).flat();
}
if (!("children" in node) || node.children.length === 0) {
return [{ ...node, depth }];
}
return [
{ ...node, depth },
...node.children.map((child) => flattenNode(child, depth + 1)).flat(),
];
}