Skip to content

Commit

Permalink
Download button: support multimedia (#275)
Browse files Browse the repository at this point in the history
Co-authored-by: Fons van der Plas <[email protected]>
  • Loading branch information
lukavdplas and fonsp authored Nov 4, 2023
1 parent 494eb12 commit c34b793
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
26 changes: 21 additions & 5 deletions src/Resource.jl
Original file line number Diff line number Diff line change
Expand Up @@ -138,25 +138,41 @@ struct DownloadButton
end
DownloadButton(data) = DownloadButton(data, "result")


function Base.show(io::IO, m::MIME"text/html", db::DownloadButton)
write(io, "<a href=\"data:")
write(io, string(mime_fromfilename(db.filename, default="")))
mime = mime_fromfilename(db.filename)
data = if db.data isa String || db.data isa AbstractVector{UInt8} || isnothing(mime)
db.data
else
repr(mime, db.data)
end

write(io, "<a href=\"data:")
write(io, string(!isnothing(mime) ? mime : ""))
write(io, ";base64,")
write(io, Base64.base64encode(db.data))
write(io, Base64.base64encode(data))
write(io, "\" download=\"")
write(io, Markdown.htmlesc(db.filename))
write(io, "\" style=\"text-decoration: none; font-weight: normal; font-size: .75em; font-family: sans-serif;\"><button>Download...</button> ")
write(io, db.filename)
write(io, "</a>")
end

function downloadbutton_data(object::Any, mime::Union{MIME, Nothing})::String
data = if object isa String || object isa AbstractVector{UInt8} || isnothing(mime)
object
else
repr(mime, object)
end
Base64.base64encode(data)
end


###
# MIMES
###

"Attempt to find the MIME pair corresponding to the extension of a filename. Defaults to `text/plain`."
function mime_fromfilename(filename; default=nothing, filename_maxlength=2000)
function mime_fromfilename(filename; default::T=nothing, filename_maxlength=2000)::Union{MIME, T} where T
if length(filename) > filename_maxlength
default
else
Expand Down
11 changes: 11 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,17 @@ end

end

@testset "DownloadButton" begin
data = "test"
db1 = DownloadButton(data, "test.txt")
db2 = DownloadButton(html"<b>test</b>", "test.html")

hr(x) = repr(MIME"text/html"(), x)

hr(db1)
hr(db2)
end

function default(x)
new = AbstractPlutoDingetjes.Bonds.initial_value(x)
if Core.applicable(Base.get, x)
Expand Down

0 comments on commit c34b793

Please sign in to comment.