Giter Club home page Giter Club logo

ksvg's Introduction

Coverage license Travis Download

Kotlin Multiplatform SVG DSL

I had a Kotlin microservice that needed to produce a simple heatmap chart on an HTML page to a large audience very rapidly. This was an ad hoc DevOps requirement, so I didn't want to take on an involved Javascript solution. Instead, I went with spitting out a half page of inline SVG text generated by the server itself. This DSL made the server code trivial and has easily met the performance needs.

Installation

The library can be obtained from JitPack.io.

In build.gradle.kts:

repositories {
    mavenCentral()
    maven("https://jitpack.io")
}
sourceSets {
    commonMain {
        dependencies {
            implementation("com.github.nwillc.ksvg:ksvg:master-SNAPSHOT")
        }
    }

    val jvmMain by getting {
        dependencies {
            // No dependency required!
        }
    }

    val jsMain by getting  {
        dependencies {
            // No dependency required!
        }
    }
}

Example

fun codeMonkey() {
    val svg = SVG.svg(true) {
         height = "300"
         width = "300"
         style {
             body = """

                 svg .black-stroke { stroke: black; stroke-width: 2; }
                 svg .fur-color { fill: white; }

             """.trimIndent()
         }
         // Label
         text {
             x = "40"
             y = "50"
             body = "#CODE"
             fontFamily = "monospace"
             fontSize = "40px"
         }
         // Ears - example using a function because USE tag doesn't work in Safari
         ear(100, 100)
         ear(240, 70)
         // Face
         circle {
             cssClass = "black-stroke"
             id = "face"
             cx = "180"
             cy = "140"
             r = "80"
             fill = "#aa450f"
         }
         // Eyes
         circle {
             cssClass = "black-stroke fur-color"
             id = "eye"
             cx = "160"
             cy = "95"
             r = "20"
         }
         use {
             x = "45"
             y = "-5"
             href = "#eye"
         }
         // Muzzle
         circle {
             cssClass = "black-stroke fur-color"
             cx = "195"
             cy = "178"
             r = "65"
         }
         // Nostrils
         circle {
             id = "nostril"
             cx = "178"
             cy = "138"
             r = "4"
             fill = "black"
         }
         use {
             x = "35"
             y = "-5"
             href = "#nostril"
         }
         // Mouth
         path {
             cssClass = "black-stroke"
             d = "M 150 150 C 100,250 305,260 230,140 C 205,190 165,170 150,150 Z"
             fill = "red"
         }
     }

     FileWriter("build/tmp/codeMonkey.svg").use {
         svg.render(it, SVG.RenderMode.FILE)
     }
    }

    private fun Container.ear(x: Int, y: Int) {
        circle {
            cssClass = "black-stroke fur-color"
            cx = x.toString()
            cy = y.toString()
            r = "40"
        }
        circle {
            cssClass = "black-stroke fur-color"
            cx = x.toString()
            cy = y.toString()
            r = "28"
        }
    }

Yields a code monkey: code monkey

Validation

Originally the attribute values were appropriate types, but eventually as support for percentage values etc. was added, and considering they are always represented as strings in SVG, the value type was changed to String. But that made errors like length = "foo" possible. Therefore, attribute validation was added. Over time other validations became apparent too. With validation on, while the SVG is created, things are checked, for example when an attribute string is assigned, if it can be properly validated, it is. Validation can be turned off for performance reasons.

About Inline vs File SVG

SVG is an XML tag based format. Those tags can be put into an .svg file, or in modern browsers appear directly inline in the HTML5. However some attributes and other details differ slightly between these modes. This DSL is biased toward the inline representation because that's its origin, but it supports indicating the rendering mode and in the limitted scenarios tested it works.

A Limited Set of Elements

Currently only a small set of SVG Elements are supported. Adding more is straight forward, I just met my own needs, and so additions can be done by others, or as my needs increase.

Multiplatform Support

This is a multiplatform project currently targeting JVM and JavaScript. The JVM target is fully baked, the JavaScript is still a bit doughy. Looking for JavaScript folks to help me polish it.

As Compared To kotlinx.html

Why did I write yet another SVG DSL when SVG is covered by the kotlinx.html? Let's just say ... you try using it. I could not figure out how to use it based on the SVG specification. This package is as close to a one to one mapping as I could make it. So what if you want to combine them? Not a problem, just use unsafe/raw:

 val svg = SVG.svg {
   // ....
 }
 System.out.appendHTML().html {
     body {
        unsafe {
            raw(svg.toString())
        }
     }
 }

See Also

ksvg's People

Contributors

andreyakinshin avatar harryjph avatar nikkyai avatar nwillc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

ksvg's Issues

Repository needs new host

With the closure of Bintray, the old repository at https://dl.bintray.com/nwillc/maven is no longer available. Install instructions in #8 are no longer accurate, but cannot be updated until a new repository url is available.

add function to add raw SVG elements

having the option to insert "raw" child elements from string would be convenient

example:

fun generateSVG(
    shapeViewBox: String = "0 0 100 100",
    shapeContent: String = """<path d="M0 13.3333C0 5.96954 5.96954 0 13.3333 0H86.6667C94.0305 0 100 5.96954 100 13.3333V86.6667C100 94.0305 94.0305 100 86.6667 100H13.3333C5.96954 100 0 94.0305 0 86.6667V13.3333Z" fill="currentColor"/>"""
): String {
    val svg = SVG.svg {
        /* ...*/
        children += SVG.svg {
            id = "shape"
            width = "100%"
            height = "100%"
            attributes["x"] = "0"
            attributes["y"] = "0"
            viewBox = shapeViewBox
            body = "replace_shape"
        }
    }
    return buildString {
        svg.render(this, RenderMode.INLINE)
    }.replace("replace_shape", "\n" +shapeContent + "\n")
}

i recently came across a problem in which i was given raw svg paths and viewport of a SVG and had to assemble nested SVGs out of them

i solved it by assigning a "replace_thing" value to tthe body of the nested SVGs and did some string manipulation on the rendered output

regardless.. a nicer api would make this type of problem easier to solve

nested SVGs will generate XML declaration in each SVG

nested SVGs are a easy way to group elements together and drawing a picture inside a picture

sadly it seems like RenderMode.FILE did not take this into account (also the x, y properties)

example:

val svg = SVG.svg {
    id = "s0"
    width = "256"
    height = "256"
    rect {
        id = "r0"
        width = "100%"
        height = "100%"
        x = "0"
        y = "0"
        stroke = "red"
        strokeWidth = "3"
        fill = "purple"
    }
    children += SVG.svg {
        id = "s1"
        width = "80%"
        height = "80%"
        attributes["x"] = "10%"
        attributes["y"] = "10%"
        rect {
            id = "r1"
            width = "100%"
            height = "100%"
            x = "0"
            y = "0"
            stroke = "red"
            strokeWidth = "3"
            fill = "blue"
        }
        children += SVG.svg {
            id = "s2"
            width = "80%"
            height = "80%"
            attributes["x"] = "10%"
            attributes["y"] = "10%"
            rect {
                id = "r2"
                width = "100%"
                height = "100%"
                x = "0"
                y = "0"
                stroke = "red"
                strokeWidth = "3"
                fill = "cyan"
            }
        }
    }
}
val borkedSVG = buildString {
    svg.render(this, RenderMode.FILE)
}.also {
    File("test_broken.svg").writeText(it)
    println(it)
}

broken output:

<?xml version="1.0" encoding="UTF-8" ?>
<svg height="256" id="s0" width="256" xmlns="http://www.w3.org/2000/svg">
<rect fill="purple" height="100%" id="r0" stroke="red" stroke-width="3" width="100%" x="0" y="0"/>
<?xml version="1.0" encoding="UTF-8" ?>
<svg height="80%" id="s1" width="80%" x="10%" xmlns="http://www.w3.org/2000/svg" y="10%">
<rect fill="blue" height="100%" id="r1" stroke="red" stroke-width="3" width="100%" x="0" y="0"/>
<?xml version="1.0" encoding="UTF-8" ?>
<svg height="80%" id="s2" width="80%" x="10%" xmlns="http://www.w3.org/2000/svg" y="10%">
<rect fill="cyan" height="100%" id="r2" stroke="red" stroke-width="3" width="100%" x="0" y="0"/>
</svg>
</svg>
</svg>

expected/fixed:

<?xml version="1.0" encoding="UTF-8" ?>
<svg height="256" id="s0" width="256" xmlns="http://www.w3.org/2000/svg">
<rect fill="purple" height="100%" id="r0" stroke="red" stroke-width="3" width="100%" x="0" y="0"/>
<svg height="80%" id="s1" width="80%" x="10%" y="10%">
<rect fill="blue" height="100%" id="r1" stroke="red" stroke-width="3" width="100%" x="0" y="0"/>
<svg height="80%" id="s2" width="80%" x="10%" y="10%">
<rect fill="cyan" height="100%" id="r2" stroke="red" stroke-width="3" width="100%" x="0" y="0"/>
</svg>
</svg>
</svg>

Request for multiplatform

Is it possible to package this for multiplatform?

for my own project i just copied your code into my commonMain

i use this with kotlin/js and react, but having it in common code leaves the option open to render stuff serverside too

seems like Chat.isUpperCase() does not exist on js so i solved it expect/actual, iirc this is the only problem i ran into

//common
expect val Char.isUpperCase: Boolean

// js
actual val Char.isUpperCase: Boolean
    get() = (this == this.toUpperCase() && this != this.toLowerCase())

// jvm
actual val Char.isUpperCase: Boolean
    get() = isUpperCase()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.