Jupyter widget for synchronizing localStorage state between client and server
Built with Anywidget
/** @param {{ model: DOMWidgetModel, el: HTMLElement }} context */ | |
export function render({ model, el }) { | |
const pull = () => { | |
const key = model.get("key"); | |
const value = model.get("value"); | |
if (localStorage.getItem(key) != value) { | |
if (value === null) { | |
localStorage.removeItem(key); | |
} else { | |
localStorage.setItem(key, value); | |
} | |
console.debug("localStorage: value of key '" + key + "' changed to " + JSON.stringify(value) + " by server"); | |
} | |
}; | |
const push = () => { | |
const key = model.get("key"); | |
const value = localStorage.getItem(key); | |
if (model.get("value") != value) { | |
model.set("value", value); | |
model.save_changes(); | |
console.debug("localStorage: value of key '" + key + "' changed to " + JSON.stringify(value) + " by client"); | |
} | |
}; | |
if (model.get("value") === null) { | |
setTimeout(push); | |
} else { | |
setTimeout(pull); | |
} | |
const onStorage = ({ key, storageArea = localStorage }) => { | |
if (storageArea === localStorage && (key === null || key == model.get("key"))) push(); | |
}; | |
window.addEventListener("storage", onStorage); | |
model.on("change:value", pull); | |
return () => { | |
window.removeEventListener("storage", onStorage); | |
model.off("change:value", pull); | |
}; | |
} |
Jupyter widget for synchronizing localStorage state between client and server
Built with Anywidget
from importlib.resources import files | |
import traitlets | |
from anywidget import AnyWidget | |
class LocalStorage(AnyWidget): | |
_esm = files(__package__).joinpath("ipylocalstorage.js").read_text(encoding="utf-8") | |
key = traitlets.Unicode().tag(sync=True) # TODO: Add key validation | |
value = traitlets.Unicode(allow_none=True, default_value=None).tag(sync=True) |