Skip to content

Gradient

Bases: Text

Text styled with gradient color.

Parameters:

Name Type Description Default
text `str` | `rich.text.Text`

The text to print. Defaults to "".

''
colors `GradientColors`, optional

An optional list of colors [1]_ from which to make the Gradient. Defaults to None.

None
rainbow `bool`

Whether to print the gradient text in rainbow colors across the spectrum. Defaults to False.

False
hues `int`

The number of colors in the gradient. Defaults to 3.

4
style `StyleType`

The style of the gradient text. Defaults to None.

null()
verbose `bool`

Whether to print verbose output. Defaults to False.

False
justify `JustifyMethod`

Justify method: "left", "center", "full", "right". Defaults to None.

DEFAULT_JUSTIFY
overflow Optional[OverflowMethod]

Overflow method: "crop", "fold", "ellipsis". Defaults to None.

DEFAULT_OVERFLOW
end str

Character to end text with. Defaults to "\n".

'\n'
no_wrap bool

Disable text wrapping, or None for default. Defaults to None.

None
tab_size int

Number of spaces per tab, or None to use console.tab_size. Defaults to 4.

4
spans List[Span]

A list of predefined style spans. Defaults to None.

.. [1] colors: List[Optional[Color|Tuple|str|int]

None
Source code in src/rich_gradient/gradient.py
 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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
class Gradient(Text):
    """Text styled with gradient color.

    Args:
        text ( `str` | `rich.text.Text` ): The text to print. Defaults to `""`.
        colors ( `GradientColors`, optional ): An optional list of colors [1]_ from
            which to make the Gradient. Defaults to None.
        rainbow ( `bool` ): Whether to print the gradient text in rainbow colors
            across the spectrum. Defaults to False.
        hues ( `int` ): The number of colors in the gradient. Defaults to `3`.
        style ( `StyleType` ): The style of the gradient text. Defaults to None.
        verbose ( `bool` ): Whether to print verbose output. Defaults to False.
        justify ( `JustifyMethod`, optional): Justify method: "left", "center",
            "full", "right". Defaults to None.
        overflow (Optional[OverflowMethod]):  Overflow method: "crop", "fold",
            "ellipsis". Defaults to None.
        end (str, optional): Character to end text with. Defaults to "\\\\n".
        no_wrap (bool, optional): Disable text wrapping, or None for default.
            Defaults to None.
        tab_size (int): Number of spaces per tab, or `None` to use
            `console.tab_size`. Defaults to 4.
        spans (List[Span], optional): A list of predefined style spans.
            Defaults to None.


            .. [1] colors: List[Optional[Color|Tuple|str|int]
    """


    __slots__ = [
        "_colors",
        "_text",
        "_length",
        "length",
        "_end",
        "_hues",
        "_justify",
        "_no_wrap",
        "overflow",
        "_overflow",
        "simple",
        "style",
        "_style",
        "_spans",
        "_rainbow",
        "verbose",
    ]

    def __init__(
        self,
        text: str | Text = "",
        colors: GradientColors = None,
        *,
        rainbow: bool = False,
        hues: int = 4,
        style: StyleType = Style.null(),
        justify: Optional[JustifyMethod] = DEFAULT_JUSTIFY,
        overflow: Optional[OverflowMethod] = DEFAULT_OVERFLOW,
        no_wrap: Optional[bool] = None,
        end: str = "\n",
        tab_size: Optional[int] = 4,
        verbose: bool = False,
        spans: Optional[List[Span]] = None,
    ) -> None:
        """
        Text styled with gradient color.

        Args:
            text (text): The text to print. Defaults to `""`.\n
            colors (List[Optional[Color|Tuple|str|int]]): A list of colors to use \
                for the gradient. Defaults to None.\n
            rainbow (bool): Whether to print the gradient text in rainbow colors\
                  across the spectrum. Defaults to False.\n
            hues (int): The number of colors in the gradient. Defaults to `4`.\n
            style (StyleType): The style of the gradient text. Defaults to None.\n
            verbose (bool): Whether to print verbose output. Defaults to False.
            justify (Optional[JustifyMethod]): Justify method: "left", "center",\
                "full", "right". Defaults to None.\n
            overflow (Optional[OverflowMethod]):  Overflow method: "crop", "fold", \
                "ellipsis". Defaults to None.\n
            end (str, optional): Character to end text with. Defaults to "\\\\n".\n
            no_wrap (bool, optional): Disable text wrapping, or None for default.\
                Defaults to None.\n
            tab_size (int): Number of spaces per tab, or `None` to use\
                `console.tab_size`. Defaults to 4.\n
            spans (List[Span], optional): A list of predefined style spans.\
                Defaults to None.\n

        """
        self.simple = False
        self.verbose = verbose or False
        self.text = text  # type: ignore
        self.hues = hues
        self.justify = justify or DEFAULT_JUSTIFY
        self.overflow = overflow or DEFAULT_OVERFLOW
        self.style: StyleType = Style.parse(style) if isinstance(style, str) else style
        self.colors = self.validate_colors(colors or [], rainbow=rainbow)  # type: ignore
        if len(self.colors) == 2:
            self.simple = True
        if len(self.colors) > 2:
            self.hues = len(self.colors)
        else:
            self.hues = hues
        self.verbose = verbose

        super().__init__(
            text=self.text,
            style=style,
            justify=justify,
            overflow=overflow,
            no_wrap=no_wrap,
            end=end,
            tab_size=tab_size or 4,
            spans=spans,
        )
        indexes = self.generate_indexes()
        substrings = self.generate_substrings(indexes)
        subgradients = self.generate_subgradients(substrings)
        self._spans = self.join_subgradients(subgradients).spans

    def __len__(self) -> int:
        """Return the length of the gradient text."""
        return self._length

    def __str__(self) -> str:
        """Return the gradient text as a string."""
        return self.text

    def __int__(self) -> int:
        """Return the number of colors in the gradient."""
        return len(self.colors)

    @property
    def text(self) -> str:
        """
        Returns the concatenated string representation of the `_text` attribute.

        Returns:
            str: The concatenated string representation of the `_text` attribute.
        """
        return "".join(self._text) if isinstance(self._text, list) else self._text

    @text.setter
    def text(self, value: Optional[str] | Optional[Text]) -> None:
        """
        Setter for the text attribute.

        Args:
            value (str|Text): The value to set for the text attribute.

        Returns:
            None
        """
        if isinstance(value, Text):
            self._length = value._length
            self._text = value._text
            self._spans = value.spans
        elif isinstance(value, str):
            sanitized_text = strip_control_codes(value)
            self._length = len(sanitized_text)
            self._text = list(sanitized_text)
        elif value is None:
            raise ValueError("Text cannot be None.")
        else:
            raise TypeError(f"Text must be a string or Text, not {type(value)}")

    @property
    def hues(self) -> int:
        """The number of colors in the gradient."""
        return self._hues

    @hues.setter
    def hues(self, hues: int) -> None:
        """Set the number of colors in the gradient.

        Args:
            hues (int): The number of colors in the gradient. Defaults to `4`.
        """
        if hues < 2:
            raise ValueError("Gradient must have at least two colors.")
        self._hues = hues

    @property  # type: ignore
    def justify(self) -> JustifyMethod:
        """The justify method of the gradient."""
        if not hasattr(self, "_justify"):
            return DEFAULT_JUSTIFY
        return self._justify  # type: ignore

    @justify.setter
    def justify(self, justify: JustifyMethod) -> None:
        """Set the justify method of the gradient.

        Args:
            justify (JustifyMethod): The justify method of the gradient.
        """
        self._justify = justify

    @property
    def no_wrap(self) -> Optional[bool]:
        """Whether to wrap the gradient text."""
        try:
            return self._no_wrap
        except AttributeError:
            return None

    @no_wrap.setter
    def no_wrap(self, no_wrap: Optional[bool]) -> None:
        """Set whether to wrap the gradient text.

        Args:
            no_wrap (bool): Whether to wrap the gradient text.
        """
        self._no_wrap = no_wrap

    @property
    def colors(self) -> List[Color]:
        """The colors in the gradient."""
        return self._colors

    @colors.setter
    def colors(self, values: Optional[List[ColorType]] | Optional[List[Color]]) -> None:
        """Set the colors in the gradient.

        Args:
            colors (List[Color]): The colors in the gradient.
        """
        self._colors = self.validate_colors(values)
        self._hues = len(self._colors)

    def validate_colors(
        self,
        colors: Optional[List[ColorType]] | Optional[List[Color]],
        rainbow: bool = False,
    ) -> List[Color]:
        """Validate input colors, and convert them into `Color` objects.

        Colors may be passed in as strings or tuples, names, or Color objects.
        If no colors are provided, a random gradient will be generated.

        Args:
            colors (List[ColorType]): The colors to validate and convert

        Returns:
            List[Color]: The validated colors.

        Raises:
            PydanticCustomError: If any of the colors are invalid.
        """
        _colors: List[Color] = []
        if colors is None or colors == []:
            if not rainbow:
                color_list = Spectrum()
                for index, color in enumerate(color_list):
                    _colors.append(color)
                    if index == self.hues - 1:
                        break
                return _colors
            else:
                self.hues = 20
                if self._length < 20:
                    self.hues = self._length
                color_list = Spectrum()
                for index, color in enumerate(color_list):
                    _colors.append(color)
                    if index == self.hues - 1:
                        break
                return _colors
        elif isinstance(colors, tuple):
            for color in colors:
                try:
                    color = Color(color)
                except PydanticCustomError as pce:
                    raise pce
                else:
                    _colors.append(color)
            assert len(_colors) >= 2, "Gradient must have at least two colors."
            return _colors
        elif isinstance(colors, list):
            for color in colors:  # type: ignore
                try:
                    color = Color(color)
                except PydanticCustomError as pce:
                    raise pce
                else:
                    _colors.append(color)
            assert len(_colors) >= 2, "Gradient must have at least two colors."
            return _colors
        else:
            raise TypeError(f"Colors must be a list or tuple, not {type(colors)}.")

    def _base_span(self) -> None:
        if not hasattr(self, "_spans"):
            self._spans = [Span(0, self._length - 1, self.style)]

    @property
    def spans(self) -> List[Span]:
        """The spans of the gradient."""
        self._base_span()
        return self._spans

    @spans.setter
    def spans(self, spans: List[Span]) -> None:
        """Set the spans of the gradient.

        Args:
            spans (List[Span]): The spans of the gradient.
        """
        self._spans = spans

    @staticmethod
    def arange(start, stop=None, step=1, dtype=None):
        if stop is None:
            # If only one argument is provided, it's the stop value, and start is 0
            start, stop = 0, start

        if step == 0:
            raise ValueError("Step must be non-zero")

        if dtype is None:
            # Automatically detect dtype
            if isinstance(start, int) and (
                isinstance(stop, float) or isinstance(step, float)
            ):
                dtype = float
            else:
                dtype = type(start)

        current = start
        result = []

        # Determine the comparison operation based on the sign of the step
        if step > 0:
            while current < stop:
                result.append(dtype(current))
                current += step
        else:
            while current > stop:
                result.append(dtype(current))
                current += step

        return result

    @staticmethod
    def array_split(arr, indices_or_sections):
        if isinstance(indices_or_sections, int):
            if indices_or_sections <= 0:
                raise ValueError("Number of sections must be greater than 0.")

            # Calculate the size of each section
            section_size = len(arr) // indices_or_sections
            remainder = len(arr) % indices_or_sections

            sections = []
            start = 0

            for i in range(indices_or_sections):
                end = start + section_size + (1 if i < remainder else 0)
                sections.append(arr[start:end])
                start = end

            return sections

        elif isinstance(indices_or_sections, (list, tuple)):
            sections = []
            prev_index = 0

            for index in indices_or_sections:
                sections.append(arr[prev_index:index])
                prev_index = index

            sections.append(arr[prev_index:])

            return sections

        else:
            raise TypeError(
                "indices_or_sections must be an integer or a list/tuple of integers."
            )

    def generate_indexes(self) -> List[List[int]]:
        """Chunk the text into a list of strings.

        Returns:
            List[str]: The list of strings.
        """
        result = self.array_split(self.arange(self._length), self.hues - 1)  # noqa: F722
        indexes: List[List[int]] = [sublist for sublist in result]
        return indexes

    def generate_substrings(self, indexes: List[List[int]]) -> List[str]:
        """Split the text into substrings based on the indexes.

        Args:
            indexes (List[List[int]]): The indexes to split the text on.

        Returns:
            List[str]: The list of substrings.
        """
        substrings: List[str] = []
        slices: List[Tuple[int, int]] = []

        # For each index get the first and last element
        for index in indexes:
            start = index[0]
            end = index[-1] + 1
            slices.append((start, end))  #  # Slice the text

        # If the text is a list, join it into a single string
        if isinstance(self.text, list):
            text = " ".join(self.text)
        elif isinstance(self.text, str):
            text = self.text
        else:
            raise TypeError(f"Text must be a string or list, not {type(self.text)}")

        # split the text into substrings
        for index, (start, end) in enumerate(slices, 1):  # type: ignore
            substring = text[start:end]
            substrings.append(substring)
        return substrings

    def generate_subgradients(self, substrings: List[str]) -> List[SimpleGradient]:
        """Generate simple gradients.

        Args:
            substrings (List[str]): The substrings to generate gradients for.

        Returns:
            List[SimpleGradient]: The list of simple gradients.
        """
        subgradients: List[SimpleGradient] = []

        if self.simple:
            return [
                SimpleGradient(
                    self.text,
                    color1=self.colors[0].hex,
                    color2=self.colors[1].hex,
                    style=self.style,
                    justify=self.justify or DEFAULT_JUSTIFY,
                    overflow=self.overflow or DEFAULT_OVERFLOW,
                    no_wrap=self.no_wrap or False,
                    end=self.end or "\n",
                    spans=self.spans,
                )
            ]
        else:
            for index, substring in enumerate(substrings):
                # Get the colors for the gradient
                color_1 = self.colors[index]
                color_2 = self.colors[index + 1]

                assert self.overflow is not None, "Overflow must be set."

                # Create a simple gradient
                gradient = SimpleGradient(
                    substring,  # type: ignore
                    color1=color_1.hex,
                    color2=color_2.hex,
                    justify=self.justify,
                    overflow=self.overflow,
                    style=self.style,
                    no_wrap=self.no_wrap or False,
                    end=self.end or "\n",
                    spans=self.spans,
                )

                subgradients.append(gradient)
            return subgradients

    def join_subgradients(self, subgradients: List[SimpleGradient]) -> Text:
        """Join the subgradients into a single gradient.

        Args:
            subgradients (List[SimpleGradient]): The list of subgradients.

        Returns:
            Text: The joined gradient.
        """
        result = Text()
        for gradient in subgradients:
            result.append(gradient)
        return result

    def as_text(self) -> Text:
        """Convert the gradient to a `Text`.

        Returns:
            Text: The gradient as a `rich.text.Text` object.
        """
        overflow: OverflowMethod = DEFAULT_OVERFLOW
        justify: JustifyMethod = DEFAULT_JUSTIFY
        if self.justify is None:
            justify = DEFAULT_JUSTIFY
        if self.overflow is None:
            overflow = DEFAULT_OVERFLOW
        return Text(
            text=self.text,
            style=self.style,
            justify=justify,
            overflow=overflow,
            no_wrap=self.no_wrap,
            end=self.end or "\n",
            tab_size=self.tab_size,
            spans=self._spans,
        )

    @classmethod
    def named_gradient_example(
        cls,
        save: bool = False,
        path: str = str(Path.cwd() / "docs" / "img" / "named_gradient_example.svg"),
    ) -> None:
        """
        Generate an example of a gradient with defined colors.

        Args:
            save (bool, optional): Whether to save the gradient to a file. Defaults to False.
            path (Optional[Path], optional): The filename to save the gradient to. Defaults \
        to Path("/Users/maxludden/dev/py/MaxGradient/docs/img/named_gradient_example.svg").
                console (Console, optional): The console to print the gradient to. Defaults to console.
        """
        if save:
            console = Console(width=60, record=True)
        else:
            console = Console(width=60)
        gradient = Gradient(
            "The quick brown fox jumps over the lazy dog.",
            colors=["magenta", "purple", "violet"],
        )
        panel_content = Text.assemble(
            gradient,
            Text("\n\nThis gradient starts with "),
            Text("magenta", style="b #ff00ff"),
            Text(". It fades to "),
            Text("purple", style="b #af00ff"),
            Text(", and ends in "),
            Text("violet", style="b #5f00ff"),
            Text("."),
            justify="center",
        )
        console.line(2)
        console.print(
            Panel(panel_content, title="[b #ffffff]Named Gradient[/]", padding=(1, 4)),
            justify="center",
        )
        console.print(
            "[dim i]Named gradients are graidents that have user \
specified colors[/]",
            justify="center",
        )
        if save:
            console.save_svg(path, title="rich-gradient", theme=GRADIENT_TERMINAL_THEME)

    @classmethod
    def random_gradient_example(
        cls,
        save: bool = False,
        path: str = str(Path.cwd() / "docs" / "img" / "random_gradient_example.svg"),
    ) -> None:
        """
        Generate an example of a gradient with random adjacent colors.

        Args:
            save (bool, optional): Whether to save the gradient to a file. Defaults to False.
            path (Optional[Path], optional): The filename to save the gradient to. Defaults \
        to Path("/Users/maxludden/dev/py/MaxGradient/docs/img/named_gradient_example.svg").
                console (Console, optional): The console to print the gradient to. Defaults to console.
        """
        if save:
            console = Console(width=60, record=True)
        else:
            console = Console(width=60)
        console.line()
        console.print(
            Panel(
                Gradient(
                    text="The quick brown fox jumps over the lazy dog.",
                    justify="center",
                ),
                title="[b #ffffff]Random Gradient[/b #ffffff]",
                padding=(1, 4),
            ),
            justify="center",
        )
        console.print(
            "[i dim]Random gradients are randomly generated by \
gradient automatically.[/]",
            justify="center",
        )
        console.line()
        if save:
            console.save_svg(path, title="rich-gradient", theme=GRADIENT_TERMINAL_THEME)

    @classmethod
    def rainbow_gradient_example(
        cls,
        save: bool = False,
        path: str = str(Path.cwd() / "docs" / "img" / "rainbow_gradient_example.svg"),
    ) -> None:
        """
        Generate an example of a gradient with the whole spectrum of colors.

        Args:
            save (bool, optional): Whether to save the gradient to a file. Defaults to False.
            path (Optional[Path], optional): The filename to save the gradient to. Defaults \
        to Path("/Users/maxludden/dev/py/MaxGradient/docs/img/named_gradient_example.svg").
                console (Console, optional): The console to print the gradient to. Defaults to console.
        """
        if save:
            console = Console(width=60, record=True)
        else:
            console = Console(width=60)

        console.line(1)
        console.print(
            Panel(
                Gradient(
                    text="The quick brown fox jumps over the lazy dog.",
                    rainbow=True,
                    justify="center",
                ),
                title=Gradient("Rainbow Gradient", rainbow=True),
                padding=(1, 4),
            ),
            justify="center",
        )
        console.print(
            "[dim i]Rainbow gradients are also automated and will randomly \
span a gradient from one point on the spectrum (randomly) all the way around \
until it returns to it's starting color.",
            justify="center",
        )
        console.line(1)
        if save:
            console.save_svg(path, title="rich-gradient", theme=GRADIENT_TERMINAL_THEME)

    @classmethod
    def example(cls) -> None:
        Gradient.named_gradient_example(True)
        Gradient.random_gradient_example(True)
        Gradient.rainbow_gradient_example(True)

colors: List[Color] property writable

The colors in the gradient.

hues: int property writable

The number of colors in the gradient.

justify: JustifyMethod property writable

The justify method of the gradient.

no_wrap: Optional[bool] property writable

Whether to wrap the gradient text.

spans: List[Span] property writable

The spans of the gradient.

text: str property writable

Returns the concatenated string representation of the _text attribute.

Returns:

Name Type Description
str str

The concatenated string representation of the _text attribute.

__init__(text='', colors=None, *, rainbow=False, hues=4, style=Style.null(), justify=DEFAULT_JUSTIFY, overflow=DEFAULT_OVERFLOW, no_wrap=None, end='\n', tab_size=4, verbose=False, spans=None)

Text styled with gradient color.

Parameters:

Name Type Description Default
text text

The text to print. Defaults to "".

''
colors List[Optional[Color | Tuple | str | int]]

A list of colors to use for the gradient. Defaults to None.

None
rainbow bool

Whether to print the gradient text in rainbow colors across the spectrum. Defaults to False.

False
hues int

The number of colors in the gradient. Defaults to 4.

4
style StyleType

The style of the gradient text. Defaults to None.

null()
verbose bool

Whether to print verbose output. Defaults to False.

False
justify Optional[JustifyMethod]

Justify method: "left", "center", "full", "right". Defaults to None.

DEFAULT_JUSTIFY
overflow Optional[OverflowMethod]

Overflow method: "crop", "fold", "ellipsis". Defaults to None.

DEFAULT_OVERFLOW
end str

Character to end text with. Defaults to "\n".

'\n'
no_wrap bool

Disable text wrapping, or None for default. Defaults to None.

None
tab_size int

Number of spaces per tab, or None to use console.tab_size. Defaults to 4.

4
spans List[Span]

A list of predefined style spans. Defaults to None.

None
Source code in src/rich_gradient/gradient.py
def __init__(
    self,
    text: str | Text = "",
    colors: GradientColors = None,
    *,
    rainbow: bool = False,
    hues: int = 4,
    style: StyleType = Style.null(),
    justify: Optional[JustifyMethod] = DEFAULT_JUSTIFY,
    overflow: Optional[OverflowMethod] = DEFAULT_OVERFLOW,
    no_wrap: Optional[bool] = None,
    end: str = "\n",
    tab_size: Optional[int] = 4,
    verbose: bool = False,
    spans: Optional[List[Span]] = None,
) -> None:
    """
    Text styled with gradient color.

    Args:
        text (text): The text to print. Defaults to `""`.\n
        colors (List[Optional[Color|Tuple|str|int]]): A list of colors to use \
            for the gradient. Defaults to None.\n
        rainbow (bool): Whether to print the gradient text in rainbow colors\
              across the spectrum. Defaults to False.\n
        hues (int): The number of colors in the gradient. Defaults to `4`.\n
        style (StyleType): The style of the gradient text. Defaults to None.\n
        verbose (bool): Whether to print verbose output. Defaults to False.
        justify (Optional[JustifyMethod]): Justify method: "left", "center",\
            "full", "right". Defaults to None.\n
        overflow (Optional[OverflowMethod]):  Overflow method: "crop", "fold", \
            "ellipsis". Defaults to None.\n
        end (str, optional): Character to end text with. Defaults to "\\\\n".\n
        no_wrap (bool, optional): Disable text wrapping, or None for default.\
            Defaults to None.\n
        tab_size (int): Number of spaces per tab, or `None` to use\
            `console.tab_size`. Defaults to 4.\n
        spans (List[Span], optional): A list of predefined style spans.\
            Defaults to None.\n

    """
    self.simple = False
    self.verbose = verbose or False
    self.text = text  # type: ignore
    self.hues = hues
    self.justify = justify or DEFAULT_JUSTIFY
    self.overflow = overflow or DEFAULT_OVERFLOW
    self.style: StyleType = Style.parse(style) if isinstance(style, str) else style
    self.colors = self.validate_colors(colors or [], rainbow=rainbow)  # type: ignore
    if len(self.colors) == 2:
        self.simple = True
    if len(self.colors) > 2:
        self.hues = len(self.colors)
    else:
        self.hues = hues
    self.verbose = verbose

    super().__init__(
        text=self.text,
        style=style,
        justify=justify,
        overflow=overflow,
        no_wrap=no_wrap,
        end=end,
        tab_size=tab_size or 4,
        spans=spans,
    )
    indexes = self.generate_indexes()
    substrings = self.generate_substrings(indexes)
    subgradients = self.generate_subgradients(substrings)
    self._spans = self.join_subgradients(subgradients).spans

__int__()

Return the number of colors in the gradient.

Source code in src/rich_gradient/gradient.py
def __int__(self) -> int:
    """Return the number of colors in the gradient."""
    return len(self.colors)

__len__()

Return the length of the gradient text.

Source code in src/rich_gradient/gradient.py
def __len__(self) -> int:
    """Return the length of the gradient text."""
    return self._length

__str__()

Return the gradient text as a string.

Source code in src/rich_gradient/gradient.py
def __str__(self) -> str:
    """Return the gradient text as a string."""
    return self.text

as_text()

Convert the gradient to a Text.

Returns:

Name Type Description
Text Text

The gradient as a rich.text.Text object.

Source code in src/rich_gradient/gradient.py
def as_text(self) -> Text:
    """Convert the gradient to a `Text`.

    Returns:
        Text: The gradient as a `rich.text.Text` object.
    """
    overflow: OverflowMethod = DEFAULT_OVERFLOW
    justify: JustifyMethod = DEFAULT_JUSTIFY
    if self.justify is None:
        justify = DEFAULT_JUSTIFY
    if self.overflow is None:
        overflow = DEFAULT_OVERFLOW
    return Text(
        text=self.text,
        style=self.style,
        justify=justify,
        overflow=overflow,
        no_wrap=self.no_wrap,
        end=self.end or "\n",
        tab_size=self.tab_size,
        spans=self._spans,
    )

generate_indexes()

Chunk the text into a list of strings.

Returns:

Type Description
List[List[int]]

List[str]: The list of strings.

Source code in src/rich_gradient/gradient.py
def generate_indexes(self) -> List[List[int]]:
    """Chunk the text into a list of strings.

    Returns:
        List[str]: The list of strings.
    """
    result = self.array_split(self.arange(self._length), self.hues - 1)  # noqa: F722
    indexes: List[List[int]] = [sublist for sublist in result]
    return indexes

generate_subgradients(substrings)

Generate simple gradients.

Parameters:

Name Type Description Default
substrings List[str]

The substrings to generate gradients for.

required

Returns:

Type Description
List[SimpleGradient]

List[SimpleGradient]: The list of simple gradients.

Source code in src/rich_gradient/gradient.py
def generate_subgradients(self, substrings: List[str]) -> List[SimpleGradient]:
    """Generate simple gradients.

    Args:
        substrings (List[str]): The substrings to generate gradients for.

    Returns:
        List[SimpleGradient]: The list of simple gradients.
    """
    subgradients: List[SimpleGradient] = []

    if self.simple:
        return [
            SimpleGradient(
                self.text,
                color1=self.colors[0].hex,
                color2=self.colors[1].hex,
                style=self.style,
                justify=self.justify or DEFAULT_JUSTIFY,
                overflow=self.overflow or DEFAULT_OVERFLOW,
                no_wrap=self.no_wrap or False,
                end=self.end or "\n",
                spans=self.spans,
            )
        ]
    else:
        for index, substring in enumerate(substrings):
            # Get the colors for the gradient
            color_1 = self.colors[index]
            color_2 = self.colors[index + 1]

            assert self.overflow is not None, "Overflow must be set."

            # Create a simple gradient
            gradient = SimpleGradient(
                substring,  # type: ignore
                color1=color_1.hex,
                color2=color_2.hex,
                justify=self.justify,
                overflow=self.overflow,
                style=self.style,
                no_wrap=self.no_wrap or False,
                end=self.end or "\n",
                spans=self.spans,
            )

            subgradients.append(gradient)
        return subgradients

generate_substrings(indexes)

Split the text into substrings based on the indexes.

Parameters:

Name Type Description Default
indexes List[List[int]]

The indexes to split the text on.

required

Returns:

Type Description
List[str]

List[str]: The list of substrings.

Source code in src/rich_gradient/gradient.py
def generate_substrings(self, indexes: List[List[int]]) -> List[str]:
    """Split the text into substrings based on the indexes.

    Args:
        indexes (List[List[int]]): The indexes to split the text on.

    Returns:
        List[str]: The list of substrings.
    """
    substrings: List[str] = []
    slices: List[Tuple[int, int]] = []

    # For each index get the first and last element
    for index in indexes:
        start = index[0]
        end = index[-1] + 1
        slices.append((start, end))  #  # Slice the text

    # If the text is a list, join it into a single string
    if isinstance(self.text, list):
        text = " ".join(self.text)
    elif isinstance(self.text, str):
        text = self.text
    else:
        raise TypeError(f"Text must be a string or list, not {type(self.text)}")

    # split the text into substrings
    for index, (start, end) in enumerate(slices, 1):  # type: ignore
        substring = text[start:end]
        substrings.append(substring)
    return substrings

join_subgradients(subgradients)

Join the subgradients into a single gradient.

Parameters:

Name Type Description Default
subgradients List[SimpleGradient]

The list of subgradients.

required

Returns:

Name Type Description
Text Text

The joined gradient.

Source code in src/rich_gradient/gradient.py
def join_subgradients(self, subgradients: List[SimpleGradient]) -> Text:
    """Join the subgradients into a single gradient.

    Args:
        subgradients (List[SimpleGradient]): The list of subgradients.

    Returns:
        Text: The joined gradient.
    """
    result = Text()
    for gradient in subgradients:
        result.append(gradient)
    return result

named_gradient_example(save=False, path=str(Path.cwd() / 'docs' / 'img' / 'named_gradient_example.svg')) classmethod

Generate an example of a gradient with defined colors.

Parameters:

Name Type Description Default
save bool

Whether to save the gradient to a file. Defaults to False.

False
path Optional[Path]

The filename to save the gradient to. Defaults to Path("/Users/maxludden/dev/py/MaxGradient/docs/img/named_gradient_example.svg"). console (Console, optional): The console to print the gradient to. Defaults to console.

str(cwd() / 'docs' / 'img' / 'named_gradient_example.svg')
Source code in src/rich_gradient/gradient.py
    @classmethod
    def named_gradient_example(
        cls,
        save: bool = False,
        path: str = str(Path.cwd() / "docs" / "img" / "named_gradient_example.svg"),
    ) -> None:
        """
        Generate an example of a gradient with defined colors.

        Args:
            save (bool, optional): Whether to save the gradient to a file. Defaults to False.
            path (Optional[Path], optional): The filename to save the gradient to. Defaults \
        to Path("/Users/maxludden/dev/py/MaxGradient/docs/img/named_gradient_example.svg").
                console (Console, optional): The console to print the gradient to. Defaults to console.
        """
        if save:
            console = Console(width=60, record=True)
        else:
            console = Console(width=60)
        gradient = Gradient(
            "The quick brown fox jumps over the lazy dog.",
            colors=["magenta", "purple", "violet"],
        )
        panel_content = Text.assemble(
            gradient,
            Text("\n\nThis gradient starts with "),
            Text("magenta", style="b #ff00ff"),
            Text(". It fades to "),
            Text("purple", style="b #af00ff"),
            Text(", and ends in "),
            Text("violet", style="b #5f00ff"),
            Text("."),
            justify="center",
        )
        console.line(2)
        console.print(
            Panel(panel_content, title="[b #ffffff]Named Gradient[/]", padding=(1, 4)),
            justify="center",
        )
        console.print(
            "[dim i]Named gradients are graidents that have user \
specified colors[/]",
            justify="center",
        )
        if save:
            console.save_svg(path, title="rich-gradient", theme=GRADIENT_TERMINAL_THEME)

rainbow_gradient_example(save=False, path=str(Path.cwd() / 'docs' / 'img' / 'rainbow_gradient_example.svg')) classmethod

Generate an example of a gradient with the whole spectrum of colors.

Parameters:

Name Type Description Default
save bool

Whether to save the gradient to a file. Defaults to False.

False
path Optional[Path]

The filename to save the gradient to. Defaults to Path("/Users/maxludden/dev/py/MaxGradient/docs/img/named_gradient_example.svg"). console (Console, optional): The console to print the gradient to. Defaults to console.

str(cwd() / 'docs' / 'img' / 'rainbow_gradient_example.svg')
Source code in src/rich_gradient/gradient.py
    @classmethod
    def rainbow_gradient_example(
        cls,
        save: bool = False,
        path: str = str(Path.cwd() / "docs" / "img" / "rainbow_gradient_example.svg"),
    ) -> None:
        """
        Generate an example of a gradient with the whole spectrum of colors.

        Args:
            save (bool, optional): Whether to save the gradient to a file. Defaults to False.
            path (Optional[Path], optional): The filename to save the gradient to. Defaults \
        to Path("/Users/maxludden/dev/py/MaxGradient/docs/img/named_gradient_example.svg").
                console (Console, optional): The console to print the gradient to. Defaults to console.
        """
        if save:
            console = Console(width=60, record=True)
        else:
            console = Console(width=60)

        console.line(1)
        console.print(
            Panel(
                Gradient(
                    text="The quick brown fox jumps over the lazy dog.",
                    rainbow=True,
                    justify="center",
                ),
                title=Gradient("Rainbow Gradient", rainbow=True),
                padding=(1, 4),
            ),
            justify="center",
        )
        console.print(
            "[dim i]Rainbow gradients are also automated and will randomly \
span a gradient from one point on the spectrum (randomly) all the way around \
until it returns to it's starting color.",
            justify="center",
        )
        console.line(1)
        if save:
            console.save_svg(path, title="rich-gradient", theme=GRADIENT_TERMINAL_THEME)

random_gradient_example(save=False, path=str(Path.cwd() / 'docs' / 'img' / 'random_gradient_example.svg')) classmethod

Generate an example of a gradient with random adjacent colors.

Parameters:

Name Type Description Default
save bool

Whether to save the gradient to a file. Defaults to False.

False
path Optional[Path]

The filename to save the gradient to. Defaults to Path("/Users/maxludden/dev/py/MaxGradient/docs/img/named_gradient_example.svg"). console (Console, optional): The console to print the gradient to. Defaults to console.

str(cwd() / 'docs' / 'img' / 'random_gradient_example.svg')
Source code in src/rich_gradient/gradient.py
    @classmethod
    def random_gradient_example(
        cls,
        save: bool = False,
        path: str = str(Path.cwd() / "docs" / "img" / "random_gradient_example.svg"),
    ) -> None:
        """
        Generate an example of a gradient with random adjacent colors.

        Args:
            save (bool, optional): Whether to save the gradient to a file. Defaults to False.
            path (Optional[Path], optional): The filename to save the gradient to. Defaults \
        to Path("/Users/maxludden/dev/py/MaxGradient/docs/img/named_gradient_example.svg").
                console (Console, optional): The console to print the gradient to. Defaults to console.
        """
        if save:
            console = Console(width=60, record=True)
        else:
            console = Console(width=60)
        console.line()
        console.print(
            Panel(
                Gradient(
                    text="The quick brown fox jumps over the lazy dog.",
                    justify="center",
                ),
                title="[b #ffffff]Random Gradient[/b #ffffff]",
                padding=(1, 4),
            ),
            justify="center",
        )
        console.print(
            "[i dim]Random gradients are randomly generated by \
gradient automatically.[/]",
            justify="center",
        )
        console.line()
        if save:
            console.save_svg(path, title="rich-gradient", theme=GRADIENT_TERMINAL_THEME)

validate_colors(colors, rainbow=False)

Validate input colors, and convert them into Color objects.

Colors may be passed in as strings or tuples, names, or Color objects. If no colors are provided, a random gradient will be generated.

Parameters:

Name Type Description Default
colors List[ColorType]

The colors to validate and convert

required

Returns:

Type Description
List[Color]

List[Color]: The validated colors.

Raises:

Type Description
PydanticCustomError

If any of the colors are invalid.

Source code in src/rich_gradient/gradient.py
def validate_colors(
    self,
    colors: Optional[List[ColorType]] | Optional[List[Color]],
    rainbow: bool = False,
) -> List[Color]:
    """Validate input colors, and convert them into `Color` objects.

    Colors may be passed in as strings or tuples, names, or Color objects.
    If no colors are provided, a random gradient will be generated.

    Args:
        colors (List[ColorType]): The colors to validate and convert

    Returns:
        List[Color]: The validated colors.

    Raises:
        PydanticCustomError: If any of the colors are invalid.
    """
    _colors: List[Color] = []
    if colors is None or colors == []:
        if not rainbow:
            color_list = Spectrum()
            for index, color in enumerate(color_list):
                _colors.append(color)
                if index == self.hues - 1:
                    break
            return _colors
        else:
            self.hues = 20
            if self._length < 20:
                self.hues = self._length
            color_list = Spectrum()
            for index, color in enumerate(color_list):
                _colors.append(color)
                if index == self.hues - 1:
                    break
            return _colors
    elif isinstance(colors, tuple):
        for color in colors:
            try:
                color = Color(color)
            except PydanticCustomError as pce:
                raise pce
            else:
                _colors.append(color)
        assert len(_colors) >= 2, "Gradient must have at least two colors."
        return _colors
    elif isinstance(colors, list):
        for color in colors:  # type: ignore
            try:
                color = Color(color)
            except PydanticCustomError as pce:
                raise pce
            else:
                _colors.append(color)
        assert len(_colors) >= 2, "Gradient must have at least two colors."
        return _colors
    else:
        raise TypeError(f"Colors must be a list or tuple, not {type(colors)}.")