Chatrooms
*********

A chatroom lets participants on the same page exchange text messages
in real time. It is part of a "ModularPage" and communicates over a
WebSocket channel.


Basic setup
===========

A chatroom needs two pieces:

1. "EnableChatrooms" opens the server-side WebSocket handler. Place it
   once in the timeline, before any page with a chatroom.

2. "ChatRoom" configures the chatroom on one page. Pass it to
   "ModularPage" as "chatroom".

The "chatroom_simple" demo pairs participants with a "SimpleGrouper"
and gives each pair a room of its own:

   timeline = Timeline(
       EnableChatrooms(),
       SimpleGrouper(
           group_type=GROUP,
           initial_group_size=2,
           waiting_message="Waiting for your partner",
           max_wait_time=120,
       ),
       StaticTrialMaker(
           id_="chat",
           trial_class=ChatTrial,
           nodes=[
               StaticNode(definition={"topic": topic})
               for topic in [
                   "your favourite food",
                   "the best film you have seen recently",
               ]
           ],
           expected_trials_per_participant=1,
           max_trials_per_participant=1,
           sync_group_type=GROUP,
           sync_group_waiting_message="Waiting for your partner",
       ),
       InfoPage("That's the end of the experiment!", time_estimate=5),
   )


   class ChatTrial(StaticTrial):
       time_estimate = 60

       def show_trial(self, experiment, participant):
           return join(
               self.chat_page(participant, topic=self.definition["topic"]),
               # Partners leave together, and the chat page ticks whoever has finished.
               GroupBarrier(
                   id_="finished_chatting",
                   group_type=GROUP,
                   waiting_message="Waiting for your partner to finish chatting",
                   # Whoever presses Next first may wait out the rest of the chat.
                   max_wait_time=CHAT_SECONDS + 30,
               ),
           )

       def chat_page(self, participant, topic):
           prompt = tags.div()
           with prompt:
               tags.h1("Chatroom")
               tags.p(f"Discuss the following topic with your partner: {topic}")

           # Both partners' trials have the same sync_group, so they meet in one room,
           # even if they are also in groups of other types.
           return ModularPage(
               "chat",
               GroupPrompt(
                   prompt,
                   group=self.sync_group,
                   participant=participant,
                   names="shown",
                   note="Press Next when you have finished; the chat also ends "
                   "by itself when the time runs out. "
                   "A tick shows when your partner has finished, "
                   "or a dash if their time ran out.",
               ),
               chatroom=ChatRoom(
                   room_id=f"chat_room_{self.sync_group.id}",
                   # The GroupPrompt already shows who is in the room.
                   show_participants=False,
                   show_history=True,
               ),
               time_estimate=60,
               # Moves on by itself, so a partner who never presses Next can't hold the other up.
               time_limit=CHAT_SECONDS,
           )


Room IDs
========

Participants whose "room_id" values match share the same messages and
participant list. The "room_id" can be any string. To give each group
a private room, build it from "Trial.sync_group", as the demo does.
"self.sync_group" returns the group of the trial maker's (or, for a
cued trial, the trial class's) "sync_group_type" that the trial was
played in, so it works even when a participant is in several groups,
and still returns the group after the participant has left it (see
Groups and barriers in detail).


Options
=======

"ChatRoom" has three options:

"show_participants" (default "False")
   Show a sidebar with the participants currently in the room.

"show_history" (default "False")
   Show the messages sent in the room before the participant opened
   the page: every message sent with this "room_id", so a "room_id"
   reused across rounds shows the earlier rounds too. The chatroom is
   enabled once the earlier messages have loaded.

"names" (default ""shown"")
   ""shown"" labels everyone else by pseudonym. ""anonymous"" draws
   them all as the same grey figure, labelled as by a "GroupPrompt"
   with "names="anonymous"": "Your partner" while only one other
   member has appeared in the room, and "Another player" once more
   have, even if some have left since. For a pair, or a larger group
   once everyone has joined the chat, this matches the GroupPrompt.
   The server then doesn't send this participant the others'
   pseudonyms or participant IDs, even for someone inspecting the
   page: the others appear under aliases numbered by order of joining
   each room ("member-1", "member-2", ...), which say nothing about
   who they are. Use it on pages whose GroupPrompt is anonymous. A
   chat writes a name next to every message, so GroupPrompt's
   ""on_hover"" isn't available.


Pseudonyms
==========

Participants see each other by pseudonym, such as "Blue fox", with a
small picture of the animal in that colour; their own messages are
labelled "You". See Pseudonyms for how pseudonyms are chosen and
customized.


Stored data
===========

Every message is stored in the "ChatMessage" table, with the sender's
participant and node IDs, the room ID, the text and the time the
server received it. Joining and leaving a room is stored in the
"ChatRoomMember" table, with timestamps and an "active" flag, the
"page_uuid" of the page they joined from and an "anonymous" flag for
rooms with "names="anonymous"". A membership counts only while the
participant is still on that page. Both tables appear in exports as
"database/chat_message.csv" and "database/chat_room_member.csv" (see
What an export contains).


Customizing the chatroom
========================

The built-in chatroom widget is the Jinja macro "chatroom_widget" in
"psynet/templates/macros/chatroom.html"; it talks to the server over
WebSockets as described in Real-time interaction. To replace it with
your own HTML, CSS and JavaScript, subclass "ChatRoom" and point it at
a template in your experiment's "templates/" directory:

   class MyChatRoom(ChatRoom):
       macro = "my_chatroom"
       external_template = "my-chatroom.html"

Then create "templates/my-chatroom.html". The macro receives the
"ChatRoom" instance as its only argument, "config", so every attribute
of the subclass is available in the template:

   {% macro my_chatroom(config) %}
   {# config.room_id, config.show_participants, config.show_history
      and any custom attributes you add are all available here. #}
   <div id="chatroom-widget">
       ...
   </div>
   {% endmacro %}

Keep the macro to markup: inline "<script>" and "<style>" blocks in a
custom template are rejected under in-place timeline transitions.
Supply page-local CSS and JavaScript through the component's
"get_css()" and "get_js_page_modules()" methods, and configuration
through "get_js_vars()". "ModularPage" collects these from the
chatroom and refreshes them for each page:

   class MyChatRoom(ChatRoom):
       macro = "my_chatroom"
       external_template = "my-chatroom.html"

       def get_css(self):
           return ["#chatroom-widget { height: 400px; }"]

       def get_js_vars(self):
           return {
               "my_chatroom_config": {
                   "room_id": self.room_id,
                   "channel": self.channel,
               }
           }

       def get_js_page_modules(self):
           return ["/static/my-chatroom.js"]

The script reads its configuration from "psynet.var" ("vars" in
"activate()"), not from global variables. Deprecated "window" access
to "js_vars" is controlled by "legacy_js_var_globals"; see Upgrading
to PsyNet 14 and Configuration.

   export async function activate({root, trial, vars}) {
       const config = vars["my_chatroom_config"];
       // ... open the websocket and wire up elements beneath root ...

       return async function cleanup() {
           // ... leave the room and close the socket ...
       };
   }

The built-in "ChatRoom" works the same way; see "get_css",
"get_js_vars" and "get_js_page_modules" in "psynet/chatroom.py".
PsyNet activates the widget script for each page and calls the
returned cleanup function before leaving. "psynet/static/scripts
/chatroom-widget.js" shows the WebSocket protocol, message rendering,
occupancy updates and cleanup.

For small style changes, such as a different height or color scheme,
override the built-in IDs ("#chatroom-widget", "#chatroom-messages",
"#chatroom-input-row" and so on) in your experiment's stylesheet
instead of replacing the template.
