Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace Termwind\ValueObjects;
6
 
7
use Closure;
8
use Termwind\Actions\StyleToMethod;
9
use Termwind\Components\Element;
10
use Termwind\Components\Hr;
11
use Termwind\Components\Li;
12
use Termwind\Components\Ol;
13
use Termwind\Components\Ul;
14
use Termwind\Enums\Color;
15
use Termwind\Exceptions\ColorNotFound;
16
use Termwind\Exceptions\InvalidStyle;
17
use Termwind\Repositories\Styles as StyleRepository;
18
use function Termwind\terminal;
19
 
20
/**
21
 * @internal
22
 */
23
final class Styles
24
{
25
    /**
26
     * Finds all the styling on a string.
27
     */
28
    public const STYLING_REGEX = "/\<[\w=#\/\;,:.&,%?-]+\>|\\e\[\d+m/";
29
 
30
    /** @var array<int, string> */
31
    private array $styles = [];
32
 
33
    private ?Element $element = null;
34
 
35
    /**
36
     * Creates a Style formatter instance.
37
     *
38
     * @param  array<string, mixed>  $properties
39
     * @param  array<string, Closure(string, array<string, string|int>, array<string, int[]>): string>  $textModifiers
40
     * @param  array<string, Closure(string, array<string, string|int>): string>  $styleModifiers
41
     * @param  string[]  $defaultStyles
42
     */
43
    final public function __construct(
44
        private array $properties = [
45
            'colors' => [],
46
            'options' => [],
47
            'isFirstChild' => false,
48
        ],
49
        private array $textModifiers = [],
50
        private array $styleModifiers = [],
51
        private array $defaultStyles = []
52
    ) {
53
    }
54
 
55
    /**
56
     * @param  Element  $element
57
     * @return $this
58
     */
59
    public function setElement(Element $element): self
60
    {
61
        $this->element = $element;
62
 
63
        return $this;
64
    }
65
 
66
    /**
67
     * Gets default styles.
68
     *
69
     * @return string[]
70
     */
71
    public function defaultStyles(): array
72
    {
73
        return $this->defaultStyles;
74
    }
75
 
76
    /**
77
     * Gets the element's style properties.
78
     *
79
     * @return array<string, mixed>
80
     */
81
    final public function getProperties(): array
82
    {
83
        return $this->properties;
84
    }
85
 
86
    /**
87
     * Sets the element's style properties.
88
     *
89
     * @param  array<string, mixed>  $properties
90
     */
91
    public function setProperties(array $properties): self
92
    {
93
        $this->properties = $properties;
94
 
95
        return $this;
96
    }
97
 
98
    /**
99
     * Sets the styles to the element.
100
     */
101
    final public function setStyle(string $style): self
102
    {
103
        $this->styles = array_unique(array_merge($this->styles, [$style]));
104
 
105
        return $this;
106
    }
107
 
108
    /**
109
     * Checks if the element has the style.
110
     */
111
    final public function hasStyle(string $style): bool
112
    {
113
        return in_array($style, $this->styles, true);
114
    }
115
 
116
    /**
117
     * Adds a style to the element.
118
     */
119
    final public function addStyle(string $style): self
120
    {
121
        return StyleToMethod::multiple($this, $style);
122
    }
123
 
124
    /**
125
     * Inherit styles from given Styles object.
126
     */
127
    final public function inheritFromStyles(self $styles): self
128
    {
129
        foreach (['ml', 'mr', 'pl', 'pr', 'width', 'minWidth', 'maxWidth', 'spaceY', 'spaceX'] as $style) {
130
            $this->properties['parentStyles'][$style] = array_merge(
131
                $this->properties['parentStyles'][$style] ?? [],
132
                $styles->properties['parentStyles'][$style] ?? []
133
            );
134
 
135
            $this->properties['parentStyles'][$style][] = $styles->properties['styles'][$style] ?? 0;
136
        }
137
 
138
        $this->properties['parentStyles']['justifyContent'] = $styles->properties['styles']['justifyContent'] ?? false;
139
 
140
        foreach (['bg', 'fg'] as $colorType) {
141
            $value = (array) ($this->properties['colors'][$colorType] ?? []);
142
            $parentValue = (array) ($styles->properties['colors'][$colorType] ?? []);
143
 
144
            if ($value === [] && $parentValue !== []) {
145
                $this->properties['colors'][$colorType] = $styles->properties['colors'][$colorType];
146
            }
147
        }
148
 
149
        if (! is_null($this->properties['options']['bold'] ?? null) ||
150
            ! is_null($styles->properties['options']['bold'] ?? null)) {
151
            $this->properties['options']['bold'] = $this->properties['options']['bold']
152
                ?? $styles->properties['options']['bold']
153
                ?? false;
154
        }
155
 
156
        return $this;
157
    }
158
 
159
    /**
160
     * Adds a background color to the element.
161
     */
162
    final public function bg(string $color, int $variant = 0): self
163
    {
164
        return $this->with(['colors' => [
165
            'bg' => $this->getColorVariant($color, $variant),
166
        ]]);
167
    }
168
 
169
    /**
170
     * Adds a bold style to the element.
171
     */
172
    final public function fontBold(): self
173
    {
174
        return $this->with(['options' => [
175
            'bold' => true,
176
        ]]);
177
    }
178
 
179
    /**
180
     * Removes the bold style on the element.
181
     */
182
    final public function fontNormal(): self
183
    {
184
        return $this->with(['options' => [
185
            'bold' => false,
186
        ]]);
187
    }
188
 
189
    /**
190
     * Adds a bold style to the element.
191
     */
192
    final public function strong(): self
193
    {
194
        $this->styleModifiers[__METHOD__] = static fn ($text): string => sprintf("\e[1m%s\e[0m", $text);
195
 
196
        return $this;
197
    }
198
 
199
    /**
200
     * Adds an italic style to the element.
201
     */
202
    final public function italic(): self
203
    {
204
        $this->styleModifiers[__METHOD__] = static fn ($text): string => sprintf("\e[3m%s\e[0m", $text);
205
 
206
        return $this;
207
    }
208
 
209
    /**
210
     * Adds an underline style.
211
     */
212
    final public function underline(): self
213
    {
214
        $this->styleModifiers[__METHOD__] = static fn ($text): string => sprintf("\e[4m%s\e[0m", $text);
215
 
216
        return $this;
217
    }
218
 
219
    /**
220
     * Adds the given margin left to the element.
221
     */
222
    final public function ml(int $margin): self
223
    {
224
        return $this->with(['styles' => [
225
            'ml' => $margin,
226
        ]]);
227
    }
228
 
229
    /**
230
     * Adds the given margin right to the element.
231
     */
232
    final public function mr(int $margin): self
233
    {
234
        return $this->with(['styles' => [
235
            'mr' => $margin,
236
        ]]);
237
    }
238
 
239
    /**
240
     * Adds the given margin bottom to the element.
241
     */
242
    final public function mb(int $margin): self
243
    {
244
        return $this->with(['styles' => [
245
            'mb' => $margin,
246
        ]]);
247
    }
248
 
249
    /**
250
     * Adds the given margin top to the element.
251
     */
252
    final public function mt(int $margin): self
253
    {
254
        return $this->with(['styles' => [
255
            'mt' => $margin,
256
        ]]);
257
    }
258
 
259
    /**
260
     * Adds the given horizontal margin to the element.
261
     */
262
    final public function mx(int $margin): self
263
    {
264
        return $this->with(['styles' => [
265
            'ml' => $margin,
266
            'mr' => $margin,
267
        ]]);
268
    }
269
 
270
    /**
271
     * Adds the given vertical margin to the element.
272
     */
273
    final public function my(int $margin): self
274
    {
275
        return $this->with(['styles' => [
276
            'mt' => $margin,
277
            'mb' => $margin,
278
        ]]);
279
    }
280
 
281
    /**
282
     * Adds the given margin to the element.
283
     */
284
    final public function m(int $margin): self
285
    {
286
        return $this->my($margin)->mx($margin);
287
    }
288
 
289
    /**
290
     * Adds the given padding left to the element.
291
     */
292
    final public function pl(int $padding): static
293
    {
294
        return $this->with(['styles' => [
295
            'pl' => $padding,
296
        ]]);
297
    }
298
 
299
    /**
300
     * Adds the given padding right.
301
     */
302
    final public function pr(int $padding): static
303
    {
304
        return $this->with(['styles' => [
305
            'pr' => $padding,
306
        ]]);
307
    }
308
 
309
    /**
310
     * Adds the given horizontal padding.
311
     */
312
    final public function px(int $padding): self
313
    {
314
        return $this->pl($padding)->pr($padding);
315
    }
316
 
317
    /**
318
     * Adds the given padding top.
319
     */
320
    final public function pt(int $padding): static
321
    {
322
        return $this->with(['styles' => [
323
            'pt' => $padding,
324
        ]]);
325
    }
326
 
327
    /**
328
     * Adds the given padding bottom.
329
     */
330
    final public function pb(int $padding): static
331
    {
332
        return $this->with(['styles' => [
333
            'pb' => $padding,
334
        ]]);
335
    }
336
 
337
    /**
338
     * Adds the given vertical padding.
339
     */
340
    final public function py(int $padding): self
341
    {
342
        return $this->pt($padding)->pb($padding);
343
    }
344
 
345
    /**
346
     * Adds the given padding.
347
     */
348
    final public function p(int $padding): self
349
    {
350
        return $this->pt($padding)->pr($padding)->pb($padding)->pl($padding);
351
    }
352
 
353
    /**
354
     * Adds the given vertical margin to the childs, ignoring the first child.
355
     */
356
    final public function spaceY(int $space): self
357
    {
358
        return $this->with(['styles' => [
359
            'spaceY' => $space,
360
        ]]);
361
    }
362
 
363
    /**
364
     * Adds the given horizontal margin to the childs, ignoring the first child.
365
     */
366
    final public function spaceX(int $space): self
367
    {
368
        return $this->with(['styles' => [
369
            'spaceX' => $space,
370
        ]]);
371
    }
372
 
373
    /**
374
     * Adds a border on top of each element.
375
     */
376
    final public function borderT(int $width = 1): self
377
    {
378
        if (! $this->element instanceof Hr) {
379
            throw new InvalidStyle('`border-t` can only be used on an "hr" element.');
380
        }
381
 
382
        $this->styleModifiers[__METHOD__] = function ($text, $styles): string {
383
            $length = $this->getLength($text);
384
            if ($length < 1) {
385
                $margins = (int) ($styles['ml'] ?? 0) + ($styles['mr'] ?? 0);
386
 
387
                return str_repeat('─', self::getParentWidth($this->properties['parentStyles'] ?? []) - $margins);
388
            }
389
 
390
            return str_repeat('─', $length);
391
        };
392
 
393
        return $this;
394
    }
395
 
396
    /**
397
     * Adds a text alignment or color to the element.
398
     */
399
    final public function text(string $value, int $variant = 0): self
400
    {
401
        if (in_array($value, ['left', 'right', 'center'], true)) {
402
            return $this->with(['styles' => [
403
                'text-align' => $value,
404
            ]]);
405
        }
406
 
407
        return $this->with(['colors' => [
408
            'fg' => $this->getColorVariant($value, $variant),
409
        ]]);
410
    }
411
 
412
    /**
413
     * Truncates the text of the element.
414
     */
415
    final public function truncate(int $limit = 0, string $end = '…'): self
416
    {
417
        $this->textModifiers[__METHOD__] = function ($text, $styles) use ($limit, $end): string {
418
            $width = $styles['width'] ?? 0;
419
 
420
            if (is_string($width)) {
421
                $width = self::calcWidthFromFraction(
422
                    $width,
423
                    $styles,
424
                    $this->properties['parentStyles'] ?? []
425
                );
426
            }
427
 
428
            [, $paddingRight, , $paddingLeft] = $this->getPaddings();
429
            $width -= $paddingRight + $paddingLeft;
430
 
431
            $limit = $limit > 0 ? $limit : $width;
432
            if ($limit === 0) {
433
                return $text;
434
            }
435
 
436
            $limit -= mb_strwidth($end, 'UTF-8');
437
 
438
            if ($this->getLength($text) <= $limit) {
439
                return $text;
440
            }
441
 
442
            return rtrim(self::trimText($text, $limit).$end);
443
        };
444
 
445
        return $this;
446
    }
447
 
448
    /**
449
     * Forces the width of the element.
450
     */
451
    final public function w(int|string $width): static
452
    {
453
        return $this->with(['styles' => [
454
            'width' => $width,
455
        ]]);
456
    }
457
 
458
    /**
459
     * Forces the element width to the full width of the terminal.
460
     */
461
    final public function wFull(): static
462
    {
463
        return $this->w('1/1');
464
    }
465
 
466
    /**
467
     * Removes the width set on the element.
468
     */
469
    final public function wAuto(): static
470
    {
471
        return $this->with(['styles' => [
472
            'width' => null,
473
        ]]);
474
    }
475
 
476
    /**
477
     * Defines a minimum width of an element.
478
     */
479
    final public function minW(int|string $width): static
480
    {
481
        return $this->with(['styles' => [
482
            'minWidth' => $width,
483
        ]]);
484
    }
485
 
486
    /**
487
     * Defines a maximum width of an element.
488
     */
489
    final public function maxW(int|string $width): static
490
    {
491
        return $this->with(['styles' => [
492
            'maxWidth' => $width,
493
        ]]);
494
    }
495
 
496
    /**
497
     * Makes the element's content uppercase.
498
     */
499
    final public function uppercase(): self
500
    {
501
        $this->textModifiers[__METHOD__] = static fn ($text): string => mb_strtoupper($text, 'UTF-8');
502
 
503
        return $this;
504
    }
505
 
506
    /**
507
     * Makes the element's content lowercase.
508
     */
509
    final public function lowercase(): self
510
    {
511
        $this->textModifiers[__METHOD__] = static fn ($text): string => mb_strtolower($text, 'UTF-8');
512
 
513
        return $this;
514
    }
515
 
516
    /**
517
     * Makes the element's content capitalize.
518
     */
519
    final public function capitalize(): self
520
    {
521
        $this->textModifiers[__METHOD__] = static fn ($text): string => mb_convert_case($text, MB_CASE_TITLE, 'UTF-8');
522
 
523
        return $this;
524
    }
525
 
526
    /**
527
     * Makes the element's content in snakecase.
528
     */
529
    final public function snakecase(): self
530
    {
531
        $this->textModifiers[__METHOD__] = static fn ($text): string => mb_strtolower(
532
            (string) preg_replace(['/([a-z\d])([A-Z])/', '/([^_])([A-Z][a-z])/'], '$1_$2', $text),
533
            'UTF-8'
534
        );
535
 
536
        return $this;
537
    }
538
 
539
    /**
540
     * Makes the element's content with a line through.
541
     */
542
    final public function lineThrough(): self
543
    {
544
        $this->styleModifiers[__METHOD__] = static fn ($text): string => sprintf("\e[9m%s\e[0m", $text);
545
 
546
        return $this;
547
    }
548
 
549
    /**
550
     * Makes the element's content invisible.
551
     */
552
    final public function invisible(): self
553
    {
554
        $this->styleModifiers[__METHOD__] = static fn ($text): string => sprintf("\e[8m%s\e[0m", $text);
555
 
556
        return $this;
557
    }
558
 
559
    /**
560
     * Do not display element's content.
561
     */
562
    final public function hidden(): self
563
    {
564
        return $this->with(['styles' => [
565
            'display' => 'hidden',
566
        ]]);
567
    }
568
 
569
    /**
570
     * Makes a line break before the element's content.
571
     */
572
    final public function block(): self
573
    {
574
        return $this->with(['styles' => [
575
            'display' => 'block',
576
        ]]);
577
    }
578
 
579
    /**
580
     * Makes an element eligible to work with flex-1 element's style.
581
     */
582
    final public function flex(): self
583
    {
584
        return $this->with(['styles' => [
585
            'display' => 'flex',
586
        ]]);
587
    }
588
 
589
    /**
590
     * Makes an element grow and shrink as needed, ignoring the initial size.
591
     */
592
    final public function flex1(): self
593
    {
594
        return $this->with(['styles' => [
595
            'flex-1' => true,
596
        ]]);
597
    }
598
 
599
    /**
600
     * Justifies childs along the element with an equal amount of space between.
601
     */
602
    final public function justifyBetween(): self
603
    {
604
        return $this->with(['styles' => [
605
            'justifyContent' => 'between',
606
        ]]);
607
    }
608
 
609
    /**
610
     * Justifies childs along the element with an equal amount of space between
611
     * each item and half around.
612
     */
613
    final public function justifyAround(): self
614
    {
615
        return $this->with(['styles' => [
616
            'justifyContent' => 'around',
617
        ]]);
618
    }
619
 
620
    /**
621
     * Justifies childs along the element with an equal amount of space around each item.
622
     */
623
    final public function justifyEvenly(): self
624
    {
625
        return $this->with(['styles' => [
626
            'justifyContent' => 'evenly',
627
        ]]);
628
    }
629
 
630
    /**
631
     * Justifies childs along the center of the container’s main axis.
632
     */
633
    final public function justifyCenter(): self
634
    {
635
        return $this->with(['styles' => [
636
            'justifyContent' => 'center',
637
        ]]);
638
    }
639
 
640
    /**
641
     * Repeats the string given until it fills all the content.
642
     */
643
    final public function contentRepeat(string $string): self
644
    {
645
        $string = preg_replace("/\[?'?([^'|\]]+)'?\]?/", '$1', $string) ?? '';
646
 
647
        $this->textModifiers[__METHOD__] = static fn (): string => str_repeat($string, (int) floor(terminal()->width() / mb_strlen($string, 'UTF-8')));
648
 
649
        return $this->with(['styles' => [
650
            'contentRepeat' => true,
651
        ]]);
652
    }
653
 
654
    /**
655
     * Prepends text to the content.
656
     */
657
    final public function prepend(string $string): self
658
    {
659
        $this->textModifiers[__METHOD__] = static fn ($text): string => $string.$text;
660
 
661
        return $this;
662
    }
663
 
664
    /**
665
     * Appends text to the content.
666
     */
667
    final public function append(string $string): self
668
    {
669
        $this->textModifiers[__METHOD__] = static fn ($text): string => $text.$string;
670
 
671
        return $this;
672
    }
673
 
674
    /**
675
     * Prepends the list style type to the content.
676
     */
677
    final public function list(string $type, int $index = 0): self
678
    {
679
        if (! $this->element instanceof Ul && ! $this->element instanceof Ol && ! $this->element instanceof Li) {
680
            throw new InvalidStyle(sprintf(
681
                'Style list-none cannot be used with %s',
682
                $this->element !== null ? $this->element::class : 'unknown element'
683
            ));
684
        }
685
 
686
        if (! $this->element instanceof Li) {
687
            return $this;
688
        }
689
 
690
        return match ($type) {
691
            'square' => $this->prepend('Ă¢â€“Âª '),
692
            'disc' => $this->prepend('• '),
693
            'decimal' => $this->prepend(sprintf('%d. ', $index)),
694
            default => $this,
695
        };
696
    }
697
 
698
    /**
699
     * Adds the given properties to the element.
700
     *
701
     * @param  array<string, mixed>  $properties
702
     */
703
    public function with(array $properties): self
704
    {
705
        $this->properties = array_replace_recursive($this->properties, $properties);
706
 
707
        return $this;
708
    }
709
 
710
    /**
711
     * Sets the href property to the element.
712
     */
713
    final public function href(string $href): self
714
    {
715
        $href = str_replace('%', '%%', $href);
716
 
717
        return $this->with(['href' => array_filter([$href])]);
718
    }
719
 
720
    /**
721
     * Formats a given string.
722
     */
723
    final public function format(string $content): string
724
    {
725
        foreach ($this->textModifiers as $modifier) {
726
            $content = $modifier(
727
                $content,
728
                $this->properties['styles'] ?? [],
729
                $this->properties['parentStyles'] ?? []
730
            );
731
        }
732
 
733
        $content = $this->applyWidth($content);
734
 
735
        foreach ($this->styleModifiers as $modifier) {
736
            $content = $modifier($content, $this->properties['styles'] ?? []);
737
        }
738
 
739
        return $this->applyStyling($content);
740
    }
741
 
742
    /**
743
     * Get the format string including required styles.
744
     */
745
    private function getFormatString(): string
746
    {
747
        $styles = [];
748
 
749
        /** @var array<int, string> $href */
750
        $href = $this->properties['href'] ?? [];
751
        if ($href !== []) {
752
            $styles[] = sprintf('href=%s', array_pop($href));
753
        }
754
 
755
        $colors = $this->properties['colors'] ?? [];
756
 
757
        foreach ($colors as $option => $content) {
758
            if (in_array($option, ['fg', 'bg'], true)) {
759
                $content = is_array($content) ? array_pop($content) : $content;
760
 
761
                $styles[] = "$option=$content";
762
            }
763
        }
764
 
765
        $options = $this->properties['options'] ?? [];
766
 
767
        if ($options !== []) {
768
            $options = array_keys(array_filter(
769
                $options, fn ($option) => $option === true
770
            ));
771
            $styles[] = count($options) > 0
772
                ? 'options='.implode(',', $options)
773
                : 'options=,';
774
        }
775
 
776
        // If there are no styles we don't need extra tags
777
        if ($styles === []) {
778
            return '%s%s%s%s%s';
779
        }
780
 
781
        return '%s<'.implode(';', $styles).'>%s%s%s</>%s';
782
    }
783
 
784
    /**
785
     * Get the margins applied to the element.
786
     *
787
     * @return array{0: int, 1: int, 2: int, 3: int}
788
     */
789
    private function getMargins(): array
790
    {
791
        $isFirstChild = (bool) $this->properties['isFirstChild'];
792
 
793
        $spaceY = $this->properties['parentStyles']['spaceY'] ?? [];
794
        $spaceY = ! $isFirstChild ? end($spaceY) : 0;
795
 
796
        $spaceX = $this->properties['parentStyles']['spaceX'] ?? [];
797
        $spaceX = ! $isFirstChild ? end($spaceX) : 0;
798
 
799
        return [
800
            $spaceY > 0 ? $spaceY : $this->properties['styles']['mt'] ?? 0,
801
            $this->properties['styles']['mr'] ?? 0,
802
            $this->properties['styles']['mb'] ?? 0,
803
            $spaceX > 0 ? $spaceX : $this->properties['styles']['ml'] ?? 0,
804
        ];
805
    }
806
 
807
    /**
808
     * Get the paddings applied to the element.
809
     *
810
     * @return array{0: int, 1: int, 2: int, 3: int}
811
     */
812
    private function getPaddings(): array
813
    {
814
        return [
815
            $this->properties['styles']['pt'] ?? 0,
816
            $this->properties['styles']['pr'] ?? 0,
817
            $this->properties['styles']['pb'] ?? 0,
818
            $this->properties['styles']['pl'] ?? 0,
819
        ];
820
    }
821
 
822
    /**
823
     * It applies the correct width for the content.
824
     */
825
    private function applyWidth(string $content): string
826
    {
827
        $styles = $this->properties['styles'] ?? [];
828
        $minWidth = $styles['minWidth'] ?? -1;
829
        $width = max($styles['width'] ?? -1, $minWidth);
830
        $maxWidth = $styles['maxWidth'] ?? 0;
831
 
832
        if ($width < 0) {
833
            return $content;
834
        }
835
 
836
        if ($width === 0) {
837
            return '';
838
        }
839
 
840
        if (is_string($width)) {
841
            $width = self::calcWidthFromFraction(
842
                $width,
843
                $styles,
844
                $this->properties['parentStyles'] ?? []
845
            );
846
        }
847
 
848
        if ($maxWidth > 0) {
849
            $width = min($styles['maxWidth'], $width);
850
        }
851
 
852
        $width -= ($styles['pl'] ?? 0) + ($styles['pr'] ?? 0);
853
        $length = $this->getLength($content);
854
 
855
        preg_match_all("/\n+/", $content, $matches);
856
 
857
        $width *= count($matches[0] ?? []) + 1;
858
        $width += mb_strlen($matches[0][0] ?? '', 'UTF-8');
859
 
860
        if ($length <= $width) {
861
            $space = $width - $length;
862
 
863
            return match ($styles['text-align'] ?? '') {
864
                'right' => str_repeat(' ', $space).$content,
865
                'center' => str_repeat(' ', (int) floor($space / 2)).$content.str_repeat(' ', (int) ceil($space / 2)),
866
                default => $content.str_repeat(' ', $space),
867
            };
868
        }
869
 
870
        return self::trimText($content, $width);
871
    }
872
 
873
    /**
874
     * It applies the styling for the content.
875
     */
876
    private function applyStyling(string $content): string
877
    {
878
        $display = $this->properties['styles']['display'] ?? 'inline';
879
 
880
        if ($display === 'hidden') {
881
            return '';
882
        }
883
 
884
        $isFirstChild = (bool) $this->properties['isFirstChild'];
885
 
886
        [$marginTop, $marginRight, $marginBottom, $marginLeft] = $this->getMargins();
887
        [$paddingTop, $paddingRight, $paddingBottom, $paddingLeft] = $this->getPaddings();
888
 
889
        $content = (string) preg_replace('/\r[ \t]?/', "\n",
890
            (string) preg_replace(
891
                '/\n/',
892
                str_repeat(' ', $marginRight + $paddingRight)
893
                ."\n".
894
                str_repeat(' ', $marginLeft + $paddingLeft),
895
                $content)
896
        );
897
 
898
        $formatted = sprintf(
899
            $this->getFormatString(),
900
            str_repeat(' ', $marginLeft),
901
            str_repeat(' ', $paddingLeft),
902
            $content,
903
            str_repeat(' ', $paddingRight),
904
            str_repeat(' ', $marginRight),
905
        );
906
 
907
        $empty = str_replace(
908
            $content,
909
            str_repeat(' ', $this->getLength($content)),
910
            $formatted
911
        );
912
 
913
        $items = [];
914
 
915
        if (in_array($display, ['block', 'flex'], true) && ! $isFirstChild) {
916
            $items[] = "\n";
917
        }
918
 
919
        if ($marginTop > 0) {
920
            $items[] = str_repeat("\n", $marginTop);
921
        }
922
 
923
        if ($paddingTop > 0) {
924
            $items[] = $empty."\n";
925
        }
926
 
927
        $items[] = $formatted;
928
 
929
        if ($paddingBottom > 0) {
930
            $items[] = "\n".$empty;
931
        }
932
 
933
        if ($marginBottom > 0) {
934
            $items[] = str_repeat("\n", $marginBottom);
935
        }
936
 
937
        return implode('', $items);
938
    }
939
 
940
    /**
941
     * Get the length of the text provided without the styling tags.
942
     */
943
    public function getLength(string $text = null): int
944
    {
945
        return mb_strlen(preg_replace(
946
            self::STYLING_REGEX,
947
            '',
948
            $text ?? $this->element?->toString() ?? ''
949
        ) ?? '', 'UTF-8');
950
    }
951
 
952
    /**
953
     * Get the length of the element without margins.
954
     */
955
    public function getInnerWidth(): int
956
    {
957
        $innerLength = $this->getLength();
958
        [, $marginRight, , $marginLeft] = $this->getMargins();
959
 
960
        return $innerLength - $marginLeft - $marginRight;
961
    }
962
 
963
    /**
964
     * Get the constant variant color from Color class.
965
     */
966
    private function getColorVariant(string $color, int $variant): string
967
    {
968
        if ($variant > 0) {
969
            $color .= '-'.$variant;
970
        }
971
 
972
        if (StyleRepository::has($color)) {
973
            return StyleRepository::get($color)->getColor();
974
        }
975
 
976
        $colorConstant = mb_strtoupper(str_replace('-', '_', $color), 'UTF-8');
977
 
978
        if (! defined(Color::class."::$colorConstant")) {
979
            throw new ColorNotFound($colorConstant);
980
        }
981
 
982
        return constant(Color::class."::$colorConstant");
983
    }
984
 
985
    /**
986
     * Calculates the width based on the fraction provided.
987
     *
988
     * @param  array<string, int>  $styles
989
     * @param  array<string, array<int, int|string>>  $parentStyles
990
     */
991
    private static function calcWidthFromFraction(string $fraction, array $styles, array $parentStyles): int
992
    {
993
        $width = self::getParentWidth($parentStyles);
994
 
995
        preg_match('/(\d+)\/(\d+)/', $fraction, $matches);
996
 
997
        if (count($matches) !== 3 || $matches[2] === '0') {
998
            throw new InvalidStyle(sprintf('Style [%s] is invalid.', "w-$fraction"));
999
        }
1000
 
1001
        /** @@phpstan-ignore-next-line  */
1002
        $width = (int) floor($width * $matches[1] / $matches[2]);
1003
        $width -= ($styles['ml'] ?? 0) + ($styles['mr'] ?? 0);
1004
 
1005
        return $width;
1006
    }
1007
 
1008
    /**
1009
     * Gets the width of the parent element.
1010
     *
1011
     * @param  array<string, array<int|string>>  $styles
1012
     */
1013
    public static function getParentWidth(array $styles): int
1014
    {
1015
        $width = terminal()->width();
1016
        foreach ($styles['width'] ?? [] as $index => $parentWidth) {
1017
            $minWidth = (int) $styles['minWidth'][$index];
1018
            $maxWidth = (int) $styles['maxWidth'][$index];
1019
            $margins = (int) $styles['ml'][$index] + (int) $styles['mr'][$index];
1020
 
1021
            $parentWidth = max($parentWidth, $minWidth);
1022
 
1023
            if ($parentWidth < 1) {
1024
                $parentWidth = $width;
1025
            } elseif (is_int($parentWidth)) {
1026
                $parentWidth += $margins;
1027
            }
1028
 
1029
            preg_match('/(\d+)\/(\d+)/', (string) $parentWidth, $matches);
1030
 
1031
            $width = count($matches) !== 3
1032
                ? (int) $parentWidth
1033
                : (int) floor($width * $matches[1] / $matches[2]); //@phpstan-ignore-line
1034
 
1035
            if ($maxWidth > 0) {
1036
                $width = min($maxWidth, $width);
1037
            }
1038
 
1039
            $width -= $margins;
1040
            $width -= (int) $styles['pl'][$index] + (int) $styles['pr'][$index];
1041
        }
1042
 
1043
        return $width;
1044
    }
1045
 
1046
    /**
1047
     * It trims the text properly ignoring all escape codes and
1048
     * `<bg;fg;options>` tags.
1049
     */
1050
    private static function trimText(string $text, int $width): string
1051
    {
1052
        preg_match_all(self::STYLING_REGEX, $text, $matches, PREG_OFFSET_CAPTURE);
1053
        $text = rtrim(mb_strimwidth(preg_replace(self::STYLING_REGEX, '', $text) ?? '', 0, $width, '', 'UTF-8'));
1054
 
1055
        foreach ($matches[0] ?? [] as [$part, $index]) {
1056
            $text = substr($text, 0, $index).$part.substr($text, $index, null);
1057
        }
1058
 
1059
        return $text;
1060
    }
1061
}