Advertisement
danysk

prima metà html kotlin 2022

Oct 5th, 2022
822
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.58 KB | None | 0 0
  1. #!/usr/bin/env kotlin
  2.  
  3. sealed interface Element {
  4.     sealed interface Tag<out C : Element> : Element {
  5.  
  6.         val children: List<C>
  7.         val attributes: List<Attribute>
  8.  
  9.         interface Unique<out C : Element> : Tag<C>
  10.         interface Repeatable<out C : Element> : Tag<C>
  11.     }
  12.     data class Text(val content: String) : Element
  13. }
  14.  
  15. interface Attribute {
  16.     val key: String
  17.     val value: String
  18. }
  19.  
  20. typealias Tag<C> = Element.Tag<C>
  21. typealias UniqueTag<C> = Element.Tag.Unique<C>
  22. typealias Text = Element.Text
  23.  
  24. abstract class AbstractTag<C : Element> : Tag<C> {
  25.     protected var actualChildren: List<C> = emptyList()
  26.     final override val children: List<C> get() = actualChildren
  27.     final override val attributes: List<Attribute> = emptyList()
  28. }
  29.  
  30. class Title(title: String) : UniqueTag<Text> {
  31.     override val children: List<Text> = listOf(Text(title))
  32.     override val attributes: List<Attribute> = emptyList()
  33. }
  34. class Head() : AbstractTag<Tag<Element>>(), UniqueTag<Tag<Element>> {
  35.     fun title(produceTitle: () -> String): Head = apply { actualChildren += Title(produceTitle()) }
  36. }
  37. class Body() : AbstractTag<Element>(), UniqueTag<Element> { }
  38.  
  39. class HTML() : AbstractTag<Element>(), UniqueTag<Element> {
  40.     fun head(configuration: Head.() -> Head): Head = Head().apply { configuration() }
  41.     fun body(configuration: Body.() -> Body): Body = Body().apply { configuration() }
  42. }
  43.  
  44. fun html(configuration: HTML.() -> Unit): HTML = HTML().apply { configuration() }
  45.  
  46. val result = html {
  47.     head {
  48.         title { "Ciao" }
  49.     }
  50. }
  51.  
  52. println(result)
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement