module Surveys
using Dates
using Genie.Renderers.Html
import Base: show, isvalid, isempty
export Survey, SurveyPart, Question,
Answer, Response, update!, clear!, nonempty,
SurveyID, ResponseID,
Checkbox, TextInput, DateInput, NumberInput, IntegerInput,
TextArea, Dropdown, RadioSelect, MultiSelect, RangeSelect
# ---------------------
# Main Types
# ---------------------
# Input Field
abstract type FormField{T} end
# Question
struct Question{F <: FormField}
id::Symbol
prompt::AbstractString
field::F
validators::Vector{Function}
postprocessors::Vector{Function}
function Question(id::Symbol, prompt::AbstractString,
field::F, validators::Vector{Function},
postprocessors::Vector{Function}) where {F<:FormField}
if id in (:uid, :page)
@warn "Question uses a reserved id $id, this is likely to cause issues"
end
postprocessors = map(p -> if p == last; lastsoftfail else p end, postprocessors)
new{F}(id, prompt, field, validators, postprocessors)
end
end
function nonempty(value::AbstractString)
if ismissing(value) || (isa(value, AbstractString) && isempty(strip(value)))
"Must be answered"
end
end
function nonempty(values::Vector{<:AbstractString})
if length(values) == 0 || all(isempty, strip.(values))
"Must be answered"
end
end
nonempty(::Bool) = nothing
lastsoftfail(v::Vector) = if length(v) > 0
last(v)
else
""
end
defaultpostprocessors(::FormField) = Function[last, strip]
function Question(id::Symbol, prompt::AbstractString, field::FormField;
validators::Union{Function, Vector{<:Function}}=Function[],
postprocessors::Union{Function, Vector{<:Function}}=defaultpostprocessors(field),
mandatory::Bool=true)
fullvalidators = if mandatory
vcat(nonempty, validators)
else
vcat(validators)
end
Question(id, prompt, field, fullvalidators, postprocessors)
end
function prompttoid(prompt::String)
prompt |>
p -> replace(p, r"[^A-Za-z0-9\s]" => "") |>
p -> replace(p, r"\s+" => "_") |>
lowercase |>
Symbol
end
Question(prompt::AbstractString, field::FormField; kargs...) =
Question(prompttoid(prompttoid), prompt, field; kargs...)
# Field-based question constructors
function (F::Type{<:FormField})(id::Symbol, prompt::AbstractString, args...;
validators::Union{Function, Vector{<:Function}}=Function[],
mandatory::Bool=true,
kwargs...)
Question(id, prompt, F(args...; kwargs...); validators, mandatory)
end
function (F::Type{<:FormField})(prompt::AbstractString, args...; kwargs...)
F(prompttoid(prompt), prompt, args...; kwargs...)
end
# Survey Part
struct SurveyPart
label::Union{AbstractString, Nothing}
questions::Vector{Question}
end
Base.getindex(p::SurveyPart, id::Symbol) = findfirst(q -> q.id == id, p.questions)
Base.getindex(p::SurveyPart, index::Integer) = p.questions[index]
Base.length(p::SurveyPart) = length(p.questions)
SurveyPart(label::Union{AbstractString, Nothing}, questions::Question...) =
SurveyPart(label, questions |> collect)
SurveyPart(questions::Question...) = SurveyPart(nothing, questions |> collect)
# Survey
const SurveyID = UInt32
struct Survey
id::SurveyID
name::AbstractString
description::Union{AbstractString, Nothing}
parts::Vector{Pair{Union{AbstractString, Nothing}, Vector{Symbol}}}
questions::Dict{Symbol, Question}
end
Base.getindex(s::Survey, id::Symbol) = s.questions[id]
Base.getindex(s::Survey, part::Integer) =
SurveyPart(s.parts[part].first,
getindex.(Ref(s.questions), s.parts[part].second))
Base.length(s::Survey) = length(s.parts)
function Survey(name::AbstractString,
description::Union{AbstractString, Nothing},
parts::Vector{<:Pair{<:Union{<:AbstractString, Nothing}, <:Vector{Symbol}}},
questions::Dict{Symbol, Question})
# Create an id that only depends on:
# 1. Question IDs
# 2. Question Prompts
# 3. Question field types
# Hopefully memhashing a Tuple of Symbols and Strings is somewhat stable,
# I checked this on Julia 1.3 and 1.6 and it looked alright.
id = xor(map(values(questions)) do q
hash((q.id, q.prompt, string(typeof(q.field))))
end...) |>
h -> xor(reinterpret(SurveyID, [h])...)
Survey(id, name, description, parts, questions)
end
Survey(name::AbstractString,
description::Union{AbstractString, Nothing},
parts::SurveyPart...) =
Survey(name, description,
map(p -> p.label => getfield.(p.questions, :id), parts) |> collect,
Dict(q.id => q for q in
Iterators.flatten(getfield.(parts, :questions))))
Survey(name::AbstractString, parts::SurveyPart...) =
Survey(name, nothing, parts...)
Survey(name::AbstractString,
description::Union{AbstractString, Nothing},
questions::Question...) =
Survey(name, description,
[nothing => getfield.(questions, :id) |> collect],
Dict(q.id => q for q in questions))
Survey(name::AbstractString, questions::Question...) =
Survey(name, nothing, questions...)
# Answer to a Question
struct Answer{T}
value::Union{T, Missing}
error::Union{AbstractString, Nothing}
end
Answer{T}() where {T <: Any} = Answer{T}(missing, nothing)
isempty(a::Answer) = ismissing(a.value)
isempty(a::Answer{<:AbstractString}) = ismissing(a.value) || isempty(a.value)
# Survey Response
const ResponseID = UInt32
mutable struct Response
survey::SurveyID
id::ResponseID
page::Integer
answers::Dict{Symbol, Answer}
started::DateTime
completed::Union{DateTime, Nothing}
end
Base.getindex(r::Response, id::Symbol) = r.answers[id]
# ---------------------
# Handling responses
# ---------------------
# Response templates
Answer(::Question{<:FormField{T}}) where {T} = Answer{T}(missing, nothing)
Response(s::Survey, id::ResponseID=rand(ResponseID)) =
Response(s.id, id, 1,
Dict(q.id => Answer(q) for q in
Iterators.flatten([s[i].questions for i in 1:length(s)])),
now(), nothing)
function Response(s::Survey, oldids::Vector{ResponseID})
newid = rand(ResponseID)
while newid in oldids
newid = rand(ResponseID)
end
Response(s, newid)
end
interpret(::FormField{<:AbstractString}, value::AbstractString) = value
interpret(::FormField{Number}, value::AbstractString) =
something(tryparse(Int64, value), parse(Float64, value))
interpret(::FormField{T}, value::AbstractString) where {T} = parse(T, value)
# Response interpretation
function Answer(q::Question{<:FormField{T}}, value::Union{String, Vector{String}}) where {T}
try
processedvalue = interpret(q.field, ∘(identity, reverse(q.postprocessors)...)(value))
error = nothing
for validator in q.validators
error = validator(processedvalue)
isnothing(error) || break
end
Answer{T}(processedvalue, error)
catch e
@warn "Answer construction failure" exception=(e, catch_backtrace())
Answer{T}(missing, first(split(sprint(showerror, e), '\n')))
end
end
function Answer(q::Question{<:FormField{T}}, ::Missing) where {T}
if nonempty in q.validators
Answer{T}(missing, "Must be answered")
else
Answer{T}(missing, nothing)
end
end
# Response updating
function update!(r::Response, s::Survey, datum::Pair{Symbol, <:Any})
id, value = datum
if haskey(r.answers, id) && haskey(s.questions, id)
r.answers[id] = Answer(s.questions[id], value)
else
@warn "$id not in response"
end
end
function update!(r::Response, s::Survey, data::Dict{Symbol, <:Any})
foreach(data) do datum
update!(r, s, datum)
end
end
clear!(r::Response, ids::Vector{Symbol}) =
foreach(ids) do id
r.answers[id] = Answer{typeof(r.answers[id])}()
end
clear!(r::Response, q::Question) = clear!(r, [q.id])
clear!(r::Response, p::SurveyPart) = clear!(r, keys(p.questions))
clear!(r::Response, s::Survey) = clear!(r, keys(s.questions))
clear!(r::Response) = clear!(r, keys(r.answers))
# Response validity
isvalid(a::Answer) = isnothing(a.error)
isvalid(a::Answer, q::Question) =
isvalid(a) && !(isempty(a) && nonempty in q.validators)
isvalid(r::Response, q::Question) = isvalid(r.answers[q.id], q)
isvalid(r::Response, p::SurveyPart) = all(isvalid.(Ref(r), p.questions))
isvalid(r::Response, s::Survey) =
all(isvalid.(Ref(r), Iterators.flatten([s[i].questions for i in 1:length(s)])))
# ---------------------
# General htmlrenderer
# ---------------------
htmlcontent(::FormField, value) = ""
htmlelement(::FormField) = "?"
htmlattrs(::FormField, value) = []
htmlvoidelem(::FormField) = false
htmlpostprocess(::FormField, ::Symbol) = identity
elem(e::AbstractString, content::AbstractString="", attrs::Pair{Symbol,<:Any}...) =
Html.normal_element(content, e, [], attrs...)
elem(e::AbstractString, attrs::Pair{Symbol,<:Any}...) = elem(e, "", attrs...)
velem(e::AbstractString, attrs::Pair{Symbol,<:Any}...) =
Html.void_element(e, [], Vector{Pair{Symbol,Any}}(collect(attrs)))
function htmlrender(field::FormField, value::Any, id, mandatory, invalid)
element = htmlelement(field)
attrs = vcat(htmlattrs(field, value),
[:id => string("qn-", id),
:name => id,
Symbol("aria-invalid") => invalid,
:required => mandatory && !isa(field, Checkbox)])
if htmlvoidelem(field)
velem(element, attrs...)
else
content = htmlcontent(field, value)
elem(element, if ismissing(content) "" else string(content) end,
attrs...)
end |> htmlpostprocess(field, id)
end
# ---------------------
# Form fields & html rendering
# ---------------------
#
struct FormInput{T} <: FormField{T}
FormInput{T}() where {T} =
if T <: Union{Bool, String, Integer, Number, Date}
new()
else
TypeError(:FormInput, Union{Bool, String, Integer, Number, Date}, T)
end
end
htmlelement(::FormInput) = "input"
htmlvoidelem(::FormInput) = true
htmlattrs(::FormInput, value) =
[:value => if ismissing(value) false else string(value) end]
#
interpret(::FormInput{Bool}, value::AbstractString) = value == "yes"
htmlattrs(::FormInput{Bool}, value::Union{Bool, Missing}) =
[:type => "checkbox", :value => "yes", :checked => !ismissing(value) && value === true]
htmlpostprocess(::FormInput{Bool}, id::Symbol) =
s -> string(input(type="hidden", name=id, value="no"), s)
#
function htmlattrs(::FormInput{T}, value) where {T <: Union{Date, Number, Integer, String}}
type = Dict(Date => "date",
Number => "number",
Integer => "number",
String => "text")[T]
[:type => type,
:value => if ismissing(value) false else string(value) end]
end
const Checkbox = FormInput{Bool}
const TextInput = FormInput{String}
const DateInput = FormInput{Date}
const NumberInput = FormInput{Number}
const IntegerInput = FormInput{Integer}
#