Created
March 13, 2024 14:34
-
-
Save felher/c8419503ba5868d245f2d51b1b53f2b8 to your computer and use it in GitHub Desktop.
leaking var laminar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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