-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCreateShapesCommandHandler.ts
More file actions
81 lines (64 loc) · 2.22 KB
/
CreateShapesCommandHandler.ts
File metadata and controls
81 lines (64 loc) · 2.22 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
import { CommandHandler } from "../../commands-setup/CommandHandler";
import { CreateShapesCommand, SupportedShapes } from "./CreateShapesCommand";
export class CreateShapesCommandHandler
implements CommandHandler<CreateShapesCommand>
{
private readonly separationBetweenShapes = 150;
constructor(private readonly figma: PluginAPI) {}
handle({
payload: { numberOfShapes, typeOfShapes },
}: CreateShapesCommand): void {
const shapes = Array.from({ length: numberOfShapes }).map(
this.toShape(typeOfShapes)
);
this.focusUiOn(shapes);
}
private toShape(
typeOfShapes?: SupportedShapes
): (_: unknown, iteration: number) => SceneNode {
return (_: unknown, iteration: number): SceneNode => {
const hasToRandomizeShapeTypes = typeOfShapes === undefined;
const shapesCreator = hasToRandomizeShapeTypes
? this.createRandomShape.bind(this)
: this.createShape(typeOfShapes);
const shape = shapesCreator();
this.styleShape(shape, iteration);
this.figma.currentPage.appendChild(shape);
return shape;
};
}
private createShape(
typeOfShapes: SupportedShapes
): () => RectangleNode | EllipseNode {
return (): RectangleNode | EllipseNode =>
typeOfShapes === "Rectangle"
? this.figma.createRectangle()
: this.figma.createEllipse();
}
private createRandomShape(): RectangleNode | EllipseNode {
const isRectangleShape = this.randomBoolean();
if (isRectangleShape) {
return this.figma.createRectangle();
}
return this.figma.createEllipse();
}
private styleShape(
shape: RectangleNode | EllipseNode,
shapeNumber: number
): void {
shape.x = shapeNumber * this.separationBetweenShapes;
shape.rotation = Math.random() * 100;
shape.fills = [{ type: "SOLID", color: this.randomColor() }];
shape.name = `${shape.name} ${shapeNumber}`;
}
private randomBoolean(): boolean {
return Math.random() < 0.5;
}
private randomColor(): RGB {
return { r: Math.random(), g: Math.random(), b: Math.random() };
}
private focusUiOn(createdShapes: SceneNode[]) {
this.figma.currentPage.selection = createdShapes;
this.figma.viewport.scrollAndZoomIntoView(createdShapes);
}
}