aboutsummaryrefslogtreecommitdiff
path: root/mavigator-cockpit/src/main/scala/mavigator/util/Page.scala
blob: f8f0deee7ffd406af304b631d09f097693e1aaab (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package mavigator
package util

import org.scalajs.dom
import org.scalajs.dom.html

/** Contents of a single-page app, consisting of styles and a main element. */
trait Page {

  private var isAttached = false
  private def attached[A](action: => A) = if (!isAttached) {
    sys.error("Page has not been attached to an environment yet.")
  } else {
    action
  }

  private var baseUrl: String = null

  def asset(path: String): String = attached { baseUrl + "/" + path }

  def styles: Seq[String]

  def elements: Seq[html.Element]

  /** Attach this page to a website. */
  def attach(env: Environment): Unit = {
    baseUrl = env.baseUrl
    isAttached = true

    val styleText = dom.document.createTextNode(styles.reduce(_ + _))
    env.styleRoot.appendChild(styleText)

    for (elem <- elements) {
      env.root.appendChild(elem)
    }
  }

}