Skip to content

Instantly share code, notes, and snippets.

@egormkn
Last active October 14, 2023 09:57
Show Gist options
  • Save egormkn/35c982b371311fbf8816822bf3f9ce92 to your computer and use it in GitHub Desktop.
Save egormkn/35c982b371311fbf8816822bf3f9ce92 to your computer and use it in GitHub Desktop.
ipylocalstorage.py
/** @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);
};
}

ipylocalstorage

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment