File size: 13,387 Bytes
cc14d64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<?php
/**
 * Figma frame -> YOOtheme page-builder layout.
 *
 * The layout carries no colours, sizes or fonts of its own. It refers to the
 * style — a section whose Figma fill is the brand colour becomes
 * `"style": "primary"`, not `"background": "#647b91"` — so importing it into a
 * site running the child theme from the same import lands pre-styled, and
 * re-styling later moves the layout with it.
 *
 * ponytail: builder element vocabulary is deliberately small (section, row,
 * column, headline, text, image, button, divider). Anything unrecognised becomes
 * its text content rather than a guessed element; the HTML twin is the escape
 * hatch when a frame does not fit the builder's grid model.
 */

namespace Fyoo\FigmaBridge;

class Layout
{
    /** Builder export version. Bump to match the target YOOtheme Pro if it refuses an import. */
    public const BUILDER_VERSION = '4.5.6';

    private array $frame;
    private array $styleColors;
    private string $name;

    /**
     * @param array $styleColors role => hex, from the compiled token set, so fills
     *                           can be resolved to section styles instead of literals.
     */
    public function __construct(array $frame, array $styleColors = [])
    {
        $this->frame = $frame;
        $this->styleColors = array_map('strtoupper', array_filter($styleColors));
        $this->name = (string) ($frame['name'] ?? 'Layout');
    }

    public function name(): string
    {
        return $this->name;
    }

    public function slug(): string
    {
        return trim(strtolower(preg_replace('~[^A-Za-z0-9]+~', '-', $this->name)), '-') ?: 'layout';
    }

    /** The importable builder document. */
    public function builder(): array
    {
        return [
            'type'     => 'layout',
            'version'  => self::BUILDER_VERSION,
            'children' => array_values(array_filter(array_map(
                fn(array $node) => $this->section($node),
                $this->sections()
            ))),
        ];
    }

    public function json(): string
    {
        return json_encode($this->builder(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    }

    /**
     * Direct children that span most of the frame are sections; a frame with none
     * (a flat design with no grouping) is treated as one section itself.
     */
    private function sections(): array
    {
        $width = (float) ($this->frame['absoluteBoundingBox']['width'] ?? 0);
        $sections = [];

        foreach ($this->frame['children'] ?? [] as $child) {
            $childWidth = (float) ($child['absoluteBoundingBox']['width'] ?? 0);

            if ($width <= 0 || $childWidth >= $width * 0.6) {
                $sections[] = $child;
            }
        }

        return $sections ?: [$this->frame];
    }

    private function section(array $node): ?array
    {
        $children = $this->rows($node);

        if (!$children) {
            return null;
        }

        $props = ['style' => $this->sectionStyle($node)];
        $padding = (float) ($node['paddingTop'] ?? 0);

        if ($padding > 0) {
            $props['padding'] = $padding >= 80 ? 'large' : ($padding <= 20 ? 'small' : 'default');
        }

        return ['type' => 'section', 'props' => $props, 'children' => $children];
    }

    /** Resolves a fill to a named YOOtheme section style rather than a literal colour. */
    private function sectionStyle(array $node): string
    {
        $fill = $this->fill($node);

        if ($fill === null) {
            return 'default';
        }

        foreach (['brand-primary' => 'primary', 'brand-secondary' => 'secondary', 'surface-muted' => 'muted'] as $token => $style) {
            if (isset($this->styleColors[$token]) && $this->styleColors[$token] === $fill) {
                return $style;
            }
        }

        // An unmatched dark fill is still visually a "primary" band; light stays default.
        if (isset($this->styleColors['surface']) && $this->styleColors['surface'] === $fill) {
            return 'default';
        }

        return Figma::luminance($fill) < 0.5 ? 'secondary' : 'muted';
    }

    private function fill(array $node): ?string
    {
        foreach ($node['fills'] ?? [] as $paint) {
            if (($paint['type'] ?? '') === 'SOLID' && ($paint['visible'] ?? true)) {
                return Figma::hex($paint['color'], $paint['opacity'] ?? 1);
            }
        }

        return null;
    }

    /**
     * A horizontal auto-layout (or a run of side-by-side children) becomes one row
     * of columns; everything else stacks into a single full-width column.
     */
    private function rows(array $node): array
    {
        $content = $this->contentChildren($node);

        if (!$content) {
            return [];
        }

        if ($this->isHorizontal($node, $content)) {
            $columns = [];

            foreach ($content as $child) {
                $elements = $this->elements($child);

                if ($elements) {
                    $columns[] = ['type' => 'column', 'props' => $this->columnProps($child), 'children' => $elements];
                }
            }

            return $columns ? [['type' => 'row', 'children' => $columns]] : [];
        }

        $elements = [];

        foreach ($content as $child) {
            $elements = array_merge($elements, $this->elements($child));
        }

        return $elements
            ? [['type' => 'row', 'children' => [['type' => 'column', 'children' => $elements]]]]
            : [];
    }

    /** Unwraps a single wrapper frame so a container div does not become a column. */
    private function contentChildren(array $node): array
    {
        $children = $node['children'] ?? [];

        while (count($children) === 1 && in_array($children[0]['type'] ?? '', ['FRAME', 'GROUP'], true) && !empty($children[0]['children'])) {
            $children = $children[0]['children'];
        }

        return $children;
    }

    private function isHorizontal(array $node, array $children): bool
    {
        if (($node['layoutMode'] ?? '') === 'HORIZONTAL') {
            return count($children) > 1;
        }

        if (count($children) < 2) {
            return false;
        }

        // No auto-layout: infer from geometry — siblings sharing a band of rows.
        $tops = array_map(fn($c) => (float) ($c['absoluteBoundingBox']['y'] ?? 0), $children);
        $heights = array_map(fn($c) => (float) ($c['absoluteBoundingBox']['height'] ?? 1), $children);

        return (max($tops) - min($tops)) < (min($heights) ?: 1) * 0.5;
    }

    private function columnProps(array $node): array
    {
        $parentWidth = (float) ($this->frame['absoluteBoundingBox']['width'] ?? 0);
        $width = (float) ($node['absoluteBoundingBox']['width'] ?? 0);

        if ($parentWidth <= 0 || $width <= 0) {
            return [];
        }

        $ratio = $width / $parentWidth;

        foreach (['1-4' => 0.25, '1-3' => 0.333, '1-2' => 0.5, '2-3' => 0.667, '3-4' => 0.75] as $fraction => $value) {
            if (abs($ratio - $value) < 0.08) {
                return ['width' => $fraction];
            }
        }

        return [];
    }

    /** @return array builder elements for one node subtree */
    private function elements(array $node, int $depth = 0): array
    {
        $type = $node['type'] ?? '';

        if ($type === 'TEXT') {
            return [$this->textElement($node)];
        }

        if ($this->isButton($node)) {
            return [[
                'type'  => 'button',
                'props' => ['content' => $this->firstText($node) ?: 'Button', 'link' => '#', 'style' => 'primary'],
            ]];
        }

        if ($this->isImage($node)) {
            return [[
                'type'  => 'image',
                'props' => [
                    'image'     => 'templates/yootheme_child/assets/' . $this->slugName($node) . '.png',
                    'alt'       => $node['name'] ?? '',
                    'image_width' => (int) ($node['absoluteBoundingBox']['width'] ?? 0),
                ],
            ]];
        }

        if ($depth > 6) {
            return [];
        }

        $elements = [];

        foreach ($this->contentChildren($node) as $child) {
            $elements = array_merge($elements, $this->elements($child, $depth + 1));
        }

        return $elements;
    }

    private function textElement(array $node): array
    {
        $content = trim((string) ($node['characters'] ?? ''));
        $size = (float) ($node['style']['fontSize'] ?? 16);
        $weight = (int) ($node['style']['fontWeight'] ?? 400);

        // Big or bold and short reads as a headline; a paragraph is a paragraph.
        if (($size >= 24 || ($weight >= 600 && mb_strlen($content) < 80)) && !str_contains($content, "\n")) {
            return [
                'type'  => 'headline',
                'props' => [
                    'content'       => $content,
                    'title_element' => $size >= 40 ? 'h1' : ($size >= 30 ? 'h2' : ($size >= 24 ? 'h3' : 'h4')),
                    'text_align'    => strtolower((string) ($node['style']['textAlignHorizontal'] ?? 'left')) === 'center' ? 'center' : 'left',
                ],
            ];
        }

        return [
            'type'  => 'text',
            'props' => ['content' => '<p>' . nl2br(htmlspecialchars($content, ENT_QUOTES)) . '</p>'],
        ];
    }

    private function isButton(array $node): bool
    {
        if (preg_match('~\b(button|btn|cta)\b~i', (string) ($node['name'] ?? ''))) {
            return true;
        }

        $box = $node['absoluteBoundingBox'] ?? null;

        return $box
            && !empty($node['cornerRadius'])
            && $this->fill($node) !== null
            && ($box['height'] ?? 0) <= 72
            && ($box['width'] ?? 0) <= 320
            && $this->firstText($node) !== '';
    }

    private function isImage(array $node): bool
    {
        foreach ($node['fills'] ?? [] as $paint) {
            if (($paint['type'] ?? '') === 'IMAGE') {
                return true;
            }
        }

        return in_array($node['type'] ?? '', ['VECTOR', 'BOOLEAN_OPERATION'], true)
            || (bool) preg_match('~\b(image|img|photo|logo|icon)\b~i', (string) ($node['name'] ?? ''));
    }

    private function firstText(array $node): string
    {
        if (($node['type'] ?? '') === 'TEXT') {
            return trim((string) ($node['characters'] ?? ''));
        }

        foreach ($node['children'] ?? [] as $child) {
            $text = $this->firstText($child);

            if ($text !== '') {
                return $text;
            }
        }

        return '';
    }

    private function slugName(array $node): string
    {
        return trim(strtolower(preg_replace('~[^A-Za-z0-9]+~', '-', (string) ($node['name'] ?? 'image'))), '-') ?: 'image';
    }

    /**
     * The same tree as UIkit markup. The builder JSON is the better artefact when
     * it imports cleanly; this always works, in a Custom HTML element or a page
     * template, and uses only classes the child theme already styles.
     */
    public function html(): string
    {
        $out = '';

        foreach ($this->builder()['children'] as $section) {
            $style = $section['props']['style'] ?? 'default';
            $class = 'uk-section' . ($style !== 'default' ? " uk-section-$style" : '');
            $out .= "<div class=\"$class\">\n  <div class=\"uk-container\">\n";

            foreach ($section['children'] as $row) {
                $columns = $row['children'];
                $out .= '    <div class="uk-grid-match uk-child-width-expand@m" uk-grid>' . "\n";

                foreach ($columns as $column) {
                    $out .= "      <div>\n";

                    foreach ($column['children'] as $element) {
                        $out .= '        ' . $this->elementHtml($element) . "\n";
                    }

                    $out .= "      </div>\n";
                }

                $out .= "    </div>\n";
            }

            $out .= "  </div>\n</div>\n";
        }

        return $out;
    }

    private function elementHtml(array $element): string
    {
        $props = $element['props'] ?? [];

        return match ($element['type']) {
            'headline' => sprintf(
                '<%1$s class="uk-%1$s%2$s">%3$s</%1$s>',
                $props['title_element'] ?? 'h2',
                ($props['text_align'] ?? '') === 'center' ? ' uk-text-center' : '',
                htmlspecialchars($props['content'] ?? '', ENT_QUOTES)
            ),
            'text'   => $props['content'] ?? '',
            'button' => sprintf(
                '<a class="uk-button uk-button-%s" href="%s">%s</a>',
                $props['style'] ?? 'primary',
                htmlspecialchars($props['link'] ?? '#', ENT_QUOTES),
                htmlspecialchars($props['content'] ?? '', ENT_QUOTES)
            ),
            'image'  => sprintf(
                '<img src="%s" alt="%s" width="%d" loading="lazy">',
                htmlspecialchars($props['image'] ?? '', ENT_QUOTES),
                htmlspecialchars($props['alt'] ?? '', ENT_QUOTES),
                (int) ($props['image_width'] ?? 0)
            ),
            default  => '',
        };
    }
}