Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env kotlin
- sealed interface Element {
- sealed interface Tag<out C : Element> : Element {
- val children: List<C>
- val attributes: List<Attribute>
- interface Unique<out C : Element> : Tag<C>
- interface Repeatable<out C : Element> : Tag<C>
- }
- data class Text(val content: String) : Element
- }
- interface Attribute {
- val key: String
- val value: String
- }
- typealias Tag<C> = Element.Tag<C>
- typealias UniqueTag<C> = Element.Tag.Unique<C>
- typealias Text = Element.Text
- abstract class AbstractTag<C : Element> : Tag<C> {
- protected var actualChildren: List<C> = emptyList()
- final override val children: List<C> get() = actualChildren
- final override val attributes: List<Attribute> = emptyList()
- }
- class Title(title: String) : UniqueTag<Text> {
- override val children: List<Text> = listOf(Text(title))
- override val attributes: List<Attribute> = emptyList()
- }
- class Head() : AbstractTag<Tag<Element>>(), UniqueTag<Tag<Element>> {
- fun title(produceTitle: () -> String): Head = apply { actualChildren += Title(produceTitle()) }
- }
- class Body() : AbstractTag<Element>(), UniqueTag<Element> { }
- class HTML() : AbstractTag<Element>(), UniqueTag<Element> {
- fun head(configuration: Head.() -> Head): Head = Head().apply { configuration() }
- fun body(configuration: Body.() -> Body): Body = Body().apply { configuration() }
- }
- fun html(configuration: HTML.() -> Unit): HTML = HTML().apply { configuration() }
- val result = html {
- head {
- title { "Ciao" }
- }
- }
- println(result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement