aboutsummaryrefslogtreecommitdiff
path: root/lib/elements
diff options
context:
space:
mode:
authorSébastien Dailly <sebastien@dailly.me>2022-02-07 15:22:05 +0100
committerSébastien Dailly <sebastien@dailly.me>2022-02-07 16:22:43 +0100
commit3ce21441d5116b69eb511f5dba70765ec6eccbd2 (patch)
treeb5a4f44d577638437f2256db9df4e1ad8e34bd58 /lib/elements
parent92fe01fc6e93faf3ef77b45eb77632bc2806f202 (diff)
Added a file loader element
Diffstat (limited to 'lib/elements')
-rwxr-xr-xlib/elements/input.ml47
1 files changed, 47 insertions, 0 deletions
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 )