From 3ce21441d5116b69eb511f5dba70765ec6eccbd2 Mon Sep 17 00:00:00 2001 From: Sébastien Dailly Date: Mon, 7 Feb 2022 15:22:05 +0100 Subject: Added a file loader element --- lib/elements/input.ml | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) (limited to 'lib/elements') diff --git a/lib/elements/input.ml b/lib/elements/input.ml index 6ae9aa8..8a082d8 100755 --- a/lib/elements/input.ml +++ b/lib/elements/input.ml @@ -21,3 +21,50 @@ let slider |> S.hold init_value in slider, event + +type file = + { file : File.t + ; content : Jstr.t + } + +(** Read the content from the file *) +let file_loader + : file Note.E.send -> File.t -> unit + = fun event file -> + let blob = File.as_blob file in + Fut.await + (Blob.text blob) + (Result.iter + (fun content -> + event ({file; content}) )) + +(** Create an imput which load a file. + + [file_loader (Jstr.v ".json"] will create an input which only accept json + files, and an event which gives access to the file. + +*) +let file_loader + : Jstr.t -> file Note.event * Brr.El.t + = fun selector -> + + let add_file_event, add_file_sender = Note.E.create () in + + let i = El.input () + ~at:[ At.type' (Jstr.v "file") + ; (At.v (Jstr.v "accept")) selector + ] in + + (* The event return a list of files. + + We are only interested by a single on, and keep only the first from the + list. *) + let on_change files = + file_loader add_file_sender (List.hd files) in + + Ev.listen + Ev.change + (fun _e -> on_change (El.Input.files i)) (El.as_target i); + + ( add_file_event + , i ) -- cgit v1.2.3