From 99c446fde714dea3db4b39b930ac924857dc7cd7 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Tue, 10 Dec 2024 11:49:51 +0300 Subject: [PATCH] feat: add create-box strategy --- .../src/strategy/create-box.strategy.ts | 94 +++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 fragments/fragments-generator/src/strategy/create-box.strategy.ts diff --git a/fragments/fragments-generator/src/strategy/create-box.strategy.ts b/fragments/fragments-generator/src/strategy/create-box.strategy.ts new file mode 100644 index 0000000..bbc5e3f --- /dev/null +++ b/fragments/fragments-generator/src/strategy/create-box.strategy.ts @@ -0,0 +1,94 @@ +import { Frame } from 'figma-js' +import { createElement } from 'react' + +import { ThemeMappingStrategy } from './theme-mapping.strategy.js' + +export class CreateBoxStrategy extends ThemeMappingStrategy { + constructor(theme: Record>) { + super(theme) + } + + getPaddingFromTheme(padding: number | undefined) { + if (padding === undefined) { + return undefined + } + + return this.getValueKeyFromTheme('spaces', `${padding}px`) || `${padding}px` + } + + createPaddingAttributes({ + paddingTop, + paddingBottom, + paddingLeft, + paddingRight, + }: Record) { + const top = this.getPaddingFromTheme(paddingTop) + const bottom = this.getPaddingFromTheme(paddingBottom) + const left = this.getPaddingFromTheme(paddingLeft) + const right = this.getPaddingFromTheme(paddingRight) + + if ([top, bottom, left, right].every((value) => value && value === top)) { + return { padding: top } + } + + const attributes: Record = {} + + if (top && bottom && top === bottom) { + attributes.paddingY = top + } + + if (left && right && left === right) { + attributes.paddingX = left + } + + if (top && !attributes.paddingY) { + attributes.paddingTop = top + } + + if (bottom && !attributes.paddingY) { + attributes.paddingBottom = bottom + } + + if (left && !attributes.paddingX) { + attributes.paddingLeft = left + } + + if (right && !attributes.paddingX) { + attributes.paddingRight = right + } + + return attributes + } + + getImports() { + return [`import { Box } from '@ui/layout'`] + } + + createElement(node: Frame) { + const { + layoutMode, + itemSpacing, + counterAxisAlignItems, + primaryAxisAlignItems, + paddingBottom, + paddingLeft, + paddingRight, + paddingTop, + } = node + + const figmaAlignItems = { + CENTER: 'center', + SPACE_BETWEEN: 'space-between', + } + + return createElement('Box', { + flexDirection: layoutMode === 'VERTICAL' ? 'column' : undefined, + justifyContent: figmaAlignItems[primaryAxisAlignItems!] || undefined, + alignItems: figmaAlignItems[counterAxisAlignItems!] || undefined, + gap: itemSpacing + ? this.getValueKeyFromTheme('spaces', `${itemSpacing}px`) || `${itemSpacing}px` + : undefined, + ...this.createPaddingAttributes({ paddingBottom, paddingLeft, paddingRight, paddingTop }), + }) + } +}