Writing pages
*************

The examples on this page come from the "demos/features/pages" demo,
which you can run with "psynet debug local" from the demo directory:

   def get_timeline():
       return Timeline(
           InfoPage(
               """
               The InfoPage displays text to the participant without collecting any response.
               """,
               time_estimate=5,
           ),
           ModularPage(
               label="push_button_page",
               prompt="""
               More complex pages are typically implemented as ModularPages,
               which allow you to combine arbitrary 'Prompts' with arbitrary 'Controls'.
               This example combines the default text prompt with a push-button control.

               I hope that was clear?
               """,
               control=PushButtonControl(
                   choices=["Yes, it was clear", "Sorry, it was not clear"],
               ),
               time_estimate=5,
           ),
           ModularPage(
               label="image_prompt",
               prompt=ImagePrompt(
                   "static/images/lake_mirror_reflection_yosemite.jpg",
                   text="""
                   This is an example of an image prompt.
                   Here we've placed the image in the static directory.
                   """,
                   width="767px",
                   height="512px",
                   margin_bottom="25px",
               ),
               time_estimate=5,
           ),
           ModularPage(
               label="audio_prompt",
               prompt=AudioPrompt(
                   "static/audio/clarinet.mp3",
                   text="""
                   This is an example of an audio prompt, again using the static directory.
                   We've combined it with a text control, which allows the participant to type in free text.
                   """,
               ),
               control=TextControl(),
               time_estimate=5,
           ),
           ModularPage(
               label="audio_prompt_and_record",
               prompt=AudioPrompt(
                   "static/audio/clarinet.mp3",
                   text="""
                   Here's a more complex example, where we play some audio and then record from the
                   participant's microphone.
                   """,
                   play_window=[0, 3.0],
               ),
               control=AudioRecordControl(
                   duration=3.0,
                   # A WAV file, like the browser's own recordings.
                   bot_response_media="static/audio/bot_recording.wav",
               ),
               time_estimate=10.0,
               events={
                   "recordStart": Event(is_triggered_by="promptEnd", delay=0.5),
               },
               progress_display=ProgressDisplay(
                   stages=[
                       ProgressStage([0.0, 3.0], "Listen...", "blue"),
                       ProgressStage([3.0, 3.5], "Get ready...", "orange"),
                       ProgressStage([3.5, 6.5], "Recording...", "red"),
                       ProgressStage(
                           [6.5, 7.0], "Finished recording.", "blue", persistent=True
                       ),
                   ],
               ),
           ),
       )


Kinds of page
=============

An "InfoPage" shows text. Wrap HTML in "markupsafe.Markup" to format
it:

   InfoPage(Markup("Welcome to the <strong>experiment</strong>!"), time_estimate=5)

Pages and prompts also accept dominate tags, which build longer
structured content without writing HTML strings:

   from dominate import tags

   InfoPage(
       tags.div(tags.h2("Instructions"), tags.p("Press Next to begin.")),
       time_estimate=5,
   )

Use one approach per piece of content. "dominate" escapes strings
placed inside its tags, including "Markup" strings, so their HTML is
shown as text. Only put trusted text in "Markup", never participant-
provided data. To show participant text inside your own HTML, let
"Markup.format" escape it rather than using an f-string:

   Markup("Another participant wrote: <strong>{}</strong>").format(answer)

"Markup.format" escapes a "dominate" tag too, so pass
"Markup(tag.render())" to insert one.

The same rule applies to control labels, such as the "labels" of
"PushButtonControl", to "Button" text and to "WaitPage" content: a
plain string is shown as text, and HTML needs "Markup" or a "dominate"
tag:

   PushButtonControl(
       choices=["cat", "dog"],
       labels=[Markup('<img src="/static/cat.png" alt="Cat">'), "Dog"],
   )

A "ModularPage" takes a label, a prompt (plain text or a prompt
object), and optionally a control. The API reference documents every
prompt and control. Commonly used prompts:

* "AudioPrompt", "VideoPrompt", "ImagePrompt", "ColorPrompt",
  "MusicNotationPrompt";

* "JSSynth" for melodies played in the browser;

* "GraphicPrompt" for animations generated in code.

Commonly used controls:

* choices: "PushButtonControl", "KeyboardPushButtonControl",
  "TimedPushButtonControl", "CheckboxControl", "RadioButtonControl",
  "DropdownControl";

* sliders and ratings: "SliderControl", "RatingControl",
  "MultiRatingControl";

* text and numbers: "TextControl", "NumberControl";

* recording: "AudioRecordControl", "VideoRecordControl",
  "AudioMeterControl";

* surveys: "SurveyJSControl";

* clickable graphics: "GraphicControl".

A consent page usually opens the timeline. The built-in forms in
"psynet.consent" name the institutions they were written for, so most
studies need their own; see Consent.

Pages that go beyond prompts and controls are custom front ends.


What happens to a response
==========================

Pass "save_answer" to store the answer in a participant variable:

   ModularPage(
       "age",
       "How old are you?",
       NumberControl(),
       time_estimate=5,
       save_answer="age",
   )

The most recent answer is also available as "participant.answer".
Every response is a row of the "response" table: "question" holds the
page's label, alongside "answer", "metadata" (including "time_taken"),
and "successful_validation". Responses submitted on the pages of a
trial also store that trial's ID in "trial_id" (feedback pages are not
part of the trial), so you can group a trial's responses in the
export. PsyNet stores the summed time of the trial's accepted pages in
the trial's "time_taken" column and links the last page's response as
its "response"; see "Trial" and "Response". A recording made on a
feedback page ("show_feedback()") is stored with the trial that just
finished, even though that page's response has no "trial_id".

Choice controls save the element of "choices" that the participant
picked, keeping its type: "DropdownControl([1, 2, 3])" saves the
integer "3", and "CheckboxControl" saves a list of choices.
"TimedPushButtonControl" is the exception; it saves the timing of each
button press. The browser submits choices as text, so a control whose
choices share the same text, such as "1" and ""1"", raises
"ValueError". "NumberControl" saves an "int" for a whole number such
as "100" and a "float" otherwise.

The experiment rejects an answer that is not one of the control's
choices, such as an offer of 11 from a tampered request in a 0–10
game, so you don't need to check this yourself. The check runs before
any "validate", including a page that overrides "validate", so a
"validate" cannot accept such an answer. An empty answer, such as
"None" from a page that submits without a click, still passes this
check; where a control has "force_selection", that decides whether to
accept it. A radio button control with "show_free_text_option=True"
accepts any text. If the saved answer is something other than a
choice, for example because the control or the page overrides
"format_answer" to wrap the choice in a dictionary, pass
"restrict_to_choices=False" to the control, or set the class attribute
"restrict_to_choices = False" on your control subclass.
"TimedPushButtonControl" does this for you. See "OptionControl".

The experiment builds the page again when the response arrives, re-
running a "PageMaker" function or a trial's "show_trial", and checks
the answer against the choices of that new page. The choices must
therefore be the same each time the page is built. If you pick them at
random, for example with "random.sample", pick them once and reuse
them: choose them in the trial's "finalize_definition", or store them
in "participant.var" (keyed by the repetition, if the page repeats in
a loop). Otherwise the participant's click can be rejected with "You
need to select an answer!"; the server log then shows a warning with
the page label, the answer and the choices. If the choices cannot be
kept stable, pass "restrict_to_choices=False".

To validate a response, subclass the control and implement "validate".
The method returns "None" to accept the response, or a message for the
participant to reject it. This control from "demos/features/validate"
rejects the answer ""green"":

   class NoGreenControl(PushButtonControl):
       def validate(self, response, **kwargs):
           if response.answer == "green":
               return "Green is an invalid answer!"

The message can also be wrapped in "FailedValidation".


Timing within a page
====================

The demo's last page plays a sound, then records. "events" maps event
names to "Event" objects that change when things happen: here,
"recordStart" is triggered half a second after the prompt ends
("promptEnd"), instead of immediately. "ProgressDisplay" and
"ProgressStage" show the participant what is happening when. Another
common pattern prevents responding before a sound has finished:

   events={"submitEnable": Event(is_triggered_by="promptEnd")}


Look and language
=================

Page colors come from the theme's CSS tokens. To change them, redefine
the tokens in a stylesheet under "static/" and list it in the
experiment class's "css_links".

To translate page text, wrap each string in "_", obtained from
"get_translator()".

See also:

  Page and ModularPage in the API reference.

  The Develop experiment front end and Playwright testing skills.
