From e20974010f6a6e928ab594167ea677d31a2a6463 Mon Sep 17 00:00:00 2001 From: Sébastien Dailly Date: Tue, 7 Dec 2021 16:35:35 +0100 Subject: Auto url --- editor/editor.css | 2 +- editor/plugins/plugins.ml | 38 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/editor/editor.css b/editor/editor.css index d3700c2..c156768 100755 --- a/editor/editor.css +++ b/editor/editor.css @@ -326,7 +326,7 @@ li.ProseMirror-selectednode:after { .ProseMirror p { margin-bottom: 1em } .editor [contenteditable="true"] em::before, .editor [contenteditable="true"] em::after { - content: "//" + content: "__" } .editor [contenteditable="true"] blockquote p::before { diff --git a/editor/plugins/plugins.ml b/editor/plugins/plugins.ml index 51b761c..6645628 100755 --- a/editor/plugins/plugins.ml +++ b/editor/plugins/plugins.ml @@ -73,6 +73,10 @@ let handle_backspace pm state dispatch = Js._false ) +(** Activate the given mark at position. + + [toggle_mark regex pm] will create a rule with the given regex, and + then apply the mark *) let toggle_mark : Js.regExp Js.t -> PM.t -> string -> PM.InputRule.input_rule Js.t = fun regExp pm mark_type_name -> @@ -110,11 +114,41 @@ let toggle_mark : Js.some tr ) ) +(** Transform the selection into URL *) +let into_url : Js.regExp Js.t -> PM.t -> PM.InputRule.input_rule Js.t = + fun regExp pm -> + PM.InputRule.create + pm + regExp + ~fn: + ( Js.wrap_callback + @@ fun (state : PM.State.editor_state Js.t) content ~from ~to_ -> + let matched_text = Js.array_get content 1 |> Js.Optdef.to_option + and mark = PM.O.get state##.schema##.marks "link" in + + match (matched_text, mark) with + | Some url, Some mark_type -> + let attrs = PM.O.init [| ("href", url) |] in + (* Create the mark containing the URL *) + let m = state##.schema##mark_fromType mark_type (Js.some attrs) in + (* Apply the mark as a transaction *) + let tr = + state + ##. tr + ## (addMark ~from ~to_ m) + ## (insertText (Jstr.v " ") ~from:Js.null ~to_:Js.null) + in + Js.some tr + | _ -> + Js.null ) + + let input_rule pm = let bold = toggle_mark (new%js Js.regExp (Js.string "\\*\\*$")) pm "strong" - and em = toggle_mark (new%js Js.regExp (Js.string "//$")) pm "em" in + and em = toggle_mark (new%js Js.regExp (Js.string "__$")) pm "em" + and url = into_url (new%js Js.regExp (Js.string "(\\w+://\\S+)\\s$")) pm in - PM.InputRule.to_plugin pm (Js.array [| bold; em |]) + PM.InputRule.to_plugin pm (Js.array [| bold; url; em |]) let default pm schema = -- cgit v1.2.3