open Js_of_ocaml open Brr module PM = Prosemirror let storage_key = (Jstr.v "editor") let storage = Brr_io.Storage.local G.window let create_new_state pm mySchema content = let module PM = Prosemirror in let doc = PM.Model.( DOMParser.parse (DOMParser.from_schema pm mySchema) (Jv.Id.of_jv content)) in let props = PM.State.creation_prop () in props##.doc := Js.some doc; props##.plugins := Plugins.default pm mySchema; PM.State.create pm props let page_id : unit -> Jstr.t option = fun () -> let uri = Brr.Window.location Brr.G.window in let query = Brr.Uri.query uri in let params = Brr.Uri.Params.of_jstr query in Brr.Uri.Params.find (Jstr.v "page") params (** Read the state from the local storage, or load the content from the given element *) let load' : PM.t -> PM.Model.schema Js.t -> Jv.t -> Jstr.t -> PM.State.editor_state Js.t = fun pm schema content key -> let opt_data = Brr_io.Storage.get_item storage key in match opt_data with | None -> create_new_state pm schema content | Some contents -> (* Try to load from the storage *) match Json.decode contents with | Error _ -> create_new_state pm schema content | Ok json -> let obj = PM.State.configuration_prop () in obj##.plugins := Plugins.default pm schema; obj##.schema := Js.some schema; PM.State.fromJSON pm obj json let load : PM.t -> PM.Model.schema Js.t -> Jv.t -> PM.State.editor_state Js.t = fun pm schema content -> match page_id () with | None -> load' pm schema content storage_key | Some value -> let key = Jstr.concat ~sep:(Jstr.v "_") [storage_key ; value] in load' pm schema content key (** Save the view *) let save' : PM.View.editor_view Js.t -> Jstr.t -> unit = fun view key -> let contents = view##.state##toJSON () in let storage = Brr_io.Storage.local G.window in Brr_io.Storage.set_item storage key (Json.encode @@ contents) |> Console.log_if_error ~use:() let save : PM.View.editor_view Js.t -> unit = fun view -> match page_id () with | None -> save' view storage_key | Some value -> let key = Jstr.concat ~sep:(Jstr.v "_") [storage_key ; value] in save' view key