Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 43 additions & 7 deletions lib/statifier_examples/screen_editor.ex
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,18 @@ defmodule StatifierExamples.ScreenEditor do
group and each named for the document's own type under `myapp.screens.`:
the screen itself (`key`, `title`, and an `elements` slot), and the
element types `heading`, `text`, `text_question`, `choice_question`,
`boolean_question`, `secret_question`, `button` and `variant`. Their
fields are spelled as the document spells them. `registrations/0` lists
them.
`boolean_question`, `secret_question`, `button`, `variant`, `image`,
`divider` and `link`. Their fields are spelled as the document spells
them, but for the few the walk turns back into the document's shape
(`StatifierExamples.ScreenEditor.Walk`). `registrations/0` lists them.

A text question's date and time formats are choices of its `format`
field, and a slider is its `style` hint with a numeric format, `min`,
`max` and `step`, because the document spells both on a text question
rather than as types of their own. An option's description and a
question's checks are rows on the question
(`StatifierExamples.ScreenEditor.ChoiceQuestion`,
`StatifierExamples.ScreenEditor.Element.checks_field/0`).

The `core.*` vocabulary is registered underneath, because a document's
root is a block and `core.sequence` is the plain ordered one: its `body`
Expand Down Expand Up @@ -51,7 +60,10 @@ defmodule StatifierExamples.ScreenEditor do
BooleanQuestion,
Button,
ChoiceQuestion,
Divider,
Heading,
Image,
Link,
Screen,
SecretQuestion,
Text,
Expand All @@ -70,7 +82,10 @@ defmodule StatifierExamples.ScreenEditor do
{"myapp.screens.boolean_question", BooleanQuestion},
{"myapp.screens.secret_question", SecretQuestion},
{"myapp.screens.button", Button},
{"myapp.screens.variant", Variant}
{"myapp.screens.variant", Variant},
{"myapp.screens.image", Image},
{"myapp.screens.divider", Divider},
{"myapp.screens.link", Link}
]

@doc """
Expand Down Expand Up @@ -103,8 +118,10 @@ defmodule StatifierExamples.ScreenEditor do
end

@doc """
The values the screen editor offers for a choice question's `style`: an
open list, so a renderer's own style name can still be typed.
The values the screen editor offers for the hints a renderer reads - a
choice question's and a text question's `style`, an image's `size` and
`fit`, and a link's `style` - each as an open list, so a renderer's own
name can still be typed.
"""
@spec field_candidates() :: %{optional({String.t(), String.t()}) => term()}
def field_candidates do
Expand All @@ -116,7 +133,26 @@ defmodule StatifierExamples.ScreenEditor do
{"dropdown", "Dropdown"},
{"checkboxes", "Checkboxes"},
{"list", "List"}
]}
]},
{"myapp.screens.text_question", "style"} =>
{:open,
[
{"multiline", "More than one line"},
{"slider", "Slider, for a number"},
{"stepper", "Stepper, for a number"}
]},
{"myapp.screens.image", "size"} =>
{:open,
[
{"icon", "Icon"},
{"avatar", "Avatar"},
{"small", "Small"},
{"medium", "Medium"},
{"large", "Large"},
{"banner", "Banner"}
]},
{"myapp.screens.image", "fit"} => {:open, [{"contain", "Contain"}, {"cover", "Cover"}]},
{"myapp.screens.link", "style"} => {:open, [{"inline", "Inline"}, {"button", "Button"}]}
}
end
end
8 changes: 6 additions & 2 deletions lib/statifier_examples/screen_editor/boolean_question.ex
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ defmodule StatifierExamples.ScreenEditor.BooleanQuestion do
`myapp.screens.boolean_question`: a lone checkbox or toggle submitting
true or false - "I agree to the library's lending rules". `required`
asks for true, and `help` is a line of guidance shown beside it.
`checks` are the question's own conditions, one row each
(`StatifierExamples.ScreenEditor.Element.checks_field/0`).
"""

use StatifierBlocks.BlockType
Expand All @@ -15,15 +17,17 @@ defmodule StatifierExamples.ScreenEditor.BooleanQuestion do
[
Element.field("label", :string, "Label", true, ""),
Element.field("help", :string, "Help", false, ""),
Element.field("required", :boolean, "Required", false, false)
Element.field("required", :boolean, "Required", false, false),
Element.checks_field()
]
end

@impl StatifierBlocks.BlockType
def validate_config(config) do
Element.validate(
config,
Element.present(config, "label", "a question needs the label a patron is asked")
Element.present(config, "label", "a question needs the label a patron is asked") ++
Element.check_findings(config)
)
end

Expand Down
80 changes: 78 additions & 2 deletions lib/statifier_examples/screen_editor/choice_question.ex
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,19 @@ defmodule StatifierExamples.ScreenEditor.ChoiceQuestion do
key-shaped and so never holds an `=`, while a label may hold anything.
Each value is checked here as the document will check it: key-shaped,
and unique within the question.

## `option_descriptions`, one row per described option

An option may carry a `description`, a line a renderer shows under its
label - what a family card covers, say. A row of `answer_options` already
splits at its first `=` and its label may hold anything, so a description
has rows of its own, each written `value=Description` - `family=For two
adults and their children` - naming an option of the question once. The
walk puts each description on its option and leaves the field itself out
of the document, which has no such field.

`checks` are the question's own conditions, one row each
(`StatifierExamples.ScreenEditor.Element.checks_field/0`).
"""

use StatifierBlocks.BlockType
Expand All @@ -38,12 +51,20 @@ defmodule StatifierExamples.ScreenEditor.ChoiceQuestion do
Element.field("label", :string, "Label", true, ""),
Element.field("select", {:select, @selects}, "Select", true, "one"),
Element.field("answer_options", {:list, :string}, "Answer options", true, []),
Element.field(
"option_descriptions",
{:list, :string},
"Option descriptions",
false,
[]
),
Element.field("style", :string, "Style", false, ""),
Element.field("help", :string, "Help", false, ""),
Element.field("default", :string, "Default", false, ""),
Element.field("required", :boolean, "Required", false, false),
Element.field("min_selections", :integer, "Min selections", false, nil),
Element.field("max_selections", :integer, "Max selections", false, nil)
Element.field("max_selections", :integer, "Max selections", false, nil),
Element.checks_field()
]
end

Expand All @@ -54,7 +75,9 @@ defmodule StatifierExamples.ScreenEditor.ChoiceQuestion do
Element.validate(
config,
Element.present(config, "label", "a question needs the label a patron is asked") ++
option_findings(options) ++ selection_findings(config, options)
option_findings(options) ++
description_findings(Map.get(config, "option_descriptions"), options) ++
selection_findings(config, options) ++ Element.check_findings(config)
)
end

Expand Down Expand Up @@ -97,6 +120,37 @@ defmodule StatifierExamples.ScreenEditor.ChoiceQuestion do
end
end

@doc """
The descriptions `rows` give the options valued `values`, by value, or
`:error` when a row is not `value=Description`, names no option of
`values`, or names one a second time.

iex> StatifierExamples.ScreenEditor.ChoiceQuestion.option_descriptions(
...> ["family=For two adults"],
...> ["standard", "family"]
...> )
{:ok, %{"family" => "For two adults"}}

iex> StatifierExamples.ScreenEditor.ChoiceQuestion.option_descriptions(["student=Ages 12 to 18"], ["standard"])
:error
"""
@spec option_descriptions([String.t()], [String.t()]) ::
{:ok, %{String.t() => String.t()}} | :error
def option_descriptions(rows, values) when is_list(rows) and is_list(values) do
Enum.reduce_while(rows, {:ok, %{}}, fn row, {:ok, acc} ->
case row_pair(row) do
{:ok, pair} -> describe(pair, values, acc)
:error -> {:halt, :error}
end
end)
end

defp describe({value, description}, values, acc) do
if value in values and not is_map_key(acc, value),
do: {:cont, {:ok, Map.put(acc, value, description)}},
else: {:halt, :error}
end

defp row_pair(row) when is_binary(row) do
case String.split(row, "=", parts: 2) do
[value, label] when label != "" -> {:ok, {value, label}}
Expand All @@ -116,6 +170,28 @@ defmodule StatifierExamples.ScreenEditor.ChoiceQuestion do
defp option_findings(_none),
do: [{"answer_options", "a choice question needs at least one option"}]

defp description_findings(blank, _options) when blank in [nil, []], do: []

defp description_findings(rows, options) when is_list(rows) do
values =
case answer_options(List.wrap(options)) do
{:ok, pairs} -> Enum.map(pairs, &elem(&1, 0))
:error -> []
end

case option_descriptions(rows, values) do
{:ok, _descriptions} -> []
:error -> [description_finding()]
end
end

defp description_findings(_other, _options), do: [description_finding()]

defp description_finding do
{"option_descriptions",
"each description is written value=Description, naming an option of the question once"}
end

defp value_findings(values) do
cond do
not Enum.all?(values, &Element.key?/1) ->
Expand Down
33 changes: 33 additions & 0 deletions lib/statifier_examples/screen_editor/divider.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
defmodule StatifierExamples.ScreenEditor.Divider do
@moduledoc """
`myapp.screens.divider`: a rule between the elements before it and the
elements after it - between a patron's contact details and the PIN they
choose, say. It carries no field of its own, only the two every element
carries (`StatifierExamples.ScreenEditor.Element`).
"""

use StatifierBlocks.BlockType

alias StatifierExamples.ScreenEditor.Element

@impl StatifierBlocks.BlockType
def config_schema(_config), do: Element.common_fields()

@impl StatifierBlocks.BlockType
def validate_config(config), do: Element.validate(config, [])

@impl StatifierBlocks.BlockType
def palette_entry do
%{
label: "Divider",
group: "Screens",
description: "A rule between one part of a screen and the next.",
icon: "minus",
keywords: ["divider", "rule", "separator", "section"],
order: 11
}
end

@impl StatifierBlocks.BlockType
def emit(_block, context), do: Element.emit_leaf(context)
end
86 changes: 86 additions & 0 deletions lib/statifier_examples/screen_editor/element.ex
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ defmodule StatifierExamples.ScreenEditor.Element do
alias StatifierBlocks.Core.Emit

@key_shape ~r/\A[a-z][a-z0-9_]*\z/
@check_code ~r/\Acheck(\.[a-z][a-z0-9_]*)+\z/

@doc """
The `key` and `condition` field declarations, in that order, ahead of a
Expand Down Expand Up @@ -96,6 +97,91 @@ defmodule StatifierExamples.ScreenEditor.Element do
end
end

@doc """
The `checks` field every question type declares after its own fields:
conditions a patron's response has to satisfy, one row per check.

The document holds `checks` as a list of objects - `condition`, `code`
and `message` - and the editor's field types have no list of objects. So
each row is written `code: condition => message`, split at its first `:`
and then at the first ` => ` after it: `check.birth_date_in_future:
trim(responses.birth_date)::date <= context.today::date => A date of
birth cannot be in the future.` That is unambiguous for the code, which
is `check.` and key-shaped segments and so never holds a `:`, and for a
condition outside its string literals, where ` => ` is no operator; a
condition whose string literal holds ` => ` cannot be written this way.
"""
@spec checks_field() :: BlockType.field_decl()
def checks_field, do: field("checks", {:list, :string}, "Checks", false, [])

@doc """
The check objects `rows` hold, in order, or `:error` when a row is not
`code: condition => message` with a code in the `check.` shape.

iex> StatifierExamples.ScreenEditor.Element.checks(["check.adult: responses.age >= 18 => You must be 18."])
{:ok, [%{"code" => "check.adult", "condition" => "responses.age >= 18", "message" => "You must be 18."}]}

iex> StatifierExamples.ScreenEditor.Element.checks(["adult: responses.age >= 18 => You must be 18."])
:error
"""
@spec checks([String.t()]) :: {:ok, [%{String.t() => String.t()}]} | :error
def checks(rows) when is_list(rows) do
rows
|> Enum.reduce_while({:ok, []}, fn row, {:ok, acc} ->
case check_row(row) do
{:ok, check} -> {:cont, {:ok, [check | acc]}}
:error -> {:halt, :error}
end
end)
|> case do
{:ok, checks} -> {:ok, Enum.reverse(checks)}
:error -> :error
end
end

@doc """
The findings on a question's `checks` rows: each row readable, and each
code used once on the question, as the document will hold them.
"""
@spec check_findings(Block.config()) :: [BlockType.finding()]
def check_findings(config) do
case Map.get(config, "checks") do
blank when blank in [nil, []] ->
[]

rows when is_list(rows) ->
case checks(rows) do
{:ok, checks} -> unique_code_findings(Enum.map(checks, & &1["code"]))
:error -> [{"checks", "each check is written check.<name>: condition => message"}]
end

_other ->
[{"checks", "each check is written check.<name>: condition => message"}]
end
end

defp unique_code_findings(codes) do
if Enum.uniq(codes) == codes,
do: [],
else: [{"checks", "each check's code is used once on the question"}]
end

defp check_row(row) when is_binary(row) do
with [code, rest] <- String.split(row, ":", parts: 2),
code = String.trim(code),
true <- Regex.match?(@check_code, code),
[condition, message] <- String.split(rest, " => ", parts: 2),
condition = String.trim(condition),
message = String.trim(message),
true <- condition != "" and message != "" do
{:ok, %{"condition" => condition, "code" => code, "message" => message}}
else
_not_a_check -> :error
end
end

defp check_row(_row), do: :error

@doc "The inert state a leaf element compiles to: entered, and done at once."
@spec emit_leaf(Context.t()) :: {:ok, StatifierBlocks.Emission.t()}
def emit_leaf(context) do
Expand Down
Loading
Loading