CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-python-fasthtml

The fastest way to create HTML apps - a next-generation Python web framework for building fast, scalable web applications with minimal code

Pending
Overview
Eval results
Files

svg-components.mddocs/

SVG Components and Graphics

Comprehensive SVG element generation system for creating scalable vector graphics, charts, diagrams, and interactive visualizations.

Capabilities

SVG Root Element

Create SVG container elements with automatic namespace handling and viewport configuration.

def Svg(*args, viewBox=None, h=None, w=None, height=None, width=None, xmlns="http://www.w3.org/2000/svg", **kwargs):
    """
    SVG root element with automatic xmlns namespace.
    
    Creates the main SVG container with proper namespace declaration
    and optional viewport configuration.
    
    Args:
        *args: Child SVG elements
        viewBox: Viewport definition (e.g., "0 0 100 100")
        h: Height (alternative to height)
        w: Width (alternative to width)
        height: SVG height
        width: SVG width
        xmlns: XML namespace (automatically set)
        **kwargs: Additional SVG attributes
        
    Returns:
        SVG root element with namespace and configuration
    """

def ft_svg(tag: str, *c, transform=None, opacity=None, clip=None, mask=None, filter=None, **kwargs):
    """
    Create SVG element with SVG-specific attributes.
    
    Enhanced SVG element creation with support for SVG-specific
    attributes like transforms, clipping, and filters.
    
    Args:
        tag: SVG element tag name
        *c: Child content
        transform: SVG transform attribute
        opacity: Element opacity (0-1)
        clip: Clipping path reference
        mask: Mask reference
        filter: Filter reference
        **kwargs: Additional SVG attributes
        
    Returns:
        SVG element with processed attributes
    """

Basic SVG Shapes

Fundamental geometric shapes for building SVG graphics.

def Rect(width, height, x=0, y=0, fill=None, stroke=None, stroke_width=None, rx=None, ry=None, **kwargs):
    """
    SVG rectangle element.
    
    Args:
        width: Rectangle width
        height: Rectangle height
        x: X coordinate of top-left corner
        y: Y coordinate of top-left corner
        fill: Fill color
        stroke: Stroke color
        stroke_width: Stroke width
        rx: X-axis corner radius
        ry: Y-axis corner radius
        **kwargs: Additional attributes
        
    Returns:
        SVG rect element
    """

def Circle(r, cx=0, cy=0, fill=None, stroke=None, stroke_width=None, **kwargs):
    """
    SVG circle element.
    
    Args:
        r: Circle radius
        cx: Center X coordinate
        cy: Center Y coordinate
        fill: Fill color
        stroke: Stroke color
        stroke_width: Stroke width
        **kwargs: Additional attributes
        
    Returns:
        SVG circle element
    """

def Ellipse(rx, ry, cx=0, cy=0, fill=None, stroke=None, stroke_width=None, **kwargs):
    """
    SVG ellipse element.
    
    Args:
        rx: X-axis radius
        ry: Y-axis radius
        cx: Center X coordinate
        cy: Center Y coordinate
        fill: Fill color
        stroke: Stroke color
        stroke_width: Stroke width
        **kwargs: Additional attributes
        
    Returns:
        SVG ellipse element
    """

def Line(x1, y1, x2=0, y2=0, stroke='black', w=None, stroke_width=1, **kwargs):
    """
    SVG line element.
    
    Args:
        x1: Starting X coordinate
        y1: Starting Y coordinate
        x2: Ending X coordinate
        y2: Ending Y coordinate
        stroke: Line color
        w: Line width (alternative to stroke_width)
        stroke_width: Line width
        **kwargs: Additional attributes
        
    Returns:
        SVG line element
    """

Complex Shapes and Paths

Advanced shape elements for complex graphics and custom paths.

def Polyline(*args, points=None, fill=None, stroke=None, stroke_width=None, **kwargs):
    """
    SVG polyline element for connected line segments.
    
    Args:
        *args: Point coordinates as individual arguments
        points: Points as string or list (e.g., "0,0 10,10 20,0")
        fill: Fill color
        stroke: Stroke color
        stroke_width: Stroke width
        **kwargs: Additional attributes
        
    Returns:
        SVG polyline element
    """

def Polygon(*args, points=None, fill=None, stroke=None, stroke_width=None, **kwargs):
    """
    SVG polygon element for closed shapes.
    
    Args:
        *args: Point coordinates as individual arguments
        points: Points as string or list
        fill: Fill color
        stroke: Stroke color
        stroke_width: Stroke width
        **kwargs: Additional attributes
        
    Returns:
        SVG polygon element
    """

class PathFT:
    """Advanced path builder for complex SVG paths."""
    
    def __init__(self):
        """Initialize path builder."""
    
    def M(self, x, y):
        """Move to absolute position."""
    
    def L(self, x, y):
        """Line to absolute position."""
    
    def C(self, x1, y1, x2, y2, x, y):
        """Cubic Bézier curve."""
    
    def Z(self):
        """Close path."""

def Path(d='', fill=None, stroke=None, stroke_width=None, **kwargs):
    """
    SVG path element for complex shapes.
    
    Args:
        d: Path data string (SVG path commands)
        fill: Fill color
        stroke: Stroke color
        stroke_width: Stroke width
        **kwargs: Additional attributes
        
    Returns:
        SVG path element
    """

Text and Typography

SVG text elements with advanced typography features.

def Text(*args, x=0, y=0, font_family=None, font_size=None, fill=None, text_anchor=None, **kwargs):
    """
    SVG text element.
    
    Args:
        *args: Text content
        x: X coordinate
        y: Y coordinate
        font_family: Font family name
        font_size: Font size
        fill: Text color
        text_anchor: Text alignment (start, middle, end)
        **kwargs: Additional text attributes
        
    Returns:
        SVG text element
    """

Grouping and Organization

Elements for organizing and structuring complex SVG graphics.

def G(*args, **kwargs):
    """
    SVG group element for organizing related elements.
    
    Args:
        *args: Child SVG elements
        **kwargs: Group attributes (transform, etc.)
        
    Returns:
        SVG g (group) element
    """

def Defs(*args, **kwargs):
    """
    SVG definitions element for reusable components.
    
    Args:
        *args: Definition elements (gradients, patterns, etc.)
        **kwargs: Additional attributes
        
    Returns:
        SVG defs element
    """

def Use(href=None, x=0, y=0, **kwargs):
    """
    SVG use element for referencing defined elements.
    
    Args:
        href: Reference to defined element (e.g., "#myElement")
        x: X coordinate offset
        y: Y coordinate offset
        **kwargs: Additional attributes
        
    Returns:
        SVG use element
    """

def Symbol(*args, viewBox=None, **kwargs):
    """
    SVG symbol element for reusable graphics.
    
    Args:
        *args: Symbol content
        viewBox: Symbol viewport
        **kwargs: Additional attributes
        
    Returns:
        SVG symbol element
    """

Gradients and Patterns

Advanced fill and stroke options using gradients and patterns.

def LinearGradient(*args, id=None, x1=None, y1=None, x2=None, y2=None, **kwargs):
    """
    SVG linear gradient definition.
    
    Args:
        *args: Gradient stops
        id: Gradient identifier for referencing
        x1: Starting X coordinate (0-1 or percentage)
        y1: Starting Y coordinate (0-1 or percentage)
        x2: Ending X coordinate (0-1 or percentage)
        y2: Ending Y coordinate (0-1 or percentage)
        **kwargs: Additional gradient attributes
        
    Returns:
        SVG linearGradient element
    """

def RadialGradient(*args, id=None, cx=None, cy=None, r=None, **kwargs):
    """
    SVG radial gradient definition.
    
    Args:
        *args: Gradient stops
        id: Gradient identifier
        cx: Center X coordinate
        cy: Center Y coordinate
        r: Gradient radius
        **kwargs: Additional gradient attributes
        
    Returns:
        SVG radialGradient element
    """

def Stop(offset, stop_color=None, stop_opacity=None, **kwargs):
    """
    SVG gradient stop.
    
    Args:
        offset: Stop position (0-1 or percentage)
        stop_color: Stop color
        stop_opacity: Stop opacity
        **kwargs: Additional stop attributes
        
    Returns:
        SVG stop element
    """

def Pattern(*args, id=None, width=None, height=None, patternUnits=None, **kwargs):
    """
    SVG pattern definition for complex fills.
    
    Args:
        *args: Pattern content
        id: Pattern identifier
        width: Pattern width
        height: Pattern height
        patternUnits: Pattern coordinate system
        **kwargs: Additional pattern attributes
        
    Returns:
        SVG pattern element
    """

Transform Utilities

Utility functions for SVG transformations.

def transformd(translate=None, scale=None, rotate=None, skewX=None, skewY=None, matrix=None):
    """
    Transform dictionary to SVG transform string.
    
    Converts transform parameters to SVG transform attribute string.
    
    Args:
        translate: Translation (x, y) tuple
        scale: Scale factor or (x, y) tuple
        rotate: Rotation angle in degrees
        skewX: X-axis skew angle
        skewY: Y-axis skew angle
        matrix: Transform matrix (a, b, c, d, e, f)
        
    Returns:
        str: SVG transform attribute string
    """

HTMX Integration

SVG elements with HTMX support for dynamic graphics.

def SvgOob(*args, **kwargs):
    """
    SVG out-of-band update for HTMX.
    
    Args:
        *args: SVG content for out-of-band update
        **kwargs: Update attributes
        
    Returns:
        SVG element with HTMX out-of-band attributes
    """

def SvgInb(*args, **kwargs):
    """
    SVG inline update for HTMX.
    
    Args:
        *args: SVG content for inline update
        **kwargs: Update attributes
        
    Returns:
        SVG element with HTMX inline attributes
    """

Usage Examples

Basic SVG Graphics

from fasthtml.common import *

app, rt = fast_app()

@rt('/svg-demo')
def svg_demo():
    return Titled("SVG Graphics Demo",
        Container(
            H1("SVG Components"),
            
            # Basic shapes
            Div(
                H2("Basic Shapes"),
                Svg(
                    Rect(width="100", height="60", x="10", y="10", 
                         fill="lightblue", stroke="navy", stroke_width="2"),
                    Circle(r="30", cx="80", cy="80", 
                           fill="lightcoral", stroke="darkred", stroke_width="2"),
                    Ellipse(rx="40", ry="20", cx="150", cy="50", 
                            fill="lightgreen", stroke="darkgreen", stroke_width="2"),
                    Line(x1="10", y1="120", x2="180", y2="120", 
                         stroke="purple", stroke_width="3"),
                    viewBox="0 0 200 140",
                    width="400",
                    height="280"
                )
            ),
            
            # Text and typography
            Div(
                H2("SVG Text"),
                Svg(
                    Text("Hello SVG!", x="10", y="30", 
                         font_family="Arial", font_size="20", fill="darkblue"),
                    Text("Centered Text", x="100", y="60", 
                         text_anchor="middle", font_size="16", fill="red"),
                    Text("Right Aligned", x="190", y="90", 
                         text_anchor="end", font_size="14", fill="green"),
                    viewBox="0 0 200 100",
                    width="400",
                    height="200"
                )
            )
        )
    )

Complex Shapes and Paths

from fasthtml.common import *

app, rt = fast_app()

@rt('/svg-complex')
def svg_complex():
    return Titled("Complex SVG Shapes",
        Container(
            H1("Advanced SVG Graphics"),
            
            # Polygons and polylines
            Div(
                H2("Polygons and Polylines"),
                Svg(
                    Polygon(points="50,10 90,90 10,90", 
                            fill="orange", stroke="darkorange", stroke_width="2"),
                    Polyline(points="110,10 150,50 190,10 230,50 270,10", 
                             fill="none", stroke="blue", stroke_width="3"),
                    viewBox="0 0 280 100",
                    width="560",
                    height="200"
                )
            ),
            
            # Custom paths
            Div(
                H2("Custom Paths"),
                Svg(
                    Path(d="M10,50 Q50,10 90,50 T170,50", 
                         fill="none", stroke="purple", stroke_width="3"),
                    Path(d="M10,80 C10,80 50,40 90,80 S170,120 210,80", 
                         fill="none", stroke="darkgreen", stroke_width="2"),
                    Path(d="M10,110 L50,110 L30,140 Z", 
                         fill="red", stroke="darkred", stroke_width="2"),
                    viewBox="0 0 220 150",
                    width="440",
                    height="300"
                )
            )
        )
    )

Interactive SVG with HTMX

from fasthtml.common import *

app, rt = fast_app()

@rt('/svg-interactive')
def svg_interactive():
    return Titled("Interactive SVG",
        Container(
            H1("Interactive SVG Graphics"),
            
            # Interactive shapes
            Div(
                H2("Click the shapes to change them"),
                Svg(
                    Circle(
                        r="30", cx="60", cy="60", 
                        fill="lightblue", stroke="navy", stroke_width="2",
                        hx_post="/svg/change-circle",
                        hx_target="#interactive-svg",
                        hx_swap="innerHTML",
                        style="cursor: pointer;"
                    ),
                    Rect(
                        width="60", height="40", x="120", y="40", 
                        fill="lightcoral", stroke="darkred", stroke_width="2",
                        hx_post="/svg/change-rect",
                        hx_target="#interactive-svg",
                        hx_swap="innerHTML",
                        style="cursor: pointer;"
                    ),
                    id="interactive-svg",
                    viewBox="0 0 220 120",
                    width="440",
                    height="240"
                )
            ),
            
            # Dynamic chart
            Div(
                H2("Dynamic Chart"),
                Button(
                    "Update Chart",
                    hx_post="/svg/update-chart",
                    hx_target="#chart-svg",
                    hx_swap="innerHTML"
                ),
                Svg(id="chart-svg",
                    *[Rect(
                        width="20", height=f"{20 + i * 10}", 
                        x=f"{30 + i * 30}", y=f"{100 - (20 + i * 10)}", 
                        fill="steelblue", stroke="navy", stroke_width="1"
                    ) for i in range(5)],
                    viewBox="0 0 200 120",
                    width="400",
                    height="240"
                )
            )
        )
    )

@rt('/svg/change-circle', methods=['POST'])
def change_circle():
    import random
    colors = ['lightblue', 'lightcoral', 'lightgreen', 'lightyellow', 'lightpink']
    color = random.choice(colors)
    radius = random.randint(20, 40)
    
    return [
        Circle(
            r=str(radius), cx="60", cy="60", 
            fill=color, stroke="navy", stroke_width="2",
            hx_post="/svg/change-circle",
            hx_target="#interactive-svg",
            hx_swap="innerHTML",
            style="cursor: pointer;"
        ),
        Rect(
            width="60", height="40", x="120", y="40", 
            fill="lightcoral", stroke="darkred", stroke_width="2",
            hx_post="/svg/change-rect",
            hx_target="#interactive-svg",
            hx_swap="innerHTML",
            style="cursor: pointer;"
        )
    ]

@rt('/svg/change-rect', methods=['POST'])
def change_rect():
    import random
    colors = ['lightcoral', 'lightblue', 'lightgreen', 'lightyellow', 'lightpink']
    color = random.choice(colors)
    width = random.randint(40, 80)
    height = random.randint(30, 50)
    
    return [
        Circle(
            r="30", cx="60", cy="60", 
            fill="lightblue", stroke="navy", stroke_width="2",
            hx_post="/svg/change-circle",
            hx_target="#interactive-svg",
            hx_swap="innerHTML",
            style="cursor: pointer;"
        ),
        Rect(
            width=str(width), height=str(height), x="120", y="40", 
            fill=color, stroke="darkred", stroke_width="2",
            hx_post="/svg/change-rect",
            hx_target="#interactive-svg",
            hx_swap="innerHTML",
            style="cursor: pointer;"
        )
    ]

@rt('/svg/update-chart', methods=['POST'])
def update_chart():
    import random
    data = [random.randint(10, 80) for _ in range(5)]
    
    return [
        Rect(
            width="20", height=str(height), 
            x=str(30 + i * 30), y=str(100 - height), 
            fill="steelblue", stroke="navy", stroke_width="1"
        ) for i, height in enumerate(data)
    ]

Gradients and Advanced Styling

from fasthtml.common import *

app, rt = fast_app()

@rt('/svg-gradients')
def svg_gradients():
    return Titled("SVG Gradients and Patterns",
        Container(
            H1("Advanced SVG Styling"),
            
            # Linear gradients
            Div(
                H2("Linear Gradients"),
                Svg(
                    Defs(
                        LinearGradient(
                            Stop(offset="0%", stop_color="red"),
                            Stop(offset="50%", stop_color="yellow"),
                            Stop(offset="100%", stop_color="blue"),
                            id="linear1",
                            x1="0%", y1="0%", x2="100%", y2="0%"
                        ),
                        LinearGradient(
                            Stop(offset="0%", stop_color="purple"),
                            Stop(offset="100%", stop_color="pink"),
                            id="linear2",
                            x1="0%", y1="0%", x2="0%", y2="100%"
                        )
                    ),
                    Rect(width="100", height="60", x="10", y="10", 
                         fill="url(#linear1)", stroke="black", stroke_width="2"),
                    Circle(r="30", cx="150", cy="40", 
                           fill="url(#linear2)", stroke="black", stroke_width="2"),
                    viewBox="0 0 200 80",
                    width="400",
                    height="160"
                )
            ),
            
            # Radial gradients
            Div(
                H2("Radial Gradients"),
                Svg(
                    Defs(
                        RadialGradient(
                            Stop(offset="0%", stop_color="white"),
                            Stop(offset="50%", stop_color="orange"),
                            Stop(offset="100%", stop_color="red"),
                            id="radial1",
                            cx="50%", cy="50%", r="50%"
                        )
                    ),
                    Circle(r="40", cx="100", cy="50", 
                           fill="url(#radial1)", stroke="darkred", stroke_width="3"),
                    viewBox="0 0 200 100",
                    width="400",
                    height="200"
                )
            )
        )
    )

Data Visualization

from fasthtml.common import *

app, rt = fast_app()

@rt('/svg-charts')
def svg_charts():
    # Sample data
    data = [30, 45, 60, 35, 50, 40, 55]
    labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    
    # Create bar chart
    chart_width = 300
    chart_height = 200
    bar_width = chart_width / len(data)
    max_value = max(data)
    
    bars = []
    text_labels = []
    
    for i, (value, label) in enumerate(zip(data, labels)):
        bar_height = (value / max_value) * (chart_height - 40)
        x = i * bar_width + 10
        y = chart_height - bar_height - 20
        
        bars.append(
            Rect(
                width=str(bar_width - 2), height=str(bar_height),
                x=str(x), y=str(y),
                fill="steelblue", stroke="navy", stroke_width="1"
            )
        )
        
        text_labels.extend([
            Text(str(value), x=str(x + bar_width/2), y=str(y - 5),
                 text_anchor="middle", font_size="12", fill="black"),
            Text(label, x=str(x + bar_width/2), y=str(chart_height - 5),
                 text_anchor="middle", font_size="10", fill="gray")
        ])
    
    return Titled("SVG Data Visualization",
        Container(
            H1("Data Charts with SVG"),
            
            Div(
                H2("Weekly Sales Chart"),
                Svg(
                    *bars,
                    *text_labels,
                    # Y-axis
                    Line(x1="5", y1="20", x2="5", y2=str(chart_height - 20),
                         stroke="black", stroke_width="2"),
                    # X-axis  
                    Line(x1="5", y1=str(chart_height - 20), x2=str(chart_width + 10), y2=str(chart_height - 20),
                         stroke="black", stroke_width="2"),
                    viewBox=f"0 0 {chart_width + 20} {chart_height + 10}",
                    width=str((chart_width + 20) * 2),
                    height=str((chart_height + 10) * 2)
                )
            )
        )
    )

Install with Tessl CLI

npx tessl i tessl/pypi-python-fasthtml

docs

application-routing.md

authentication.md

css-styling.md

development-tools.md

form-handling.md

html-components.md

htmx-integration.md

index.md

javascript-integration.md

notifications.md

svg-components.md

tile.json