Skip to content

Instantly share code, notes, and snippets.

@felher
Created March 13, 2024 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felher/c8419503ba5868d245f2d51b1b53f2b8 to your computer and use it in GitHub Desktop.
Save felher/c8419503ba5868d245f2d51b1b53f2b8 to your computer and use it in GitHub Desktop.
leaking var laminar
package org.felher.crust.util
import com.raquo.laminar.api.L.*
import io.circe.*
import org.scalajs.dom
object PersistentVar:
/**
* This function should not be used for dynamically created values
* since it will never be cleaned up.
*/
def leakingPersistentVar[A](name: String, default: A)(using
enc: Encoder[A],
dec: Decoder[A]
): Var[A] =
val key = storageKey(name)
val v = dom.window.sessionStorage.getItem(key) match
case null => Var(default)
case s =>
io.circe.parser.decode[A](s) match
case Left(_) => Var(default)
case Right(a) => Var(a)
v.signal.foreach(value => dom.window.sessionStorage.setItem(key, enc(value).noSpaces))(unsafeWindowOwner)
v
private def storageKey(suffix: String): String =
"org.felher.crust" + suffix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment