diff --git a/src/types.jl b/src/types.jl index 80bad88..dfa87dd 100644 --- a/src/types.jl +++ b/src/types.jl @@ -130,6 +130,42 @@ Base.convert(::Type{Matrix{ARGB32}}, cached::AbstractCachedDocument) = rasterize Base.size(cached::AbstractCachedDocument) = cached.dims +#= +### Convert arbitrary Julia objects to Documents + +TODOs: +- Allow the conversion to use the constructor, if there is a method. +=# + + +function Base.convert(T::Type{<: AbstractDocument}, x) + if !showable(mimetype(T), x) + error("Object of type $(typeof(x)) is not showable as mime type $(mimetype(T)).") + end + return T(sprint(show, mimetype(T), x)) +end +# This resolves an ambiguity otherwise. +Base.convert(::Type{T}, x::T) where T <: AbstractDocument = x + +function Base.convert(::Type{AbstractDocument}, x) + for DocType in [TEXDocument, TypstDocument, SVGDocument, PDFDocument] + if showable(mimetype(DocType), x) + return convert(DocType, x) + end + end + error("MakieTeX: Object of type $(typeof(x)) is not showable as an AbstractDocument.") +end + + +function Base.convert(::Type{AbstractCachedDocument}, x) + for DocType in [CachedTEX, CachedTypst, CachedSVG, CachedPDF] + if showable(mimetype(DocType), x) + return convert(DocType, x) + end + end + error("MakieTeX: Object of type $(typeof(x)) is not showable as an AbstractCachedDocument.") +end + #= ### Makie.jl function definitions @@ -277,6 +313,18 @@ Available keyword arguments are: """ texdoc(contents; kwargs...) = TEXDocument(contents, true; kwargs...) +function Base.convert(::Type{TEXDocument}, x) + if !showable(mimetype(TEXDocument), x) + error("Object of type $(typeof(x)) is not showable as mime type $(mimetype(TEXDocument)).") + end + texstring = sprint(show, mimetype(TEXDocument), x) + if contains(texstring, "\\begin{document}") + return TEXDocument(texstring, false) # assume this to be a fixed document + else + return TEXDocument(texstring, true) # assume this to require a preamble + end +end + struct TypstDocument <: AbstractDocument contents::String page::Int diff --git a/test/integrations.jl b/test/integrations.jl new file mode 100644 index 0000000..f22786b --- /dev/null +++ b/test/integrations.jl @@ -0,0 +1,23 @@ +using DataFrames + +using SummaryTables +data = DataFrame( + sex = ["m", "m", "m", "m", "f", "f", "f", "f", "f", "f"], + age = [27, 45, 34, 85, 55, 44, 24, 29, 37, 76], + blood_type = ["A", "0", "B", "B", "B", "A", "0", "A", "A", "B"], + smoker = [true, false, false, false, true, true, true, false, false, false], +) + +tab = table_one( + data, + [:age => "Age (years)", :blood_type => "Blood type", :smoker => "Smoker"], + groupby = :sex => "Sex", + show_n = true +) + +tex = convert(TEXDocument, tab) +typst = convert(TypstDocument, tab) + + +@test_broken teximg(tex) +@test_nowarn teximg(typst) \ No newline at end of file