diff options
| author | RblSb <msrblsb@gmail.com> | 2020-03-11 11:12:29 +0300 |
|---|---|---|
| committer | RblSb <msrblsb@gmail.com> | 2020-03-11 11:12:29 +0300 |
| commit | fcea47721fd27dff36c92613bea73a23e3926c89 (patch) | |
| tree | 16543334e05fbd7726ae7d4f6d3679b21f6a1f15 /src/client/Settings.hx | |
| parent | 21c4be884d6c278b5dac67960ed459a6dd2630a2 (diff) | |
Local settings
closes #1
Diffstat (limited to 'src/client/Settings.hx')
| -rw-r--r-- | src/client/Settings.hx | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/src/client/Settings.hx b/src/client/Settings.hx new file mode 100644 index 0000000..47d67fc --- /dev/null +++ b/src/client/Settings.hx @@ -0,0 +1,65 @@ +package client; + +import haxe.Json; +import js.html.Storage; +import js.Browser; + +private typedef Vers = {version:Int}; +private typedef Updater = (data:Any, version:Int)->Any; + +class Settings { + + static var defaults:Null<Vers>; + static var updater:Null<Updater>; + static var storage:Storage; + static var isSupported = false; + + public static function init(def:Vers, ?upd:Updater):Void { + storage = Browser.getLocalStorage(); + isSupported = storage != null; + defaults = def; + updater = upd; + } + + public static function read():Any { + if (!isSupported) return defaults; + final data:Any = Json.parse(storage.getItem("data")); + return checkData(data); + } + + static function checkData(data:Vers):Any { + if (defaults == null) throw "read: default data is null"; + if (data == null) return defaults; + if (data.version == defaults.version) return data; + if (data.version > defaults.version) + throw "read: current data version is larger than default data version"; + if (updater == null) throw "read: updater function is null"; + while (data.version < defaults.version) { + data = updater(data, data.version); + data.version++; + } + write(data); + return data; + } + + public static function set(sets:Any):Void { + final data = read(); + final fields = Reflect.fields(sets); + for (field in fields) { + final value = Reflect.field(sets, field); + Reflect.setField(data, field, value); + } + write(data); + } + + public static function write(data:Vers):Void { + if (!isSupported) return; + storage.setItem("data", Json.stringify(data)); + } + + public static function reset():Void { + if (defaults == null) throw "reset: default data is null"; + write(defaults); + } + +} |
