114 Commits
Author SHA1 Message Date
SalastilandClaude Sonnet 5.5 335ac8b59d Merge development into master: 1.1.0, Steam
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 15:49:35 -04:00
SalastilandClaude Sonnet 5.5 b877529367 1.1.0: Steam fully ported; the README lists the protocols
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 15:49:22 -04:00
Salastil 9eb3078996 Merge remote-tracking branch 'origin/development' into protocol/steam
# Conflicts:
#	nobilis
2026-10-13 15:48:36 -04:00
SalastilandClaude Sonnet 5.5 fea81593ed nobilis: no service headings for Steam conversations
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 15:35:47 -04:00
SalastilandClaude Sonnet 5.5 83fb0542b7 nobilis: remembered Steam names
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 15:26:12 -04:00
SalastilandClaude Sonnet 5.5 ba19eaaf26 Copying a Steam invite link goes through the main process's clipboard, as everywhere else: the page's own is refused
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 15:21:31 -04:00
SalastilandClaude Sonnet 5.5 239c1e0ced Direct-messages headings made from a Steam account's folders are called protocol, then folder; a probe for QR sign-in
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 15:17:43 -04:00
SalastilandClaude Sonnet 5.5 21b5076899 History: scrolling to the top stops asking once there is nothing older. Direct-messages headings start from a Steam account's folders once and are local after that
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 15:05:26 -04:00
SalastilandClaude Sonnet 5.5 2329abe29b Probes: leave a Steam group through the window, and list an account's groups after a fresh sign-in
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 14:55:04 -04:00
SalastilandClaude Sonnet 5.5 a1be5673fc The New category dialog says Steam's own client shows a folder made here after it is restarted
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 14:52:07 -04:00
SalastilandClaude Sonnet 5.5 f03f8b276b Leaving a Steam group: a room's menu offers it, the settings dialog says when it fails, and a voice room is left with the group
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 14:41:44 -04:00
SalastilandClaude Sonnet 5.5 ed194f4c3b nobilis: the group sticker probe
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 14:33:04 -04:00
SalastilandClaude Sonnet 5.5 9616b3de25 nobilis: the group picture probe
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 14:30:13 -04:00
SalastilandClaude Sonnet 5.5 c6e3dd7ebf Steam group invitation on the Invitations tile, photographed; nobilis updated
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 14:10:38 -04:00
SalastilandClaude Sonnet 5.5 8fcf7533da Steam group invitations are on the Invitations tile: accepted opens the group, declined takes it off
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 13:54:02 -04:00
SalastilandClaude Sonnet 5.5 0633a2c835 Dropping a conversation on a category lights the whole category, not a line above it
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 13:24:02 -04:00
SalastilandClaude Sonnet 5.5 786936e6e0 Steam account page: Steam's folders are headings that are made, renamed, deleted and filled on Steam
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 13:19:54 -04:00
SalastilandClaude Sonnet 5.5 b0bc9b6d3d Steam account page: friends under Steam's folders, moved by dragging, and the move made on Steam
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 13:08:12 -04:00
SalastilandClaude Sonnet 5.5 9f8a104c53 A probe that places and answers a Steam 1:1 call against the official client
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 12:45:54 -04:00
SalastilandClaude Sonnet 5.5 48c070915b Steam voice: a refused acknowledgement of a new offer does not end the call, as in the client; a probe that joins a group's voice room
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 12:35:25 -04:00
SalastilandClaude Sonnet 5.5 f492181d2d nobilis: the whole-tree reformat taken back out, the Steam fixes kept
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 11:58:59 -04:00
SalastilandClaude Sonnet 5.5 4ffc656cc1 Steam window: no Reply or Mute where Steam has none
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 11:56:07 -04:00
SalastilandClaude Sonnet 5.5 7634dc33db Steam voice: try again as the client does when a call fails in passing
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 08:55:41 -04:00
SalastilandClaude Sonnet 5.5 f87928bcde Steam window: kick lengths, two notification settings, role giving as its own permission, calls that may not ring
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 08:12:12 -04:00
SalastilandClaude Sonnet 5.5 741726dbcd nobilis: a group's picture address
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 07:47:43 -04:00
SalastilandClaude Sonnet 5.5 90539c57f9 Steam group settings: Change picture
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 07:21:53 -04:00
SalastilandClaude Sonnet 5.5 810f780c73 Steam voice in the window: a group's voice rooms and calls to friends
The window holds the WebRTC session (lib/steamvoice.ts, a port of the Steam
client's own order of calls) and the daemon carries the signalling. A voice
room is listed under a group's channels with who is in it and who is speaking,
the call you are in is the same Voice panel as any other, a friend can be
called from their conversation, a call ringing is the same incoming-call
panel, and the footer's mute and deafen apply. Tried against real Steam as the
throwaway account: connected in two seconds with audio going to the relay.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 07:10:53 -04:00
SalastilandClaude Sonnet 5.5 0a07aa6f28 Steam chat groups in the window: a group is a server, its rooms are channels
The rail entry has Group settings (name and tagline, rooms, people and what
they may do, roles and permissions, invite links, how loudly to be told);
the member list moderates a Steam group's members; the Join page joins one
from an invite link and starts one; a room's own messages can be deleted.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 01:30:24 -04:00
SalastilandClaude Sonnet 5.5 2488bb2d08 Steam: sign in with a QR code; what Steam says about the account, and where it is signed in
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 00:49:20 -04:00
SalastilandClaude Sonnet 5.5 dc051ca232 Steam: Profile opens the card every service uses, with the names they have had; invite links and blocked people on the add-a-friend page
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 00:32:56 -04:00
SalastilandClaude Sonnet 5.5 6cc8578c41 Steam friend groups are headings on the direct-messages page, kept the same both ways
A group is one of moho's own categories: its friends' conversations are under it, and
filing, renaming or deleting it here is done to the group on Steam, as what Steam does is
done here. What was last agreed is remembered so neither side echoes the other.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 00:19:36 -04:00
SalastilandClaude Sonnet 5.5 7eac8104f3 Steam: Profile in a friend's right-click menu opens a column about them
Where the member list would be: their status, the game they are playing, when they were
last seen, the names they have had, and what they wrote on their profile. Status and game
are live from their presence.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-13 00:06:59 -04:00
SalastilandClaude Sonnet 5.5 c7730e4c49 nobilis: the Steam warning banner survives a rename
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 23:47:40 -04:00
SalastilandClaude Sonnet 5.5 ac75118270 nobilis: Steam warning banner survives a restart
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 23:41:00 -04:00
SalastilandClaude Sonnet 5.5 3b427131c0 A Steam warning is a red dismissable banner over the conversation and a red line in the log
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 23:28:34 -04:00
SalastilandClaude Sonnet 5.5 5b3eaa8b00 nobilis: presence probe
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 22:20:38 -04:00
SalastilandClaude Sonnet 5.5 ce38d537ec Steam: the message just sent is recognised when Steam made a picture or card of its link
Before, the grey copy never matched the stored one, so an image link showed twice.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 22:06:46 -04:00
SalastilandClaude Sonnet 5.5 0770478d70 A link at the end of a clause does not take the clause's punctuation
Steam pages' cards draw as any link's do; checked in the real window.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 21:56:37 -04:00
SalastilandClaude Sonnet 5.5 2a2fda35fb A Steam sticker is drawn at the size Steam draws it, not as a small emoji
The rule sizing every emoji to the line outranked the sticker's own size.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 21:24:51 -04:00
SalastilandClaude Sonnet 5.5 8b2f867c59 Steam stickers: names with spaces in the window
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 21:14:57 -04:00
SalastilandClaude Sonnet 5.5 6e319f1b51 nobilis: Steam picker refreshes the account's list
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 21:04:13 -04:00
SalastilandClaude Sonnet 5.5 042f7b6116 nobilis: Kick chat on the new realtime service
Kick turned its Pusher application off; chat moves to the service kick.com now uses.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 20:56:11 -04:00
SalastilandClaude Sonnet 5.5 5342e6670a nobilis: Kick chat on the new realtime service
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 20:52:25 -04:00
SalastilandClaude Sonnet 5.5 f1c87cd314 nobilis: Steam reconnect keeps names; heartbeat during catch-up; endings logged
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 20:40:49 -04:00
SalastilandClaude Sonnet 5.5 846feb114a Steam videos are drawn, and a spoilered picture or video is covered like Discord's
The marker names a picture or a video, which an address with no extension cannot.
Anything in a spoiler - Steam's, Sneedchat's, a Discord ||link|| - gets the SPOILER
cover, and a link followed by || no longer loses its extension to the bars.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 20:21:29 -04:00
SalastilandClaude Sonnet 5.5 9365d7cee9 The file picker offers only the kinds of file Steam takes
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 20:12:21 -04:00
SalastilandClaude Sonnet 5.5 3bc85427b1 Steam pictures are drawn as pictures, and a spoilered one is hidden until clicked
Steam's uploaded pictures have no file extension in their address, so they are
recognised by where Steam keeps them. A picture inside a spoiler is covered like a
Discord spoiler attachment. The stored form of the tag is read too.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 20:09:57 -04:00
SalastilandClaude Sonnet 5.5 aa73b27db2 nobilis: Steam file upload reads Steam's answer
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 20:03:27 -04:00
SalastilandClaude Sonnet 5.5 8473cc0a76 Steam: attach pictures and videos, with a spoiler toggle; unsupported files are refused at the box
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 19:37:25 -04:00
SalastilandClaude Sonnet 5.5 0967c2601b Steam: a message with an emoticon no longer sits pending and times out
The box sends :name: and Steam logs a picture, which comes back as [steam:emote:name];
a typed bracket likewise comes back changed. The window matched the sent message to its
echo by exact text, so neither matched and the send was reported failed. Steam's
conversations now compare the two as the same text.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 19:21:02 -04:00
SalastilandClaude Sonnet 5.5 77d168be0b Steam: picking an emoticon from the picker inserts the emoticon, not the words steam:name
The picker's per-service sections sent back the entry's id, which for Steam is the
steam:name key. Steam's section now sends the [steam:emote:name] token the box draws
and the message and reaction paths read.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 19:16:13 -04:00
SalastilandClaude Sonnet 5.5 6728b53f6a A Steam conversation's emoji picker has no Unicode emoji and no GIF button
The picker offers the account's own emoticons, with a Stickers tab for its
stickers; reactions pick from the same two; the GIF button is not drawn in a
Steam conversation.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 19:10:36 -04:00
SalastilandClaude Sonnet 5.5 a3635beb44 Steam friends: set a nickname, remove, block, and mute from the menu
A Steam friend's conversation menu - on its row and in its header - offers
what to call them, removing them as a friend, and blocking them, the last two
behind a question. Muting a Steam conversation is told to Steam so it follows
the account.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 18:38:10 -04:00
SalastilandClaude Sonnet 5.5 ab740a3d49 Steam: reactions are drawn and can be added from a message
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 16:52:46 -04:00
SalastilandClaude Sonnet 5.5 a6997fef4f Steam: emoticons draw and send; the composer offers no formatting for Steam
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 16:44:16 -04:00
SalastilandClaude Sonnet 5.5 d1d07706d0 nobilis: Sneedchat member pictures
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 16:22:25 -04:00
SalastilandClaude Sonnet 5.5 68684a4004 The profile card has a Status section
How they are showing (the dot and its word) and what they are doing - a game,
a track, or words they wrote, with an away message standing in for the words -
in a section of its own at the top of the card. What they are doing comes from
the lookup where the service gave it, and otherwise from the member lists,
which already carry it for every service.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 16:16:08 -04:00
SalastilandClaude Sonnet 5.5 82665ee4a5 Comfy lists follow Discord on every service; classic stays names
In comfy a member list has a face on everybody and, under each name, what they
are doing - a gamepad and the game, a note and the artist, or words with no
picture - and a direct message's row says the same under its name. In classic
both are plain names, as IRC and Sneedchat always were. A screenshot script
photographs the two.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 16:10:39 -04:00
SalastilandClaude Sonnet 5.5 0200d7b8a7 nobilis: Steam history, read state and typing
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 15:52:29 -04:00
SalastilandClaude Sonnet 5.5 0e3e1fcfe5 Steam: show what a friend is doing beside their name
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 15:25:25 -04:00
SalastilandClaude Sonnet 5.5 72046a4b70 nobilis: Steam message ids
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 15:07:01 -04:00
SalastilandClaude Sonnet 5.5 9ee99216c0 nobilis: hear Steam's service notifications
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 14:58:20 -04:00
SalastilandClaude Sonnet 5.5 61827ead9e Direct messages sort under a heading per account: "Protocol - Username"
Each account that has direct messages gets a heading on the direct-messages
page the first time it is seen, and its conversations are filed under it as
they arrive. Conversations that already exist are filed the first time this
runs, which is how accounts added before this get sorted without being
removed and added again. The headings are the ordinary ones, so renaming,
moving or deleting them sticks: a deleted heading is not made again and a
conversation moved out is not put back.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 14:49:56 -04:00
SalastilandClaude Sonnet 5.5 f2494a9cb6 Every yes-or-no a service asks goes to the Invitations tile
Matrix invitations leave the Join page, Discord's incoming friend requests
leave the Join page's request list, and a Matrix verification waiting to be
accepted is offered there instead of as a dialog (the dialog takes over once it
is accepted, for the emoji comparison). Accepting a Discord friend opens the
direct message with them. What this account sent stays on Join.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 14:44:15 -04:00
SalastilandClaude Sonnet 5.5 f10e16136c Invitations from every service share one rail tile and one list
A single envelope tile, there while anything waits on an answer. Selecting it
lists every pending invitation in the channel pane - Matrix rooms and direct
messages, Steam friend requests - and the pane beside it offers Accept and
Decline for the chosen one. Accepting turns that pane into the conversation
(the friend's direct message, the room) as soon as the service reports it, and
the invitation leaves the list the moment it is answered.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 14:36:17 -04:00
SalastilandClaude Sonnet 5.5 72774f1fb4 Friend requests wait in the server list beside Matrix invitations
Each request is a tile of its own, drawn with a person-add icon, and its page
says who asked with Accept and Decline. Answered here or on another client,
the tile goes. Steam is the first service to use it; the state and the tile
are any service's. The Join page keeps the add box and the requests still
waiting on the other side.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 14:28:14 -04:00
SalastilandClaude Sonnet 5.5 a77b8458c6 Steam: the sign-in form no longer offers the desktop session
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 14:22:27 -04:00
SalastilandClaude Sonnet 5.5 994a4fe783 nobilis: error 24 named
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 14:18:33 -04:00
SalastilandClaude Sonnet 5.5 2e71a1697d nobilis: a refused friend request is logged and explained
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 14:15:35 -04:00
SalastilandClaude Sonnet 5.5 2c5ca3eb27 Steam: friends are added from Add or join a server, not from Accounts
Adding someone and answering requests is joining something, so it lives
with the other services' join pages. A Steam account is offered there, and
the request toast points to it.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 14:11:38 -04:00
SalastilandClaude Sonnet 5.5 cdd3874661 Steam: the account's page asks, accepts, declines and cancels friend requests
An add box taking an account name, a Steam id or a friend code; the people
who have asked listed with Accept and Decline; the people asked listed with
Cancel request. A new request is announced once as a toast pointing here.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 14:07:27 -04:00
SalastilandClaude Sonnet 5.5 97dee82e55 Steam: the window signs in, and offers online, away and invisible
A Steam form on the Accounts page - account name, password, which kind of
session, and Tor - that follows the sign-in as the daemon reports it: the
authenticator or emailed code Steam asks for, or an approval on the phone,
and a mistyped code asked for again. Closing the form cancels a sign-in
that is still waiting. Steam gets its mark, its name, and its three states.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-12 13:23:00 -04:00
SalastilandClaude Sonnet 5.5 3c6f6e90c3 Development takes only the README from GitHub: master's .gitattributes and PKGBUILD stay on master
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-11 20:31:53 -04:00
SalastilandClaude Sonnet 5.5 74a6a43a61 nobilis: the README as it stands on GitHub
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-11 20:30:36 -04:00
Salastil f046e28a37 Revise README for protocol updates and clarity
Updated README to reflect changes in protocol support and features.
2026-10-11 20:19:55 -04:00
Salastil 6d4545f5ec Add showcase screenshot to README
Added a showcase screenshot to the README.
2026-10-11 20:11:14 -04:00
SalastilandClaude Sonnet 5.5 7e94675b2f Merge branch 'development'
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-11 17:26:25 -04:00
SalastilandClaude Sonnet 5.5 02e5aa364f moho 1.0.0
Moho 1.0. Five protocols in one window - IRC, Discord, Matrix, Kick and Sneedchat - over a daemon that keeps them connected; this is everything since the first release candidate: the rebuilt interface and settings, GIFs and link cards on every service, idle detection, the tray, Kick events as cards, conversations that open where you stopped reading, and every Rust test read.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-11 17:26:09 -04:00
SalastilandClaude Sonnet 5.5 09c060df51 Which end of a Matrix call offers now has a test where the rule lives, and nobilis carries the test review: every test read, the ones that could not fail made to, and the faults they were hiding fixed
The offering rule was only ever tested through a copy of it compiled for the daemon's tests; the window's own is checked here, including that two devices of one person tell each other apart and that nobody offers to themselves.

nobilis: ddd4503

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-11 16:14:00 -04:00
SalastilandClaude Sonnet 5.5 47653c5f7f nobilis: tests for the Sneedchat caches
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-11 14:54:18 -04:00
SalastilandClaude Sonnet 5.5 f1183958ab Kick subscriptions, moderation and the stream's going live or ending are cards in the same theme as the gifts, raids and redeems
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-11 13:44:49 -04:00
SalastilandClaude Sonnet 5.5 b0e67750ff nobilis: tests found by mutation testing, and an unpin that never reached the screen
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-11 01:15:58 -04:00
SalastilandClaude Sonnet 5.5 8a7e3e7337 nobilis: tests that could not fail now can
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-11 00:37:28 -04:00
SalastilandClaude Sonnet 5.5 d99ad2ba68 Documentation brought up to date: the settings pages, how a conversation opens, presence and the tray, link cards and Kick events, Discord mutes set on the account, the tests and the tidy step, and the daemon described as it is rather than as it was meant to be
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-11 00:30:08 -04:00
SalastilandClaude Sonnet 5.5 97611c8742 No reference to the maintainer's own server: .gitmodules and PKGBUILD are the public ones on every branch, the nobilis release is its own script and the mirroring is kept outside the repository, and the maintainer is [email protected] everywhere it is named
Closes #335

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-11 00:28:47 -04:00
SalastilandClaude Sonnet 5.5 64ade92ee1 Kick cards sit where a person does: no join mark beside them, starting at the picture's edge with the name where a name is in the log - in comfy and in bubbles, where they had been centred - and with the air above them a message has
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-11 00:07:59 -04:00
SalastilandClaude Sonnet 5.5 39dcba548a A conversation opens as Discord's does: at its first unread only when the run is short (fifty or fewer), otherwise at its end with the bar to go back by - and the line from a visit is dropped when the conversation is left, so a return no longer goes up the history to a place nothing is unread
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-10 23:58:14 -04:00
SalastilandClaude Sonnet 5.5 7bae0eaaa8 Kick events are cards in Kick's shape on this client's surfaces: KICKs sent with the gift and its tier, gifted subs with their recipients on a purple bar, a raid, and a redeemed reward in the streamer's colour
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-10 20:49:58 -04:00
SalastilandClaude Sonnet 5.5 db495d2e98 Merge branch 'development'
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-10 16:37:52 -04:00
SalastilandClaude Sonnet 5.5 9b14536112 moho 1.0.0-rc.5
Fifth release candidate: GIFs on every service with a picker, idle detection, YouTube and GIF cards on every service including over Tor, the tray's number counted by the window, mentions-only counts that survive a mute, and Discord mutes set on the account.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-10 16:37:23 -04:00
SalastilandClaude Sonnet 5.5 5d826a785d Mirror script: MIRROR_GITEA reaches Gitea by its own address for the files Cloudflare will not take
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-10 16:33:00 -04:00
SalastilandClaude Sonnet 5.5 99e03116e9 Mirror script: a file over Cloudflare's 100 MB limit stays on GitHub only, said plainly, instead of stopping the mirror before nobilis
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-10 16:28:04 -04:00
SalastilandClaude Sonnet 5.5 ee0120ff5e A deploy tidies first: old AppImages, debug and cross builds, and a daemon build directory past 8 GB are removed, so a checkout stops growing to a hundred gigabytes
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-10 16:12:52 -04:00
SalastilandClaude Sonnet 5.5 7803cc38a6 A mute stops the interruptions, not the count: a muted channel still shows its mentions in the list, the rail, the switcher and the tray; a muted direct message shows none; and muting on Discord is written to the account as it is on Matrix
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-10 13:33:05 -04:00
SalastilandClaude Sonnet 5.5 987f31cf77 The number beside a conversation is what is addressed to you: mentions in a channel, each unread message in a direct message - the bold name says there is activity, a count of it does not
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-10 13:21:56 -04:00
SalastilandClaude Sonnet 5.5 336335a8a3 Scrolling a long unread run no longer snaps back: the place being read is found through the bar laid over the top of the log, not read off the bar, so a card or picture settling above does not put the view back where the bar appeared
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-10 13:17:22 -04:00
SalastilandClaude Sonnet 5.5 638b02e07f nobilis: link cards survive edits and reach backlog on every service
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-09 23:07:05 -04:00
SalastilandClaude Sonnet 5.5 8064e79bc3 nobilis: YouTube cards for accounts on Tor, from the video's page when oEmbed is refused
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-09 22:57:05 -04:00
SalastilandClaude Sonnet 5.5 1e314f85b6 The tray's number is the window's: counted by the rail's rule - muted and hidden conversations out, a direct message by each unread message, anywhere else by its mentions - and told to the tray whenever it changes, instead of a tally of its own that drifted
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-09 20:08:34 -04:00
SalastilandClaude Sonnet 5.5 07f4fc2ef6 The window does not load the forum's own files itself: the daemon fetches them through the account's route, and asked for from the reader's address the host refuses them and Tor is bypassed
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-09 19:06:23 -04:00
SalastilandClaude Sonnet 5.5 55248eb583 GIFs: a linked GIF is drawn as the picture - silent, looping, without the player - on every service, a GIF picker with trending, categories and search, and Klipy/Tenor/Giphy pages are never probed (#331)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-09 17:55:10 -04:00
SalastilandClaude Sonnet 5.5 23c87dd353 Idle detection: how long since anything was used, from the system where it will say and moho's own windows where it will not; a setting for it and for how long; the plaque says Idle (away) and keeps what was chosen checked (#332)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-09 17:35:58 -04:00
Salastil 74af46a6f2 Merge branch 'development' 2026-10-09 15:40:06 -04:00
SalastilandClaude Sonnet 5.5 069371959a moho 1.0.0-rc.4: the rail's mention counts and Matrix unmute fixes join the release
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-09 15:40:06 -04:00
SalastilandClaude Sonnet 5.5 95f1784dbc A room unmuted on the account stops being drawn as muted: the buffer merge takes the flags the daemon leaves out as cleared; an unmute the server did not take is reported
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-09 15:37:39 -04:00
SalastilandClaude Sonnet 5.5 0dc048cdc0 Server rail: a tile counts the mentions waiting in it and not the messages, and a muted room counts for nothing, mentions included
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-09 15:28:01 -04:00
Salastil 5929fff8bb Merge branch 'development' 2026-10-09 15:21:54 -04:00
SalastilandClaude Sonnet 5.5 dc94dc3aca moho 1.0.0-rc.4
Fourth release candidate: a rebuilt tray, statuses by service, Do not disturb that silences notifications, and fixes to switching servers, Matrix rate limits and mutes, and Discord's connection.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-09 15:21:54 -04:00
SalastilandClaude Sonnet 5.5 745641a1ad The window stays where it is put: the link coming up is acted on once, a refresh does not follow the open conversation to its server, and the tray is told only what changed; Matrix's invisible is called offline; a mute held on a Matrix account can be taken off from the menu
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-09 11:45:38 -04:00
SalastilandClaude Sonnet 5.5 c1bcb72a38 Status: the plaque and the tray offer what each service has; idle from the tray reaches Discord and IRC and leaves the rest online; do-not-disturb silences desktop notifications everywhere
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-09 11:26:52 -04:00
SalastilandClaude Sonnet 5.5 0dfff0d74b nobilis: Matrix rate limits are waited out (status from the tray)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-09 11:15:38 -04:00
SalastilandClaude Sonnet 5.5 53fb0f34ce Tray: no notifications switch of its own - Do not disturb is that, and now silences an account's desktop notifications and the taskbar flash (#330)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-09 11:07:50 -04:00
SalastilandClaude Sonnet 5.5 24106e51f4 Tray: a bubble drawn for the system's colour scheme with the number waiting on it; a menu of what is new, Status, notifications, Settings, Restart moho and Quit; no daemon plumbing (#330)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-09 11:00:10 -04:00
SalastilandClaude Sonnet 5.5 b151ef8c07 nobilis: Discord request timeouts, history fetch guard, gateway tally
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-09 10:37:44 -04:00
137 changed files with 9627 additions and 690 deletions
+29 -4
View File
@@ -99,9 +99,8 @@ jobs:
build: ${{ steps.stamp.outputs.build }}
steps:
# nobilis is a submodule, and on master its URL is the public GitHub
# one - on development it points at Gitea. That is the other reason this
# workflow only ever runs on master.
# nobilis is a submodule at a commit its own master holds, which is why
# this workflow only ever runs on master.
#
# Depth 1 is enough: nobilis/build.rs only asks git for a short sha and
# a dirty flag, and falls back to "unknown" rather than failing.
@@ -270,6 +269,32 @@ jobs:
- name: layout check
run: xvfb-run -a npm run test:ui
# The tray cannot be looked at, so this reads what main gave it - icon,
# tooltip, menu - and presses its entries, including Restart moho, which
# has to bring back both the window and a daemon of its own.
- name: tray check
run: xvfb-run -a npm run test:tray
# GIFs: that a message carrying one is drawn as the picture, that a page
# nothing could read stays a link, and that the picker finds and sends.
# Needs ffmpeg, for the pictures it plays.
- name: gif check
run: |
sudo apt-get install -y --no-install-recommends ffmpeg
xvfb-run -a npm run test:gif
# Scrolling through a long unread run: that the view stays where it is
# read when something above it changes size, with the "new messages" bar
# up over the top of the log.
- name: scroll check
run: xvfb-run -a npm run test:scroll
# Kick event cards: where they sit in each layout, measured against a
# chat line beside them - the picture's column, the name's place, and the
# air above.
- name: kick card check
run: xvfb-run -a npm run test:kick
# MOHO_BUILD is computed inside the npm script - a shell assignment on
# the electron-builder line - so it cannot be injected from out here.
# The only way to control what the artifact is called is to guarantee
@@ -314,7 +339,7 @@ jobs:
retention-days: 7
# The daemon on its own, for nobilis's release - attached to that by
# scripts/mirror-release.sh, since this job's token can only release
# scripts/release-nobilis.sh, since this job's token can only release
# here. Not an asset of moho's release: the AppImage already carries it.
- uses: actions/upload-artifact@v4
if: github.ref_type == 'tag'
+32 -12
View File
@@ -6,9 +6,10 @@ How the two halves fit together, what the daemon speaks, and where it puts thing
## Why two parts
- **`nobilis`** (`nobilis/`, Rust) speaks each protocol directly and translates it into a small
unified JSON model (accounts, buffers, messages) over a Unix socket. It never exposes
protocol-specific concepts to the client; it speaks the unified model, and each backend module
happens to be how that model gets populated for a given service.
unified JSON model (accounts, buffers, messages) over a Unix socket. What every service has in
common - sending, editing, reacting, backlog, search - is one set of calls and events. What
only one service has - a Matrix room's power levels, a Discord poll, a Kick prediction - is a
call of its own, so a client never has to pretend the services are the same where they are not.
- **The Electron client** (`src/`) spawns and supervises `nobilis` and renders whatever it reports.
Keeping the protocol work in a separate long-lived daemon means connections, Tor circuits, and
@@ -42,14 +43,29 @@ Three panes: an account-grouped buffer sidebar, the message log, and a member li
sidebar and member list independently foldable. Closing the window hides it to the tray; nobilis
keeps running, so connections and unread tracking survive.
- **Message rendering** - an IRC-style log by default, with nick colouring, BBCode and
markdown, spoilers, code and quote blocks, inline image/video/YouTube embeds, custom emoji,
emotes and stickers (Discord's animated Lottie ones included), reactions, replies, inline
edit, and Sneedchat's bundled smilies. "Comfy" groups consecutive messages under one avatar,
and "Bubbles" draws them as chat bubbles.
- **Settings** - a category rail covering General, IRC, Sneedchat, Tor, Discord, Matrix, Kick
- **Message rendering** - an IRC-style log by default ("Classic"), with nick colouring, BBCode and
markdown, spoilers, code and quote blocks, inline image/video embeds, custom emoji, emotes and
stickers (Discord's animated Lottie ones included), reactions, replies, inline edit, and
Sneedchat's bundled smilies. "Comfy" groups consecutive messages under one avatar, and "Bubbles"
draws them as chat bubbles. A link is described by the daemon for every service, not only the
ones that do it themselves: a YouTube link becomes a titled card, a Tenor or Giphy link is drawn
as the GIF, and a GIF picker sends one from the composer. What somebody did on a Kick stream -
KICKs sent, subscriptions gifted and to whom, a raid, a redeemed reward - is drawn as a card.
- **Settings** - a searchable rail of categories: Accounts and Downloads; General, Appearance,
Notifications and Keybinds; a page for each network (IRC, Sneedchat, Tor, Discord, Matrix, Kick);
and About. Message-kind filters (joins, parts, mode changes) are applied client-side, so toggling
one takes effect immediately without a reconnect.
- **Moving around** - Ctrl+K opens a quick switcher over every conversation on every account.
A conversation opens at its first unread message when the unread run is short, and at its end,
with a bar to go back by, when it is long - as Discord does it. Escape marks the conversation
read and Shift+Escape the whole server; a muted conversation stays quiet but still counts the
times your name was used in it.
- **Presence and the tray** - the status menu offers only the statuses each service has (Discord
all four, IRC away and back, Matrix online and offline) and sends nothing to a service that
has no such thing. Do not disturb silences desktop notifications everywhere and is Discord's
real do-not-disturb on Discord. When nothing has been used for a while an account is put on
Idle and back, from the system's idle time where it will say and moho's own windows where it
will not. The tray draws a number counted by the window by the rule the server rail uses.
- **Per-protocol join pages** - each service's mechanism is genuinely different (IRC joins by
channel name, Discord offers the friends list and sends joining, adding a friend and making
a server to discord.com - see below - Matrix takes a room address
@@ -165,7 +181,8 @@ called `subscribe` for that buffer.
gateway. Messages with edit/delete/reactions/replies/forwarding, threads and forum posts, slash
commands with buttons, menus and modal forms, polls that can be voted in, stickers sent and
drawn, pinned messages, Discord's own search, invites, scheduled events, AutoMod's verdicts,
and server and channel mutes read from the account itself.
and server and channel mutes - read from the account itself, and set on it when a channel is muted
here, so a phone is quiet too.
Voice and video are moho's own connections rather than a library's: voice, the camera and Go
Live streams - hosted and watched, with sound - over Discord's RTP with DAVE end-to-end
@@ -197,8 +214,9 @@ called `subscribe` for that buffer.
is a renegotiation rather than a new call.
- **Kick** - the streaming site's chat, over its Pusher socket. Joins by streamer handle, imports
the account's follows, and carries the three emote tiers with subscriber gating (and 7TV and
BTTV beside them), redemptions, subscriptions, gifted subs and raids, moderation, chat modes,
and polls and predictions that can be answered rather than only watched. The stream itself
BTTV beside them), KICKs sent to a streamer, redemptions, subscriptions, gifted subs with who
received them, raids, moderation, chat modes, and polls and predictions that can be answered
rather than only watched. The stream itself
plays in the window over HLS, with its VODs and clips.
## On-disk state
@@ -209,6 +227,8 @@ called `subscribe` for that buffer.
| `~/.config/nobilis/scrollback.db` | SQLite scrollback |
| `~/.config/nobilis/matrix-crypto/` | Matrix E2EE device keys and Olm sessions |
| `~/.config/nobilis/voice.toml` | microphone, speakers, volumes and voice processing |
| `~/.config/nobilis/highlights.toml`, `ignores.toml` | the words that count as a mention, and who is ignored |
| `~/.config/nobilis/dcc.toml`, `irc-sts.toml` | DCC settings, and the IRC networks that have pinned TLS (STS) |
| `~/.config/nobilis/tor-state/`, `tor-cache/` | the embedded Tor client's state |
| `~/.cache/nobilis/` | re-derivable media caches (Matrix media, Discord thumbnails, stickers and sounds, Kick emotes, Sneedchat avatars and attachments), each held to a size and to thirty days, and fetched again when a missing file is looked at - see `nobilis/src/media_cache.rs` |
| `~/.cache/moho/moho.log` | the app's log, the daemon's included |
+177 -15
View File
@@ -17,18 +17,86 @@ Each section has two parts:
that made it, including dependency updates
(`node scripts/changelog-deps.mjs <previous tag>` lists those).
## [1.0.0-rc.3]
## [1.1.0]
### Major features
- **Steam, fully ported:** friends and direct messages, group chats with their rooms, members, roles and permissions, voice rooms and one-to-one voice calls, all in the same window as everything else.
- **Steam friends:** the friends list with presence and what each person is playing, friend requests and invitations, blocking and unblocking, nicknames, and profile cards; Steam's own friend folders are the headings on the Steam account's own page, made, renamed, deleted and filled on Steam, and what people were last called is kept between runs so a start shows names and not numbers.
- **Steam messages:** emoticons, stickers and reactions in both directions, pictures and files (spoilers too) into friends and group rooms, mentions with `@name`, `@all` and `@online`, link cards, message history that stops asking once it reaches the start, and Steam's own wording for every refusal.
- **Steam group chats:** joining by link, a friend's invitation answered from the Invitations tile, leaving, bans, kicks, role giving, notification levels, a group's picture, and the group's voice rooms with who is in them.
- **Steam voice:** group voice rooms and one-to-one calls over the same relay the Steam client uses, with the speaking indicator, and a call that retries the way the client does when Steam fails it in passing.
- **Sign in to Steam two ways:** a password with Steam Guard, or a QR code scanned by the Steam phone app; the token Steam hands back is kept, not the password.
- **One Invitations tile** for everything that waits on a yes or a no, from every service: Matrix rooms, Steam friend requests and group invitations, Discord requests, and verification.
- **Direct messages sorted under a heading per account** ("Steam - Goons", "Discord - name"), made once and yours to rename, move and delete after that.
### Fixes, patches and changes
- Kick chat moved from Pusher to Kick's realtime service ([moho `042f7b6`](https://github.com/Moho-Chat/moho/commit/042f7b6), [nobilis `c26f968`](https://github.com/Moho-Chat/nobilis/commit/c26f968))
- Fixed a link at the end of a clause taking the clause's punctuation with it ([moho `0770478`](https://github.com/Moho-Chat/moho/commit/0770478))
- Fixed Sneedchat members having no pictures ([nobilis `d1d0770`](https://github.com/Moho-Chat/nobilis/commit/d1d0770))
- The profile card has a Status section ([moho `68684a4`](https://github.com/Moho-Chat/moho/commit/68684a4))
- Comfy message lists follow Discord's layout on every service, and Classic stays names ([moho `82665ee`](https://github.com/Moho-Chat/moho/commit/82665ee))
- Dropping a conversation on a category lights the whole category, not a line above it ([moho `0633a2c`](https://github.com/Moho-Chat/moho/commit/0633a2c))
- Fixed Steam invite links not copying: the page's own clipboard is refused, so they go through the main process like every other copy
## [1.0.0]
### Major features
- **Five protocols in one window:** IRC, Discord, Matrix with end-to-end encryption, Sneedchat, and Kick.
- **Discord voice and video:** calls, cameras, screen sharing and Go Live, stage channels, the soundboard and per-person volume, all with Discord's DAVE end-to-end encryption.
- **Matrix:** encrypted rooms with device verification and key backup, Element Call, sliding sync, spaces, and signing in by QR code from a phone.
- **Per-account Tor and SOCKS5 routing:** Clearnet, Service tunnel or Strict - Strict sends every picture, link check and embed through the account's route too. Or send everything through Tor at once.
- **One mentions inbox across every service,** link previews, YouTube cards that play in place, voice messages, polls, and exporting a conversation to disk.
- **A background daemon** (nobilis) that keeps every connection alive with the window closed.
- **Discord forums:** forum and media channels appear in the channel list and open as a pane of posts - title, tags, the first message's words, replies, age, picture and top reaction - with search, sorting, older posts, and a New Post form
- **A redesigned interface:** Discord-shaped messages with date separators and an unread bar, red mention badges, a Ctrl+K quick switcher, keyboard navigation, a rail with mention counts and folders, a member list with faces, and motion throughout
- **Settings rebuilt:** one click from the gear, a grouped rail with a search over every setting, and new Appearance (layout, spacing, zoom, clock, reduce motion), Notifications and Keybinds pages with a hotkey recorder
- **A one-box message composer:** a + menu, Send only when there is something to send, Shift+Enter for a new line on every service, an attachment tray with spoilers, and dropped files going into the tray
- **Discord notices and permissions:** Discord's own safety notices drawn as the cards they are, and a banner in place of the message box wherever nothing can be written
- **A rebuilt tray:** an icon drawn for the system's colour scheme with the number of conversations waiting on it, a tooltip that says what is waiting, and a menu of what is new, Show/Hide, Status, Settings, Restart moho and Quit - Restart moho brings back both the window and the daemon
- **Status by service:** the plaque and the tray offer only the statuses each service has - Discord all four, IRC away and back, Matrix online and offline, Kick and Sneedchat none - and Do not disturb silences desktop notifications on every service, and is Discord's real mode there
- **GIFs on every service:** a linked GIF is drawn as the picture - silent, looping, without the player - whichever service it came from, and a GIF picker with trending, categories and search sends one from the composer. Klipy, Tenor and Giphy pages are never probed for what they are.
- **Idle detection:** moho notices when nothing has been used for a while, from the system where it can say and from its own windows where it cannot, and puts an account that has an idle on Idle and back. It has a setting for it and for how long, and the plaque says Idle (away) while keeping what you chose checked.
- **Link cards on every service:** a YouTube link gets a titled card with its channel on IRC, Matrix, Kick and Sneedchat as it does on Discord - including through Tor, which YouTube refuses the usual way - and one added in an edit, read back from history, or posted before cards existed gets its card too.
- **Kick events as cards:** KICKs sent to a streamer, gifted subscriptions with who received them, subscriptions, raids, redeemed rewards, bans and timeouts, and the stream going live or ending are each a card in moho's own theme, sitting where a person's message does in every layout.
- **Conversations open where you stopped reading,** as Discord's do: at the first unread when the run is short, otherwise at the end with a bar to go back by, and a return to a conversation no longer lands hundreds of messages up.
### Fixes, patches and changes
- Fixed Kick's KICKs never being heard - they arrive on a subscription that was never opened - and drew KICKs, gifted subscriptions with their recipients, raids and redeemed rewards as cards ([moho `7bae0ea`](https://github.com/Moho-Chat/moho/commit/7bae0ea), [nobilis `95ee3b1`](https://github.com/Moho-Chat/nobilis/commit/95ee3b1))
- Every other Kick event is a card too: subscriptions, bans, timeouts, unbans, a cleared chat, and the stream going live or ending ([moho `f118395`](https://github.com/Moho-Chat/moho/commit/f118395), [nobilis `23489f8`](https://github.com/Moho-Chat/nobilis/commit/23489f8))
- Kick cards start at the picture's edge with the name where a name is in the log, in comfy and bubbles, with the same air above as a message ([moho `64ade92`](https://github.com/Moho-Chat/moho/commit/64ade92))
- A conversation opens as Discord's does, and the line from a visit is dropped when the conversation is left ([moho `39dcba5`](https://github.com/Moho-Chat/moho/commit/39dcba5))
- Fixed an unpinned Kick message never leaving the screen ([nobilis `81a33a1`](https://github.com/Moho-Chat/nobilis/commit/81a33a1))
- Fixed cancelling an outgoing IRC file offer that nobody had accepted doing nothing for the three minutes the offer lasts ([nobilis `b3e92b5`](https://github.com/Moho-Chat/nobilis/commit/b3e92b5))
- Fixed the IRC capability list being cut short when a server sends it over several lines with the continuation mark in the other field ([nobilis `b3e92b5`](https://github.com/Moho-Chat/nobilis/commit/b3e92b5))
- Fixed a removed account leaving six lists behind in memory, among them its silenced channels and what its network said about MONITOR ([nobilis `b3e92b5`](https://github.com/Moho-Chat/nobilis/commit/b3e92b5))
- Fixed a raid of one viewer reading "1 viewers" ([nobilis `b3e92b5`](https://github.com/Moho-Chat/nobilis/commit/b3e92b5))
- Every test was read; those that could not fail now can, tests that checked a copy of the code now check the code, and the untested cases mutation testing found are covered ([moho `8a7e3e7`](https://github.com/Moho-Chat/moho/commit/8a7e3e7), [moho `b0e6775`](https://github.com/Moho-Chat/moho/commit/b0e6775), [moho `47653c5`](https://github.com/Moho-Chat/moho/commit/47653c5), [moho `09c060d`](https://github.com/Moho-Chat/moho/commit/09c060d), [nobilis `2477514`](https://github.com/Moho-Chat/nobilis/commit/2477514), [nobilis `b522fe6`](https://github.com/Moho-Chat/nobilis/commit/b522fe6), [nobilis `b3e92b5`](https://github.com/Moho-Chat/nobilis/commit/b3e92b5))
- Nothing in the code or documentation refers to the maintainer's own server any more ([moho `97611c8`](https://github.com/Moho-Chat/moho/commit/97611c8), [nobilis `1c70d32`](https://github.com/Moho-Chat/nobilis/commit/1c70d32))
- Documentation brought up to date with the settings pages, how a conversation opens, presence, link cards, Kick events and the daemon as it is ([moho `d99ad2b`](https://github.com/Moho-Chat/moho/commit/d99ad2b), [nobilis `6a1bb8e`](https://github.com/Moho-Chat/nobilis/commit/6a1bb8e))
- Added idle detection with a setting for it and for how long ([moho `23c87dd`](https://github.com/Moho-Chat/moho/commit/23c87dd), [nobilis `35ea0b7`](https://github.com/Moho-Chat/nobilis/commit/35ea0b7))
- Added GIFs drawn as pictures on every service, and a GIF picker ([moho `55248eb`](https://github.com/Moho-Chat/moho/commit/55248eb), [nobilis `046fbb4`](https://github.com/Moho-Chat/nobilis/commit/046fbb4))
- Fixed a Sneedchat picture from the forum's uploads host - an AVIF, or an MP4 - not drawing: its domain is taken off and it is fetched through the account's route, clearnet or Tor ([moho `07f4fc2`](https://github.com/Moho-Chat/moho/commit/07f4fc2), [nobilis `ca29a63`](https://github.com/Moho-Chat/nobilis/commit/ca29a63))
- Fixed the tray's number drifting from the client's: it is now counted by the window, by the rail's rule, and told to the tray whenever it changes ([moho `1e314f8`](https://github.com/Moho-Chat/moho/commit/1e314f8))
- Fixed YouTube cards never appearing for an account on Tor: YouTube answers every Tor exit with a 403 on its card lookup, so the video's own page is read when that happens ([moho `8064e79`](https://github.com/Moho-Chat/moho/commit/8064e79), [nobilis `340342b`](https://github.com/Moho-Chat/nobilis/commit/340342b))
- Fixed link cards being lost when a message was edited, and missing from Matrix history, Discord catch-up and older messages ([moho `638b02e`](https://github.com/Moho-Chat/moho/commit/638b02e), [nobilis `dab394f`](https://github.com/Moho-Chat/nobilis/commit/dab394f))
- Fixed scrolling through a long run of unread messages snapping back to where the "new messages" bar appeared ([moho `336335a`](https://github.com/Moho-Chat/moho/commit/336335a))
- The number beside a conversation is what is addressed to you - mentions in a channel, each unread message in a direct message - and the bold name is the sign of activity ([moho `987f31c`](https://github.com/Moho-Chat/moho/commit/987f31c))
- A muted channel keeps its mention count in the list, the rail, the switcher and the tray, and stops the popups; muting a Discord channel or direct message is now set on the account, so a phone is quiet too ([moho `7803cc3`](https://github.com/Moho-Chat/moho/commit/7803cc3), [nobilis `b0fa250`](https://github.com/Moho-Chat/nobilis/commit/b0fa250))
- Reworked the tray icon and menu, and dropped Restart daemon and Stop daemon from it ([moho `24106e5`](https://github.com/Moho-Chat/moho/commit/24106e5))
- Do not disturb now silences an account's desktop notifications and the taskbar flash; the tray no longer has a switch of its own for it ([moho `53fb0f3`](https://github.com/Moho-Chat/moho/commit/53fb0f3))
- Idle from the tray reaches Discord and IRC and leaves Matrix, Kick and Sneedchat as they were; a service is no longer asked for a status it does not have ([moho `c1bcb72`](https://github.com/Moho-Chat/moho/commit/c1bcb72), [nobilis `a8441ab`](https://github.com/Moho-Chat/nobilis/commit/a8441ab))
- Fixed Matrix's rate limit on changing status showing as M_LIMIT_EXCEEDED: a limited request now waits the time the server names, and a longer wait is applied when it is over ([moho `0dfff0d`](https://github.com/Moho-Chat/moho/commit/0dfff0d), [nobilis `43135c1`](https://github.com/Moho-Chat/nobilis/commit/43135c1))
- Fixed the window being pulled back to the open conversation's server whenever you chose another: the daemon link coming up is acted on once, a refresh no longer follows the open conversation, and the tray is told only what changed ([moho `745641a`](https://github.com/Moho-Chat/moho/commit/745641a))
- Matrix's invisible is called Offline in the plaque, its popout and the tray, which is what it sets ([moho `745641a`](https://github.com/Moho-Chat/moho/commit/745641a))
- A room muted on a Matrix account can now be unmuted from the menu, including a mute set from Element ([moho `745641a`](https://github.com/Moho-Chat/moho/commit/745641a), [nobilis `59db82c`](https://github.com/Moho-Chat/nobilis/commit/59db82c))
- Server rail tiles now count the mentions waiting in them rather than the messages, and a muted room counts for nothing, mentions included ([moho `0dc048c`](https://github.com/Moho-Chat/moho/commit/0dc048c))
- Fixed a room unmuted on a Matrix account still being drawn as muted; a mute or unmute the server did not take is now reported with its reason, and Matrix requests to a server that does not answer give up ([moho `95f1784`](https://github.com/Moho-Chat/moho/commit/95f1784), [nobilis `d1bbcaf`](https://github.com/Moho-Chat/nobilis/commit/d1bbcaf))
- Discord requests now give up on a connection that has gone quiet, a history catch-up always releases its place, and the gateway logs what it receives and why a message is dropped ([moho `b151ef8`](https://github.com/Moho-Chat/moho/commit/b151ef8), [nobilis `a34821e`](https://github.com/Moho-Chat/nobilis/commit/a34821e))
- Fixed Discord reconnecting every few seconds after being told it is rate limited: it now waits out the minute Discord asks for ([nobilis `59db82c`](https://github.com/Moho-Chat/nobilis/commit/59db82c))
- Fixed Sneedchat pictures posted back to back by a script merging into one unusable link ([moho `6edae7a`](https://github.com/Moho-Chat/moho/commit/6edae7a))
- Discord files staged together now go as one message, with an upload ring that fills as it uploads ([moho `9888c80`](https://github.com/Moho-Chat/moho/commit/9888c80), [nobilis `9690905`](https://github.com/Moho-Chat/nobilis/commit/9690905))
- Fixed the release mirror script printing a traceback while the release did not exist yet ([moho `a8d9f41`](https://github.com/Moho-Chat/moho/commit/a8d9f41))
@@ -83,20 +151,6 @@ Each section has two parts:
- A window whose page dies is reloaded and the reason logged, instead of being left empty ([moho `6899694`](https://github.com/Moho-Chat/moho/commit/6899694), [moho `06bb812`](https://github.com/Moho-Chat/moho/commit/06bb812))
- Discord forums, with live and archived posts read together ([moho `dd0c25e`](https://github.com/Moho-Chat/moho/commit/dd0c25e), [nobilis `d02bba0`](https://github.com/Moho-Chat/nobilis/commit/d02bba0), [nobilis `8363003`](https://github.com/Moho-Chat/nobilis/commit/8363003), [nobilis `3cf1a5b`](https://github.com/Moho-Chat/nobilis/commit/3cf1a5b), [nobilis `6abcb8e`](https://github.com/Moho-Chat/nobilis/commit/6abcb8e))
- Added Rust crate tokio-util 0.7.19 ([nobilis `9690905`](https://github.com/Moho-Chat/nobilis/commit/9690905))
## [1.0.0]
### Major features
- **Five protocols in one window:** IRC, Discord, Matrix with end-to-end encryption, Sneedchat, and Kick.
- **Discord voice and video:** calls, cameras, screen sharing and Go Live, stage channels, the soundboard and per-person volume, all with Discord's DAVE end-to-end encryption.
- **Matrix:** encrypted rooms with device verification and key backup, Element Call, sliding sync, spaces, and signing in by QR code from a phone.
- **Per-account Tor and SOCKS5 routing:** Clearnet, Service tunnel or Strict - Strict sends every picture, link check and embed through the account's route too. Or send everything through Tor at once.
- **One mentions inbox across every service,** link previews, YouTube cards that play in place, voice messages, polls, and exporting a conversation to disk.
- **A background daemon** (nobilis) that keeps every connection alive with the window closed.
### Fixes, patches and changes
- Channel rows in the sidebar now show a single `#` instead of two ([moho `ccdf090`](https://github.com/Moho-Chat/moho/commit/ccdf090))
- Typing anywhere in the window now goes into the message box, without clicking it first ([moho `b5f920f`](https://github.com/Moho-Chat/moho/commit/b5f920f))
- Added a formatting strip over selected text in the message box, offering the formats each service can carry ([moho `9ca477c`](https://github.com/Moho-Chat/moho/commit/9ca477c))
@@ -175,3 +229,111 @@ Each section has two parts:
- Added npm package lottie-web 5.13.0 ([moho `f67c753`](https://github.com/Moho-Chat/moho/commit/f67c753))
- Added npm package happy-dom 15.11.7 ([moho `53a6f92`](https://github.com/Moho-Chat/moho/commit/53a6f92))
- Added npm package vitest 2.1.9 ([moho `53a6f92`](https://github.com/Moho-Chat/moho/commit/53a6f92))
## [1.0.0-rc.5]
### Major features
- **GIFs on every service:** a linked GIF is drawn as the picture - silent, looping, without the player - whichever service it came from, and a GIF picker with trending, categories and search sends one from the composer. Klipy, Tenor and Giphy pages are never probed for what they are.
- **Idle detection:** moho notices when nothing has been used for a while, from the system where it can say and from its own windows where it cannot, and puts an account that has an idle on Idle and back. It has a setting for it and for how long, and the plaque says Idle (away) while keeping what you chose checked.
- **Link cards on every service:** a YouTube link gets a titled card with its channel on IRC, Matrix, Kick and Sneedchat as it does on Discord - including through Tor, which YouTube refuses the usual way - and one added in an edit, read back from history, or posted before cards existed gets its card too.
### Fixes, patches and changes
- Added idle detection with a setting for it and for how long ([moho `23c87dd`](https://github.com/Moho-Chat/moho/commit/23c87dd), [nobilis `35ea0b7`](https://github.com/Moho-Chat/nobilis/commit/35ea0b7))
- Added GIFs drawn as pictures on every service, and a GIF picker ([moho `55248eb`](https://github.com/Moho-Chat/moho/commit/55248eb), [nobilis `046fbb4`](https://github.com/Moho-Chat/nobilis/commit/046fbb4))
- Fixed a Sneedchat picture from the forum's uploads host - an AVIF, or an MP4 - not drawing: its domain is taken off and it is fetched through the account's route, clearnet or Tor ([moho `07f4fc2`](https://github.com/Moho-Chat/moho/commit/07f4fc2), [nobilis `ca29a63`](https://github.com/Moho-Chat/nobilis/commit/ca29a63))
- Fixed the tray's number drifting from the client's: it is now counted by the window, by the rail's rule, and told to the tray whenever it changes ([moho `1e314f8`](https://github.com/Moho-Chat/moho/commit/1e314f8))
- Fixed YouTube cards never appearing for an account on Tor: YouTube answers every Tor exit with a 403 on its card lookup, so the video's own page is read when that happens ([moho `8064e79`](https://github.com/Moho-Chat/moho/commit/8064e79), [nobilis `340342b`](https://github.com/Moho-Chat/nobilis/commit/340342b))
- Fixed link cards being lost when a message was edited, and missing from Matrix history, Discord catch-up and older messages ([moho `638b02e`](https://github.com/Moho-Chat/moho/commit/638b02e), [nobilis `dab394f`](https://github.com/Moho-Chat/nobilis/commit/dab394f))
- Fixed scrolling through a long run of unread messages snapping back to where the "new messages" bar appeared ([moho `336335a`](https://github.com/Moho-Chat/moho/commit/336335a))
- The number beside a conversation is what is addressed to you - mentions in a channel, each unread message in a direct message - and the bold name is the sign of activity ([moho `987f31c`](https://github.com/Moho-Chat/moho/commit/987f31c))
- A muted channel keeps its mention count in the list, the rail, the switcher and the tray, and stops the popups; muting a Discord channel or direct message is now set on the account, so a phone is quiet too ([moho `7803cc3`](https://github.com/Moho-Chat/moho/commit/7803cc3), [nobilis `b0fa250`](https://github.com/Moho-Chat/nobilis/commit/b0fa250))
## [1.0.0-rc.4]
### Major features
- **A rebuilt tray:** an icon drawn for the system's colour scheme with the number of conversations waiting on it, a tooltip that says what is waiting, and a menu of what is new, Show/Hide, Status, Settings, Restart moho and Quit - Restart moho brings back both the window and the daemon
- **Status by service:** the plaque and the tray offer only the statuses each service has - Discord all four, IRC away and back, Matrix online and offline, Kick and Sneedchat none - and Do not disturb silences desktop notifications on every service, and is Discord's real mode there
### Fixes, patches and changes
- Reworked the tray icon and menu, and dropped Restart daemon and Stop daemon from it ([moho `24106e5`](https://github.com/Moho-Chat/moho/commit/24106e5))
- Do not disturb now silences an account's desktop notifications and the taskbar flash; the tray no longer has a switch of its own for it ([moho `53fb0f3`](https://github.com/Moho-Chat/moho/commit/53fb0f3))
- Idle from the tray reaches Discord and IRC and leaves Matrix, Kick and Sneedchat as they were; a service is no longer asked for a status it does not have ([moho `c1bcb72`](https://github.com/Moho-Chat/moho/commit/c1bcb72), [nobilis `a8441ab`](https://github.com/Moho-Chat/nobilis/commit/a8441ab))
- Fixed Matrix's rate limit on changing status showing as M_LIMIT_EXCEEDED: a limited request now waits the time the server names, and a longer wait is applied when it is over ([moho `0dfff0d`](https://github.com/Moho-Chat/moho/commit/0dfff0d), [nobilis `43135c1`](https://github.com/Moho-Chat/nobilis/commit/43135c1))
- Fixed the window being pulled back to the open conversation's server whenever you chose another: the daemon link coming up is acted on once, a refresh no longer follows the open conversation, and the tray is told only what changed ([moho `745641a`](https://github.com/Moho-Chat/moho/commit/745641a))
- Matrix's invisible is called Offline in the plaque, its popout and the tray, which is what it sets ([moho `745641a`](https://github.com/Moho-Chat/moho/commit/745641a))
- A room muted on a Matrix account can now be unmuted from the menu, including a mute set from Element ([moho `745641a`](https://github.com/Moho-Chat/moho/commit/745641a), [nobilis `59db82c`](https://github.com/Moho-Chat/nobilis/commit/59db82c))
- Server rail tiles now count the mentions waiting in them rather than the messages, and a muted room counts for nothing, mentions included ([moho `0dc048c`](https://github.com/Moho-Chat/moho/commit/0dc048c))
- Fixed a room unmuted on a Matrix account still being drawn as muted; a mute or unmute the server did not take is now reported with its reason, and Matrix requests to a server that does not answer give up ([moho `95f1784`](https://github.com/Moho-Chat/moho/commit/95f1784), [nobilis `d1bbcaf`](https://github.com/Moho-Chat/nobilis/commit/d1bbcaf))
- Discord requests now give up on a connection that has gone quiet, a history catch-up always releases its place, and the gateway logs what it receives and why a message is dropped ([moho `b151ef8`](https://github.com/Moho-Chat/moho/commit/b151ef8), [nobilis `a34821e`](https://github.com/Moho-Chat/nobilis/commit/a34821e))
- Fixed Discord reconnecting every few seconds after being told it is rate limited: it now waits out the minute Discord asks for ([nobilis `59db82c`](https://github.com/Moho-Chat/nobilis/commit/59db82c))
## [1.0.0-rc.3]
### Major features
- **Discord forums:** forum and media channels appear in the channel list and open as a pane of posts - title, tags, the first message's words, replies, age, picture and top reaction - with search, sorting, older posts, and a New Post form
- **A redesigned interface:** Discord-shaped messages with date separators and an unread bar, red mention badges, a Ctrl+K quick switcher, keyboard navigation, a rail with mention counts and folders, a member list with faces, and motion throughout
- **Settings rebuilt:** one click from the gear, a grouped rail with a search over every setting, and new Appearance (layout, spacing, zoom, clock, reduce motion), Notifications and Keybinds pages with a hotkey recorder
- **A one-box message composer:** a + menu, Send only when there is something to send, Shift+Enter for a new line on every service, an attachment tray with spoilers, and dropped files going into the tray
- **Discord notices and permissions:** Discord's own safety notices drawn as the cards they are, and a banner in place of the message box wherever nothing can be written
### Fixes, patches and changes
- Fixed Sneedchat pictures posted back to back by a script merging into one unusable link ([moho `6edae7a`](https://github.com/Moho-Chat/moho/commit/6edae7a))
- Discord files staged together now go as one message, with an upload ring that fills as it uploads ([moho `9888c80`](https://github.com/Moho-Chat/moho/commit/9888c80), [nobilis `9690905`](https://github.com/Moho-Chat/nobilis/commit/9690905))
- Fixed the release mirror script printing a traceback while the release did not exist yet ([moho `a8d9f41`](https://github.com/Moho-Chat/moho/commit/a8d9f41))
- Defined the design tokens the stylesheet used but never had, and applied one set across it ([moho `9db25c8`](https://github.com/Moho-Chat/moho/commit/9db25c8), [moho `3cdfe37`](https://github.com/Moho-Chat/moho/commit/3cdfe37))
- Added a screenshot harness for before-and-after pictures of the interface ([moho `88375ba`](https://github.com/Moho-Chat/moho/commit/88375ba))
- Unread channels now read as unread, mentions are red, and every badge is one style ([moho `4ca37dd`](https://github.com/Moho-Chat/moho/commit/4ca37dd))
- Added date separators to the message list ([moho `b2464e4`](https://github.com/Moho-Chat/moho/commit/b2464e4))
- Added Mark as read on channels, categories and servers, and Escape to read what you are in ([moho `2745a2f`](https://github.com/Moho-Chat/moho/commit/2745a2f))
- Added a Ctrl+K quick switcher and keyboard navigation between channels ([moho `1eef37e`](https://github.com/Moho-Chat/moho/commit/1eef37e))
- Voice panel: a horizontal microphone bar, the connection's real latency, and a share button ([moho `ad0f0c0`](https://github.com/Moho-Chat/moho/commit/ad0f0c0), [nobilis `e0f6169`](https://github.com/Moho-Chat/nobilis/commit/e0f6169))
- Replies jump to the message they answer, and names and pictures open the profile ([moho `bf45147`](https://github.com/Moho-Chat/moho/commit/bf45147))
- Added Copy and Copy text on every message, and Copy message link on Discord ([moho `0033955`](https://github.com/Moho-Chat/moho/commit/0033955))
- The hover toolbar fades in, can be reached by keyboard, and offers Edit, Copy and your recent reactions ([moho `57e1856`](https://github.com/Moho-Chat/moho/commit/57e1856))
- Fixed six interface bugs: a nested voice button, folded categories hiding unread, muted channels hiding mentions, overlapping corners, the typing strip moving the log, and pinned rows missing their service mark ([moho `6598043`](https://github.com/Moho-Chat/moho/commit/6598043))
- Pending sends dim only their text, failed ones can be deleted, and Up in an empty box edits your last message in a multi-line editor ([moho `6a82c32`](https://github.com/Moho-Chat/moho/commit/6a82c32))
- Server rail: mention counts, folders that say what is waiting and stay open, an instant name flyout and a red close button ([moho `8072b24`](https://github.com/Moho-Chat/moho/commit/8072b24))
- Member list: faces, presence dots, and a click for the profile; Discord's member pictures now come with the list ([moho `c912ed3`](https://github.com/Moho-Chat/moho/commit/c912ed3), [nobilis `4099305`](https://github.com/Moho-Chat/nobilis/commit/4099305))
- Voice channel list: faces, muted and deafened marks, a speaking ring and a collapsible heading ([moho `843288d`](https://github.com/Moho-Chat/moho/commit/843288d))
- Comfy messages in Discord's shape, amber mention rows, one code and quote style, and marked system lines ([moho `3a7677e`](https://github.com/Moho-Chat/moho/commit/3a7677e))
- Buttons are primary, subtle or the one danger style, and the restarts ask first ([moho `2c8609c`](https://github.com/Moho-Chat/moho/commit/2c8609c))
- Escape closes only the top layer, and full-page panels close on Escape ([moho `c5e7619`](https://github.com/Moho-Chat/moho/commit/c5e7619))
- Thread panel reads the display settings, groups replies and follows the newest ([moho `33129f9`](https://github.com/Moho-Chat/moho/commit/33129f9))
- Toasts slide in and out, come in three kinds, pause on hover and fold repeats ([moho `2d1b8be`](https://github.com/Moho-Chat/moho/commit/2d1b8be))
- Context menu: keyboard navigation, checked items, shortcut hints, and placement that holds while it animates ([moho `4065963`](https://github.com/Moho-Chat/moho/commit/4065963), [moho `fcb7df5`](https://github.com/Moho-Chat/moho/commit/fcb7df5))
- A conversation opens at its first unread, with a bar saying how many are above ([moho `55fd192`](https://github.com/Moho-Chat/moho/commit/55fd192))
- Added hover fades, turning fold arrows, arriving messages, a reaction pop and growing overlays ([moho `6d8a050`](https://github.com/Moho-Chat/moho/commit/6d8a050))
- Every dialog is built from one shared frame with a close button, kept focus and a scrim below the title bar ([moho `5cb30ce`](https://github.com/Moho-Chat/moho/commit/5cb30ce), [moho `420a2f7`](https://github.com/Moho-Chat/moho/commit/420a2f7), [moho `6a329c6`](https://github.com/Moho-Chat/moho/commit/6a329c6))
- Shift+Enter makes a new line on every service and pasted line breaks stay; IRC sends them as a batch or separate lines, Sneedchat as [br], Kick as one line ([moho `9ba630c`](https://github.com/Moho-Chat/moho/commit/9ba630c), [nobilis `ccc8de6`](https://github.com/Moho-Chat/nobilis/commit/ccc8de6))
- Reply bar: its own surface, the author's face, Esc to cancel, and an @ switch to answer without pinging on Discord ([moho `f48185e`](https://github.com/Moho-Chat/moho/commit/f48185e), [nobilis `918fcfa`](https://github.com/Moho-Chat/nobilis/commit/918fcfa))
- One style for the name, command and emoji lists, with member pictures and :shortcode emoji completion ([moho `28d8b3c`](https://github.com/Moho-Chat/moho/commit/28d8b3c))
- Lightbox: step through a conversation's pictures, wheel and pinch zoom with panning, and Copy picture ([moho `817cb1e`](https://github.com/Moho-Chat/moho/commit/817cb1e))
- Emoji picker: walk it with the arrow keys, Enter picks the top result, and skin tones are remembered ([moho `99fd0d3`](https://github.com/Moho-Chat/moho/commit/99fd0d3))
- Attachment tray cards with name, size and a Discord spoiler toggle; dropped files go into the tray instead of being sent at once ([moho `15e7061`](https://github.com/Moho-Chat/moho/commit/15e7061), [nobilis `0f5669b`](https://github.com/Moho-Chat/nobilis/commit/0f5669b))
- Composer: one box with the + on the left and emoji, stickers, voice and Send on the right ([moho `a59c1ab`](https://github.com/Moho-Chat/moho/commit/a59c1ab))
- Several pictures in one message lay out as a grid, and SPOILER_ files are blurred until clicked ([moho `87ea3b8`](https://github.com/Moho-Chat/moho/commit/87ea3b8))
- Pinned messages show as a banner over the log for Discord and Matrix, with a count on the header ([moho `3a74cf0`](https://github.com/Moho-Chat/moho/commit/3a74cf0))
- Reactions say what they are and who gave them on hover ([moho `506140d`](https://github.com/Moho-Chat/moho/commit/506140d), [nobilis `1da3ad8`](https://github.com/Moho-Chat/nobilis/commit/1da3ad8))
- User footer: muted and deafened are red, voice buttons stay on every service, and the status is a popout with a custom status for Discord and Matrix and Apply to all accounts ([moho `c026609`](https://github.com/Moho-Chat/moho/commit/c026609), [nobilis `f280563`](https://github.com/Moho-Chat/nobilis/commit/f280563))
- The footer's join button is gone; the rail's + is the one way in, pinned under a rule above the settings cog while the server list scrolls ([moho `b4c1ced`](https://github.com/Moho-Chat/moho/commit/b4c1ced), [moho `dad5543`](https://github.com/Moho-Chat/moho/commit/dad5543))
- Header: one 48px row across every column, filled toggles, and the channel topic from IRC, Matrix and Discord ([moho `2ef9e35`](https://github.com/Moho-Chat/moho/commit/2ef9e35), [nobilis `44d1611`](https://github.com/Moho-Chat/nobilis/commit/44d1611))
- "(edited)" says when on hover, for edits seen live ([moho `7f4c356`](https://github.com/Moho-Chat/moho/commit/7f4c356), [nobilis `e51f139`](https://github.com/Moho-Chat/nobilis/commit/e51f139))
- Incoming Discord and Matrix calls share one card style and stack ([moho `59d4893`](https://github.com/Moho-Chat/moho/commit/59d4893))
- Settings: the gear opens it directly, with Accounts and Downloads as pages, a search, one switch for every boolean and a saved tick ([moho `66a0c0f`](https://github.com/Moho-Chat/moho/commit/66a0c0f), [moho `cc4c9f6`](https://github.com/Moho-Chat/moho/commit/cc4c9f6))
- Settings: added Appearance, Notifications and Keybinds pages, the last with a recorder for the global hotkey ([moho `fe6ad97`](https://github.com/Moho-Chat/moho/commit/fe6ad97), [moho `adca84d`](https://github.com/Moho-Chat/moho/commit/adca84d), [moho `82a0bdf`](https://github.com/Moho-Chat/moho/commit/82a0bdf))
- Accounts open by default with few accounts, Remove sits in a danger zone, and Join picks its account and says Join ([moho `f8dcccd`](https://github.com/Moho-Chat/moho/commit/f8dcccd))
- Mentions page: service and unread filters, day groups, two-line bodies and put-away ([moho `078fe41`](https://github.com/Moho-Chat/moho/commit/078fe41))
- Room settings is a tabbed dialog instead of a popover ([moho `f8936c6`](https://github.com/Moho-Chat/moho/commit/f8936c6))
- Quiet buttons such as Cancel have their own fill, so they no longer vanish into a dialog ([moho `50aaa97`](https://github.com/Moho-Chat/moho/commit/50aaa97))
- Fixed browsing an IRC network's channels freezing or blanking the window: the daemon holds the list and sends a page, it times out after a minute, and a refusal is reported ([moho `2b41c5e`](https://github.com/Moho-Chat/moho/commit/2b41c5e), [nobilis `152fdf1`](https://github.com/Moho-Chat/nobilis/commit/152fdf1))
- Channels in the list no longer jump to the top as messages arrive ([moho `9f03d6b`](https://github.com/Moho-Chat/moho/commit/9f03d6b))
- Fixed Discord's notices showing only a stand-in title: they are read as cards, and a banner replaces the message box in them and in channels this account cannot write in ([moho `ff7d313`](https://github.com/Moho-Chat/moho/commit/ff7d313), [moho `d7c4215`](https://github.com/Moho-Chat/moho/commit/d7c4215), [moho `2a4f797`](https://github.com/Moho-Chat/moho/commit/2a4f797), [nobilis `1b270be`](https://github.com/Moho-Chat/nobilis/commit/1b270be), [nobilis `97ac6bc`](https://github.com/Moho-Chat/nobilis/commit/97ac6bc), [nobilis `7561b88`](https://github.com/Moho-Chat/nobilis/commit/7561b88))
- A window whose page dies is reloaded and the reason logged, instead of being left empty ([moho `6899694`](https://github.com/Moho-Chat/moho/commit/6899694), [moho `06bb812`](https://github.com/Moho-Chat/moho/commit/06bb812))
- Discord forums, with live and archived posts read together ([moho `dd0c25e`](https://github.com/Moho-Chat/moho/commit/dd0c25e), [nobilis `d02bba0`](https://github.com/Moho-Chat/nobilis/commit/d02bba0), [nobilis `8363003`](https://github.com/Moho-Chat/nobilis/commit/8363003), [nobilis `3cf1a5b`](https://github.com/Moho-Chat/nobilis/commit/3cf1a5b), [nobilis `6abcb8e`](https://github.com/Moho-Chat/nobilis/commit/6abcb8e))
- Added Rust crate tokio-util 0.7.19 ([nobilis `9690905`](https://github.com/Moho-Chat/nobilis/commit/9690905))
+1 -1
View File
@@ -1,7 +1,7 @@
pkgname=moho-git
pkgver=r1.268751e
pkgrel=1
pkgdesc="Unified desktop chat client for IRC, Discord, Sneedchat and Matrix"
pkgdesc="Unified desktop chat client for IRC, Discord, Matrix, Kick, Sneedchat and Steam"
arch=('x86_64')
url="https://github.com/Moho-Chat/moho"
license=('GPL3')
+40 -36
View File
@@ -1,45 +1,43 @@
# moho
**Every conversation you're in, in one window.**
<img width="1545" height="912" alt="showcase-screenshot" src="https://github.com/user-attachments/assets/b9dabddb-bb3c-4a71-b872-9ad167ecd400" />
moho is a desktop chat client that speaks IRC, Discord, Matrix, Kick and Sneedchat at the
same time. One buffer list down the side, one log in the middle, one set of habits — whether
the room is a twenty-year-old IRC channel, a Discord server, an encrypted Matrix room, or a
stream's chat going past at forty lines a minute.
It isn't five web apps in a trenchcoat. Underneath sits a small Rust daemon that holds the
connections; the window is just what draws them. Close it and you stay connected. Open it
again and everything is where you left it.
moho is a desktop chat client that speaks IRC, Discord, Matrix, Kick, Sneedchat, Steam and many more protocols at the
same time. Whether the room is a twenty-year-old IRC channel, a Discord server, an encrypted Matrix room, or a
stream's chat going past at forty lines a minute you're able to be part of the conversation.
## What it does
- **Five networks, one place.** IRC, Discord, Matrix, Kick and Sneedchat, side by side, with
- **Many networks, one place.** IRC, Discord, Matrix, Kick, Sneedchat, Steam and many more protocols soon, side by side, with
the same reply, edit, react, search and tag-someone gestures on each — as far as each
service actually supports them.
- **A log, not a feed.** Compact IRC-style scrollback with nick colours, markdown and BBCode,
spoilers, code blocks, inline images and video, and custom emoji. There's a roomier mode
with avatars if you prefer one.
- **It stays connected.** The daemon keeps IRC registered, Matrix syncing and Tor circuits
open while the window is shut. Quitting says a proper goodbye rather than dropping the
socket, so you don't come back to a ghosted nick.
- **Calls.** Voice, camera and screen sharing on Discord and on Matrix, including the group
calls Element holds on a media server. On Discord, Go Live streams both ways with sound,
- **Calls.** Voice, camera and screen sharing on Discord and on Matrix, voice rooms and calls on Steam, including the group
calls Element holds on a media server. On Discord, Go Live, streams both ways with sound,
echo cancellation, volume per person, the soundboard and stage channels. A call can sit in
the corner or pop out into a window of its own.
- **Matrix, properly encrypted.** End-to-end encryption with device verification by emoji or
QR, cross-signing, key backup, and encrypted attachments.
- **Sneedchat, and Tor where you want it.** The site's proof-of-work gate and its login
captcha both handled, and every room you've joined connected at once. Any account on any of
the five can go through an embedded Tor client or a SOCKS5 proxy instead of the open internet.
- **Kick streams in the window.** Watch the stream beside its chat, in the corner or in a
window of its own, with VODs, clips, 7TV and BTTV emotes, polls and predictions.
- **No captchas on Discord, on purpose.** Discord puts joining a server, adding a friend and
making a server behind a captcha when they come from anything but its own client, and
answering one gets an account flagged for spam. moho opens discord.com for those three
instead of putting your account at risk.
window of its own, polls, predictions and other interactive methods are functional and at your fingertips.
- **Yours.** GPL-3.0, no telemetry, no account with us — your history is a SQLite file on
your own disk.
## Supported protocols
| Protocol | State | What you get |
| --- | --- | --- |
| **IRC** | Supported | Channels and queries on any number of networks, with SASL, TLS, DCC file transfers and the IRCv3 capabilities servers offer |
| **Matrix** | Supported | Rooms, spaces and direct messages, end-to-end encryption with device verification and key backup, Element Call, and signing in by QR code |
| **Discord** | Supported | Servers, direct messages, forums and threads, voice, video, screen sharing and Go Live with end-to-end encryption, stages and the soundboard |
| **Kick** | Supported | A streamer's chat beside the stream, with polls, predictions and its events drawn as cards |
| **Sneedchat** | Supported | The forum's chat rooms, over clearnet or Tor |
| **Steam** | Supported, fully ported | Friends and direct messages, group chats with rooms, roles and invitations, voice rooms and calls, emoticons, stickers, reactions, pictures and files, friend folders, and signing in by password or by QR code |
Every protocol gets the same window, mentions inbox, search and per-account Tor or SOCKS5 routing.
How much of each service's own feature set a protocol has is as far as its service lets a
third-party client go; more protocols are planned.
## Get it
Prebuilt Linux and Windows downloads are on the
@@ -47,10 +45,6 @@ Prebuilt Linux and Windows downloads are on the
changed is in [CHANGELOG.md](CHANGELOG.md). moho tells you in its mentions inbox when a newer
version is out.
Versions are MAJOR.FEATURE.FIX: a major release, then protocols added and major features,
then bug and security fixes - 1.1.0 would add a protocol, 1.0.5 is the fifth fix release
of 1.0.
The AppImage needs `libfuse2` on recent distributions; if it refuses to start, either install
that or run it with `APPIMAGE_EXTRACT_AND_RUN=1`.
@@ -85,13 +79,18 @@ npm install-scripts approve electron esbuild
## Test it
```bash
npm test # the window's unit tests (Vitest)
npm run test:ui # layout checks against the real app - popups must stay inside the window
npm test # the window's unit tests (Vitest)
npm run test:ui # layout checks against the real app - popups must stay inside the window
npm run test:tray # the tray: its icon, tooltip, menu, statuses and restart
npm run test:gif # GIFs drawn as pictures, and the GIF picker
npm run test:scroll # scrolling and where a conversation opens
npm run test:kick # where Kick event cards sit in each layout
cd nobilis && cargo test --release
```
`test:ui` builds the window, runs it against a scratch home and a fake IRC server, and needs the
daemon built first. On a machine with no display, run it under `xvfb-run`.
The `test:` scripts other than `test` build the window, run it against a scratch home and a
fake IRC server, and need the daemon built first. On a machine with no display, run them under
`xvfb-run`. `npm run shots` photographs the interface scene by scene, for looking at changes.
## Run it
@@ -107,9 +106,14 @@ npm run deploy
```
Other ways out of the box: `npm run pack:dir` for a self-contained `dist/linux-unpacked/`
directory to run in place, `npm run pack:win` for the Windows installer (cross-built with
mingw-w64; packaging it also needs wine with 32-bit support), and `makepkg -si` against the
bundled `PKGBUILD` to install it as an Arch package under `/opt/moho`.
directory to run in place, `npm run pack:deb` for a Debian package, `npm run pack:win` for the
Windows installer (cross-built with mingw-w64; packaging it also needs wine with 32-bit
support), and `makepkg -si` against the bundled `PKGBUILD` to install it as an Arch package
under `/opt/moho`.
Packaging leaves a lot behind - an AppImage per build, and Rust build output that Cargo never
cleans up. `npm run deploy` first runs `npm run tidy`, which keeps the newest two AppImages and
empties `nobilis/target/` once it passes 8 GB.
---
+1 -1
Submodule nobilis updated: baa37abde4...289b5db54a
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "moho",
"version": "1.0.0-rc.3",
"version": "1.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "moho",
"version": "1.0.0-rc.3",
"version": "1.1.0",
"license": "GPL-3.0-or-later",
"dependencies": {
"@electron-toolkit/preload": "^3.0.1",
+9 -4
View File
@@ -1,8 +1,8 @@
{
"name": "moho",
"version": "1.0.0-rc.3",
"version": "1.1.0",
"description": "Unified desktop chat client for IRC, Discord, Sneedchat and Matrix",
"author": "Salastil",
"author": "Salastil <[email protected]>",
"license": "GPL-3.0-or-later",
"homepage": "https://github.com/Moho-Chat/moho",
"repository": {
@@ -21,13 +21,18 @@
"typecheck": "tsc --noEmit -p tsconfig.node.json && tsc --noEmit -p tsconfig.web.json",
"test": "vitest run",
"test:ui": "electron-vite build && node scripts/ui-check.mjs",
"test:tray": "electron-vite build && node scripts/tray-check.mjs",
"test:gif": "electron-vite build && node scripts/gif-check.mjs",
"test:scroll": "electron-vite build && node scripts/scroll-check.mjs",
"test:kick": "electron-vite build && node scripts/kick-check.mjs",
"shots": "electron-vite build && node scripts/ui-shots.mjs",
"pack": "npm run daemon && npm run build && MOHO_BUILD=$(git rev-parse --short HEAD)$(git diff --quiet HEAD || echo -dirty) electron-builder --linux AppImage",
"pack:deb": "npm run daemon && npm run build && MOHO_BUILD=$(git rev-parse --short HEAD)$(git diff --quiet HEAD || echo -dirty) electron-builder --linux deb",
"pack:linux": "npm run daemon && npm run build && MOHO_BUILD=$(git rev-parse --short HEAD)$(git diff --quiet HEAD || echo -dirty) electron-builder --linux AppImage deb",
"pack:dir": "npm run daemon && npm run build && MOHO_BUILD=$(git rev-parse --short HEAD)$(git diff --quiet HEAD || echo -dirty) electron-builder --linux dir",
"daemon": "./scripts/build-daemon.sh",
"deploy": "npm run pack && ./scripts/install-desktop.sh",
"tidy": "./scripts/tidy.sh",
"deploy": "./scripts/tidy.sh && npm run pack && ./scripts/install-desktop.sh",
"daemon:win": "./scripts/build-daemon-win.sh",
"pack:win": "npm run daemon:win && npm run build && MOHO_BUILD=$(git rev-parse --short HEAD)$(git diff --quiet HEAD || echo -dirty) electron-builder --win nsis"
},
@@ -74,7 +79,7 @@
"AppImage",
"deb"
],
"maintainer": "Salastil <salastil@users.noreply.github.com>",
"maintainer": "Salastil <salastil@cock.li>",
"category": "Network",
"synopsis": "Unified desktop chat client",
"icon": "resources/icons/moho.png",
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 797 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 771 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

+131
View File
@@ -0,0 +1,131 @@
#!/usr/bin/env node
/**
* Checks GIFs against the running app: that one a message carries is drawn as
* the picture and not as its address, that a link to a page nothing could read
* is still a link, and that the picker finds, filters and sends.
*
* What it stands in for, and why: Discord is not here, so the picker's list is
* left for it (a fixture only a harness window reads) and the embeds are put on
* messages directly. What is real is everything the window does with them, and
* the send, which goes through the daemon to a fake IRC server and is read back
* off the wire.
*
* npm run test:gif (builds first; needs the daemon built too)
*/
import { execFileSync } from 'node:child_process'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { fakeIrc, launchApp, openIrcChannel, sleep, until, click } from './lib/harness.mjs'
let failures = 0
const check = (ok, what, detail = '') => {
console.log(`${ok ? 'ok ' : 'FAIL'} ${what}${ok ? '' : detail ? ` - ${detail}` : ''}`)
if (!ok) failures++
}
setTimeout(() => {
console.log('FAIL timed out')
process.exit(1)
}, 120000).unref()
// A GIF and a video to be served, so what is drawn has something to load: made
// with ffmpeg, a second of a flat colour. The window only plays https, blob and
// data media, so they are handed to it as the last two.
const media = fs.mkdtempSync(path.join(os.tmpdir(), 'moho-gif-'))
execFileSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'color=c=0x3a8fe0:s=96x54:d=1:r=10', '-pix_fmt', 'yuv420p', '-y', path.join(media, 'cat.mp4')])
execFileSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'color=c=0xe0a43a:s=96x54:d=1:r=10', '-y', path.join(media, 'giphy.gif')])
const MP4 = fs.readFileSync(path.join(media, 'cat.mp4')).toString('base64')
const GIF = fs.readFileSync(path.join(media, 'giphy.gif')).toString('base64')
const sent = []
const irc = await fakeIrc({
people: ['bob'],
onJoin: (channel, _nick, send) => send(`:bob!b@h PRIVMSG ${channel} :hello there`),
onLine: (line) => {
if (/^PRIVMSG/i.test(line)) sent.push(line)
}
})
const { page, stop } = await launchApp({ env: { MOHO_UI_SHOTS: '1' } })
let home = ''
try {
home = await page.evaluate('window.moho.diagnostics?.home ?? ""').catch(() => '')
await until(page, 'window.__mohoShots', 'the harness hook')
await openIrcChannel(page, { port: irc.address().port, nick: 'checker', channels: ['#lobby'], waitFor: 'hello there' })
// The same GIF, as a message that carries it.
const SIZE = (a, b, label) =>
'data:image/svg+xml;utf8,' +
encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="480" height="270"><rect width="480" height="270" fill="${a}"/><text x="240" y="150" font-size="60" fill="${b}" text-anchor="middle">${label}</text></svg>`)
await page.evaluate(`(() => {
const shots = window.__mohoShots
const s = shots.state()
const id = s.activeBufferId
const now = Math.floor(Date.now() / 1000)
const bytes = Uint8Array.from(atob('${MP4}'), (c) => c.charCodeAt(0))
const MP4_URL = URL.createObjectURL(new Blob([bytes], { type: 'video/mp4' }))
const GIF_URL = 'data:image/gif;base64,${GIF}'
const msg = (n, body, embeds) => ({ id: 'g' + n, bufferId: id, from: 'bob', senderId: 'bob', body, ts: now - (10 - n), isAction: false, isHighlight: false, kind: 'chat', isOwn: false, ...(embeds ? { embeds } : {}) })
shots.patch({
accounts: [...s.accounts, { id: 'discord:gifcheck', service: 'discord', displayName: 'x', state: 'connected', autojoin: '', currentNick: 'x', status: 'online', useTor: false, ssl: true }],
messagesByBuffer: { ...s.messagesByBuffer, [id]: [...(s.messagesByBuffer[id] || []),
msg(1, 'https://tenor.com/view/cat-gif-123', [{ kind: 'gif', url: 'https://tenor.com/view/cat-gif-123', mediaUrl: MP4_URL, mediaKind: 'video', width: 480, height: 270, provider: 'Tenor' }]),
msg(2, 'look at this https://giphy.com/gifs/dog-Z7wFi5b2VEAr6 so good', [{ kind: 'gif', url: 'https://giphy.com/gifs/dog-Z7wFi5b2VEAr6', mediaUrl: GIF_URL, mediaKind: 'image', provider: 'Giphy' }]),
msg(3, 'https://klipy.com/gifs/friends-joey-53')
] }
})
window.__gifFixture = {
categories: [{ name: 'reaction', src: '' }, { name: 'happy', src: '' }],
gifs: [
{ id: 'a', title: 'cat dancing', url: 'https://tenor.com/view/cat-dancing-gif-1', src: 'http://127.0.0.1:9/a.mp4', gifSrc: 'http://127.0.0.1:9/a.gif', preview: '', width: 480, height: 270 },
{ id: 'b', title: 'dog running', url: 'https://tenor.com/view/dog-running-gif-2', src: 'http://127.0.0.1:9/b.mp4', gifSrc: 'http://127.0.0.1:9/b.gif', preview: '', width: 270, height: 480 },
{ id: 'c', title: 'cat sleeping', url: 'https://tenor.com/view/cat-sleeping-gif-3', src: 'http://127.0.0.1:9/c.mp4', gifSrc: 'http://127.0.0.1:9/c.gif', preview: '', width: 480, height: 480 }
]
}
return true
})()`)
await sleep(800)
const row = (n) => `[...document.querySelectorAll('.message-row')].find((r) => r.innerText.includes('${n}') || r.querySelector('[data-id="g${n}"]'))`
// A message that carries a GIF shows the GIF, and not the address it came from.
const rows = await page.evaluate(`[...document.querySelectorAll('.message-row')].map((r) => ({ text: r.innerText, videos: [...r.querySelectorAll('video')].map((v) => v.getAttribute('src')), plays: [...r.querySelectorAll('video')].map((v) => ({ muted: v.muted, loop: v.loop, controls: v.controls, autoplay: v.autoplay })), images: [...r.querySelectorAll('img')].map((i) => i.getAttribute('src')) }))`)
if (process.env.GIF_DEBUG) console.log(JSON.stringify(rows.slice(-4), null, 1))
const tenor = rows.find((r) => r.videos.some((v) => v?.startsWith('blob:')))
check(!!tenor, 'a GIF message is drawn as a video')
check(!!tenor && !/tenor\.com/.test(tenor.text), 'and its page address is not drawn as well', tenor?.text)
const play = tenor?.plays?.[0]
check(!!play && play.muted && play.loop && !play.controls && play.autoplay, 'played as a GIF: silent, going round, with no player to work', JSON.stringify(play))
const giphy = rows.find((r) => r.text.includes('look at this'))
check(!!giphy && /look at this/.test(giphy.text) && /so good/.test(giphy.text) && !/giphy\.com/.test(giphy.text), 'words around a GIF link stay, and the link goes', giphy?.text)
check(!!giphy && (giphy.images.some((i) => i?.startsWith('data:image/gif'))), 'and a GIF file is drawn as a picture')
const klipy = rows.find((r) => r.text.includes('klipy.com'))
check(!!klipy && klipy.videos.length === 0, 'a Klipy page nothing could read stays a link', JSON.stringify(klipy))
// The picker.
check(await page.evaluate('!!document.querySelector(\'button[title="GIFs"]\')'), 'a GIF button is offered where there is a Discord account')
await page.evaluate(click('button[title="GIFs"]'))
await until(page, 'document.querySelector(".gif-picker")', 'the picker')
check((await page.evaluate('document.querySelectorAll(".gif-cell").length')) === 3, 'it lists what it was given')
check((await page.evaluate('document.querySelectorAll(".gif-category").length')) === 2, 'with categories to start from')
const inView = await page.evaluate(`(() => { const r = document.querySelector('.gif-picker').getBoundingClientRect(); return r.left >= 0 && r.top >= 0 && r.right <= window.innerWidth && r.bottom <= window.innerHeight })()`)
check(inView, 'inside the window')
await page.evaluate(`(() => { const i = document.querySelector('.gif-search input'); const set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set; set.call(i, 'cat'); i.dispatchEvent(new Event('input', { bubbles: true })); return true })()`)
await sleep(700)
check((await page.evaluate('document.querySelectorAll(".gif-cell").length')) === 2, 'a search narrows it')
// Choosing one sends it - to IRC, the file, which anything can show as a link.
await page.evaluate(`document.querySelector('.gif-cell[title="cat dancing"]').click()`)
await sleep(1200)
check(sent.some((l) => /PRIVMSG #lobby :?http:\/\/127\.0\.0\.1:9\/a\.gif/.test(l)), 'choosing one sends the file to a service that is not Discord', JSON.stringify(sent))
check(!(await page.evaluate('!!document.querySelector(".gif-picker")')), 'and the picker closes')
} catch (e) {
console.log('FAIL', e.message)
failures++
} finally {
await stop().catch(() => {})
irc.close()
fs.rmSync(media, { recursive: true, force: true })
}
console.log(failures ? `${failures} failed` : 'all passed')
process.exit(failures ? 1 : 0)
+99
View File
@@ -0,0 +1,99 @@
#!/usr/bin/env node
/**
* Checks where a Kick event card sits in the log, in each layout.
*
* A card is what a person did, so it takes the column a person's picture would
* (and not the mark a join gets), what is written in it starts where a name
* does, and it has the air above it that a message and an embed have. These
* are measured against a real chat line beside it rather than against numbers,
* so they hold when the layout's own numbers change.
*
* npm run test:kick (builds first; needs the daemon built too)
*/
import { fakeIrc, launchApp, openIrcChannel, sleep, until, click } from './lib/harness.mjs'
let failures = 0
const check = (ok, what, detail = '') => {
console.log(`${ok ? 'ok ' : 'FAIL'} ${what}${ok ? '' : detail ? ` - ${detail}` : ''}`)
if (!ok) failures++
}
setTimeout(() => {
console.log('FAIL timed out')
process.exit(1)
}, 120000).unref()
const irc = await fakeIrc({ people: ['bob'], onJoin: (channel, _nick, send) => send(`:bob!b@h PRIVMSG ${channel} :hello there`) })
const { page, stop } = await launchApp({ env: { MOHO_UI_SHOTS: '1' } })
const stage = `(() => {
const shots = window.__mohoShots
const s = shots.state()
const id = s.activeBufferId
const now = Math.floor(Date.now() / 1000)
const row = (n, kind, body, embed, from) => ({ id: 'k' + n, bufferId: id, from, senderId: from, body, ts: now - 600 + n * 70, isAction: false, isHighlight: false, kind, isOwn: false, embeds: embed ? [embed] : [] })
shots.patch({ messagesByBuffer: { ...s.messagesByBuffer, [id]: [
row(1, 'chat', 'that was a clean run', null, 'bob'),
row(2, 'chat', 'and then it got worse', null, 'carol'),
row(3, 'kicks', 'Currington sent 1 Kick', { kind: 'kicks', author: 'Currington', title: '1', color: 0x53fc18 }, 'kicker'),
row(4, 'sub', 'ItsDez gifted 2 subscriptions', { kind: 'gift-sub', author: 'ItsDez', title: '2', description: 'a\\nb' }, 'kicker'),
row(5, 'reward', 'poo_nana redeemed MUTE', { kind: 'redeem', author: 'poo_nana', title: 'MUTE (user) 30 MINUTES', description: 'O_C_T_O', color: 0xff4b1f }, 'kicker'),
row(6, 'raid', 'x raided with 25 viewers', { kind: 'raid', author: 'kreationX', title: '25' }, 'kicker'),
row(8, 'sub', 'bigkhernandez subscribed - 21 months', { kind: 'subscribe', author: 'bigkhernandez', title: '21' }, 'kicker'),
row(9, 'moderation', 'troll was timed out by mod', { kind: 'moderation', author: 'troll', title: 'was timed out', description: 'mod' }, 'kicker'),
row(10, 'stream', 'went live', { kind: 'stream', author: 'streamer', title: 'went live', icon: 'live' }, 'kicker'),
row(11, 'chat', 'thanks everybody', null, 'dave')
] } })
})()`
const measure = `(() => {
const x = (el) => (el ? Math.round(el.getBoundingClientRect().left) : null)
const rows = [...document.querySelectorAll('.message-row')]
const chat = rows.find((r) => !r.classList.contains('has-kick-event') && r.querySelector('.message-from'))
const cards = rows.filter((r) => r.classList.contains('has-kick-event'))
const margin = (r) => parseFloat(getComputedStyle(r).marginTop)
return {
marks: cards.filter((r) => r.querySelector('.system-mark')).length,
cards: cards.length,
chatEdge: x(chat.querySelector('.message-avatar img, .message-avatar .avatar-fallback') || chat.querySelector('.message-content')),
chatName: x(chat.querySelector('.message-from')),
cardEdge: cards.map((r) => x(r.querySelector('.kick-event'))),
cardName: cards.map((r) => x(r.querySelector('.kick-event-name'))),
gapAbove: cards.map(margin),
chatGap: margin(chat) || 0,
wide: cards.map((r) => Math.round(r.querySelector('.kick-event').getBoundingClientRect().width))
}
})()`
try {
await until(page, 'window.__mohoShots', 'the harness hook')
await openIrcChannel(page, { port: irc.address().port, nick: 'checker', channels: ['#lobby'], waitFor: 'hello there' })
for (const mode of ['comfy', 'bubbles', 'classic']) {
await page.evaluate(`window.moho.prefs.set('display.messageMode', ${JSON.stringify(mode)})`)
await page.call('Page.reload')
await until(page, 'window.__mohoShots && document.querySelector("nav[aria-label=Servers] [aria-label]")', 'the window after a reload')
await sleep(500)
await page.evaluate(click('nav[aria-label=Servers] [aria-label*="localhost"]'))
await sleep(300)
await page.evaluate(click('.buffer-row', '#lobby'))
await sleep(500)
await page.evaluate(stage)
await sleep(700)
const m = await page.evaluate(measure)
console.log(`${mode}: ${JSON.stringify(m)}`)
check(m.cards === 7, `${mode}: every kind of card is drawn`, `${m.cards}`)
check(m.marks === 0, `${mode}: no join mark beside a card`, `${m.marks}`)
if (mode !== 'classic') {
// The card starts at the picture's edge.
check(m.cardEdge.every((e) => Math.abs(e - m.chatEdge) <= 2), `${mode}: a card starts where a person's picture does`, `${m.cardEdge} vs ${m.chatEdge}`)
// And what is written in it starts where a name does.
check(m.cardName.every((n) => Math.abs(n - m.chatName) <= 2), `${mode}: the name in a card is where a name is in the log`, `${m.cardName} vs ${m.chatName}`)
}
check(m.gapAbove.every((g) => g >= (mode === 'comfy' ? m.chatGap : 4) - 0.5), `${mode}: a card has air above it`, `${m.gapAbove} vs ${m.chatGap}`)
check(m.wide.every((w) => w > 200), `${mode}: and is not squeezed or centred away`, `${m.wide}`)
}
} finally {
await stop()
irc.close()
}
console.log(failures ? `${failures} FAILED` : 'all passed')
process.exit(failures ? 1 : 0)
+5 -3
View File
@@ -207,16 +207,18 @@ function moveAside(pid) {
* The built app, against a scratch home, with a debugging port. Returns the
* page and a `stop()` that takes everything down again.
*/
export async function launchApp({ env = {} } = {}) {
export async function launchApp({ env = {}, args = [], seed } = {}) {
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'moho-ui-'))
const run = path.join(scratch, 'run')
fs.mkdirSync(run, { mode: 0o700 })
// Files the app should find on its first start, written into its own home.
seed?.(scratch)
const port = await freePort()
// A CI runner's kernel refuses Chromium's sandbox (Ubuntu 24.04 restricts
// the unprivileged namespaces it needs); there it runs without, as an
// ordinary Chromium in a container does.
const flags = [`--remote-debugging-port=${port}`, ...(process.env.CI ? ['--no-sandbox'] : [])]
const flags = [`--remote-debugging-port=${port}`, ...(process.env.CI ? ['--no-sandbox'] : []), ...args]
const app = spawn(electronPath, [root, ...flags], {
cwd: root,
detached: true,
@@ -281,7 +283,7 @@ export async function launchApp({ env = {} } = {}) {
await stop()
throw e
}
return { page, stop, port }
return { page, stop, port, scratch }
}
/**
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env node
// Draws the tray icons into resources/icons/tray-*.png.
//
// A tray cannot be recoloured by the desktop the way a themed icon can, so
// there is one set for a dark panel (a light bubble) and one for a light panel
// (a dark bubble), and main picks by the system's colour scheme. Each set is
// the bubble alone, and the bubble with a red badge carrying the number of
// conversations waiting - 1 to 9, then 9+ - because a tray is the one place
// still in view when a notification has faded, and "something" is a poorer
// answer than "three things".
//
// Run when the artwork changes; the PNGs are committed. Needs rsvg-convert.
import { execFileSync } from 'node:child_process'
import { mkdirSync, writeFileSync, rmSync } from 'node:fs'
import { join, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
const out = join(dirname(fileURLToPath(import.meta.url)), '..', 'resources', 'icons')
const SIZE = 64
// The app's mention red, so the badge is the same colour as the one in the window.
const BADGE = '#e5484d'
const BUBBLE = 'M14 8h36a8 8 0 0 1 8 8v22a8 8 0 0 1-8 8H34L22 58V46h-8a8 8 0 0 1-8-8V16a8 8 0 0 1 8-8z'
function svg(ink, label) {
const badge = label !== null
// The badge sits in a gap cut from the bubble, so it reads against any panel
// without a ring of a colour that panel may not be.
// Without one, three dots are cut from it, which is what makes the shape a
// conversation and not a label.
const mask = badge
? `<mask id="m"><rect width="64" height="64" fill="#fff"/><circle cx="46" cy="18" r="19" fill="#000"/></mask>`
: `<mask id="m"><rect width="64" height="64" fill="#fff"/><circle cx="21" cy="27" r="4" fill="#000"/><circle cx="32" cy="27" r="4" fill="#000"/><circle cx="43" cy="27" r="4" fill="#000"/></mask>`
const size = label && label.length > 1 ? 24 : 30
const text = badge
? `<circle cx="46" cy="18" r="16" fill="${BADGE}"/><text x="46" y="${18 + size * 0.36}" font-family="DejaVu Sans" font-weight="bold" font-size="${size}" text-anchor="middle" fill="#fff">${label}</text>`
: ''
return `<svg xmlns="http://www.w3.org/2000/svg" width="${SIZE}" height="${SIZE}" viewBox="0 0 64 64">${mask}<path d="${BUBBLE}" fill="${ink}" mask="url(#m)"/>${text}</svg>`
}
mkdirSync(out, { recursive: true })
const labels = [null, '1', '2', '3', '4', '5', '6', '7', '8', '9', '9+']
for (const [name, ink] of [['light', '#f1f3f5'], ['dark', '#25282e']]) {
for (const label of labels) {
const file = join(out, `tray-${name}${label === null ? '' : `-${label === '9+' ? 'more' : label}`}.png`)
const tmp = `${file}.svg`
writeFileSync(tmp, svg(ink, label))
execFileSync('rsvg-convert', ['-w', String(SIZE), '-h', String(SIZE), '-o', file, tmp])
rmSync(tmp)
}
}
console.log('tray icons written to', out)
-101
View File
@@ -1,101 +0,0 @@
#!/usr/bin/env bash
# Mirrors a published GitHub release of moho to Gitea, and makes nobilis's
# release of the same version on both hosts. Run here, by hand, once the
# release workflow has published the tag on GitHub - Gitea releases are never
# made by Actions.
#
# scripts/mirror-release.sh v1.0.0
#
# moho on Gitea: the same title, notes, pre-release flag and files as GitHub.
# nobilis, on GitHub and Gitea: tagged at the commit moho's tag points to,
# named after the same version, its notes the version's major features and
# the nobilis lines of the changelog, with the two daemon binaries the
# release's run built.
#
# Safe to run again: a release that exists is updated rather than repeated.
set -euo pipefail
TAG="${1:?usage: scripts/mirror-release.sh vX.Y.Z}"
VERSION="${TAG#v}"
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
GITEA="https://git.salastil.com/api/v1"
TOKEN="$(cat "$HOME/.config/gitea/token")"
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
gitea() { # method path [curl args...]
local method="$1" path="$2"; shift 2
curl -fsS -X "$method" -H "Authorization: token $TOKEN" "$GITEA$path" "$@"
}
# Creates or updates a Gitea release and makes its files exactly those given.
gitea_release() { # repo title notes-file prerelease file...
local repo="$1" title="$2" notes="$3" pre="$4"; shift 4
local body id
body="$(python3 -c 'import json,sys; print(json.dumps({"tag_name": sys.argv[1], "name": sys.argv[2], "body": open(sys.argv[3]).read(), "prerelease": sys.argv[4] == "true"}))' "$TAG" "$title" "$notes" "$pre")"
if id="$(gitea GET "/repos/$repo/releases/tags/$TAG" 2>/dev/null | python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])' 2>/dev/null)"; then
gitea PATCH "/repos/$repo/releases/$id" -H 'Content-Type: application/json' -d "$body" >/dev/null
for asset in $(gitea GET "/repos/$repo/releases/$id/assets" | python3 -c 'import json,sys; print(" ".join(str(a["id"]) for a in json.load(sys.stdin)))'); do
gitea DELETE "/repos/$repo/releases/$id/assets/$asset" >/dev/null
done
else
id="$(gitea POST "/repos/$repo/releases" -H 'Content-Type: application/json' -d "$body" | python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])')"
fi
for f in "$@"; do
gitea POST "/repos/$repo/releases/$id/assets?name=$(basename "$f")" -F "attachment=@$f" >/dev/null
echo " uploaded $(basename "$f") -> Gitea $repo"
done
}
# --- moho -------------------------------------------------------------------
echo "moho $TAG: GitHub -> Gitea"
read -r PRE TITLE < <(gh release view "$TAG" --repo Moho-Chat/moho --json isPrerelease,name -q '"\(.isPrerelease) \(.name)"')
gh release view "$TAG" --repo Moho-Chat/moho --json body -q .body > "$WORK/moho-notes.md"
mkdir -p "$WORK/moho"
gh release download "$TAG" --repo Moho-Chat/moho --dir "$WORK/moho"
git -C "$ROOT" push -q origin "refs/tags/$TAG" 2>/dev/null || true
gitea_release Salastil/moho "$TITLE" "$WORK/moho-notes.md" "$PRE" "$WORK"/moho/*
# --- nobilis ------------------------------------------------------------------
NOBILIS_SHA="$(git -C "$ROOT" rev-parse "$TAG:nobilis")"
echo "nobilis $TAG at ${NOBILIS_SHA:0:7}"
if ! git -C "$ROOT/nobilis" rev-parse -q --verify "refs/tags/$TAG" >/dev/null; then
git -C "$ROOT/nobilis" tag -a "$TAG" "$NOBILIS_SHA" -m "nobilis $VERSION"
fi
git -C "$ROOT/nobilis" push -q github "refs/tags/$TAG"
git -C "$ROOT/nobilis" push -q origin "refs/tags/$TAG"
# Its notes: the version's major features, and the nobilis lines only.
SECTION="$VERSION"
grep -q "^## \[$VERSION\]" "$ROOT/CHANGELOG.md" || SECTION="${VERSION%%-*}"
awk -v v="$SECTION" '
index($0, "## [" v "]") == 1 { on = 1; next }
on && /^## \[/ { exit }
!on { next }
/^### / { fixes = ($0 ~ /^### Fixes/); print; next }
/^- / { if (!fixes || /\[nobilis /) print; next }
{ print }
' "$ROOT/CHANGELOG.md" > "$WORK/nobilis-notes.md"
printf '\nnobilis is the daemon inside moho %s; these are its own builds, for running it on its own.\n' "$VERSION" >> "$WORK/nobilis-notes.md"
# The daemon binaries, from the run that built this release.
RUN="$(gh run list --repo Moho-Chat/moho --workflow release.yml --branch "$TAG" --status success --limit 1 --json databaseId -q '.[0].databaseId')"
[ -n "$RUN" ] || { echo "no successful release run for $TAG" >&2; exit 1; }
mkdir -p "$WORK/nobilis"
gh run download "$RUN" --repo Moho-Chat/moho -n daemon-linux -D "$WORK/d-linux"
gh run download "$RUN" --repo Moho-Chat/moho -n daemon-windows -D "$WORK/d-win"
install -m 755 "$WORK/d-linux/nobilis" "$WORK/nobilis/nobilis-$VERSION-linux-x86_64"
install -m 644 "$WORK/d-win/nobilis.exe" "$WORK/nobilis/nobilis-$VERSION-windows-x86_64.exe"
NOBILIS_FLAGS=(--latest)
[ "$PRE" = "true" ] && NOBILIS_FLAGS=(--prerelease --latest=false)
if gh release view "$TAG" --repo Moho-Chat/nobilis >/dev/null 2>&1; then
gh release edit "$TAG" --repo Moho-Chat/nobilis --notes-file "$WORK/nobilis-notes.md"
gh release upload "$TAG" --repo Moho-Chat/nobilis "$WORK"/nobilis/* --clobber
else
gh release create "$TAG" --repo Moho-Chat/nobilis --verify-tag --title "nobilis $VERSION" \
--notes-file "$WORK/nobilis-notes.md" "${NOBILIS_FLAGS[@]}" "$WORK"/nobilis/*
fi
echo " GitHub Moho-Chat/nobilis $TAG"
gitea_release Salastil/nobilis "nobilis $VERSION" "$WORK/nobilis-notes.md" "$PRE" "$WORK"/nobilis/*
echo "done: moho and nobilis $TAG on GitHub and Gitea"
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env node
/**
* A one-to-one Steam call with somebody on the official client: a scratch app signed in as
* the throwaway account (never the real one) with a fake microphone joins the group's voice room
* and reports what it hears every ten seconds, until ~/.local/share/moho-dev/stop exists.
*
* MODE=call node scripts/probe-steam-call.mjs (or MODE=wait, which answers the first ring)
*
* npx electron-vite build && node scripts/probe-steam-voice.mjs
*
* Needs the throwaway account's block in ~/.config/nobilis/accounts.toml. The app is the
* one built in out/, with its own home and runtime directory, and signs the account in
* for as long as this runs - so nothing else may be signed in as it.
*/
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { execFileSync } from 'node:child_process'
import { launchApp, sleep } from './lib/harness.mjs'
const live = fs.readFileSync(path.join(os.homedir(), '.config/nobilis/accounts.toml'), 'utf8')
const block = live.split(/\n(?=\[)/).find((b) => b.startsWith('[[steam_account]]') && /username\s*=\s*"mohotester"/.test(b))
if (!block) throw new Error('the throwaway account is not in accounts.toml')
const { page, stop, scratch } = await launchApp({
env: { MOHO_UI_SHOTS: '1' },
args: ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream', `--use-file-for-fake-audio-capture=${os.homedir()}/.local/share/moho-dev/speech.wav`],
seed: (home) => {
fs.mkdirSync(path.join(home, 'config/nobilis'), { recursive: true })
fs.writeFileSync(path.join(home, 'config/nobilis/accounts.toml'), block + '\n')
}
})
const say = (...a) => console.log(new Date().toISOString().slice(11, 19), ...a)
const ev = (code) => page.evaluate(code)
try {
// The window onto workspace 2, where the user does not look.
try {
const clients = JSON.parse(execFileSync('hyprctl', ['clients', '-j']).toString())
for (const c of clients.filter((c) => /electron|moho/i.test(c.class + c.title))) execFileSync('hyprctl', ['dispatch', 'movetoworkspacesilent', `2,address:${c.address}`])
} catch {}
let account = ''
for (let i = 0; i < 90 && !account; i++) {
account = await ev(`(() => { const a = window.__mohoShots.state().accounts.find((a) => a.id.startsWith('steam:') && a.state === 'connected'); return a ? a.id : '' })()`)
if (!account) await sleep(1000)
}
say('account', account || 'NOT CONNECTED')
if (!account) throw new Error('not connected')
const rpc = (m, p) => page.evaluate(`window.moho.rpc(${JSON.stringify(m)}, ${JSON.stringify(p)}).catch((e) => ({ error: String(e.message || e) }))`)
page.on('console', (m) => say('console', m.type(), m.text().slice(0, 300)))
const mode = process.env.MODE || 'call'
const stopFile = path.join(os.homedir(), '.local/share/moho-dev/stop')
const state = (expr) => ev(`(() => { const s = window.__mohoShots.state(); return ${expr} })()`)
if (mode === 'call') {
let buffer = ''
for (let i = 0; i < 60 && !buffer; i++) {
buffer = await state(`(s.buffers.find((b) => b.accountId === ${JSON.stringify(account)} && b.kind === 'dm' && b.name === 'Salastil') || {}).id || ''`)
if (!buffer) await sleep(1000)
}
say('calling', buffer)
await ev(`window.__mohoShots.store.callBuffer(${JSON.stringify(buffer)})`)
} else {
say('waiting for a ring')
}
let answered = false
let phase = ''
for (let t = 0; t < 1200 && !fs.existsSync(stopFile); t += 3) {
if (mode === 'wait' && !answered) {
const ring = await state(`s.steamRings && s.steamRings.length ? JSON.stringify(s.steamRings[0]) : ''`)
if (ring) {
say('ringing', ring)
await ev(`window.__mohoShots.store.answerSteamCall(window.__mohoShots.state().steamRings[0])`)
answered = true
}
}
const now = await state(`JSON.stringify({ phase: s.steamVoiceNow ? s.steamVoiceNow.phase : 'idle', toasts: s.toasts.map((t) => t.message || t.text || JSON.stringify(t)) })`)
if (now !== phase) { phase = now; say('state', now) }
const report = await ev(`(async () => {
const v = window.__mohoShots.store.steamVoiceLive
if (!v || !v.pc) return { none: true }
const stats = []
const rep = await v.pc.getStats()
rep.forEach((s) => { if (['outbound-rtp', 'inbound-rtp', 'media-source'].includes(s.type)) stats.push({ type: s.type, packetsSent: s.packetsSent, packetsReceived: s.packetsReceived, audioLevel: s.audioLevel }) })
return { phase: v.phase, rtt: v.rttMs, ice: v.pc.iceConnectionState, stats }
})().catch((e) => ({ error: String(e) }))`)
say('report', JSON.stringify(report))
await sleep(3000)
}
await ev(`window.__mohoShots.store.leaveVoice(${JSON.stringify(account)})`)
await sleep(2000)
say('left the call')
} finally {
await stop()
}
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env node
/**
* The groups Steam says an account is in, after a fresh sign-in: a scratch app signed in as
* the throwaway account (never the real one) with a fake microphone joins the group's voice room
* and reports what it hears every ten seconds, until ~/.local/share/moho-dev/stop exists.
*
* NAME='Biggest Newest Moho Test' WAY=rail node scripts/probe-steam-leave.mjs (WAY=rail or settings)
*
* npx electron-vite build && node scripts/probe-steam-voice.mjs
*
* Needs the throwaway account's block in ~/.config/nobilis/accounts.toml. The app is the
* one built in out/, with its own home and runtime directory, and signs the account in
* for as long as this runs - so nothing else may be signed in as it.
*/
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { execFileSync } from 'node:child_process'
import { launchApp, sleep } from './lib/harness.mjs'
const live = fs.readFileSync(path.join(os.homedir(), '.config/nobilis/accounts.toml'), 'utf8')
const block = live.split(/\n(?=\[)/).find((b) => b.startsWith('[[steam_account]]') && /username\s*=\s*"mohotester"/.test(b))
if (!block) throw new Error('the throwaway account is not in accounts.toml')
const { page, stop, scratch } = await launchApp({
env: { MOHO_UI_SHOTS: '1' },
args: ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream', `--use-file-for-fake-audio-capture=${os.homedir()}/.local/share/moho-dev/speech.wav`],
seed: (home) => {
fs.mkdirSync(path.join(home, 'config/nobilis'), { recursive: true })
fs.writeFileSync(path.join(home, 'config/nobilis/accounts.toml'), block + '\n')
}
})
const say = (...a) => console.log(new Date().toISOString().slice(11, 19), ...a)
const ev = (code) => page.evaluate(code)
try {
// The window onto workspace 2, where the user does not look.
try {
const clients = JSON.parse(execFileSync('hyprctl', ['clients', '-j']).toString())
for (const c of clients.filter((c) => /electron|moho/i.test(c.class + c.title))) execFileSync('hyprctl', ['dispatch', 'movetoworkspacesilent', `2,address:${c.address}`])
} catch {}
let account = ''
for (let i = 0; i < 90 && !account; i++) {
account = await ev(`(() => { const a = window.__mohoShots.state().accounts.find((a) => a.id.startsWith('steam:') && a.state === 'connected'); return a ? a.id : '' })()`)
if (!account) await sleep(1000)
}
say('account', account || 'NOT CONNECTED')
if (!account) throw new Error('not connected')
const rpc = (m, p) => page.evaluate(`window.moho.rpc(${JSON.stringify(m)}, ${JSON.stringify(p)}).catch((e) => ({ error: String(e.message || e) }))`)
page.on('console', (m) => say('console', m.type(), m.text().slice(0, 300)))
await sleep(5000)
say('window groups', await ev(`JSON.stringify(window.__mohoShots.state().groups.filter((g) => g.accountId === ${JSON.stringify(account)}).map((g) => g.name))`))
say('daemon groups', JSON.stringify(((await rpc('steamChatGroups', { accountId: account })) ?? []).map((g) => g.name)))
say('steam channels', await ev(`JSON.stringify(window.__mohoShots.state().buffers.filter((b) => b.accountId === ${JSON.stringify(account)} && b.kind === 'channel').map((b) => b.name))`))
} finally {
await stop()
}
+127
View File
@@ -0,0 +1,127 @@
#!/usr/bin/env node
/**
* Leaving a Steam group through the window, the way a person does: a scratch app signed in as
* the throwaway account (never the real one) with a fake microphone joins the group's voice room
* and reports what it hears every ten seconds, until ~/.local/share/moho-dev/stop exists.
*
* NAME='Biggest Newest Moho Test' WAY=rail node scripts/probe-steam-leave.mjs (WAY=rail or settings)
*
* npx electron-vite build && node scripts/probe-steam-voice.mjs
*
* Needs the throwaway account's block in ~/.config/nobilis/accounts.toml. The app is the
* one built in out/, with its own home and runtime directory, and signs the account in
* for as long as this runs - so nothing else may be signed in as it.
*/
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { execFileSync } from 'node:child_process'
import { launchApp, sleep } from './lib/harness.mjs'
const live = fs.readFileSync(path.join(os.homedir(), '.config/nobilis/accounts.toml'), 'utf8')
const block = live.split(/\n(?=\[)/).find((b) => b.startsWith('[[steam_account]]') && /username\s*=\s*"mohotester"/.test(b))
if (!block) throw new Error('the throwaway account is not in accounts.toml')
const { page, stop, scratch } = await launchApp({
env: { MOHO_UI_SHOTS: '1' },
args: ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream', `--use-file-for-fake-audio-capture=${os.homedir()}/.local/share/moho-dev/speech.wav`],
seed: (home) => {
fs.mkdirSync(path.join(home, 'config/nobilis'), { recursive: true })
fs.writeFileSync(path.join(home, 'config/nobilis/accounts.toml'), block + '\n')
}
})
const say = (...a) => console.log(new Date().toISOString().slice(11, 19), ...a)
const ev = (code) => page.evaluate(code)
try {
// The window onto workspace 2, where the user does not look.
try {
const clients = JSON.parse(execFileSync('hyprctl', ['clients', '-j']).toString())
for (const c of clients.filter((c) => /electron|moho/i.test(c.class + c.title))) execFileSync('hyprctl', ['dispatch', 'movetoworkspacesilent', `2,address:${c.address}`])
} catch {}
let account = ''
for (let i = 0; i < 90 && !account; i++) {
account = await ev(`(() => { const a = window.__mohoShots.state().accounts.find((a) => a.id.startsWith('steam:') && a.state === 'connected'); return a ? a.id : '' })()`)
if (!account) await sleep(1000)
}
say('account', account || 'NOT CONNECTED')
if (!account) throw new Error('not connected')
const rpc = (m, p) => page.evaluate(`window.moho.rpc(${JSON.stringify(m)}, ${JSON.stringify(p)}).catch((e) => ({ error: String(e.message || e) }))`)
page.on('console', (m) => say('console', m.type(), m.text().slice(0, 300)))
const name = process.env.NAME ?? ''
const way = process.env.WAY ?? 'rail'
const state = (expr) => ev(`(() => { const s = window.__mohoShots.state(); return ${expr} })()`)
if (process.env.CREATE) say('created', JSON.stringify(await rpc('steamChatGroupAction', { accountId: account, action: 'create', name })))
let group = null
for (let i = 0; i < 60 && !group; i++) {
group = await state(`(s.groups.find((g) => g.accountId === ${JSON.stringify(account)} && g.name === ${JSON.stringify(name)}) || null)`)
if (!group) await sleep(1000)
}
say('group', JSON.stringify(group))
if (process.env.VOICE && group) {
// In the group's voice room when it is left.
const number = group.id.split('steamgroup:')[1]
say('voice room', JSON.stringify(await rpc('steamChatGroupAction', { accountId: account, action: 'createRoom', groupId: number, name: 'talk', voice: true })))
let rooms = []
for (let i = 0; i < 20 && !rooms.length; i++) {
rooms = await rpc('steamVoiceRooms', { accountId: account, groupId: number })
if (!rooms.length) await sleep(500)
}
await ev(`window.__mohoShots.store.joinSteamVoice(${JSON.stringify(account)}, ${JSON.stringify(number)}, ${JSON.stringify(rooms[0].roomId)})`)
for (let i = 0; i < 30; i++) {
if ((await state(`s.steamVoiceNow ? s.steamVoiceNow.phase : 'idle'`)) === 'connected') break
await sleep(500)
}
say('in voice', await state(`s.steamVoiceNow ? s.steamVoiceNow.phase : 'idle'`))
await sleep(3000)
}
if (!group) throw new Error('the group is not in the window')
await sleep(4000)
const click = (text) => ev(`(() => { const e = [...document.querySelectorAll('button, [role=menuitem]')].find((b) => b.textContent.trim().endsWith(${JSON.stringify(text)})); if (!e) return false; e.click(); return true })()`)
if (way === 'room') {
// A room's own menu: what it offers is leaving the group.
await ev(`window.__mohoShots.store.selectGroup(${JSON.stringify(group.id)})`)
let room = null
for (let i = 0; i < 30 && !room; i++) {
room = await state(`(s.buffers.find((b) => b.groupId === ${JSON.stringify(group.id)} && b.kind === 'channel') || null)`)
if (!room) await sleep(500)
}
say('room', JSON.stringify(room && room.name))
await sleep(800)
say('menu opened', await ev(`(() => { const row = [...document.querySelectorAll('.buffer-row')][0]; if (!row) return false; const r = row.getBoundingClientRect(); row.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: r.x + 20, clientY: r.y + 10 })); return true })()`))
await sleep(400)
say('menu', JSON.stringify(await ev(`[...document.querySelectorAll('.context-menu button, .context-menu [role=menuitem]')].map((e) => e.textContent.trim())`)))
say('clicked', await click('Leave group…'))
} else if (way === 'rail') {
say('menu opened', await ev(`(() => { const tile = [...document.querySelectorAll('.rail-tile')].find((t) => t.getAttribute('aria-label') === ${JSON.stringify(name)}); if (!tile) return false; const r = tile.getBoundingClientRect(); tile.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: r.x + 10, clientY: r.y + 10 })); return true })()`))
await sleep(400)
say('menu', JSON.stringify(await ev(`[...document.querySelectorAll('.context-menu button, .context-menu [role=menuitem]')].map((e) => e.textContent.trim())`)))
say('clicked Leave server', await click('Leave server'))
} else {
say('menu opened', await ev(`(() => { const tile = [...document.querySelectorAll('.rail-tile')].find((t) => t.getAttribute('aria-label') === ${JSON.stringify(name)}); if (!tile) return false; const r = tile.getBoundingClientRect(); tile.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: r.x + 10, clientY: r.y + 10 })); return true })()`))
await sleep(400)
say('clicked Group settings', await click('Group settings'))
await sleep(800)
say('clicked Leave group', await click('Leave group'))
}
await sleep(600)
say('buttons now', JSON.stringify(await ev(`[...document.querySelectorAll('button')].map((b) => b.textContent.trim()).filter((t) => /leave/i.test(t))`)))
// The confirmation counts down before it will leave ("Leave in 10"): waited out, as a person has to.
for (let i = 0; i < 40; i++) {
if (await ev(`[...document.querySelectorAll('button')].some((b) => b.textContent.trim() === 'Leave' && !b.disabled)`)) break
await sleep(500)
}
// The dialog's own Leave (or the inline confirm's).
say('confirmed', await ev(`(() => { const all = [...document.querySelectorAll('button')].filter((b) => b.textContent.trim() === 'Leave'); const e = all[all.length - 1]; if (!e) return false; e.click(); return true })()`))
for (let i = 0; i < 30; i++) {
const still = await state(`s.groups.some((g) => g.id === ${JSON.stringify(group.id)})`)
if (!still) break
await sleep(500)
}
say('still in the window', await state(`s.groups.some((g) => g.id === ${JSON.stringify(group.id)})`))
say('toasts', await state(`JSON.stringify(s.toasts.map((t) => t.message || t.text || JSON.stringify(t)))`))
say('voice after', await state(`s.steamVoiceNow ? s.steamVoiceNow.phase : 'idle'`))
const held = await rpc('steamChatGroups', { accountId: account })
say('daemon still holds', JSON.stringify((held ?? []).map((g) => g.name)))
} finally {
await stop()
}
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env node
/**
* Signing in to Steam by scanning a QR code with the phone app, through the window as a person
* does it: a scratch app with no accounts, Accounts -> Steam -> "Sign in with a QR code". The code is
* photographed to <output directory>/qr-N.png each time Steam replaces it, for somebody to scan,
* and the run ends when the account is signed in or when STOP exists. The scratch home is thrown
* away, so the token Steam hands back is not kept.
*
* node scripts/probe-steam-qr.mjs <output directory>
*/
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { execFileSync } from 'node:child_process'
import { launchApp, sleep } from './lib/harness.mjs'
const out = process.argv[2] ?? '.'
fs.mkdirSync(out, { recursive: true })
const stopFile = path.join(os.homedir(), '.local/share/moho-dev/stop')
const { page, stop } = await launchApp({ env: { MOHO_UI_SHOTS: '1' } })
const say = (...a) => console.log(new Date().toISOString().slice(11, 19), ...a)
const ev = (code) => page.evaluate(code)
const shot = async (name) => {
const { data } = await page.call('Page.captureScreenshot', { format: 'png' })
fs.writeFileSync(path.join(out, name), Buffer.from(data, 'base64'))
}
try {
try {
const clients = JSON.parse(execFileSync('hyprctl', ['clients', '-j']).toString())
for (const c of clients.filter((c) => /electron|moho/i.test(c.class + c.title))) execFileSync('hyprctl', ['dispatch', 'movetoworkspacesilent', `2,address:${c.address}`])
} catch {}
await sleep(2500)
await page.call('Emulation.setDeviceMetricsOverride', { width: 900, height: 900, deviceScaleFactor: 1, mobile: false })
// Everything the daemon says about the sign-in, kept as it comes.
await ev(`window.__events = []; window.moho.onEvent((e) => { if (String(e.event).startsWith('steamLogin') || e.event === 'accountsChanged') window.__events.push({ at: Date.now(), event: e.event, data: JSON.stringify(e.data).slice(0, 300) }) })`)
await ev(`window.__mohoShots.store.setActivePanel('accounts')`)
await sleep(800)
const click = (text) => ev(`(() => { const e = [...document.querySelectorAll('button')].find((b) => b.textContent.trim().includes(${JSON.stringify(text)})); if (!e) return false; e.click(); return true })()`)
say('add form', JSON.stringify(await ev(`[...document.querySelectorAll('button')].map((b) => b.textContent.trim()).filter(Boolean).slice(0, 30)`)))
say('clicked Steam', await click('Steam'))
await sleep(600)
say('clicked QR', await click('Sign in with a QR code'))
let last = ''
let n = 0
for (let t = 0; t < 600 && !fs.existsSync(stopFile); t += 2) {
const src = await ev(`document.querySelector('img.qr-image')?.src ?? ''`)
if (src && src !== last) {
last = src
n++
await sleep(300)
await shot(`qr-${n}.png`)
say('QR', n, 'drawn', src.slice(-40))
}
const seen = await ev(`window.__events.splice(0)`).catch(() => [])
for (const e of seen) say('event', e.event, e.data)
const accounts = await ev(`JSON.stringify(window.__mohoShots.state().accounts.filter((a) => a.service === 'steam').map((a) => [a.id, a.state]))`)
if (accounts !== '[]') {
say('signed in', accounts)
break
}
const toasts = await ev(`JSON.stringify(window.__mohoShots.state().toasts.map((x) => x.message || x.text || JSON.stringify(x)))`)
if (toasts !== '[]' && toasts !== (globalThis.__t ?? '')) { globalThis.__t = toasts; say('toasts', toasts) }
await sleep(2000)
}
await sleep(4000)
for (const e of (await ev(`window.__events.splice(0)`).catch(() => []))) say('event', e.event, e.data)
say('accounts after', await ev(`JSON.stringify(window.__mohoShots.state().accounts.filter((a) => a.service === 'steam').map((a) => [a.id, a.state, a.displayName]))`))
await shot('qr-after.png')
} finally {
await stop()
}
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env node
/**
* Steam voice in a group that already exists, with somebody on the official client in the room too: a scratch app signed in as
* the throwaway account (never the real one) with a fake microphone joins the group's voice room
* and reports what it hears every ten seconds, until ~/.local/share/moho-dev/stop exists.
*
* GROUP=78995476 ROOM=316282066 node scripts/probe-steam-voice-join.mjs
*
* npx electron-vite build && node scripts/probe-steam-voice.mjs
*
* Needs the throwaway account's block in ~/.config/nobilis/accounts.toml. The app is the
* one built in out/, with its own home and runtime directory, and signs the account in
* for as long as this runs - so nothing else may be signed in as it.
*/
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { execFileSync } from 'node:child_process'
import { launchApp, sleep } from './lib/harness.mjs'
const live = fs.readFileSync(path.join(os.homedir(), '.config/nobilis/accounts.toml'), 'utf8')
const block = live.split(/\n(?=\[)/).find((b) => b.startsWith('[[steam_account]]') && /username\s*=\s*"mohotester"/.test(b))
if (!block) throw new Error('the throwaway account is not in accounts.toml')
const { page, stop, scratch } = await launchApp({
env: { MOHO_UI_SHOTS: '1' },
args: ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream', `--use-file-for-fake-audio-capture=${os.homedir()}/.local/share/moho-dev/speech.wav`],
seed: (home) => {
fs.mkdirSync(path.join(home, 'config/nobilis'), { recursive: true })
fs.writeFileSync(path.join(home, 'config/nobilis/accounts.toml'), block + '\n')
}
})
const say = (...a) => console.log(new Date().toISOString().slice(11, 19), ...a)
const ev = (code) => page.evaluate(code)
try {
// The window onto workspace 2, where the user does not look.
try {
const clients = JSON.parse(execFileSync('hyprctl', ['clients', '-j']).toString())
for (const c of clients.filter((c) => /electron|moho/i.test(c.class + c.title))) execFileSync('hyprctl', ['dispatch', 'movetoworkspacesilent', `2,address:${c.address}`])
} catch {}
let account = ''
for (let i = 0; i < 90 && !account; i++) {
account = await ev(`(() => { const a = window.__mohoShots.state().accounts.find((a) => a.id.startsWith('steam:') && a.state === 'connected'); return a ? a.id : '' })()`)
if (!account) await sleep(1000)
}
say('account', account || 'NOT CONNECTED')
if (!account) throw new Error('not connected')
const rpc = (m, p) => page.evaluate(`window.moho.rpc(${JSON.stringify(m)}, ${JSON.stringify(p)}).catch((e) => ({ error: String(e.message || e) }))`)
page.on('console', (m) => say('console', m.type(), m.text().slice(0, 300)))
const group = process.env.GROUP
const roomId = process.env.ROOM
const stopFile = path.join(os.homedir(), '.local/share/moho-dev/stop')
for (let i = 0; i < 40; i++) {
const rooms = await rpc('steamVoiceRooms', { accountId: account, groupId: group })
if (Array.isArray(rooms) && rooms.length) break
await sleep(500)
}
await ev(`window.__mohoShots.store.joinSteamVoice(${JSON.stringify(account)}, ${JSON.stringify(group)}, ${JSON.stringify(roomId)})`)
let phase = ''
let lastToast = ''
for (let i = 0; i < 80; i++) {
const now = await ev(`(() => { const s = window.__mohoShots.state(); return JSON.stringify({ phase: s.steamVoiceNow ? s.steamVoiceNow.phase : 'idle', toasts: s.toasts.map((t) => t.message || t.text || JSON.stringify(t)) }) })()`)
if (now !== lastToast) { lastToast = now; say('fast', now) }
await sleep(250)
}
for (let t = 0; t < 1200 && !fs.existsSync(stopFile); t += 10) {
const now = await ev(`(() => { const s = window.__mohoShots.state(); return s.steamVoiceNow ? s.steamVoiceNow.phase : 'idle' })()`)
if (now !== phase) { phase = now; say('phase', now) }
const report = await ev(`(async () => {
const v = window.__mohoShots.store.steamVoiceLive
if (!v) return { none: true }
const stats = []
const rep = await v.pc.getStats()
rep.forEach((s) => { if (['outbound-rtp', 'inbound-rtp', 'media-source', 'remote-inbound-rtp'].includes(s.type)) stats.push({ type: s.type, packetsSent: s.packetsSent, bytesSent: s.bytesSent, packetsReceived: s.packetsReceived, packetsLost: s.packetsLost, ssrc: s.ssrc, audioLevel: s.audioLevel, energy: s.totalAudioEnergy, rtt: s.roundTripTime }) })
return { statuses: v.statuses ? [...v.statuses.entries()] : null, session: v.session, owners: v.owners ? [...v.owners.entries()] : null, track: v.mic ? v.mic.getAudioTracks().map((t) => [t.enabled, t.muted, t.readyState]) : null, phase: v.phase, rtt: v.rttMs, ice: v.pc.iceConnectionState, speakers: window.__mohoShots.state().steamVoiceNow?.speakers, stats }
})().catch((e) => ({ error: String(e) }))`)
say('report', JSON.stringify(report))
say('toasts', await ev(`JSON.stringify(window.__mohoShots.state().toasts.map((t) => t.message || t.text || t))`))
say('rooms', JSON.stringify(await rpc('steamVoiceRooms', { accountId: account, groupId: group })))
await sleep(3000)
}
await ev(`window.__mohoShots.store.leaveVoice(${JSON.stringify(account)})`)
await sleep(2000)
say('left voice; the group is left in place')
} finally {
await stop()
}
+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env node
/**
* Steam voice against real Steam, through the real window: a scratch app signed in as
* the throwaway account (never the real one) with a fake microphone makes a group with a
* voice room, joins its voice, reports how it went, leaves, and leaves the group.
*
* npx electron-vite build && node scripts/probe-steam-voice.mjs
*
* Needs the throwaway account's block in ~/.config/nobilis/accounts.toml. The app is the
* one built in out/, with its own home and runtime directory, and signs the account in
* for as long as this runs - so nothing else may be signed in as it.
*/
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { execFileSync } from 'node:child_process'
import { launchApp, sleep } from './lib/harness.mjs'
const live = fs.readFileSync(path.join(os.homedir(), '.config/nobilis/accounts.toml'), 'utf8')
const block = live.split(/\n(?=\[)/).find((b) => b.startsWith('[[steam_account]]') && /username\s*=\s*"mohotester"/.test(b))
if (!block) throw new Error('the throwaway account is not in accounts.toml')
const { page, stop, scratch } = await launchApp({
env: { MOHO_UI_SHOTS: '1' },
args: ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream'],
seed: (home) => {
fs.mkdirSync(path.join(home, 'config/nobilis'), { recursive: true })
fs.writeFileSync(path.join(home, 'config/nobilis/accounts.toml'), block + '\n')
}
})
const say = (...a) => console.log(new Date().toISOString().slice(11, 19), ...a)
const ev = (code) => page.evaluate(code)
try {
// The window onto workspace 2, where the user does not look.
try {
const clients = JSON.parse(execFileSync('hyprctl', ['clients', '-j']).toString())
for (const c of clients.filter((c) => /electron|moho/i.test(c.class + c.title))) execFileSync('hyprctl', ['dispatch', 'movetoworkspacesilent', `2,address:${c.address}`])
} catch {}
let account = ''
for (let i = 0; i < 90 && !account; i++) {
account = await ev(`(() => { const a = window.__mohoShots.state().accounts.find((a) => a.id.startsWith('steam:') && a.state === 'connected'); return a ? a.id : '' })()`)
if (!account) await sleep(1000)
}
say('account', account || 'NOT CONNECTED')
if (!account) throw new Error('not connected')
const rpc = (m, p) => page.evaluate(`window.moho.rpc(${JSON.stringify(m)}, ${JSON.stringify(p)}).catch((e) => ({ error: String(e.message || e) }))`)
const made = await rpc('steamChatGroupAction', { accountId: account, action: 'create', name: 'voice probe' })
say('created', JSON.stringify(made))
const group = String(made.groupId).split('steamgroup:')[1]
say('room', JSON.stringify(await rpc('steamChatGroupAction', { accountId: account, action: 'createRoom', groupId: group, name: 'talk', voice: true })))
let rooms = []
for (let i = 0; i < 20 && !rooms.length; i++) {
rooms = await rpc('steamVoiceRooms', { accountId: account, groupId: group })
if (!rooms.length) await sleep(500)
}
say('voice rooms', JSON.stringify(rooms))
const roomId = rooms[0]?.roomId
await sleep(1500)
await ev(`window.__mohoShots.store.joinSteamVoice(${JSON.stringify(account)}, ${JSON.stringify(group)}, ${JSON.stringify(roomId)})`)
let phase = ''
const seen = []
for (let i = 0; i < 120; i++) {
const now = await ev(`(() => { const s = window.__mohoShots.state(); return s.steamVoiceNow ? s.steamVoiceNow.phase : 'idle' })()`)
if (now !== phase) { phase = now; seen.push(now); say('phase', now) }
if (now === 'connected') break
await sleep(500)
}
await sleep(4000)
const report = await ev(`(async () => {
const v = window.__mohoShots.store.steamVoiceLive
const stats = []
const rep = await v.pc.getStats()
rep.forEach((s) => { if (['outbound-rtp', 'inbound-rtp', 'candidate-pair'].includes(s.type) && (s.type !== 'candidate-pair' || s.nominated)) stats.push({ type: s.type, kind: s.kind, packetsSent: s.packetsSent, bytesSent: s.bytesSent, packetsReceived: s.packetsReceived, rtt: s.currentRoundTripTime, state: s.state, ssrc: s.ssrc }) })
return { phase: v.phase, level: v.level, rtt: v.rttMs, ice: v.pc.iceConnectionState, voiceChatId: v.voiceChatId, session: v.session, stats, mic: !!v.mic, sessions: window.__mohoShots.state().voiceSessions }
})().catch((e) => ({ error: String(e) }))`)
say('report', JSON.stringify(report, null, 1))
say('rooms while in', JSON.stringify(await rpc('steamVoiceRooms', { accountId: account, groupId: group })))
await ev(`window.__mohoShots.store.leaveVoice(${JSON.stringify(account)})`)
await sleep(2000)
say('rooms after leaving', JSON.stringify(await rpc('steamVoiceRooms', { accountId: account, groupId: group })))
say('now', await ev(`JSON.stringify(window.__mohoShots.state().steamVoiceNow)`))
say('left group', JSON.stringify(await rpc('leaveGroup', { groupId: made.groupId })))
} finally {
await stop()
}
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env bash
# Makes nobilis's release of the same version as one of moho's.
#
# Run by the maintainer once the release workflow has published moho's tag:
# the daemon is its own repository with its own releases, and the job that
# builds it holds a token that can only release moho.
#
# scripts/release-nobilis.sh v1.0.0
# scripts/release-nobilis.sh v1.0.0 --keep DIR leave the notes and the two
# daemon binaries in DIR
#
# nobilis is tagged at the commit moho's tag points to, named after the same
# version, its notes the version's major features and the nobilis lines of the
# changelog, with the two daemon binaries the release's run built. Safe to run
# again: a release that exists is updated rather than repeated.
set -euo pipefail
TAG="${1:?usage: scripts/release-nobilis.sh vX.Y.Z [--keep DIR]}"
KEEP=""
[ "${2:-}" = "--keep" ] && KEEP="${3:?--keep needs a directory}"
VERSION="${TAG#v}"
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
read -r PRE < <(gh release view "$TAG" --repo Moho-Chat/moho --json isPrerelease -q .isPrerelease)
NOBILIS_SHA="$(git -C "$ROOT" rev-parse "$TAG:nobilis")"
echo "nobilis $TAG at ${NOBILIS_SHA:0:7}"
if ! git -C "$ROOT/nobilis" rev-parse -q --verify "refs/tags/$TAG" >/dev/null; then
git -C "$ROOT/nobilis" tag -a "$TAG" "$NOBILIS_SHA" -m "nobilis $VERSION"
fi
git -C "$ROOT/nobilis" push -q github "refs/tags/$TAG"
# Its notes: the version's major features, and the nobilis lines only.
SECTION="$VERSION"
grep -q "^## \[$VERSION\]" "$ROOT/CHANGELOG.md" || SECTION="${VERSION%%-*}"
awk -v v="$SECTION" '
index($0, "## [" v "]") == 1 { on = 1; next }
on && /^## \[/ { exit }
!on { next }
/^### / { fixes = ($0 ~ /^### Fixes/); print; next }
/^- / { if (!fixes || /\[nobilis /) print; next }
{ print }
' "$ROOT/CHANGELOG.md" > "$WORK/nobilis-notes.md"
printf '\nnobilis is the daemon inside moho %s; these are its own builds, for running it on its own.\n' "$VERSION" >> "$WORK/nobilis-notes.md"
# The daemon binaries, from the run that built this release.
RUN="$(gh run list --repo Moho-Chat/moho --workflow release.yml --branch "$TAG" --status success --limit 1 --json databaseId -q '.[0].databaseId')"
[ -n "$RUN" ] || { echo "no successful release run for $TAG" >&2; exit 1; }
mkdir -p "$WORK/nobilis"
gh run download "$RUN" --repo Moho-Chat/moho -n daemon-linux -D "$WORK/d-linux"
gh run download "$RUN" --repo Moho-Chat/moho -n daemon-windows -D "$WORK/d-win"
install -m 755 "$WORK/d-linux/nobilis" "$WORK/nobilis/nobilis-$VERSION-linux-x86_64"
install -m 644 "$WORK/d-win/nobilis.exe" "$WORK/nobilis/nobilis-$VERSION-windows-x86_64.exe"
NOBILIS_FLAGS=(--latest)
[ "$PRE" = "true" ] && NOBILIS_FLAGS=(--prerelease --latest=false)
if gh release view "$TAG" --repo Moho-Chat/nobilis >/dev/null 2>&1; then
gh release edit "$TAG" --repo Moho-Chat/nobilis --notes-file "$WORK/nobilis-notes.md"
gh release upload "$TAG" --repo Moho-Chat/nobilis "$WORK"/nobilis/* --clobber
else
gh release create "$TAG" --repo Moho-Chat/nobilis --verify-tag --title "nobilis $VERSION" \
--notes-file "$WORK/nobilis-notes.md" "${NOBILIS_FLAGS[@]}" "$WORK"/nobilis/*
fi
echo " GitHub Moho-Chat/nobilis $TAG"
if [ -n "$KEEP" ]; then
mkdir -p "$KEEP"
cp "$WORK/nobilis-notes.md" "$KEEP/"
cp -r "$WORK/nobilis" "$KEEP/"
fi
+167
View File
@@ -0,0 +1,167 @@
#!/usr/bin/env node
/**
* Checks that a reader scrolling through a long unread run is not put back.
*
* The "N new messages since" bar sits over the top of the log. What the list
* remembers about where the reader is came from asking the page what is at its
* top edge - which, while the bar is up, is the bar. So the place stopped being
* kept up to date the moment the bar appeared, and the next thing to change
* size (a card arriving, a picture loading) put the view back where the
* reader had been when it appeared.
*
* npm run test:scroll (builds first; needs the daemon built too)
*/
import { fakeIrc, launchApp, openIrcChannel, sleep, until } from './lib/harness.mjs'
let failures = 0
const check = (ok, what, detail = '') => {
console.log(`${ok ? 'ok ' : 'FAIL'} ${what}${ok ? '' : detail ? ` - ${detail}` : ''}`)
if (!ok) failures++
}
setTimeout(() => {
console.log('FAIL timed out')
process.exit(1)
}, 90000).unref()
const irc = await fakeIrc({
people: ['bob'],
onJoin: (channel, _nick, send) => send(`:bob!b@h PRIVMSG ${channel} :hello there`)
})
const { page, stop } = await launchApp({ env: { MOHO_UI_SHOTS: '1' } })
try {
await until(page, 'window.__mohoShots', 'the harness hook')
await openIrcChannel(page, { port: irc.address().port, nick: 'checker', channels: ['#lobby', '#other'], waitFor: 'hello there' })
// Three hundred messages, the last two hundred of them unread.
await page.evaluate(`(() => {
const shots = window.__mohoShots
const s = shots.state()
const id = s.activeBufferId
const now = Math.floor(Date.now() / 1000)
const list = Array.from({ length: 300 }, (_, n) => ({
id: 'm' + n, bufferId: id, from: n % 3 ? 'bob' : 'carol', senderId: n % 3 ? 'bob' : 'carol',
body: 'message number ' + n + ' with a little text in it', ts: now - 40000 + n * 60,
isAction: false, isHighlight: false, kind: 'chat', isOwn: false
}))
shots.patch({
messagesByBuffer: { ...s.messagesByBuffer, [id]: list },
dividerTsByBuffer: { ...s.dividerTsByBuffer, [id]: list[99].ts }
})
})()`)
// Two hundred unread is more than a screenful: opened at its end, as
// Discord does, with the bar saying how much is above and not the log
// dropped hundreds of messages up.
await until(page, `!!document.querySelector('.unread-bar')`, 'the unread bar')
await sleep(600)
const opened = await page.evaluate(`(() => {
const el = document.querySelector('.messagelist-scroll')
return { fromBottom: el.scrollHeight - el.scrollTop - el.clientHeight, line: !!document.querySelector('.new-divider'), bar: document.querySelector('.unread-bar-text')?.textContent }
})()`)
check(opened.fromBottom < 8 && !opened.line, 'a long unread run opens at the end of the conversation', JSON.stringify(opened))
check(/^200 new messages/.test(opened.bar ?? ''), 'and the bar says how much there is', opened.bar)
await page.evaluate(`document.querySelector('.unread-bar-text').click()`)
await until(page, `!!document.querySelector('.new-divider')`, 'the New line after pressing the bar')
await sleep(600)
// Reading down past the line, the way a wheel does: the bar comes up.
await page.evaluate(`(async () => {
const el = document.querySelector('.messagelist-scroll')
el.dispatchEvent(new WheelEvent('wheel', { deltaY: 100, bubbles: true }))
for (let i = 0; i < 8; i++) {
el.scrollTop += 120
el.dispatchEvent(new WheelEvent('wheel', { deltaY: 120, bubbles: true }))
await new Promise((r) => setTimeout(r, 60))
}
})()`)
await until(page, `!!document.querySelector('.unread-bar')`, 'the unread bar')
// Further down, with the bar over the top of the log the whole way.
await page.evaluate(`(async () => {
const el = document.querySelector('.messagelist-scroll')
for (let i = 0; i < 12; i++) {
el.scrollTop += 150
el.dispatchEvent(new WheelEvent('wheel', { deltaY: 150, bubbles: true }))
await new Promise((r) => setTimeout(r, 60))
}
})()`)
await sleep(300)
const before = await page.evaluate(`document.querySelector('.messagelist-scroll').scrollTop`)
// Something above the reader settles taller - a card arriving, a picture
// loading. The row under the reader's eye is what must stay put.
const moved = await page.evaluate(`(async () => {
const el = document.querySelector('.messagelist-scroll')
const box = el.getBoundingClientRect()
const rows = [...el.querySelectorAll('[data-msg-id]')]
const watched = rows.find((r) => r.getBoundingClientRect().top > box.top + 60)
const was = watched.getBoundingClientRect().top - box.top
const above = rows.find((r) => r.getBoundingClientRect().bottom < box.top - 50)
above.style.minHeight = (above.getBoundingClientRect().height + 240) + 'px'
await new Promise((r) => setTimeout(r, 400))
return { id: watched.dataset.msgId, drift: watched.getBoundingClientRect().top - box.top - was }
})()`)
check(Math.abs(moved.drift) < 2, 'a row above growing leaves the row being read where it was', `moved ${moved.drift}px`)
// And the position itself did not fall back towards where the bar appeared.
const after = await page.evaluate(`document.querySelector('.messagelist-scroll').scrollTop`)
check(after >= before - 4, 'the view did not go back up the log', `${before} -> ${after}`)
// Leaving, and coming back after more has been said. The line was kept from
// the first visit, so the return went up the log to a place nothing was
// unread any more.
const ids = await page.evaluate(`(() => {
const s = window.__mohoShots.state()
return { lobby: s.activeBufferId, other: s.buffers.find((b) => b.name.endsWith('#other')).id }
})()`)
const said = (count) => `(() => {
const shots = window.__mohoShots
const s = shots.state()
const id = ${JSON.stringify(ids.lobby)}
const base = Math.max(...s.messagesByBuffer[id].map((m) => m.ts)) + 1
const more = Array.from({ length: ${count} }, (_, n) => ({
id: 'later' + Date.now() + '-' + n, bufferId: id, from: 'bob', senderId: 'bob', body: 'said while away ' + n, ts: base + n,
isAction: false, isHighlight: false, kind: 'chat', isOwn: false
}))
shots.patch({
messagesByBuffer: { ...s.messagesByBuffer, [id]: [...s.messagesByBuffer[id], ...more] },
buffers: s.buffers.map((b) => (b.id === id ? { ...b, unread: ${count} } : b))
})
})()`
const away = async (count) => {
await page.evaluate(`window.__mohoShots.store.selectBuffer(${JSON.stringify(ids.other)}, false)`)
await sleep(500)
await page.evaluate(said(count))
await page.evaluate(`window.__mohoShots.store.selectBuffer(${JSON.stringify(ids.lobby)}, false)`)
await sleep(1200)
return page.evaluate(`(() => {
const el = document.querySelector('.messagelist-scroll')
const line = document.querySelector('.new-divider')
const rows = [...el.querySelectorAll('[data-msg-id]')]
const after = line ? rows.filter((r) => line.compareDocumentPosition(r) & Node.DOCUMENT_POSITION_FOLLOWING).length : -1
return { fromBottom: el.scrollHeight - el.scrollTop - el.clientHeight, line: !!line, after, bar: document.querySelector('.unread-bar-text')?.textContent ?? '' }
})()`)
}
// A few unread: opens at the first of them, and the line is this visit's -
// thirty rows under it, not the two hundred of the visit before.
const few = await away(30)
check(few.line && few.after === 30, 'a short unread run opens at its first message, with the line where this visit began', JSON.stringify(few))
// A great many: opens at the end, with the bar to go back by.
const many = await away(100)
check(many.fromBottom < 8, 'a long one opens at the end and not hundreds of messages up', JSON.stringify(many))
check(/^100 new messages/.test(many.bar), 'with the bar to go back by', many.bar)
// Nothing unread: the end.
await page.evaluate(`window.__mohoShots.store.selectBuffer(${JSON.stringify(ids.other)}, false)`)
await sleep(500)
await page.evaluate(`window.__mohoShots.store.selectBuffer(${JSON.stringify(ids.lobby)}, false)`)
await sleep(1000)
const nothing = await page.evaluate(`(() => { const el = document.querySelector('.messagelist-scroll'); return { fromBottom: el.scrollHeight - el.scrollTop - el.clientHeight, line: !!document.querySelector('.new-divider') } })()`)
check(nothing.fromBottom < 8 && !nothing.line, 'a conversation left read and returned to is at its end', JSON.stringify(nothing))
} finally {
await stop()
irc.close()
}
console.log(failures ? `${failures} FAILED` : 'all passed')
process.exit(failures ? 1 : 0)
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env node
/**
* Photographs a Steam chat group as the window shows it: a server on the rail
* with its rooms as channels and its members listed, then the group's settings
* dialog on each of its tabs. Made-up state on a fake IRC server, in a scratch
* home; the daemon's answers for the group are stood in for here.
*
* node scripts/shot-steam-chatgroups.mjs <output directory>
*/
import fs from 'node:fs'
import path from 'node:path'
import { fakeIrc, launchApp, openIrcChannel, sleep } from './lib/harness.mjs'
const out = process.argv[2] ?? '.'
fs.mkdirSync(out, { recursive: true })
const irc = await fakeIrc({ people: ['alice'], onJoin: (c, _n, send) => send(`:alice!u@h PRIVMSG ${c} :hello there`) })
const { page, stop } = await launchApp({ env: { MOHO_UI_SHOTS: '1' } })
const shot = async (name) => {
const { data } = await page.call('Page.captureScreenshot', { format: 'png' })
fs.writeFileSync(path.join(out, name), Buffer.from(data, 'base64'))
}
try {
await openIrcChannel(page, { port: irc.address().port, nick: 'checker', channels: ['#ui'], waitFor: 'hello there' })
await page.call('Emulation.setDeviceMetricsOverride', { width: 1280, height: 800, deviceScaleFactor: 1, mobile: false })
await page.evaluate(`(() => {
const group = {
id: '7', railId: 'steam:me|steamgroup:7', name: 'Raiders', tagline: 'Friday nights, 8pm', owner: '76561197960265729', myRank: 50, myRankWord: 'Owner',
mayModerate: true, mayManage: true, mayInvite: true, mayChangeRoles: true, muted: false, notify: 2,
permissions: [{ key: 'chat', label: 'Write messages' }, { key: 'kick', label: 'Remove people' }, { key: 'ban', label: 'Ban people' }, { key: 'invite', label: 'Invite people and make links' }],
rooms: [{ id: '70', name: '', voice: false }, { id: '71', name: 'loot', voice: false }],
roles: [{ id: '90', name: 'Member' }, { id: '91', name: 'Raid leaders' }],
members: [
{ steamid: '76561197960265729', name: 'Gabe', rank: 50, rankWord: 'Owner', roles: ['90'] },
{ steamid: '76561197960265730', name: 'Alyx', rank: 30, rankWord: 'Moderator', roles: ['90', '91'] },
{ steamid: '76561197960265731', name: 'Eli', rank: 20, rankWord: 'Member', roles: ['90'] }
],
kicked: []
}
window.__rpcFixture = {
steamChatGroups: () => [group],
steamChatGroupAction: (params) => {
if (params.action === 'links') return { links: [{ code: 'Ga3kODnC', link: 'https://s.team/chat/Ga3kODnC', expires: 1800000000 }] }
if (params.action === 'roleActions') return { chat: true, kick: params.roleId === '91', ban: false, invite: true }
if (params.action === 'bans') return { bans: [{ steamid: '76561197960265800', name: 'Spammer' }] }
return {}
}
}
const s = window.__mohoShots
const st = s.state()
const irc = st.accounts[0]
const account = { ...irc, id: 'steam:me', service: 'steam', displayName: 'me', state: 'connected' }
const channel = st.buffers.find((b) => b.id.endsWith('|#ui'))
const room = (name, id, position) => ({ ...channel, id: 'steam:me|' + name, accountId: 'steam:me', name, kind: 'channel', remoteId: '7:' + id, groupId: 'steam:me|steamgroup:7', position, unread: 0, highlight: false, mentions: 0 })
const general = room('Raiders/#General', '70', 1)
const loot = { ...room('Raiders/#loot', '71', 2), unread: 3 }
s.patch({
accounts: [...st.accounts, account],
groups: [...st.groups, { id: 'steam:me|steamgroup:7', accountId: 'steam:me', service: 'steam', kind: 'guild', name: 'Raiders', position: 3 }],
buffers: [...st.buffers, general, loot],
activeBufferId: general.id, activeGroupId: 'steam:me|steamgroup:7',
presenceByBuffer: { ...st.presenceByBuffer, [general.id]: [
{ nick: 'Gabe', status: 'online', userId: '76561197960265729', prefix: '👑', roles: ['Owner'], powerLevel: 50 },
{ nick: 'Alyx', status: 'online', userId: '76561197960265730', prefix: '🛡', roles: ['Moderator', 'Raid leaders'], powerLevel: 30, activity: { kind: 'game', text: 'Half-Life: Alyx' } },
{ nick: 'Eli', status: 'offline', away: true, userId: '76561197960265731', powerLevel: 20 }
] }
})
})()`)
await sleep(1500)
await shot('steam-chatgroup.png')
console.log('channels:', JSON.stringify(await page.evaluate(`[...document.querySelectorAll('.sidebar')].map((s) => s.innerText).join('|')`)))
// The rail entry's menu has the settings.
await page.evaluate(`(() => { const tile = [...document.querySelectorAll('.rail-tile')].find((t) => t.getAttribute('aria-label') === 'Raiders' || t.textContent.includes('Ra')); tile.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: 40, clientY: 200 })) })()`)
await sleep(400)
const entries = await page.evaluate(`[...document.querySelectorAll('.context-menu button, .context-menu [role=menuitem]')].map((e) => e.textContent.trim())`)
console.log('menu:', JSON.stringify(entries))
await page.evaluate(`(() => { const item = [...document.querySelectorAll('.context-menu button, .context-menu [role=menuitem]')].find((e) => e.textContent.includes('Group settings')); item && item.click() })()`)
await sleep(600)
for (const tab of ['General', 'Rooms', 'People', 'Roles', 'Invites']) {
await page.evaluate(`(() => { const t = [...document.querySelectorAll('.steam-group .room-settings-tab')].find((e) => e.textContent.trim() === ${JSON.stringify(tab)}); t && t.click() })()`)
await sleep(500)
if (tab === 'Roles') await page.evaluate(`(() => { const b = [...document.querySelectorAll('.steam-group button')].find((e) => e.textContent.trim() === 'Edit' ); b && b.click() })()`)
await sleep(300)
await shot(`steam-chatgroup-${tab.toLowerCase()}.png`)
const box = await page.evaluate(`(() => { const r = document.querySelector('.steam-group')?.getBoundingClientRect(); return r ? [Math.round(r.left), Math.round(r.top), Math.round(r.right), Math.round(r.bottom)] : null })()`)
console.log(tab, 'dialog box', JSON.stringify(box))
}
} finally {
await stop()
irc.close()
}
+98
View File
@@ -0,0 +1,98 @@
#!/usr/bin/env node
/**
* Photographs a Steam account's own page with its friends under the account's folders, then moves a
* friend to another folder by dragging and says which changes the window asked Steam for. Made-up
* state on a fake IRC server, in a scratch home; the daemon's answers are stood in for here.
*
* node scripts/shot-steam-folders.mjs <output directory>
*/
import fs from 'node:fs'
import path from 'node:path'
import { fakeIrc, launchApp, openIrcChannel, sleep } from './lib/harness.mjs'
const out = process.argv[2] ?? '.'
fs.mkdirSync(out, { recursive: true })
const irc = await fakeIrc({ people: ['alice'], onJoin: (c, _n, send) => send(`:alice!u@h PRIVMSG ${c} :hello there`) })
const { page, stop } = await launchApp({ env: { MOHO_UI_SHOTS: '1' } })
const shot = async (name) => {
const { data } = await page.call('Page.captureScreenshot', { format: 'png' })
fs.writeFileSync(path.join(out, name), Buffer.from(data, 'base64'))
}
try {
await openIrcChannel(page, { port: irc.address().port, nick: 'checker', channels: ['#ui'], waitFor: 'hello there' })
await page.call('Emulation.setDeviceMetricsOverride', { width: 1280, height: 800, deviceScaleFactor: 1, mobile: false })
await page.evaluate(`(() => {
window.__calls = []
const folders = [
{ id: 1, name: 'Steam - ISRAD', members: ['76561197960265704'] },
{ id: 3, name: 'Steam - Friends', members: ['76561197960265701', '76561197960265702'] },
{ id: 5, name: 'Steam - PL', members: ['76561197960265705'] },
{ id: 7, name: 'Steam - Goons', members: ['76561197960265703'] }
]
window.__folders = folders
window.__rpcFixture = { steamFriendGroups: () => folders, steamGroupChange: (p) => { window.__calls.push(p); return {} } }
const s = window.__mohoShots
const st = s.state()
const irc = st.accounts[0]
const ircGroup = st.groups.find((g) => g.kind === 'account')
const channel = st.buffers.find((b) => b.id.endsWith('|#ui'))
const account = { ...irc, id: 'steam:me', service: 'steam', displayName: 'me', state: 'connected' }
const group = { ...ircGroup, id: 'account:steam:me', accountId: 'steam:me', service: 'steam', name: 'Steam - me' }
const friend = (name, id, category) => ({ ...channel, id: 'steam:me|' + name, accountId: 'steam:me', name, kind: 'dm', remoteId: id, groupId: group.id, category: category ?? null, position: 0, unread: 0, highlight: false, mentions: 0 })
const buffers = [
friend('Dandalf', '76561197960265701', 'Friends'), friend('GetCreped', '76561197960265702', 'Friends'),
friend('Shaod', '76561197960265703', 'Goons'), friend('WigglyQuimble', '76561197960265704', 'ISRAD'),
friend('Hujoppi', '76561197960265705', 'PL'), friend('Stranger', '76561197960265706', null)
]
s.patch({
accounts: [...st.accounts, account],
groups: [...st.groups, group],
buffers: [...st.buffers, ...buffers],
steamGroups: { 'steam:me': folders },
activeGroupId: group.id, activeBufferId: buffers[0].id
})
})()`)
await sleep(1500)
// The daemon answered the window's own question about the made-up account with nothing; say it again.
await page.evaluate(`window.__mohoShots.patch({ steamGroups: { 'steam:me': window.__folders } })`)
await sleep(500)
await shot('steam-folders.png')
console.log('classes:', JSON.stringify(await page.evaluate(`[...document.querySelectorAll('.bufferlist [class*=category]')].filter((e) => e.textContent.trim() === 'expand_morePL').map((e) => e.className + ' ' + e.tagName + ' ' + e.draggable)`)))
await page.evaluate(`(() => { const st = window.__mohoShots.store; window.__ranAll = []; const orig = st.moveSteamFriend.bind(st); st.moveSteamFriend = (...a) => { window.__moved = a; return orig(...a) }; const run = st.runSteamGroupCalls.bind(st); st.runSteamGroupCalls = (c) => { window.__ran = c; window.__ranAll.push(...c); return run(c) } })()`)
// Drag Shaod (Goons) onto the PL heading.
const moved = await page.evaluate(`(async () => {
const row = [...document.querySelectorAll('.bufferlist [draggable=true]')].find((e) => e.textContent.trim().endsWith('Shaod') && e.textContent.trim().length < 12)
const head = [...document.querySelectorAll('.bufferlist [class*=category]')].find((e) => e.textContent.trim() === 'expand_morePL')
if (!row || !head) return { row: !!row, head: !!head }
const dt = new DataTransfer()
const wait = () => new Promise((r) => setTimeout(r, 150))
row.dispatchEvent(new DragEvent('dragstart', { bubbles: true, dataTransfer: dt }))
await wait()
head.dispatchEvent(new DragEvent('dragenter', { bubbles: true, cancelable: true, dataTransfer: dt }))
head.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, dataTransfer: dt }))
await wait()
window.__finish = () => { head.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: dt })) }
return { dragged: true }
})()`)
console.log('drag:', JSON.stringify(moved))
await shot('steam-folders-drag.png')
await page.evaluate(`window.__finish && window.__finish()`)
await sleep(500)
console.log('state:', JSON.stringify(await page.evaluate(`(() => { const st = window.__mohoShots.state(); const b = st.buffers.find((x) => x.id === 'steam:me|Shaod'); return { b: b && [b.remoteId, b.category, b.accountId], g: st.steamGroups } })()`)))
console.log('moved:', JSON.stringify(await page.evaluate(`[window.__moved, window.__ran]`)))
console.log('calls:', JSON.stringify(await page.evaluate(`window.__calls`)))
// A new folder: named, and made on Steam.
await page.evaluate(`(() => { const t = [...document.querySelectorAll('.bufferlist button')].find((b) => b.textContent.includes('Steam - me')); t && t.click() })()`)
await sleep(300)
await page.evaluate(`(() => { const i = [...document.querySelectorAll('.context-menu button, .context-menu [role=menuitem]')].find((e) => e.textContent.includes('New category')); i && i.click() })()`)
await sleep(400)
await shot('steam-folders-naming.png')
await page.evaluate(`(() => { const inp = document.querySelector('.reason-prompt-box'); if (!inp) return; const set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set; set.call(inp, 'Raiders'); inp.dispatchEvent(new Event('input', { bubbles: true })) })()`)
await sleep(300)
await page.evaluate(`(() => { const inp = document.querySelector('.reason-prompt-box'); inp && inp.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })) })()`)
await sleep(500)
console.log('all calls:', JSON.stringify(await page.evaluate(`window.__ranAll`)))
} finally {
await stop()
irc.close()
}
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env node
/**
* Photographs the direct-messages page when a Steam account has friend groups:
* each group a heading, its friends' conversations under it. Then changes one
* as Steam would, and reads where the conversation went. Made-up state on a fake
* IRC server, in a scratch home.
*
* node scripts/shot-steam-groups.mjs <output directory>
*/
import fs from 'node:fs'
import path from 'node:path'
import { fakeIrc, launchApp, openIrcChannel, sleep } from './lib/harness.mjs'
const out = process.argv[2] ?? '.'
fs.mkdirSync(out, { recursive: true })
const irc = await fakeIrc({ people: ['alice'], onJoin: (c, _n, send) => send(`:alice!u@h PRIVMSG ${c} :hello there`) })
const { page, stop } = await launchApp({ env: { MOHO_UI_SHOTS: '1' } })
try {
await openIrcChannel(page, { port: irc.address().port, nick: 'checker', channels: ['#ui'], waitFor: 'hello there' })
await page.call('Emulation.setDeviceMetricsOverride', { width: 1000, height: 700, deviceScaleFactor: 1, mobile: false })
await page.evaluate(`(() => {
const s = window.__mohoShots
const st = s.state()
const irc = st.accounts[0]
const account = { ...irc, id: 'steam:me', service: 'steam', displayName: 'me', state: 'connected' }
const channel = st.buffers.find((b) => b.id.endsWith('|#ui'))
const dm = (name, remoteId) => ({ ...channel, id: 'steam:me|' + name, accountId: 'steam:me', name, kind: 'dm', remoteId, unread: 0, highlight: false, mentions: 0 })
s.patch({
accounts: [...st.accounts, account],
buffers: [...st.buffers, dm('Gabe', '76561197960265729'), dm('Alyx', '76561197960287930'), dm('Eli', '76561197960265730')],
activeBufferId: 'steam:me|Gabe', activeGroupId: '~dms',
steamGroups: { 'steam:me': [{ id: 7, name: 'Raiders', members: ['76561197960265729', '76561197960265730'] }, { id: 8, name: 'Work', members: [] }] }
})
})()`)
await sleep(1500)
const headings = () => page.evaluate(`[...document.querySelectorAll('.sidebar')].map((s) => s.innerText).join('|')`)
console.log('page:', JSON.stringify(await headings()))
const { data } = await page.call('Page.captureScreenshot', { format: 'png' })
fs.writeFileSync(path.join(out, 'steam-groups.png'), Buffer.from(data, 'base64'))
// Steam moves Alyx into Work.
await page.evaluate(`(() => { const s = window.__mohoShots; s.patch({ steamGroups: { 'steam:me': [{ id: 7, name: 'Raiders', members: ['76561197960265729', '76561197960265730'] }, { id: 8, name: 'Work', members: ['76561197960287930'] }] } }) })()`)
await sleep(1200)
console.log('after Steam moved Alyx into Work:', JSON.stringify(await headings()))
} finally {
await stop()
irc.close()
}
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env node
/**
* Photographs the Invitations tile with a Steam group invitation on it, as the window shows it.
* Made-up state on a fake IRC server, in a scratch home.
*
* node scripts/shot-steam-invite.mjs <output directory>
*/
import fs from 'node:fs'
import path from 'node:path'
import { fakeIrc, launchApp, openIrcChannel, sleep } from './lib/harness.mjs'
const out = process.argv[2] ?? '.'
fs.mkdirSync(out, { recursive: true })
const irc = await fakeIrc({ people: ['alice'], onJoin: (c, _n, send) => send(`:alice!u@h PRIVMSG ${c} :hello there`) })
const { page, stop } = await launchApp({ env: { MOHO_UI_SHOTS: '1' } })
try {
await openIrcChannel(page, { port: irc.address().port, nick: 'checker', channels: ['#ui'], waitFor: 'hello there' })
await page.call('Emulation.setDeviceMetricsOverride', { width: 1280, height: 800, deviceScaleFactor: 1, mobile: false })
await page.evaluate(`(() => {
const s = window.__mohoShots
const st = s.state()
const account = { ...st.accounts[0], id: 'steam:me', service: 'steam', displayName: 'me', state: 'connected' }
s.patch({
accounts: [...st.accounts, account],
matrixInvites: { 'steam:me': [{ roomId: '79003375', name: 'Biggest Newest Moho Test', inviter: 'Salastil', avatarUrl: null, isDirect: false }] },
activeGroupId: '~invitations'
})
})()`)
await sleep(1200)
const { data } = await page.call('Page.captureScreenshot', { format: 'png' })
fs.writeFileSync(path.join(out, 'steam-invite.png'), Buffer.from(data, 'base64'))
console.log(await page.evaluate(`document.querySelector('.invite-panel')?.innerText`))
} finally {
await stop()
irc.close()
}
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env node
/**
* Photographs a Steam conversation Steam has warned about: the red banner over
* it and the red line in the log, then the banner dismissed. Made-up state on a
* fake IRC server, in a scratch home.
*
* node scripts/shot-steam-notice.mjs <output directory>
*/
import fs from 'node:fs'
import path from 'node:path'
import { fakeIrc, launchApp, openIrcChannel, sleep } from './lib/harness.mjs'
const out = process.argv[2] ?? '.'
fs.mkdirSync(out, { recursive: true })
const irc = await fakeIrc({ people: ['alice'], onJoin: (c, _n, send) => send(`:alice!u@h PRIVMSG ${c} :hello there`) })
const { page, stop } = await launchApp({ env: { MOHO_UI_SHOTS: '1' } })
try {
await openIrcChannel(page, { port: irc.address().port, nick: 'checker', channels: ['#ui'], waitFor: 'hello there' })
await page.call('Emulation.setDeviceMetricsOverride', { width: 1000, height: 620, deviceScaleFactor: 1, mobile: false })
await page.evaluate(`(() => {
const s = window.__mohoShots
const st = s.state()
const irc = st.accounts[0]
const account = { ...irc, id: 'steam:me', service: 'steam', displayName: 'me', state: 'connected' }
const channel = st.buffers.find((b) => b.id.endsWith('|#ui'))
const notice = { kind: 'suspicious', text: 'Steam warns that this person may not be who they appear to be. Be careful with links, offers and requests for anything - and do not give out your account details.' }
const dm = { ...channel, id: 'steam:me|Gabe', accountId: 'steam:me', name: 'Gabe', kind: 'dm', remoteId: '76561197960265829', unread: 0, highlight: false, mentions: 0, notice }
const now = Math.floor(Date.now() / 1000)
const m = (id, from, body, kind = 'chat') => ({ id, bufferId: dm.id, from, body, ts: now - 600 + Number(id.split(':')[1] || 0), isAction: false, isHighlight: false, kind })
s.patch({
accounts: [...st.accounts, account], buffers: [...st.buffers, dm], activeBufferId: dm.id, activeGroupId: '~dms',
messagesByBuffer: { ...st.messagesByBuffer, [dm.id]: [
m('1:1', 'Gabe', 'hey, long time'),
m('2:2', 'Steam', notice.text, 'warning'),
m('3:3', 'Gabe', 'can you check this link for me')
] }
})
})()`)
await sleep(1000)
const shot = async (name) => {
const { data } = await page.call('Page.captureScreenshot', { format: 'png' })
fs.writeFileSync(path.join(out, name), Buffer.from(data, 'base64'))
console.log('wrote', name)
}
await shot('steam-notice-before.png')
console.log('banner:', await page.evaluate(`!!document.querySelector('.notice-banner')`), '| warning lines:', await page.evaluate(`document.querySelectorAll('.message-row.warning').length`))
await page.evaluate(`document.querySelector('.notice-banner-dismiss').click()`)
await sleep(600)
console.log('banner after dismiss:', await page.evaluate(`!!document.querySelector('.notice-banner')`), '| warning lines:', await page.evaluate(`document.querySelectorAll('.message-row.warning').length`))
await shot('steam-notice-after.png')
} finally {
await stop()
irc.close()
}
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env node
/**
* Photographs the message box of a Steam conversation with its emoji picker
* open: no GIF button, and a picker with no Unicode emoji. Made-up state, on a
* fake IRC server, in a scratch home.
*
* node scripts/shot-steam-picker.mjs <output directory>
*/
import fs from 'node:fs'
import path from 'node:path'
import { fakeIrc, launchApp, openIrcChannel, sleep } from './lib/harness.mjs'
const out = process.argv[2] ?? '.'
fs.mkdirSync(out, { recursive: true })
const irc = await fakeIrc({ people: ['alice'], onJoin: (c, _n, send) => send(`:alice!u@h PRIVMSG ${c} :hello there`) })
const { page, stop } = await launchApp({ env: { MOHO_UI_SHOTS: '1' } })
try {
await openIrcChannel(page, { port: irc.address().port, nick: 'checker', channels: ['#ui'], waitFor: 'hello there' })
await page.call('Emulation.setDeviceMetricsOverride', { width: 1000, height: 700, deviceScaleFactor: 1, mobile: false })
const shot = async (name) => {
await sleep(600)
const { data } = await page.call('Page.captureScreenshot', { format: 'png' })
fs.writeFileSync(path.join(out, name), Buffer.from(data, 'base64'))
console.log('wrote', name)
}
// A Steam account and a conversation with a friend, selected.
await page.evaluate(`(() => {
const s = window.__mohoShots
const st = s.state()
const irc = st.accounts[0]
const account = { ...irc, id: 'steam:me', service: 'steam', displayName: 'me', state: 'connected' }
const channel = st.buffers.find((b) => b.id.endsWith('|#ui'))
const dm = { ...channel, id: 'steam:me|Gabe', accountId: 'steam:me', name: 'Gabe', kind: 'dm', remoteId: '76561197960265829', unread: 0, highlight: false, mentions: 0 }
s.patch({ accounts: [...st.accounts, account], buffers: [...st.buffers, dm], activeBufferId: dm.id, activeGroupId: '~dms' })
})()`)
await shot('steam-composer.png')
await page.evaluate(`document.querySelector('button[title="Emoji"]').click()`)
await shot('steam-picker.png')
const gif = await page.evaluate(`!!document.querySelector('button[title="GIFs"]')`)
const sticker = await page.evaluate(`!!document.querySelector('button[title="Stickers"]')`)
console.log('GIF button:', gif, '| Stickers button:', sticker)
} finally {
await stop()
irc.close()
}
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env node
/**
* Photographs the column about a Steam friend, beside their conversation, and
* checks the conversation's right-click menu offers it. Made-up state on a fake
* IRC server, in a scratch home.
*
* node scripts/shot-steam-profile.mjs <output directory>
*/
import fs from 'node:fs'
import path from 'node:path'
import { fakeIrc, launchApp, openIrcChannel, sleep } from './lib/harness.mjs'
const out = process.argv[2] ?? '.'
fs.mkdirSync(out, { recursive: true })
const irc = await fakeIrc({ people: ['alice'], onJoin: (c, _n, send) => send(`:alice!u@h PRIVMSG ${c} :hello there`) })
const { page, stop } = await launchApp({ env: { MOHO_UI_SHOTS: '1' } })
try {
await openIrcChannel(page, { port: irc.address().port, nick: 'checker', channels: ['#ui'], waitFor: 'hello there' })
await page.call('Emulation.setDeviceMetricsOverride', { width: 1100, height: 700, deviceScaleFactor: 1, mobile: false })
await page.evaluate(`(() => {
const s = window.__mohoShots
const st = s.state()
const irc = st.accounts[0]
const account = { ...irc, id: 'steam:me', service: 'steam', displayName: 'me', state: 'connected' }
const channel = st.buffers.find((b) => b.id.endsWith('|#ui'))
const dm = { ...channel, id: 'steam:me|Gabe', accountId: 'steam:me', name: 'Gabe', kind: 'dm', remoteId: '76561197960265829', unread: 0, highlight: false, mentions: 0 }
const now = Math.floor(Date.now() / 1000)
const m = (id, body) => ({ id, bufferId: dm.id, from: 'Gabe', body, ts: now - 600 + Number(id.split(':')[1]), isAction: false, isHighlight: false, kind: 'chat' })
s.patch({
accounts: [...st.accounts, account], buffers: [...st.buffers, dm], activeBufferId: dm.id, activeGroupId: '~dms',
messagesByBuffer: { ...st.messagesByBuffer, [dm.id]: [m('1:1', 'want to play later?')] },
presenceByBuffer: { ...st.presenceByBuffer, [dm.id]: [{ nick: 'Gabe', status: 'online', userId: '76561197960265829', activity: { kind: 'game', text: 'Counter-Strike 2' }, client: 'desktop', rich: 'Competitive - Dust II' }] }
})
})()`)
await sleep(600)
// The right-click menu of the row, and what it offers.
const rect = await page.evaluate(`(() => { const r = [...document.querySelectorAll('.buffer-row, .buffer')].find((e) => e.textContent.includes('Gabe')); if (!r) return null; const b = r.getBoundingClientRect(); return { x: b.x + 20, y: b.y + 10 } })()`)
console.log('row at', JSON.stringify(rect))
await page.call('Input.dispatchMouseEvent', { type: 'mousePressed', x: rect.x, y: rect.y, button: 'right', clickCount: 1 })
await page.call('Input.dispatchMouseEvent', { type: 'mouseReleased', x: rect.x, y: rect.y, button: 'right', clickCount: 1 })
await sleep(400)
console.log('menu:', JSON.stringify(await page.evaluate(`[...document.querySelectorAll('[role=menuitem], .context-menu button')].map((e) => e.textContent.trim()).slice(0, 6)`)))
// Chosen from the menu, as a person would.
console.log('clicked Profile:', await page.evaluate(`(() => { const e = [...document.querySelectorAll('[role=menuitem], .context-menu button')].find((x) => x.textContent.trim() === 'Profile'); if (!e) return false; e.click(); return true })()`))
await sleep(500)
// What Steam said, as the daemon would send it: the card every service opens.
await page.evaluate(`window.__mohoShots.patch({ profile: {
service: 'steam', accountId: 'steam:me', id: '76561197960265729', name: 'Gabe', createdTs: 1300000000,
status: 'online', activity: { kind: 'game', text: 'Counter-Strike 2' },
nameHistory: [{ name: 'Gabe Newell', when: '3 Mar, 2019 @ 1:00am' }, { name: 'Valve Gabe', when: '12 Jun, 2012 @ 6:40pm' }],
extra: [{ label: 'Steam level', value: '42' }, { label: 'Real name', value: 'Gabe N' }, { label: 'Location', value: 'Bellevue, United States' }, { label: 'On', value: 'desktop' }, { label: 'Doing', value: 'Competitive - Dust II' }, { label: 'Headline', value: 'Hello' }]
} })`)
await sleep(500)
const { data } = await page.call('Page.captureScreenshot', { format: 'png' })
fs.writeFileSync(path.join(out, 'steam-profile-card.png'), Buffer.from(data, 'base64'))
console.log('wrote steam-profile-card.png; card:', await page.evaluate(`!!document.querySelector('.profile-card')`), '| previous names:', await page.evaluate(`document.querySelectorAll('.profile-name-history li').length`))
// Offline: last seen instead of playing.
await page.evaluate(`(() => { const s = window.__mohoShots; const st = s.state(); s.patch({ profile: { ...st.profile, status: 'offline', activity: null, lastActiveTs: Math.floor(Date.now() / 1000) - 7200 } }) })()`)
await sleep(400)
console.log('offline card:', JSON.stringify(await page.evaluate(`document.querySelector('.profile-card')?.innerText.replace(/\\n+/g, ' | ').slice(0, 300)`)))
} finally {
await stop()
irc.close()
}
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env node
/**
* Photographs a Steam conversation holding a picture and a video, each plain
* and each sent as a spoiler. Made-up state on a fake IRC server in a scratch
* home; Steam's addresses are answered from a generated picture and clip.
*
* node scripts/shot-steam-spoiler.mjs <output directory> <picture.png> <clip.webm>
*/
import fs from 'node:fs'
import path from 'node:path'
import { fakeIrc, launchApp, openIrcChannel, sleep } from './lib/harness.mjs'
const [out = '.', picture, clip] = process.argv.slice(2)
fs.mkdirSync(out, { recursive: true })
const irc = await fakeIrc({ people: ['alice'], onJoin: (c, _n, send) => send(`:alice!u@h PRIVMSG ${c} :hello there`) })
const { page, stop } = await launchApp({ env: { MOHO_UI_SHOTS: '1' } })
try {
await openIrcChannel(page, { port: irc.address().port, nick: 'checker', channels: ['#ui'], waitFor: 'hello there' })
await page.call('Emulation.setDeviceMetricsOverride', { width: 1000, height: 900, deviceScaleFactor: 1, mobile: false })
// Steam's addresses answered here: the picture and the clip, whatever the path.
await page.call('Fetch.enable', { patterns: [{ urlPattern: '*steamusercontent.com*' }, { urlPattern: '*steamstatic.com*' }, { urlPattern: '*example.com*' }] })
page.on('Fetch.requestPaused', async (e) => {
const video = e.request.url.includes('/cdn-video/') || e.request.url.includes('cdn.steamusercontent.com')
const body = fs.readFileSync(video ? clip : picture).toString('base64')
await page.call('Fetch.fulfillRequest', {
requestId: e.requestId,
responseCode: 200,
responseHeaders: [{ name: 'Content-Type', value: video ? 'video/webm' : 'image/png' }, { name: 'Access-Control-Allow-Origin', value: '*' }],
body
})
})
const img = (n) => `https://images.steamusercontent.com/ugc/${n}/AAAA/`
const vid = (n) => `https://cdn.steamusercontent.com/ugc/${n}/BBBB/`
await page.evaluate(`(() => {
const s = window.__mohoShots
const st = s.state()
const irc = st.accounts[0]
const account = { ...irc, id: 'steam:me', service: 'steam', displayName: 'me', state: 'connected' }
const channel = st.buffers.find((b) => b.id.endsWith('|#ui'))
const dm = { ...channel, id: 'steam:me|Gabe', accountId: 'steam:me', name: 'Gabe', kind: 'dm', remoteId: '76561197960265829', unread: 0, highlight: false, mentions: 0 }
const m = (id, body) => ({ id, bufferId: dm.id, from: 'Gabe', body, ts: Math.floor(Date.now() / 1000) - 600 + Number(id), isAction: false, isHighlight: false, kind: 'chat' })
s.patch({
accounts: [...st.accounts, account], buffers: [...st.buffers, dm], activeBufferId: dm.id, activeGroupId: '~dms',
messagesByBuffer: { ...st.messagesByBuffer, [dm.id]: [
m('1', 'a plain picture'), m('2', '\\n[steam:image:${img(1)}]\\n'),
m('3', 'a picture sent as a spoiler'), m('4', '||\\n[steam:image:${img(2)}]\\n||'),
m('5', 'a plain video'), m('6', '\\n[steam:video:${vid(3)}]\\n'),
m('7', 'a video sent as a spoiler'), m('8', '||\\n[steam:video:${vid(4)}]\\n||'),
m('9', 'an emoticon [steam:emote:steamhappy] in a line, then a sticker'), m('10', '[steam:sticker:Nyan GLaDOS]'),
m('11', 'a link with words: [look at this](https://links.invalid/a?x=1&y=2) and a bare one https://links.invalid/b, then a picture https://example.com/p.png'),
{ ...m('12', '[x.salastil.com](http://x.salastil.com)'), embeds: [{ url: 'http://x.salastil.com', title: 'Home', description: 'A privacy-focused Twitter/X frontend', provider: 'x.salastil.com', imageUrl: 'https://community.steamstatic.com/chat/image/abc/share_image' }] }
] }
})
})()`)
await sleep(1500)
const shot = async (name) => {
const { data } = await page.call('Page.captureScreenshot', { format: 'png' })
fs.writeFileSync(path.join(out, name), Buffer.from(data, 'base64'))
console.log('wrote', name)
}
await shot('steam-spoiler-before.png')
console.log('links:', JSON.stringify(await page.evaluate(`[...document.querySelectorAll('.message-body a, .message-text a, .message-row a')].map((a) => [a.textContent, a.getAttribute('href')]).filter((l) => l[1] && !l[1].startsWith('spoiler'))`)))
console.log('covers:', await page.evaluate(`document.querySelectorAll('.spoiler-cover').length`), '| embeds:', await page.evaluate(`document.querySelectorAll('.media-embed-wrap').length`))
await page.evaluate(`document.querySelector('.spoiler-cover')?.click()`)
await sleep(500)
console.log('covers after one click:', await page.evaluate(`document.querySelectorAll('.spoiler-cover').length`))
await shot('steam-spoiler-after.png')
} finally {
await stop()
irc.close()
}
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env node
/**
* Photographs Steam voice as the window shows it: a group's voice room with people in
* it, the panel for the call you are in, and a call ringing. Made-up state on a fake IRC
* server, in a scratch home.
*
* node scripts/shot-steam-voice.mjs <output directory>
*/
import fs from 'node:fs'
import path from 'node:path'
import { fakeIrc, launchApp, openIrcChannel, sleep } from './lib/harness.mjs'
const out = process.argv[2] ?? '.'
fs.mkdirSync(out, { recursive: true })
const irc = await fakeIrc({ people: ['alice'], onJoin: (c, _n, send) => send(`:alice!u@h PRIVMSG ${c} :hello there`) })
const { page, stop } = await launchApp({ env: { MOHO_UI_SHOTS: '1' } })
try {
await openIrcChannel(page, { port: irc.address().port, nick: 'checker', channels: ['#ui'], waitFor: 'hello there' })
await page.call('Emulation.setDeviceMetricsOverride', { width: 1280, height: 800, deviceScaleFactor: 1, mobile: false })
await page.evaluate(`(() => {
const s = window.__mohoShots
const st = s.state()
const account = { ...st.accounts[0], id: 'steam:me', service: 'steam', displayName: 'me', state: 'connected' }
const channel = st.buffers.find((b) => b.id.endsWith('|#ui'))
const room = (name, id, position) => ({ ...channel, id: 'steam:me|' + name, accountId: 'steam:me', name, kind: 'channel', remoteId: '7:' + id, groupId: 'steam:me|steamgroup:7', position, unread: 0, highlight: false, mentions: 0 })
const dm = { ...channel, id: 'steam:me|Gabe', accountId: 'steam:me', name: 'Gabe', kind: 'dm', remoteId: '76561197960265729', unread: 0, highlight: false, mentions: 0 }
const general = room('Raiders/#General', '70', 1)
const talk = room('Raiders/#Lounge', '71', 2)
const live = s.store.steamVoiceLive
live.speakers = new Set(['76561197960265730'])
live.statuses = new Map([['76561197960265731', { micMuted: true, outputMuted: false, noMic: false }]])
live.level = 0.4
live.rttMs = 23
s.patch({
accounts: [...st.accounts, account],
groups: [...st.groups, { id: 'steam:me|steamgroup:7', accountId: 'steam:me', service: 'steam', kind: 'guild', name: 'Raiders', position: 3 }],
buffers: [...st.buffers, general, talk, dm],
activeBufferId: general.id, activeGroupId: 'steam:me|steamgroup:7',
steamVoiceRooms: { 'steam:me|7': [{ roomId: '71', bufferId: talk.id, name: 'Lounge', members: [
{ userId: '76561197960265729', nick: 'Gabe' },
{ userId: '76561197960265730', nick: 'Alyx' },
{ userId: '76561197960265731', nick: 'Eli' },
{ userId: '76561197960287930', nick: 'me', isSelf: true }
] }] },
steamVoiceNow: { accountId: 'steam:me', phase: 'connected', target: { kind: 'room', groupId: '7', roomId: '71', bufferId: talk.id, name: 'Lounge', groupName: 'Raiders', railId: 'steam:me|steamgroup:7' } },
voiceSessions: [{ accountId: 'steam:me', channelId: '71', channelName: 'Lounge', isDirect: false, bufferId: talk.id, railId: 'steam:me|steamgroup:7' }],
steamRings: [{ accountId: 'steam:me', steamid: '76561197960265729', voiceChatId: '99' }]
})
})()`)
// The window asks the daemon who is in the voice rooms when the group opens, and the
// daemon knows no such group: the made-up answer goes in after that.
await sleep(1200)
await page.evaluate(`(() => { const s = window.__mohoShots; s.patch({ steamVoiceRooms: { 'steam:me|7': [{ roomId: '71', bufferId: 'steam:me|Raiders/#Lounge', name: 'Lounge', members: [{ userId: '76561197960265729', nick: 'Gabe' }, { userId: '76561197960265730', nick: 'Alyx' }, { userId: '76561197960265731', nick: 'Eli' }, { userId: '76561197960287930', nick: 'me', isSelf: true }] }] } }) })()`)
await sleep(800)
const { data } = await page.call('Page.captureScreenshot', { format: 'png' })
fs.writeFileSync(path.join(out, 'steam-voice.png'), Buffer.from(data, 'base64'))
console.log('panel:', JSON.stringify(await page.evaluate(`document.querySelector('.voice-panel')?.innerText`)))
console.log('ring:', JSON.stringify(await page.evaluate(`document.querySelector('.incoming-call')?.innerText`)))
} finally {
await stop()
irc.close()
}
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env node
/**
* Photographs the member list and the direct-message rows in comfy and in
* classic, with made-up presence on them (a game, a track, words somebody
* wrote), so the two looks can be compared by eye.
*
* node scripts/shot-userlist.mjs <output directory>
*
* Runs the built app against a scratch home with the screenshot hook on, and
* a fake IRC server for something to be in.
*/
import fs from 'node:fs'
import path from 'node:path'
import { fakeIrc, launchApp, openIrcChannel, sleep } from './lib/harness.mjs'
const out = process.argv[2] ?? '.'
fs.mkdirSync(out, { recursive: true })
const PEOPLE = ['Crujix', 'Currington', 'dakota', 'Gremlin_magos', 'onkell', 'Salastil', 'Taylaigh']
const MEMBERS = [
{ nick: 'Crujix', status: 'idle', activity: { kind: 'game', text: 'Songs of Syx Demo' } },
{ nick: 'Currington', status: 'online', activity: { kind: 'game', text: 'Philippians 2' } },
{ nick: 'dakota', status: 'online' },
{ nick: 'Gremlin_magos', status: 'dnd', activity: { kind: 'custom', text: 'ask questions' } },
{ nick: 'onkell', status: 'online', activity: { kind: 'game', text: 'Down to Dungeon' } },
{ nick: 'Salastil', status: 'online', activity: { kind: 'music', text: 'Ramones' } },
{ nick: 'Taylaigh', status: 'offline', away: true }
]
const irc = await fakeIrc({
people: PEOPLE,
onJoin: (channel, _nick, send) => send(`:Crujix!u@h PRIVMSG ${channel} :hello there`)
})
const { page, stop } = await launchApp({ env: { MOHO_UI_SHOTS: '1' } })
try {
await openIrcChannel(page, { port: irc.address().port, nick: 'checker', channels: ['#ui'], waitFor: 'hello there' })
await page.call('Emulation.setDeviceMetricsOverride', { width: 1100, height: 760, deviceScaleFactor: 1, mobile: false })
const shot = async (name) => {
await sleep(600)
const { data } = await page.call('Page.captureScreenshot', { format: 'png' })
fs.writeFileSync(path.join(out, name), Buffer.from(data, 'base64'))
console.log('wrote', name)
}
const dress = async () => {
await page.evaluate(`(() => {
const s = window.__mohoShots
const st = s.state()
const channel = st.buffers.find((b) => b.id.endsWith('|#ui'))
const dm = (name, extra = {}) => ({ ...channel, id: 'irc:x|' + name, name, kind: 'dm', unread: 0, highlight: false, mentions: 0, ...extra })
const gamer = dm('k. mardam bae')
const quiet = dm('Alexcellence')
s.patch({
buffers: [...st.buffers, gamer, quiet],
presenceByBuffer: {
...st.presenceByBuffer,
[channel.id]: ${JSON.stringify(MEMBERS)},
[gamer.id]: [{ nick: 'k. mardam bae', status: 'idle', activity: { kind: 'game', text: "Assassin's Creed Valhalla" } }],
[quiet.id]: [{ nick: 'Alexcellence', status: 'online' }]
}
})
})()`)
}
await dress()
await page.evaluate(`window.moho.prefs.set('display.messageMode', 'comfy')`)
await shot('comfy-channel.png')
await page.evaluate(`(() => {
const s = window.__mohoShots
const channel = s.state().buffers.find((b) => b.id.endsWith('|#ui'))
s.patch({ profile: { service: 'irc', accountId: channel.accountId, name: 'onkell', handle: 'onkell', status: 'online', extra: [{ label: 'Client', value: 'moho' }] } })
})()`)
await shot('profile-card.png')
await page.evaluate(`(() => { window.__mohoShots.patch({ profile: null }) })()`)
await page.evaluate(`(() => { const s = window.__mohoShots; s.store.selectGroup('~dms') })()`)
await shot('comfy-dms.png')
// A window is not told about its own preference change, so the new mode is
// set, the page reloaded to read it, and the made-up state put back.
await page.evaluate(`window.moho.prefs.set('display.messageMode', 'classic')`)
await sleep(300)
await page.call('Page.reload', {})
await sleep(2500)
await dress()
await page.evaluate(`(() => { const s = window.__mohoShots; s.store.selectGroup('~dms') })()`)
await shot('classic-dms.png')
await page.evaluate(`(() => { const s = window.__mohoShots; const b = s.state().buffers.find((b) => b.id.endsWith('|#ui')); s.store.selectBuffer(b.id) })()`)
await shot('classic-channel.png')
} finally {
await stop()
irc.close()
}
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env sh
# Keeps a development checkout from filling the disk.
#
# Everything this removes is build output that the next build makes again, and
# none of it is the project: it is what grew to a hundred gigabytes without
# anybody choosing it.
#
# - dist/ got one AppImage per deploy and never lost one. Only the newest few
# are kept; the installed copy lives in ~/.local/bin.
# - Cargo never removes what a build no longer uses. Every change to a
# dependency, a feature or the compiler leaves the old build beside the new
# one, so nobilis/target held fifty copies of each library. Past a size it
# is emptied, and the build that follows starts it again with only what is
# current. Run before a build, never after one: after, it would throw away
# the thing just made.
# - Debug builds and the Windows cross-build are not what a deploy uses and
# are made again when somebody asks for them.
#
# scripts/tidy.sh (also run first by `npm run deploy`)
set -eu
SRC_DIR="$(cd "$(dirname "$0")/.." && pwd)"
KEEP_APPIMAGES="${MOHO_KEEP_APPIMAGES:-2}"
# In megabytes: a clean release build of the daemon is about two gigabytes.
TARGET_LIMIT_MB="${MOHO_TARGET_LIMIT_MB:-8000}"
size_mb() { du -sm "$1" 2>/dev/null | cut -f1; }
# What is in dist/ besides the newest AppImages: older ones, Windows and
# Debian packages, the unpacked trees and their block maps.
if [ -d "$SRC_DIR/dist" ]; then
keep="$(ls -t "$SRC_DIR"/dist/*.AppImage 2>/dev/null | head -n "$KEEP_APPIMAGES")"
for f in "$SRC_DIR"/dist/* "$SRC_DIR"/dist/.[!.]*; do
[ -e "$f" ] || continue
case "$(basename "$f")" in builder-debug.yml|builder-effective-config.yaml|latest*.yml) continue ;; esac
printf '%s\n' "$keep" | grep -qxF "$f" && continue
rm -rf "$f"
done
fi
# A build directory left over from before the daemon lived in nobilis/.
rm -rf "$SRC_DIR/target"
TARGET="$SRC_DIR/nobilis/target"
if [ -d "$TARGET" ]; then
rm -rf "$TARGET/debug" "$TARGET"/x86_64-pc-windows-* "$TARGET"/aarch64-*
used="$(size_mb "$TARGET")"
if [ "${used:-0}" -gt "$TARGET_LIMIT_MB" ]; then
echo "tidy: nobilis/target is ${used} MB, over ${TARGET_LIMIT_MB} MB - emptying it; the next build starts it fresh"
rm -rf "$TARGET"
fi
fi
+274
View File
@@ -0,0 +1,274 @@
#!/usr/bin/env node
/**
* Checks the tray against the running app: what its icon, tooltip and menu say
* for what is waiting, what its entries do, and that "Restart moho" brings back
* moho and a daemon of its own.
*
* A tray cannot be photographed, so this reads what main last gave it through a
* hook that exists only under MOHO_UI_SHOTS, and presses its entries the same
* way. Main is reached over the Node inspector the app is started with.
*
* npm run test:tray (builds first; needs the daemon built too)
*/
import { execFileSync } from 'node:child_process'
import fs from 'node:fs'
import { cdp, fakeIrc, freePort, launchApp, openIrcChannel, sleep, until } from './lib/harness.mjs'
let failures = 0
const check = (ok, what, detail = '') => {
console.log(`${ok ? 'ok ' : 'FAIL'} ${what}${ok ? '' : detail ? ` - ${detail}` : ''}`)
if (!ok) failures++
}
async function mainProcess(inspectPort) {
for (let i = 0; i < 60; i++) {
try {
const list = await (await fetch(`http://127.0.0.1:${inspectPort}/json/list`)).json()
const target = list.find((t) => t.webSocketDebuggerUrl)
if (target) return cdp(target.webSocketDebuggerUrl)
} catch {
/* not up yet */
}
await sleep(500)
}
throw new Error('main never offered its inspector')
}
/** The nobilis processes that belong to this run, by the runtime directory in their environment. */
function daemons(scratch) {
const out = []
for (const entry of fs.readdirSync('/proc')) {
if (!/^\d+$/.test(entry)) continue
try {
const exe = fs.readlinkSync(`/proc/${entry}/exe`)
if (!exe.endsWith('/nobilis')) continue
if (fs.readFileSync(`/proc/${entry}/environ`, 'utf8').includes(`XDG_RUNTIME_DIR=${scratch}/run`)) out.push(Number(entry))
} catch {
/* gone, or not ours */
}
}
return out
}
// A run that hangs is a failure, and must not leave an app behind it.
setTimeout(() => {
console.log('FAIL timed out')
process.exit(1)
}, 150000).unref()
const inspectPort = await freePort()
const { page, stop, port } = await launchApp({ env: { MOHO_UI_SHOTS: '1' }, args: [`--inspect=${inspectPort}`] })
let scratchDir = ''
try {
const main = await mainProcess(inspectPort)
const tray = (expr) => main.evaluate(`(() => { const t = globalThis.__mohoTray; return ${expr} })()`)
await until(main, 'globalThis.__mohoTray', 'the tray')
scratchDir = await main.evaluate('process.env.HOME')
// Nothing waiting.
await tray('t.update({ unread: 0, dms: 0, mentions: 0 })'.replace('t.', 't.'))
check(/^tray-(light|dark)\.png$/.test(await tray('t.icon()')), 'idle: the plain bubble', await tray('t.icon()'))
check((await tray('t.menu()[0].label')) === 'Nothing new', 'idle: the menu says nothing is new')
check((await tray('t.tooltip()')) === 'moho', 'idle: the tooltip is just moho')
// Something waiting: the count is on the icon, and the menu says what.
await tray('t.update({ unread: 3, dms: 2, mentions: 1 })')
check(/^tray-(light|dark)-3\.png$/.test(await tray('t.icon()')), 'waiting: the icon carries the count', await tray('t.icon()'))
check((await tray('t.tooltip()')) === 'moho - 2 direct messages, 1 mention', 'waiting: the tooltip says what', await tray('t.tooltip()'))
check((await tray('t.menu()[0].label')) === '2 direct messages, 1 mention - open', 'waiting: the menu says what', await tray('t.menu()[0].label'))
await tray('t.update({ unread: 40, dms: 40, mentions: 0 })')
check(/-more\.png$/.test(await tray('t.icon()')), 'a great many: the icon says 9+')
await tray('t.update({ unread: 0, dms: 0, mentions: 0 })')
// The entries, and that none of them is daemon plumbing.
const labels = await tray('t.menu().map((i) => i.label ?? "-")')
check(!labels.some((l) => /daemon/i.test(l)), 'the menu offers no daemon plumbing', labels.join(' | '))
check(labels.includes('Restart moho'), 'the menu offers Restart moho')
// Settings opens in the window.
await tray('t.click(["Settings"])')
await until(page, 'window.__mohoShots.state().activePanel === "settings"', 'Settings to open')
check(true, 'Settings opens the settings page')
// A status goes to the window to carry out.
await page.evaluate('window.__trayGot = []; window.moho.onTrayCommand((c, a) => window.__trayGot.push([c, a])); true')
await tray('t.click(["Status", "Do not disturb"])')
await until(page, 'window.__trayGot.length', 'the status to reach the window')
check(JSON.stringify(await page.evaluate('window.__trayGot[0]')) === '["status","dnd"]', 'a status is handed to the window')
// There is no notifications switch of its own: Do not disturb is that.
check(!labels.some((l) => /notification/i.test(l)), 'the menu has no notifications switch of its own', labels.join(' | '))
// With an IRC account connected - which has away and back, and no invisible -
// the menu offers what IRC can be set to, and the daemon takes it.
const aways = []
const irc = await fakeIrc({
people: ['bob'],
onJoin: (channel, _nick, send) => send(`:bob!b@h PRIVMSG ${channel} :hello there`),
onLine: (line) => {
if (/^AWAY/i.test(line)) aways.push(line)
}
})
try {
await openIrcChannel(page, { port: irc.address().port, nick: 'checker', channels: ['#lobby'], waitFor: 'hello there' })
await until(main, 'globalThis.__mohoTray.menu().find((i) => i.label === "Status").submenu.length === 3', 'the menu to offer only IRC\'s statuses')
const offered = await tray('t.menu().find((i) => i.label === "Status").submenu.map((i) => i.label)')
check(JSON.stringify(offered) === '["Online","Idle","Do not disturb"]', 'IRC alone: no Invisible is offered', JSON.stringify(offered))
const statusOf = () => page.evaluate('window.moho.rpc("listAccounts", {}).then((a) => a.find((x) => x.id.startsWith("checker")).status)')
await tray('t.click(["Status", "Idle"])')
await until(page, 'window.moho.rpc("listAccounts", {}).then((a) => a.find((x) => x.id.startsWith("checker")).status === "idle")', 'IRC to go idle')
check(true, 'Idle from the tray sets the IRC account idle')
await tray('t.click(["Status", "Do not disturb"])')
await until(page, 'window.moho.rpc("listAccounts", {}).then((a) => a.find((x) => x.id.startsWith("checker")).status === "dnd")', 'IRC to go to Do not disturb')
check((await statusOf()) === 'dnd', 'Do not disturb from the tray sets it')
// Going idle when the person steps away, and only when they are online.
const shown = () => page.evaluate('window.moho.rpc("listAccounts", {}).then((a) => { const x = a.find((y) => y.id.startsWith("checker")); return { status: x.status, auto: !!x.autoIdle } })')
const waitFor = (expr, what) => until(page, `window.moho.rpc("listAccounts", {}).then((a) => { const x = a.find((y) => y.id.startsWith("checker")); return ${expr} })`, what)
await tray('t.click(["Status", "Online"])')
await waitFor('x.status === "online"', 'online again')
await tray('t.idle(true)')
await waitFor('x.status === "idle" && x.autoIdle === true', 'an online account to go idle when its person steps away')
check(true, 'stepping away turns an online account idle, as automatic')
await sleep(500)
check(aways.some((l) => /AWAY :?Idle/i.test(l)), 'and IRC is told it is away', JSON.stringify(aways))
await tray('t.idle(false)')
await waitFor('x.status === "online" && !x.autoIdle', 'it to come back')
check(aways.some((l) => /^AWAY\s*$/i.test(l)), 'coming back puts it right without anybody touching it', JSON.stringify(aways))
// What was chosen is never moved.
await tray('t.click(["Status", "Do not disturb"])')
await waitFor('x.status === "dnd"', 'Do not disturb')
await tray('t.idle(true)')
await sleep(800)
let now = await shown()
check(now.status === 'dnd' && !now.auto, 'Do not disturb is kept when they step away', JSON.stringify(now))
await tray('t.idle(false)')
await sleep(500)
now = await shown()
check(now.status === 'dnd', 'and when they come back', JSON.stringify(now))
await tray('t.click(["Status", "Idle"])')
await waitFor('x.status === "idle" && !x.autoIdle', 'a chosen Idle')
await tray('t.idle(true)')
await tray('t.idle(false)')
await sleep(500)
now = await shown()
check(now.status === 'idle' && !now.auto, 'a chosen Idle stays until Online is chosen', JSON.stringify(now))
await tray('t.click(["Status", "Online"])')
await waitFor('x.status === "online"', 'online again')
// The tray's number is the window's: it follows what is waiting, by the rail's rule.
const stage = (patch) => page.evaluate(`(() => { const s = window.__mohoShots.state(); const id = s.buffers.find((b) => b.kind === 'channel' && b.id.startsWith('checker')).id; window.__chan = id; window.__mohoShots.patch({ buffers: s.buffers.map((b) => (b.id === id ? { ...b, ...(${JSON.stringify(patch)}) } : b)) }); return id })()`)
const counted = async (want, what) => {
await until(main, `(() => { const s = globalThis.__mohoTray.state(); return s.mentions === ${want.mentions} && s.dms === ${want.dms} })()`, what)
check(true, what)
}
await tray('t.update({ unread: 0, dms: 0, mentions: 0 })')
const chan = await stage({ unread: 33, mentions: 2, highlight: true })
await counted({ mentions: 2, dms: 0 }, 'two mentions in a busy channel make the tray say two, not thirty-three')
check((await tray('t.state().latest')) === chan, 'and the menu opens that channel')
// Said the way another window would say it, through main.
const chanId = await page.evaluate('window.__chan')
await tray(`t.pref('mutedBuffers', [${JSON.stringify(chanId)}])`)
await counted({ mentions: 2, dms: 0 }, 'muting it leaves its mentions on the tray - a mute stops the popups, not the count')
await stage({ unread: 40, mentions: 0, highlight: false })
await counted({ mentions: 0, dms: 0 }, 'and what else is said in it counts for nothing')
await tray("t.pref('mutedBuffers', [])")
await stage({ unread: 33, mentions: 2, highlight: true })
await counted({ mentions: 2, dms: 0 }, 'unmuting changes nothing about the number')
await stage({ unread: 0, mentions: 0, highlight: false })
await counted({ mentions: 0, dms: 0 }, 'reading it somewhere else clears the tray as it clears the window')
await page.evaluate(`(() => { const s = window.__mohoShots.state(); window.__mohoShots.patch({ buffers: [...s.buffers, { id: 'checker@localhost|bobdm', accountId: s.accounts[0].id, kind: 'dm', name: 'bob', lastActivityTs: 1, unread: 3, highlight: false, mentions: 0 }] }); return true })()`)
await counted({ mentions: 0, dms: 3 }, 'a direct message counts for each unread message in it')
check(/3 direct messages/.test(await tray('t.tooltip()')), 'and the tooltip says so', await tray('t.tooltip()'))
await page.evaluate(`(() => { const s = window.__mohoShots.state(); window.__mohoShots.patch({ buffers: s.buffers.filter((b) => b.id !== 'checker@localhost|bobdm') }); return true })()`)
await counted({ mentions: 0, dms: 0 }, 'and the tray is empty again')
} finally {
irc.close()
}
// The tray being redrawn - which it is whenever something unread changes - must
// not move the window: somebody who has chosen another server stays on it. The
// redraw tells the window the link is up, and taking each for a reconnection
// sent the pane back to the server of whatever conversation was open.
const away = await page.evaluate('window.__mohoShots.state().activeGroupId')
await page.evaluate('window.__mohoShots.store.selectGroup("~mentions")')
for (let i = 0; i < 6; i++) {
await tray(`t.update({ unread: ${i}, dms: ${i}, mentions: 0 })`)
await sleep(200)
}
await sleep(1500)
const stayed = await page.evaluate('window.__mohoShots.state().activeGroupId')
check(stayed === '~mentions', 'a redrawn tray leaves the chosen server chosen', `${away} -> ${stayed}`)
await tray('t.update({ unread: 0, dms: 0, mentions: 0 })')
// Using a window is heard by main - and only that it happened.
const heardBefore = await tray('t.lastActivity()')
await sleep(6000)
await page.call('Input.dispatchMouseEvent', { type: 'mouseMoved', x: 300, y: 300, button: 'none', clickCount: 0 })
await sleep(500)
const heardAfter = await tray('t.lastActivity()')
check(heardAfter > heardBefore, 'moving the pointer in a window is heard as being here', `${heardBefore} -> ${heardAfter}`)
// Restart brings back moho and a daemon of its own.
const before = daemons(scratchDir)
const pidBefore = await main.evaluate('process.pid')
check(before.length === 1, 'one daemon is running', String(before))
// Not waited for: the app quits under this call, and the inspector with it.
void tray('t.click(["Restart moho"])').catch(() => {})
// And the inspector let go, because a process that is being inspected waits
// for the inspector to disconnect before it will exit.
await sleep(500)
main.close()
let pidAfter = pidBefore
let again = null
for (let i = 0; i < 80 && pidAfter === pidBefore; i++) {
await sleep(500)
try {
again = await mainProcess(inspectPort)
pidAfter = await again.evaluate('process.pid')
} catch {
/* between the two */
}
}
check(pidAfter !== pidBefore, 'moho came back as a new process', `${pidBefore} -> ${pidAfter}`)
await sleep(4000)
const after = daemons(scratchDir)
check(after.length === 1 && !before.includes(after[0]), 'with a daemon of its own, the old one gone', `${before} -> ${after}`)
// Whatever it started has to go with this run.
try {
for (const pid of daemons(scratchDir)) process.kill(pid, 'SIGTERM')
} catch {
/* gone */
}
} catch (e) {
console.log('FAIL', e.message)
failures++
} finally {
// The relaunched copy is not the one the harness started, so it is not in the
// group stop() ends. It is found by the debugging port it was told to use -
// it shows no environment to be found by - and what it started goes when it
// does. Ended first, and twice since it may still be starting, because it
// writes into the directory stop() is about to remove.
for (let i = 0; i < 2; i++) {
await sleep(1500)
try {
execFileSync('pkill', ['-9', '-f', `remote-debugging-port=${port}`])
} catch {
/* none left */
}
for (const entry of fs.readdirSync('/proc')) {
if (!/^\d+$/.test(entry) || Number(entry) === process.pid || !scratchDir) continue
try {
if (fs.readFileSync(`/proc/${entry}/environ`, 'utf8').includes(`HOME=${scratchDir}\0`)) process.kill(Number(entry), 'SIGKILL')
} catch {
/* gone, or not ours to read */
}
}
}
await sleep(1500)
await stop().catch(() => {})
if (scratchDir) fs.rmSync(scratchDir, { recursive: true, force: true })
}
console.log(failures ? `${failures} failed` : 'all passed')
process.exit(failures ? 1 : 0)
+132 -3
View File
@@ -94,14 +94,14 @@ const DISCORD = `(() => {
const ch = (id, name, category, extra = {}) => ({
id: acc + '|' + id, accountId: acc, kind: 'channel', name: 'Button Eye Crochet/#' + name,
lastActivityTs: now, groupId: g1, category, position: Number(id.replace(/\\D/g, '')) || 0,
unread: 0, highlight: false, ...extra
unread: 0, highlight: false, mentions: 0, ...extra
})
const buffers = [
ch('c1', '📜-rules', undefined),
ch('c2', '📢-announcements', undefined, { unread: 2 }),
ch('c3', '🤠-general', 'TEXT CHANNELS'),
ch('c4', '📹-clips', 'TEXT CHANNELS', { unread: 5 }),
ch('c5', '📷-screenshots', 'TEXT CHANNELS', { unread: 1, highlight: true }),
ch('c5', '📷-screenshots', 'TEXT CHANNELS', { unread: 1, highlight: true, mentions: 1 }),
ch('c6', '💩-shitpost', 'TEXT CHANNELS', { unread: 9 }),
ch('c7', '🎨-crafts', 'TEXT CHANNELS'),
ch('c8', '🐈-cats', 'ANIMALS', { unread: 3 }),
@@ -136,7 +136,7 @@ const DISCORD = `(() => {
{ id: g2, accountId: acc, service: 'discord', kind: 'guild', name: 'Moho Dev', position: 1 }
],
buffers: [...s.buffers.filter((b) => b.accountId !== acc), ...buffers,
{ id: acc + '|d1', accountId: acc, kind: 'channel', name: 'Moho Dev/#general', lastActivityTs: now, groupId: g2, unread: 2, highlight: true }],
{ id: acc + '|d1', accountId: acc, kind: 'channel', name: 'Moho Dev/#general', lastActivityTs: now, groupId: g2, unread: 33, highlight: true, mentions: 2 }],
messagesByBuffer: { ...s.messagesByBuffer, [general]: messages },
presenceByBuffer: { ...s.presenceByBuffer, [general]: members([['Gaunt King', 'online'], ['Clarence', 'idle'], ['Wren', 'dnd'], ['Salastil', 'online'], ['Old Friend', 'offline'], ['Quiet One', 'offline']]) },
activeGroupId: g1,
@@ -171,6 +171,76 @@ const discord = (inCall) => async (page) => {
await sleep(300)
}
// --- GIFs (#331) ---------------------------------------------------------------
/**
* Three messages that link to GIFs, with or without what the daemon or Discord
* says about them: a Tenor page, a Giphy page and a Klipy page. Without, they
* are the addresses they were before; with, the first two are the GIFs - the
* Klipy page is one nothing can read, and stays a link either way.
*
* The pictures are made with ffmpeg and handed to the window as blob and data
* URLs, since it plays only https media and nothing is fetched from anywhere.
*/
const stageGifs = (withEmbeds) => async (page) => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'moho-gifs-'))
const clip = (name, source) => {
const file = path.join(dir, name)
execFileSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', source, '-pix_fmt', 'yuv420p', '-y', file])
return fs.readFileSync(file).toString('base64')
}
const mp4 = clip('cat.mp4', 'gradients=s=300x200:d=3:r=15:speed=0.02:c0=0xe0a43a:c1=0xb0457a:c2=0x3a8fe0:nb_colors=3')
const gif = (() => {
const file = path.join(dir, 'wave.gif')
execFileSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'gradients=s=260x180:d=2:r=12:speed=0.03:c0=0x3ae0a4:c1=0x4a2f9a:nb_colors=2', '-y', file])
return fs.readFileSync(file).toString('base64')
})()
fs.rmSync(dir, { recursive: true, force: true })
await page.evaluate(`(() => {
const shots = window.__mohoShots
const s = shots.state()
const id = s.activeBufferId
const now = Math.floor(Date.now() / 1000)
const bytes = Uint8Array.from(atob('${mp4}'), (c) => c.charCodeAt(0))
const MP4 = URL.createObjectURL(new Blob([bytes], { type: 'video/mp4' }))
const GIF = 'data:image/gif;base64,${gif}'
const msg = (n, from, body, embeds) => ({ id: 'gif' + n, bufferId: id, from, senderId: from, body, ts: now - (60 - n) * 20, isAction: false, isHighlight: false, kind: 'chat', isOwn: false, ...(embeds ? { embeds } : {}) })
const embeds = ${withEmbeds ? 'true' : 'false'}
shots.patch({ messagesByBuffer: { ...s.messagesByBuffer, [id]: [...(s.messagesByBuffer[id] || []),
msg(1, 'alice', 'this is how it feels on a monday https://tenor.com/view/monday-cat-gif-22954713', embeds ? [{ kind: 'gif', url: 'https://tenor.com/view/monday-cat-gif-22954713', mediaUrl: MP4, mediaKind: 'video', width: 300, height: 200, provider: 'Tenor' }] : undefined),
msg(2, 'bob', 'https://giphy.com/gifs/wave-hello-Z7wFi5b2VEAr6', embeds ? [{ kind: 'gif', url: 'https://giphy.com/gifs/wave-hello-Z7wFi5b2VEAr6', mediaUrl: GIF, mediaKind: 'image', width: 260, height: 180, provider: 'Giphy' }] : undefined),
msg(3, 'carol', 'and from klipy: https://klipy.com/gifs/friends-joey-53')
] } })
return true
})()`)
await sleep(900)
}
/** The GIF picker, open, with a handful of invented GIFs to look through. */
const openGifPicker = async (page) => {
await page.evaluate(`(() => {
const shots = window.__mohoShots
const s = shots.state()
const art = (a, b, label, w, h) => 'data:image/svg+xml;utf8,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="' + w + '" height="' + h + '" viewBox="0 0 ' + w + ' ' + h + '"><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="' + a + '"/><stop offset="1" stop-color="' + b + '"/></linearGradient></defs><rect width="' + w + '" height="' + h + '" fill="url(#g)"/><text x="' + (w / 2) + '" y="' + (h / 2 + 14) + '" font-size="44" font-family="sans-serif" fill="#fff" text-anchor="middle">' + label + '</text></svg>')
const gif = (id, title, a, b, w, h) => ({ id, title, url: 'https://tenor.com/view/' + id, src: '', gifSrc: '', preview: art(a, b, title, w, h), width: w, height: h })
window.__gifFixture = {
categories: [{ name: 'reaction', src: '' }, { name: 'happy', src: '' }, { name: 'dancing', src: '' }, { name: 'cats', src: '' }, { name: 'applause', src: '' }, { name: 'facepalm', src: '' }],
gifs: [
gif('1', 'cat dance', '#e0a43a', '#b0457a', 480, 300), gif('2', 'thumbs up', '#3a8fe0', '#4a2f9a', 300, 300),
gif('3', 'happy dog', '#3ae0a4', '#1f6f5a', 480, 270), gif('4', 'mind blown', '#e05a3a', '#7a2f2f', 300, 360),
gif('5', 'clapping', '#8a5ae0', '#3a3fa0', 480, 270), gif('6', 'wow', '#e0d03a', '#a07a1f', 300, 300)
]
}
shots.patch({ accounts: [...s.accounts, { id: 'discord:gifs', service: 'discord', displayName: 'x', state: 'connected', autojoin: '', currentNick: 'x', status: 'online', useTor: false, ssl: true }] })
return true
})()`)
await sleep(500)
await page.evaluate(click('button[title="GIFs"]'))
await until(page, 'document.querySelector(".gif-cell")', 'the GIFs')
await sleep(500)
}
// --- scenes ------------------------------------------------------------------
/** Messages with several pictures, one of them a spoiler (#304): two, three and four, then a lone spoiler. */
@@ -270,6 +340,52 @@ const setMode = async (page, mode) => {
* `video` scenes are recorded instead, while `act` runs.
*/
const SCENES = [
{
name: 'gif-links-before',
setup: async (p) => { await setMode(p, 'comfy'); await openChannel(p, '#general'); await stageGifs(false)(p) }
},
{
name: 'gif-links-after',
setup: async (p) => { await setMode(p, 'comfy'); await openChannel(p, '#general'); await stageGifs(true)(p) }
},
{
name: 'gif-picker',
setup: async (p) => { await setMode(p, 'comfy'); await openChannel(p, '#general'); await openGifPicker(p) }
},
{
// What somebody did on a Kick stream: KICKs sent, subscriptions gifted. Put
// on a channel's messages directly - a stream is not here to do it.
name: 'kick-events',
setup: async (p, mode = 'classic') => {
await setMode(p, mode)
await openChannel(p, '#general')
await p.evaluate(`(() => {
const shots = window.__mohoShots
const s = shots.state()
const id = s.activeBufferId
const now = Math.floor(Date.now() / 1000)
const row = (n, kind, body, embed, from = 'bob') => ({ id: 'k' + n, bufferId: id, from, senderId: from, body, ts: now - 60 + n, isAction: false, isHighlight: false, kind, isOwn: false, embeds: embed ? [embed] : [] })
const chat = (n, from, body) => row(n, 'chat', body, null, from)
shots.patch({ messagesByBuffer: { ...s.messagesByBuffer, [id]: [
chat(1, 'bob', 'that was a clean run'),
row(2, 'kicks', 'Currington sent 1 Kick', { kind: 'kicks', author: 'Currington', authorColor: '#75FD46', title: '1', provider: 'Hell Yeah', color: 0x53fc18 }),
chat(3, 'carol', 'lets gooo'),
row(4, 'kicks', 'Maverick sent 500 Kicks: take my money', { kind: 'kicks', author: 'Maverick', authorColor: '#E26EFF', title: '500', provider: 'Full Send', description: 'take my money', color: 0xb45cff }),
row(5, 'sub', 'ItsDez gifted 5 subscriptions', { kind: 'gift-sub', author: 'ItsDez', title: '5', description: 'Interstelar\\nRon_OSRS\\nAuzzzii\\nMeowtimeJay\\nstradivarius31' }),
row(6, 'sub', 'LurkinLeepa gifted a subscription', { kind: 'gift-sub', author: 'LurkinLeepa', title: '1', description: 'onkhell' }),
row(10, 'sub', 'bigkhernandez subscribed - 21 months', { kind: 'subscribe', author: 'bigkhernandez', title: '21' }),
row(11, 'moderation', 'troll was timed out by mod', { kind: 'moderation', author: 'troll', title: 'was timed out', description: 'mod' }),
row(12, 'stream', 'went live', { kind: 'stream', author: 'streamer', title: 'went live', icon: 'live' }),
row(7, 'raid', 'kreationX raided with 25 viewers', { kind: 'raid', author: 'kreationX', title: '25' }),
row(8, 'reward', 'onkhell redeemed 5 TONGUE TWISTERS', { kind: 'redeem', author: 'onkhell', title: '5 TONGUE TWISTERS', color: 0xff55b3 }),
chat(9, 'bob', 'thanks everybody')
] } })
})()`)
await sleep(500)
}
},
{ name: 'kick-events-comfy', setup: async (p) => { await SCENES.find((x) => x.name === 'kick-events').setup(p, 'comfy') } },
{ name: 'kick-events-bubbles', setup: async (p) => { await SCENES.find((x) => x.name === 'kick-events').setup(p, 'bubbles') } },
{ name: 'irc-channel-comfy', setup: async (p) => { await setMode(p, 'comfy'); await openChannel(p, '#general') } },
{
// History from several days, scrolled to its start: where date
@@ -511,6 +627,19 @@ const SCENES = [
await sleep(300)
}
},
{
name: 'settings-presence',
setup: async (p) => {
await p.evaluate(`window.__mohoShots.store.setActivePanel('settings')`)
await sleep(400)
await p.evaluate(`(() => {
const el = [...document.querySelectorAll('h1, h2, h3, h4, .settings-section-title')].find((e) => e.textContent.trim() === 'Presence')
el?.scrollIntoView({ block: 'start' })
return !!el
})()`)
await sleep(400)
}
},
{ name: 'settings-general', setup: async (p) => { await p.evaluate(`window.__mohoShots.store.setActivePanel('settings')`); await sleep(400) } },
{
name: 'settings-tor',
+107
View File
@@ -0,0 +1,107 @@
import { describe, expect, it } from 'vitest'
import { IdleWatcher } from './idle'
const MIN = 60_000
/** A watcher on a clock the test holds, with the system's idle time a figure it sets. */
function watcher(over: { enabled?: boolean; minutes?: number } = {}): {
w: IdleWatcher
clock: { now: number; system: number; enabled: boolean }
said: boolean[]
} {
const clock = { now: 1_000_000, system: 0, enabled: over.enabled ?? true }
const said: boolean[] = []
const w = new IdleWatcher({
now: () => clock.now,
systemIdleSeconds: () => clock.system,
enabled: () => clock.enabled,
thresholdMs: () => (over.minutes ?? 10) * MIN,
onChange: (idle) => said.push(idle)
})
return { w, clock, said }
}
describe('being away, by moho\'s own windows', () => {
it('is away after the threshold with nothing touched, and says so once', () => {
const { w, clock, said } = watcher()
clock.now += 9 * MIN
w.evaluate()
expect(w.isIdle()).toBe(false)
clock.now += 2 * MIN
w.evaluate()
w.evaluate()
expect(w.isIdle()).toBe(true)
expect(said).toEqual([true])
})
it('is back the moment anything is used', () => {
const { w, clock, said } = watcher()
clock.now += 11 * MIN
w.evaluate()
w.activity()
expect(w.isIdle()).toBe(false)
expect(said).toEqual([true, false])
})
it('counts use as starting the clock again', () => {
const { w, clock } = watcher()
clock.now += 9 * MIN
w.activity()
clock.now += 9 * MIN
w.evaluate()
expect(w.isIdle()).toBe(false)
})
it('does nothing at all when it is switched off', () => {
const { w, clock, said } = watcher({ enabled: false })
clock.now += 60 * MIN
w.evaluate()
expect(said).toEqual([])
})
it('comes back when it is switched off while away', () => {
const { w, clock, said } = watcher()
clock.now += 11 * MIN
w.evaluate()
clock.enabled = false
w.evaluate()
expect(said).toEqual([true, false])
})
})
describe('being away, by the system\'s idle time', () => {
it('does not take a zero that never changes for somebody who never stops', () => {
// A platform that cannot say reports zero for ever; moho's own windows decide.
const { w, clock } = watcher()
clock.system = 0
clock.now += 11 * MIN
w.evaluate()
expect(w.isIdle()).toBe(true)
})
it('believes the system once it has been seen to be anything but zero, and counts use elsewhere as being here', () => {
const { w, clock } = watcher()
clock.system = 3
w.evaluate()
// Eleven minutes of not touching moho, but the keyboard was used a minute ago.
clock.now += 11 * MIN
clock.system = 60
w.evaluate()
expect(w.isIdle()).toBe(false)
// And then it really is eleven minutes everywhere.
clock.system = 11 * 60
w.evaluate()
expect(w.isIdle()).toBe(true)
})
})
describe('locking', () => {
it('is away at once when the screen locks and back when it unlocks', () => {
const { w, said } = watcher()
w.lock()
expect(w.isIdle()).toBe(true)
w.unlock()
expect(w.isIdle()).toBe(false)
expect(said).toEqual([true, false])
})
})
+97
View File
@@ -0,0 +1,97 @@
/**
* Whether the person has stepped away, which is all this knows.
*
* Discord's own client and every IRC client that sets itself away work from the
* same one fact - how long since anything was touched - and nothing else: not
* what is on screen, not what was typed, not which program is in front. This is
* kept to that, and is deliberately small: a clock, two sources of "how long",
* and a threshold.
*
* The two sources are the system's own idle time, where the platform will say
* (Windows, macOS, X11), and moho's own windows being used, which every
* platform can say. Some Wayland desktops give Chromium no idle time at all and
* report zero for ever, which looks exactly like somebody who never stops
* typing; so the system's figure is only believed once it has been seen to be
* anything but zero, and until then - and where it never is - moho goes by its
* own windows.
*/
export interface IdleOptions {
now: () => number
/** Seconds since the last keyboard or mouse input anywhere; 0 where the platform cannot say. */
systemIdleSeconds: () => number
enabled: () => boolean
thresholdMs: () => number
/** Said when the answer changes, and only then. */
onChange: (idle: boolean) => void
}
export class IdleWatcher {
private lastActivity: number
private systemKnown = false
private away = false
/** The screen is locked or the machine asleep: away at once, whatever the clock says. */
private locked = false
private forced: boolean | null = null
constructor(private o: IdleOptions) {
this.lastActivity = o.now()
}
isIdle(): boolean {
return this.away
}
/** When something was last used in a moho window, for the harness to see that it was heard. */
lastActivityAt(): number {
return this.lastActivity
}
/** Something was used in a moho window - including coming back to one. */
activity(): void {
this.lastActivity = this.o.now()
this.locked = false
this.evaluate()
}
lock(): void {
this.locked = true
this.evaluate()
}
unlock(): void {
this.locked = false
this.lastActivity = this.o.now()
this.evaluate()
}
/** For the harness: an answer that the clock does not get to change. */
forceForTesting(idle: boolean | null): void {
this.forced = idle
this.evaluate()
}
/** Asks the clocks, and says so if the answer is different. Run on a timer, and when a setting moves. */
evaluate(): void {
this.set(this.decide())
}
private decide(): boolean {
if (this.forced !== null) return this.forced
if (!this.o.enabled()) return false
if (this.locked) return true
const system = this.o.systemIdleSeconds()
if (system > 0) this.systemKnown = true
const own = this.o.now() - this.lastActivity
// Whichever is shorter: a keystroke in another program counts as being
// here once the system can say so, and one in moho counts either way.
const idleFor = this.systemKnown ? Math.min(own, system * 1000) : own
return idleFor >= this.o.thresholdMs()
}
private set(idle: boolean): void {
if (idle === this.away) return
this.away = idle
this.o.onChange(idle)
}
}
+223 -73
View File
@@ -11,18 +11,23 @@ import {
globalShortcut,
ipcMain,
nativeImage,
nativeTheme,
net,
powerMonitor,
session,
Menu,
screen,
shell,
Tray
Tray,
type MenuItemConstructorOptions
} from 'electron'
import { electronApp, is, optimizer } from '@electron-toolkit/utils'
import { defaultSocketPath, NobilisClient } from './nobilis-client'
import { NobilisProcess } from './nobilis-process'
import { Prefs } from './prefs'
import { Notifier } from './notifications'
import { IdleWatcher } from './idle'
import { NOTHING_WAITING, trayIconFile, trayMenu, trayTooltip, type TrayState, type TrayStatus } from './tray'
import { browserLogin, LOGIN_FLOWS } from './browser-login'
import { EDIT_ACTIONS, IPC, POPOUT_FLAG, UI_SHOTS_FLAG, type EditAction, type EditMenuRequest, type PopoutState } from '../shared/ipc'
import { clearnetLinks } from '../shared/clearnet'
@@ -131,6 +136,7 @@ let prefs: Prefs
let nobilis: NobilisProcess
let client: NobilisClient
let notifier: Notifier
let idleWatcher: IdleWatcher
let registeredHotkey: string | null = null
/**
@@ -190,6 +196,52 @@ function sniffImage(head: Buffer): string | null {
}
/** Every window with a renderer in it, main and popped-out conversations alike. */
/**
* Sets a preference and tells whoever holds a copy of it.
*
* `except` is the window that made the change, which already knows and has
* drawn it. The tray's own entries come through here too, so a setting flipped
* from the tray moves its switch in Settings.
*/
function applyPref(key: string, value: unknown, except?: Electron.WebContents): void {
prefs.set(key, value)
// The badge and the flash are decided from these as they stand.
if (key === 'notifications.badge' || key === 'notifications.flash') updateTray(lastTray)
// Every window keeps its own cache of these, so a setting changed in one
// is stale in the others until they are told. That is not cosmetic once
// there are several windows: muting a conversation, or switching the log
// to compact, would apply to whichever window happened to be asked.
for (const w of liveWindows()) {
if (w.webContents !== except) w.webContents.send(IPC.prefsChanged, key, value)
}
// Pins and mutes feed the tray/notification rules, which live here.
if (key === 'pinnedBuffers' || key === 'mutedBuffers') notifier.publish()
if (key === 'hotkey.toggle') applyHotkey(String(value))
if (key === 'presence.autoIdle' || key === 'presence.autoIdleMinutes') idleWatcher?.evaluate()
}
/**
* Brings up a conversation: a click on its notification, or on the tray's
* "open" entry.
*
* If it has a window of its own, that window is what the click asked for.
* Raising the main one and switching it would move somebody away from whatever
* they were reading in order to show them a conversation that was already open
* on their screen.
*/
function openConversation(bufferId: string): void {
const popout = popouts.get(bufferId)
if (popout && !popout.isDestroyed()) {
if (popout.isMinimized()) popout.restore()
popout.show()
popout.focus()
return
}
mainWindow?.show()
mainWindow?.focus()
mainWindow?.webContents.send(IPC.activateBuffer, bufferId)
}
function liveWindows(): BrowserWindow[] {
const all = mainWindow ? [mainWindow, ...popouts.values()] : [...popouts.values()]
return all.filter((w) => !w.isDestroyed())
@@ -353,6 +405,9 @@ function createWindow(): void {
pendingDeepLink = null
mainWindow?.webContents.send(IPC.deepLink, url)
})
// The tray's first action is to show or hide this window, and says which.
mainWindow.on('show', refreshTrayMenu)
mainWindow.on('hide', refreshTrayMenu)
mainWindow.on('maximize', () => mainWindow?.webContents.send(IPC.maximizeChanged, true))
mainWindow.on('unmaximize', () => mainWindow?.webContents.send(IPC.maximizeChanged, false))
mainWindow.on('closed', () => {
@@ -562,61 +617,112 @@ function toggleWindow(): void {
}
}
function trayIcon(hasAlert: boolean): Electron.NativeImage {
const file = resourcePath('icons', hasAlert ? 'tray-alert.png' : 'tray.png')
const img = nativeImage.createFromPath(file)
function trayIcon(unread: number): Electron.NativeImage {
lastTrayIcon = trayIconFile(nativeTheme.shouldUseDarkColors, unread)
const img = nativeImage.createFromPath(resourcePath('icons', lastTrayIcon))
// A missing icon file would otherwise produce an invisible tray entry the
// user can never click; fall back to the app icon so the entry still exists.
return img.isEmpty() ? nativeImage.createFromPath(resourcePath('icons', 'moho.png')) : img
}
function createTray(): void {
tray = new Tray(trayIcon(false))
tray.setToolTip('moho')
tray.setContextMenu(
Menu.buildFromTemplate([
{ label: 'Show/hide', click: toggleWindow },
{ label: 'Restart daemon', click: () => nobilis.restart() },
{
label: 'Stop daemon',
// Deliberately separate from Quit: stopping the daemon disconnects
// every account, which is worth asking for explicitly rather than
// making it a side effect of closing a window.
click: () => {
void stopDaemon()
}
/** What the window last said each connected account's status is. */
let accountStatus: Record<string, string> = {}
/** The status the menu shows as checked, and the ones it offers: what the connected accounts can be set to. */
let trayStatus: TrayStatus | null = null
let trayOffered: TrayStatus[] = []
let trayInvisibleName = 'Invisible'
const isTrayStatus = (v: unknown): v is TrayStatus => v === 'online' || v === 'idle' || v === 'dnd' || v === 'invisible'
/**
* Asks the window to do something, showing it first: the tray's entries that
* are about moho itself - settings, and a status set across every account -
* are the window's to carry out, since it is what holds the accounts.
*/
function tellWindow(command: 'settings' | 'status', arg?: string): void {
if (!mainWindow) createWindow()
if (command === 'settings') {
mainWindow?.show()
mainWindow?.focus()
}
mainWindow?.webContents.send(IPC.trayCommand, command, arg)
}
/**
* Starts moho again, daemon and all.
*
* Quitting already takes the daemon down cleanly - QUIT to every network, then
* gone - and the new process starts its own, so restarting is quit-and-relaunch.
* An AppImage has to be relaunched by the path it was started from: its
* executable is a temporary mount that disappears when it exits.
*/
function restartMoho(): void {
const appImage = process.env.APPIMAGE
app.relaunch(appImage ? { execPath: appImage, args: process.argv.slice(1) } : undefined)
app.quit()
}
/** What the tray last offered and showed, kept for the UI harness to read. */
let lastTrayMenu: MenuItemConstructorOptions[] = []
let lastTrayIcon = ''
let lastTrayTooltip = 'moho'
function refreshTrayMenu(): void {
if (!tray) return
lastTrayMenu = trayMenu(
{
state: lastTray,
windowVisible: !!mainWindow && !mainWindow.isDestroyed() && mainWindow.isVisible(),
status: trayStatus,
offered: trayOffered,
invisibleName: trayInvisibleName
},
{
toggleWindow,
openLatest: () => {
const id = lastTray.latest ?? notifier.latestUnread()
if (id) openConversation(id)
},
{ type: 'separator' },
{
label: 'Quit',
click: () => {
app.quit()
}
}
])
openSettings: () => tellWindow('settings'),
setStatus: (status) => {
trayStatus = status
tellWindow('status', status)
},
restart: restartMoho,
quit: () => app.quit()
}
)
tray.setContextMenu(Menu.buildFromTemplate(lastTrayMenu))
}
function createTray(): void {
tray = new Tray(trayIcon(0))
tray.setToolTip('moho')
refreshTrayMenu()
tray.on('click', toggleWindow)
// The icon is drawn for the panel it sits on, so it is drawn again when the
// system changes colour scheme.
nativeTheme.on('updated', () => updateTray(lastTray))
}
/** What the notifier last said, kept so a change of setting can redraw without waiting for the next message. */
let lastUnread = 0
let lastAlert = false
let lastTray: TrayState = NOTHING_WAITING
function updateTray(unreadCount: number, hasAlert: boolean): void {
lastUnread = unreadCount
lastAlert = hasAlert
// The unread badge: the tray's alert dot and count, and the launcher's
// count where the desktop has one. Off, the tray is just the tray.
function updateTray(state: TrayState): void {
lastTray = state
// The unread badge: the tray's count and the launcher's count where the
// desktop has one. Off, the tray is just the tray.
const badge = prefs.get<boolean>('notifications.badge', true)
app.setBadgeCount(badge ? unreadCount : 0)
app.setBadgeCount(badge ? state.unread : 0)
// The taskbar flash: asking for attention while the window is not in front.
const flash = prefs.get<boolean>('notifications.flash', true)
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.flashFrame(flash && hasAlert && !mainWindow.isFocused())
mainWindow.flashFrame(flash && state.unread > 0 && trayStatus !== 'dnd' && !mainWindow.isFocused())
}
refreshTrayMenu()
if (!tray) return
tray.setImage(trayIcon(badge && hasAlert))
tray.setToolTip(badge && unreadCount > 0 ? `moho - ${unreadCount} unread` : 'moho')
tray.setImage(trayIcon(badge ? state.unread : 0))
lastTrayTooltip = trayTooltip(state, badge)
tray.setToolTip(lastTrayTooltip)
send(IPC.link, client.linkUp)
}
@@ -667,21 +773,27 @@ function wireIpc(): void {
})
ipcMain.handle(IPC.prefsGetAll, () => prefs.all())
ipcMain.handle(IPC.prefsSet, (e, key: string, value: unknown) => {
prefs.set(key, value)
// The badge and the flash are decided from these as they stand.
if (key === 'notifications.badge' || key === 'notifications.flash') updateTray(lastUnread, lastAlert)
// Every window keeps its own cache of these, so a setting changed in one
// is stale in the others until they are told. That is not cosmetic once
// there are several windows: muting a conversation, or switching the log
// to compact, would apply to whichever window happened to be asked.
// Not echoed to the window that set it - it already knows, and has drawn.
for (const w of liveWindows()) {
if (w.webContents !== e.sender) w.webContents.send(IPC.prefsChanged, key, value)
}
// Pins and mutes feed the tray/notification rules, which live here.
if (key === 'pinnedBuffers' || key === 'mutedBuffers') notifier.publish()
if (key === 'hotkey.toggle') applyHotkey(String(value))
ipcMain.handle(IPC.prefsSet, (e, key: string, value: unknown) => applyPref(key, value, e.sender))
// The window says what status its accounts are at, for the tray's menu to check.
ipcMain.on(IPC.trayStatus, (_e, statuses: Record<string, string>, offered: string[], shown: string | null, invisibleName: string) => {
accountStatus = statuses && typeof statuses === 'object' ? statuses : {}
trayOffered = Array.isArray(offered) ? offered.filter(isTrayStatus) : []
trayStatus = isTrayStatus(shown) ? shown : null
trayInvisibleName = invisibleName === 'Offline' ? 'Offline' : 'Invisible'
refreshTrayMenu()
// Do not disturb is asking for quiet, including from the taskbar.
updateTray(lastTray)
})
ipcMain.on(IPC.activity, () => idleWatcher.activity())
// What is waiting, as the window counts it. The tray's number is the window's
// own: counted here from notifications it drifted from what the window showed.
ipcMain.on(IPC.trayUnread, (_e, count: { dms: number; mentions: number; latest: string | null }) => {
const dms = Math.max(0, Number(count?.dms) || 0)
const mentions = Math.max(0, Number(count?.mentions) || 0)
updateTray({ unread: dms + mentions, dms, mentions, latest: typeof count?.latest === 'string' ? count.latest : null })
})
ipcMain.handle(IPC.markBufferRead, (_e, bufferId: string) => notifier.clear(bufferId))
@@ -790,10 +902,19 @@ function wireIpc(): void {
return res.canceled || !res.filePath ? null : res.filePath
})
ipcMain.handle(IPC.pickFile, async (e) => {
ipcMain.handle(IPC.pickFile, async (e, extensions?: string[]) => {
const parent = callerWindow(e) ?? mainWindow
if (!parent) return null
const res = await dialog.showOpenDialog(parent, { properties: ['openFile'] })
// Where a service takes only some kinds of file, the dialog shows only
// those and has no "all files" to widen it: a file that would be refused
// is not offered. Extensions only, as the dialog wants them - no dots.
const taken = Array.isArray(extensions)
? extensions.filter((x): x is string => typeof x === 'string' && /^[A-Za-z0-9]{1,8}$/.test(x))
: []
const res = await dialog.showOpenDialog(parent, {
properties: ['openFile'],
...(taken.length ? { filters: [{ name: 'Pictures and videos', extensions: taken }] } : {})
})
if (res.canceled || !res.filePaths[0]) return null
// The renderer draws a thumbnail of what was staged, and that goes back
// through the guarded media scheme like every other local file. Where
@@ -1137,32 +1258,38 @@ app.whenReady().then(() => {
nobilis = new NobilisProcess()
client = new NobilisClient()
// Going idle when the person steps away. What it says, and to whom, is
// decided in the daemon - which accounts are online, which are in a call -
// so all this says is whether they are here.
idleWatcher = new IdleWatcher({
now: () => Date.now(),
systemIdleSeconds: () => powerMonitor.getSystemIdleTime(),
enabled: () => prefs.get<boolean>('presence.autoIdle', true),
thresholdMs: () => (Number(prefs.get<unknown>('presence.autoIdleMinutes', '10')) || 10) * 60_000,
onChange: (idle) => void client.request('setUserIdle', { idle }).catch(() => {})
})
setInterval(() => idleWatcher.evaluate(), 10_000).unref()
app.on('browser-window-focus', () => idleWatcher.activity())
powerMonitor.on('lock-screen', () => idleWatcher.lock())
powerMonitor.on('suspend', () => idleWatcher.lock())
powerMonitor.on('unlock-screen', () => idleWatcher.unlock())
powerMonitor.on('resume', () => idleWatcher.unlock())
notifier = new Notifier(
prefs,
updateTray,
(bufferId) => {
// If this conversation has a window of its own, that window is what the
// click asked for. Raising the main one and switching it would move
// somebody away from whatever they were reading in order to show them a
// conversation that was already open on their screen.
const popout = popouts.get(bufferId)
if (popout && !popout.isDestroyed()) {
if (popout.isMinimized()) popout.restore()
popout.show()
popout.focus()
return
}
mainWindow?.show()
mainWindow?.focus()
mainWindow?.webContents.send(IPC.activateBuffer, bufferId)
},
// The tray's number is the window's, not this tally's - see IPC.trayUnread.
() => {},
openConversation,
() => mainWindow?.webContents ?? null,
(bufferId) => popoutState().watched.includes(bufferId)
(bufferId) => popoutState().watched.includes(bufferId),
(accountId) => accountStatus[accountId] === 'dnd'
)
client.on('link', (up) => {
send(IPC.link, up)
if (!up) return
// A daemon that has just started knows nothing of this.
if (idleWatcher.isIdle()) void client.request('setUserIdle', { idle: true }).catch(() => {})
// Before anything is fetched for the window: whether its own traffic goes
// through Tor or the proxy is the daemon's setting, asked of it here.
void applyTunnel((method, params) => client.request(method, params))
@@ -1204,6 +1331,29 @@ app.whenReady().then(() => {
createWindow()
createTray()
applyHotkey(prefs.get<string>('hotkey.toggle'))
// For the UI harness, which has no way to look inside a tray: what it shows
// and offers, and the entries themselves to be clicked. Only when it asks.
if (process.env.MOHO_UI_SHOTS === '1') {
;(globalThis as Record<string, unknown>).__mohoTray = {
update: updateTray,
idle: (v: boolean | null) => idleWatcher.forceForTesting(v),
lastActivity: () => idleWatcher.lastActivityAt(),
state: () => lastTray,
pref: (key: string, value: unknown) => applyPref(key, value),
icon: () => lastTrayIcon,
tooltip: () => lastTrayTooltip,
menu: () => lastTrayMenu,
click: (path: string[]) => {
let items: MenuItemConstructorOptions[] = lastTrayMenu
let item: MenuItemConstructorOptions | undefined
for (const label of path) {
item = items.find((i) => i.label === label || (i.label ?? '').startsWith(label))
items = (item?.submenu as MenuItemConstructorOptions[]) ?? []
}
item?.click?.({ checked: !item.checked } as never, undefined, {} as never)
}
}
}
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
+49 -4
View File
@@ -19,13 +19,14 @@ vi.mock('electron', () => {
})
import { Notifier } from './notifications'
import type { TrayState } from './tray'
const payload = { accountId: 'a', bufferId: 'b', title: 'alice', body: 'hi' }
function notifier(settings: Record<string, unknown>): { n: Notifier; alerts: [number, boolean][] } {
const alerts: [number, boolean][] = []
function notifier(settings: Record<string, unknown>, dnd: string[] = []): { n: Notifier; alerts: TrayState[] } {
const alerts: TrayState[] = []
const prefs = { get: <T>(key: string, fallback: T): T => (key in settings ? (settings[key] as T) : fallback) }
const n = new Notifier(prefs as never, (count, alert) => alerts.push([count, alert]), () => {})
const n = new Notifier(prefs as never, (state) => alerts.push(state), () => {}, () => null, () => false, (account) => dnd.includes(account))
return { n, alerts }
}
@@ -44,7 +45,7 @@ describe('notification settings', () => {
const { n, alerts } = notifier({ 'notifications.desktop': false })
await n.handle(payload)
expect(shown).toHaveLength(0)
expect(alerts.at(-1)?.[0]).toBe(1)
expect(alerts.at(-1)?.unread).toBe(1)
})
it('makes them silent when the sound is off', async () => {
@@ -52,3 +53,47 @@ describe('notification settings', () => {
expect(shown[0].silent).toBe(true)
})
})
describe('what the tray is told is waiting', () => {
const buffer = (id: string, kind: string): never => ({ id, kind }) as never
it('counts direct messages and mentions apart, and lights for both', async () => {
const { n, alerts } = notifier({ 'notifications.desktop': false })
n.trackBuffer(buffer('dm', 'dm'), false)
n.trackBuffer(buffer('chan', 'channel'), false)
await n.handle({ ...payload, bufferId: 'dm' })
await n.handle({ ...payload, bufferId: 'chan' })
expect(alerts.at(-1)).toEqual({ unread: 2, dms: 1, mentions: 1 })
})
it('names the newest waiting conversation, and none once they are read', async () => {
const { n } = notifier({ 'notifications.desktop': false })
expect(n.latestUnread()).toBeNull()
await n.handle({ ...payload, bufferId: 'first' })
await n.handle({ ...payload, bufferId: 'second' })
expect(n.latestUnread()).toBe('second')
n.clear('second')
expect(n.latestUnread()).toBe('first')
n.clearAll()
expect(n.latestUnread()).toBeNull()
})
})
describe('Do not disturb', () => {
beforeEach(() => {
shown.length = 0
})
it('shows no notification for an account that is set to it, but still counts the conversation', async () => {
const { n, alerts } = notifier({}, ['a'])
await n.handle(payload)
expect(shown).toHaveLength(0)
expect(alerts.at(-1)?.unread).toBe(1)
})
it('leaves the other accounts alone', async () => {
const { n } = notifier({}, ['somebody-else'])
await n.handle(payload)
expect(shown).toHaveLength(1)
})
})
+31 -18
View File
@@ -4,6 +4,7 @@ import path from 'node:path'
import { Notification, nativeImage, net } from 'electron'
import type { WebContents } from 'electron'
import type { Prefs } from './prefs'
import type { TrayState } from './tray'
import type { Buffer as ChatBuffer } from '../shared/wire'
/**
@@ -48,7 +49,7 @@ export class Notifier {
constructor(
private prefs: Prefs,
private onAlertChange: (unreadCount: number, hasAlert: boolean) => void,
private onAlertChange: (state: TrayState) => void,
private onActivate: (bufferId: string) => void,
/** The renderer, borrowed only to decode formats nativeImage cannot. */
private renderer: () => WebContents | null = () => null,
@@ -60,7 +61,16 @@ export class Notifier {
* them what they can already see, and a tray badge counting it as unread
* is simply wrong.
*/
private isWatched: (bufferId: string) => boolean = () => false
private isWatched: (bufferId: string) => boolean = () => false,
/**
* Whether this account has been set to Do not disturb.
*
* That is the one switch for silence: an account that says so gets no popup
* and no sound, however its conversations behave. What it is sent still
* counts as unread - the tray and the badge keep their numbers, as Discord's
* own do - and is there to be read when it is looked at.
*/
private isDnd: (accountId: string) => boolean = () => false
) {}
trackBuffer(buffer: ChatBuffer, removed: boolean): void {
@@ -103,6 +113,8 @@ export class Notifier {
this.publish()
}
if (this.isDnd(payload.accountId)) return
// Switched off in Settings: the conversation still counts as unread above,
// it just does not pop up.
if (!this.prefs.get<boolean>('notifications.desktop', true)) return
@@ -288,24 +300,25 @@ export class Notifier {
}
/**
* Whether the tray should show something is waiting.
* What the tray should say is waiting.
*
* A direct message counts, and this is the change: the tray used to light up
* only for *pinned* buffers, on the reasoning that a DM had already had its
* desktop notification and the tray was for things important enough to pin.
* In practice that made the icon nearly inert - somebody messages you, and
* the one place still on screen after the notification has faded says
* nothing, unless you happened to have pinned that exact conversation.
*
* Pinned buffers still count, so a channel worth pinning can still raise it.
* There is no count here: a tray icon is around 22 pixels, which is room for
* "yes" and not for a number.
* Everything held here was worth a notification - a direct message, or
* somebody mentioning this account - so all of it lights the tray, and it
* says how many conversations and of which kind. It used to light only for
* direct messages and pinned conversations, on the reasoning that a mention
* had had its notification and the tray was for what mattered more; the
* effect was an icon that stayed dark while somebody was asking for you.
*/
publish(): void {
const pinned = this.prefs.get<string[]>('pinnedBuffers', [])
const hasAlert = [...this.unread].some(
(id) => this.buffers.get(id)?.kind === 'dm' || pinned.includes(id)
)
this.onAlertChange(this.unread.size, hasAlert)
let dms = 0
for (const id of this.unread) if (this.buffers.get(id)?.kind === 'dm') dms++
this.onAlertChange({ unread: this.unread.size, dms, mentions: this.unread.size - dms })
}
/** The conversation that has been waiting for you the shortest time. */
latestUnread(): string | null {
let latest: string | null = null
for (const id of this.unread) latest = id
return latest
}
}
+97
View File
@@ -0,0 +1,97 @@
import { describe, expect, it, vi } from 'vitest'
import { trayIconFile, trayMenu, trayTooltip, waitingSummary, NOTHING_WAITING, type TrayActions } from './tray'
const acts = (): TrayActions => ({
toggleWindow: vi.fn(),
openLatest: vi.fn(),
openSettings: vi.fn(),
setStatus: vi.fn(),
restart: vi.fn(),
quit: vi.fn()
})
describe('the tray icon', () => {
it('is a light bubble on a dark system and a dark one on a light system', () => {
expect(trayIconFile(true, 0)).toBe('tray-light.png')
expect(trayIconFile(false, 0)).toBe('tray-dark.png')
})
it('carries the count to nine and says more after that', () => {
expect(trayIconFile(true, 1)).toBe('tray-light-1.png')
expect(trayIconFile(true, 9)).toBe('tray-light-9.png')
expect(trayIconFile(false, 10)).toBe('tray-dark-more.png')
expect(trayIconFile(false, 400)).toBe('tray-dark-more.png')
})
})
describe('what is said about what is waiting', () => {
it('names direct messages and mentions apart, and in the singular for one', () => {
expect(waitingSummary({ unread: 3, dms: 2, mentions: 1 })).toBe('2 direct messages, 1 mention')
expect(waitingSummary({ unread: 1, dms: 1, mentions: 0 })).toBe('1 direct message')
expect(waitingSummary({ unread: 4, dms: 0, mentions: 4 })).toBe('4 mentions')
})
it('leaves the tooltip plain with nothing waiting or the badge off', () => {
expect(trayTooltip(NOTHING_WAITING, true)).toBe('moho')
expect(trayTooltip({ unread: 2, dms: 1, mentions: 1 }, false)).toBe('moho')
expect(trayTooltip({ unread: 2, dms: 1, mentions: 1 }, true)).toBe('moho - 1 direct message, 1 mention')
})
})
describe('the menu', () => {
const model = { state: NOTHING_WAITING, windowVisible: true, status: 'idle' as const, offered: [], invisibleName: 'Invisible' }
const labels = (items: ReturnType<typeof trayMenu>): string[] => items.map((i) => i.label ?? '-')
it('offers no daemon plumbing, and a restart that is of moho as a whole', () => {
const l = labels(trayMenu(model, acts()))
expect(l).not.toContain('Restart daemon')
expect(l).not.toContain('Stop daemon')
expect(l).toContain('Restart moho')
})
it('says nothing is new, and offers nothing to open, when that is so', () => {
const [first] = trayMenu(model, acts())
expect(first.label).toBe('Nothing new')
expect(first.enabled).toBe(false)
})
it('says what is waiting and opens it', () => {
const a = acts()
const [first] = trayMenu({ ...model, state: { unread: 2, dms: 1, mentions: 1 } }, a)
expect(first.label).toBe('1 direct message, 1 mention - open')
first.click?.({} as never, undefined, {} as never)
expect(a.openLatest).toHaveBeenCalled()
})
it('has no notifications switch of its own: Do not disturb is that', () => {
expect(labels(trayMenu(model, acts())).join('|')).not.toMatch(/notification/i)
const status = trayMenu(model, acts()).find((i) => i.label === 'Status')
expect((status?.submenu as { label: string }[]).map((s) => s.label)).toContain('Do not disturb')
})
it('offers only what the connected accounts can be set to', () => {
const labelsOf = (offered: ('online' | 'idle' | 'dnd' | 'invisible')[]): string[] =>
(trayMenu({ ...model, offered }, acts()).find((i) => i.label === 'Status')?.submenu as { label: string }[]).map((s) => s.label)
expect(labelsOf(['online', 'dnd'])).toEqual(['Online', 'Do not disturb'])
expect(labelsOf(['online', 'idle', 'dnd', 'invisible'])).toHaveLength(4)
expect(labelsOf([])).toHaveLength(4)
})
it('calls invisible offline where only Matrix has it', () => {
const sub = trayMenu({ ...model, offered: ['online', 'invisible'], invisibleName: 'Offline' }, acts()).find((i) => i.label === 'Status')?.submenu as { label: string }[]
expect(sub.map((s) => s.label)).toEqual(['Online', 'Offline'])
})
it('asks for the window to be shown or hidden as it stands', () => {
expect(labels(trayMenu({ ...model, windowVisible: true }, acts()))).toContain('Hide moho')
expect(labels(trayMenu({ ...model, windowVisible: false }, acts()))).toContain('Show moho')
})
it('checks the status the accounts are at', () => {
const status = trayMenu(model, acts()).find((i) => i.label === 'Status')
const sub = status?.submenu as { label: string; checked: boolean }[]
expect(sub.filter((s) => s.checked).map((s) => s.label)).toEqual(['Idle'])
const none = trayMenu({ ...model, status: null }, acts()).find((i) => i.label === 'Status')?.submenu as { checked: boolean }[]
expect(none.some((s) => s.checked)).toBe(false)
})
})
+109
View File
@@ -0,0 +1,109 @@
/**
* What the tray says and offers, apart from the Electron objects that show it.
*
* Kept as plain functions of plain data so that what the icon, the tooltip and
* the menu say about a given set of unread conversations can be checked
* without a desktop to look at.
*/
import type { MenuItemConstructorOptions } from 'electron'
/** What is waiting, as the notifier counts it. */
export interface TrayState {
/** Conversations with something unread that was worth a notification. */
unread: number
/** Of those, direct messages. */
dms: number
/** Of those, everything else: somebody mentioning this account in a channel. */
mentions: number
/** The conversation the menu's first line opens, where the window has said. */
latest?: string | null
}
export const NOTHING_WAITING: TrayState = { unread: 0, dms: 0, mentions: 0 }
export type TrayStatus = 'online' | 'idle' | 'dnd' | 'invisible'
/**
* The icon file for a panel and a count.
*
* `dark` is the system's colour scheme, and a dark system wants the light
* bubble. The count is drawn into the icon up to nine; past that it says "9+",
* since a tray icon is about 22 pixels and has no room for a second digit.
*/
export function trayIconFile(dark: boolean, unread: number): string {
const ink = dark ? 'light' : 'dark'
if (unread <= 0) return `tray-${ink}.png`
return `tray-${ink}-${unread > 9 ? 'more' : unread}.png`
}
const plural = (n: number, one: string, many: string): string => `${n} ${n === 1 ? one : many}`
/** "2 direct messages, 1 mention" - what is waiting, in the words a person would use. */
export function waitingSummary(s: TrayState): string {
const parts: string[] = []
if (s.dms > 0) parts.push(plural(s.dms, 'direct message', 'direct messages'))
if (s.mentions > 0) parts.push(plural(s.mentions, 'mention', 'mentions'))
return parts.join(', ')
}
export function trayTooltip(s: TrayState, badge: boolean): string {
return badge && s.unread > 0 ? `moho - ${waitingSummary(s)}` : 'moho'
}
export interface TrayActions {
toggleWindow: () => void
openLatest: () => void
openSettings: () => void
setStatus: (status: TrayStatus) => void
restart: () => void
quit: () => void
}
export interface TrayModel {
state: TrayState
windowVisible: boolean
/** The status the accounts are at, where the window has said. */
status: TrayStatus | null
/** What the connected accounts can be set to; none reported yet means all of them. */
offered: TrayStatus[]
/** What invisible is called: Matrix, which has only offline presence, says offline. */
invisibleName: string
}
const STATUSES: { id: TrayStatus; label: string }[] = [
{ id: 'online', label: 'Online' },
{ id: 'idle', label: 'Idle' },
{ id: 'dnd', label: 'Do not disturb' },
{ id: 'invisible', label: 'Invisible' }
]
/**
* The right-click menu: what is new, how to get to moho, how to say what you
* are doing - which includes Do not disturb, the one switch for silencing it -
* and how to leave. Daemon plumbing - restart it, stop it - is
* deliberately not here; it is a thing for Settings, and "restart moho"
* covers what somebody reaching for it from a tray actually wants.
*/
export function trayMenu(model: TrayModel, act: TrayActions): MenuItemConstructorOptions[] {
const waiting = model.state.unread > 0
return [
waiting
? { label: `${waitingSummary(model.state)} - open`, click: act.openLatest }
: { label: 'Nothing new', enabled: false },
{ type: 'separator' },
{ label: model.windowVisible ? 'Hide moho' : 'Show moho', click: act.toggleWindow },
{
label: 'Status',
submenu: STATUSES.filter((s) => model.offered.length === 0 || model.offered.includes(s.id)).map((s) => ({
label: s.id === 'invisible' ? model.invisibleName : s.label,
type: 'radio' as const,
checked: model.status === s.id,
click: () => act.setStatus(s.id)
}))
},
{ label: 'Settings', click: act.openSettings },
{ type: 'separator' },
{ label: 'Restart moho', click: act.restart },
{ label: 'Quit', click: act.quit }
]
}
+41 -1
View File
@@ -83,6 +83,27 @@ const api = {
return () => ipcRenderer.off(IPC.activateBuffer, handler)
},
/** The tray menu asking this window to open Settings, or to set a status on every account. */
onTrayCommand(cb: (command: 'settings' | 'status', arg?: string) => void): () => void {
const handler = (_e: unknown, command: 'settings' | 'status', arg?: string): void => cb(command, arg)
ipcRenderer.on(IPC.trayCommand, handler)
return () => ipcRenderer.off(IPC.trayCommand, handler)
},
/**
* Says what status each connected account is at, which statuses any of them
* can be set to, and the one to show as checked: for the tray menu, and for
* main to stay quiet for an account on Do not disturb.
*/
setAccountStatuses(statuses: Record<string, string>, offered: string[], shown: string | null, invisibleName: string): void {
ipcRenderer.send(IPC.trayStatus, statuses, offered, shown, invisibleName)
},
/** Says what is waiting, counted the way the rail counts it, for the tray's number. */
setTrayUnread(count: { dms: number; mentions: number; latest: string | null }): void {
ipcRenderer.send(IPC.trayUnread, count)
},
onMaximizeChange(cb: (maximized: boolean) => void): () => void {
const handler = (_e: unknown, v: boolean): void => cb(v)
ipcRenderer.on(IPC.maximizeChanged, handler)
@@ -135,7 +156,7 @@ const api = {
*/
pathForFile: (file: File): string => webUtils.getPathForFile(file),
pickFile: (): Promise<string | null> => ipcRenderer.invoke(IPC.pickFile),
pickFile: (extensions?: string[]): Promise<string | null> => ipcRenderer.invoke(IPC.pickFile, extensions),
/**
* Answers the main process when it needs a screen or window chosen.
*
@@ -212,6 +233,25 @@ const api = {
}
}
/**
* Tells main that somebody is using this window.
*
* Only that it happened - the event's kind and what it touched are not looked
* at, and nothing about them is sent. It is what lets moho know the person has
* stepped away, which is the one thing it wants to know, and it is sent at most
* every few seconds however much is going on.
*/
let lastActivityPing = 0
const noteActivity = (): void => {
const now = Date.now()
if (now - lastActivityPing < 5000) return
lastActivityPing = now
ipcRenderer.send(IPC.activity)
}
for (const kind of ['pointerdown', 'pointermove', 'keydown', 'wheel', 'touchstart']) {
;(globalThis as unknown as EventTarget).addEventListener(kind, noteActivity, { capture: true, passive: true })
}
contextBridge.exposeInMainWorld('moho', api)
export type MohoApi = typeof api
+24 -2
View File
@@ -7,12 +7,14 @@ import { ForumPane } from './components/ForumPane'
import { MessageList } from './components/MessageList'
import { MentionsInbox } from './components/MentionsInbox'
import { MentionsPage } from './components/MentionsPage'
import { INVITE_PREFIX, MENTIONS_GROUP_ID } from './lib/groups'
import { INVITATIONS_GROUP_ID, MENTIONS_GROUP_ID } from './lib/groups'
import { trayCount } from './lib/traycount'
import { Composer } from './components/Composer'
import { MembershipGate } from './components/MembershipGate'
import { NickList } from './components/NickList'
import { ThreadPanel } from './components/ThreadPanel'
import { InvitePanel } from './components/InvitePanel'
import { SteamFriendDialogs } from './components/SteamFriendDialogs'
import { VerificationDialog } from './components/VerificationDialog'
import { ProfileCard } from './components/ProfileCard'
import { ConversationTools } from './components/ConversationTools'
@@ -33,6 +35,7 @@ import { Icon, IconButton } from './components/Icon'
import { ConversationMenu } from './components/ConversationMenu'
import { watchDelta, watchedKickBuffers } from './lib/kickwatch'
import { useActiveBuffer, useChat, usePref, usePrefsReady, useStore } from './state/hooks'
import { useDmCategories } from './state/useDmCategories'
import { bufferDisplayName, setHourFormat } from './lib/util'
import type { BufferEntry } from './state/store'
import { loadLocalEmotes, recoverMissingEmotes } from './lib/emotecache'
@@ -52,6 +55,8 @@ export default function App(): JSX.Element {
useEscapeLayer(() => store.setActivePanel(''), panelOpen)
const store = useStore()
const prefsReady = usePrefsReady()
// Every account's direct messages under a heading of its own.
useDmCategories()
const [booted, setBooted] = useState(false)
const accounts = useChat((s) => s.accounts)
@@ -89,6 +94,22 @@ export default function App(): JSX.Element {
else delete document.documentElement.dataset.reduceMotion
}, [density, reduceMotion])
const [userListFolded, setUserListFolded] = usePref<boolean>('ui.userListFolded', false)
// What the tray says is waiting, which is whatever the rail would add up to:
// the same rule, from the same lists, said to the main process whenever the
// answer changes. Told only when it has, since most changes to the buffers
// are not to what is waiting.
const [trayMuted] = usePref<string[]>('mutedBuffers', [])
const [trayHidden] = usePref<string[]>('hiddenBuffers', [])
const [trayMutedGroups] = usePref<string[]>('mutedGroups', [])
const lastTray = useRef('')
useEffect(() => {
const count = trayCount(allBuffers, trayMuted, trayHidden, trayMutedGroups)
const said = JSON.stringify(count)
if (said === lastTray.current) return
lastTray.current = said
window.moho.setTrayUnread(count)
}, [allBuffers, trayMuted, trayHidden, trayMutedGroups])
const [savedBufferId] = usePref<string>('ui.activeBufferId', '')
const [savedGroupId] = usePref<string>('ui.activeGroupId', '')
@@ -303,6 +324,7 @@ export default function App(): JSX.Element {
room you share - and a dialog only the account panel can show is a
request nobody can answer. */}
<VerificationDialog />
<SteamFriendDialogs />
{/* Over everything: a call arrives while you are looking elsewhere. */}
<IncomingCallPanel />
@@ -393,7 +415,7 @@ function Body({
if (activeGroupId === MENTIONS_GROUP_ID) return <MentionsPage />
// An invitation stands where the conversation would, because it is the
// conversation being offered.
if (activeGroupId.startsWith(INVITE_PREFIX)) return <InvitePanel groupId={activeGroupId} />
if (activeGroupId === INVITATIONS_GROUP_ID) return <InvitePanel />
// A forum is a list of posts, not a log.
if (hasBuffer && activeBuffer?.forum) return <ForumPane buffer={activeBuffer} />
if (hasBuffer) return <MessageList />
+510 -2
View File
@@ -1572,6 +1572,208 @@ button.video-tile {
line-height: 1;
}
/* What somebody did on a Kick stream - KICKs sent, subscriptions gifted - as
the card Kick draws it: a bar down the edge, who and what at the left, and
the thing itself at the right. On this client's own surfaces; the accent is
the gift's tier (Kick green for an ordinary one), tinted into the plate so a
large gift is bigger at a glance without the card leaving the theme. */
.message-row.has-kick-event {
align-items: center;
}
/* Where the card sits in the log, which is where the picture of the person
speaking would: it starts at the picture's edge, in the column a join's mark
would have taken, and what is written inside it starts where a name does. So
the indent is the picture, the gap after it, and - in a bubble - the
bubble's own padding. A message row that is not a person speaking gets no
avatar, and a card with none lets the content start at the edge. */
.message-row.comfy:not(.bubbles).has-kick-event {
--kick-lead: var(--avatar);
--kick-indent: calc(var(--avatar) + var(--spacing-m));
}
.message-row.bubbles.system.has-kick-event {
--kick-lead: 28px;
--kick-indent: calc(28px + var(--spacing-s) + var(--spacing-s));
justify-content: flex-start;
margin-top: var(--spacing-s);
}
.message-row.bubbles.system.has-kick-event .message-content {
flex: 1 1 auto;
max-width: 100%;
padding: 0;
background: none;
text-align: left;
}
.message-row.classic.has-kick-event,
.message-row:not(.comfy).has-kick-event {
margin-top: var(--spacing-xs);
}
.message-row.comfy.has-kick-event .message-content {
flex: 1 1 auto;
min-width: 0;
}
.message-row.comfy.has-kick-event .kick-event {
position: relative;
max-width: min(100%, 560px);
/* Less the bar, which is in the card's own edge. */
padding-left: calc(var(--kick-indent) - var(--kick-border, 3px));
}
.message-row.comfy.has-kick-event .kick-event.raid,
.message-row.comfy.has-kick-event .kick-event.stream {
--kick-border: 1px;
}
/* The mark at the left takes the picture's column - centred on where the
picture would be - instead of sitting in the text's way. */
.message-row.comfy.has-kick-event .kick-event > .kick-event-badge.lead {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: var(--kick-lead);
}
.kick-event {
--kick-accent: #53fc18;
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--spacing-l);
min-width: 260px;
max-width: min(100%, 520px);
padding: var(--spacing-s) var(--spacing-m);
border: 1px solid var(--outline-medium);
border-left: 3px solid var(--kick-accent);
border-radius: var(--corner-radius);
background: color-mix(in srgb, var(--kick-accent) 7%, var(--surface-container-high));
color: var(--surface-text);
font-style: normal;
}
/* Kick draws a gifted subscription in purple and a raid with no bar at all; a
redeemed reward takes the streamer's colour, set inline. */
.kick-event.gift {
--kick-accent: #a970ff;
justify-content: flex-start;
}
.kick-event.redeem,
.kick-event.subscribe,
.kick-event.moderation {
justify-content: flex-start;
}
.kick-event.subscribe {
--kick-accent: #a970ff;
}
/* A ban, a timeout, a chat cleared: said in the room's own danger colour. */
.kick-event.moderation {
--kick-accent: var(--danger);
}
/* The stream going live or ending is a plate like a raid's, and the mark is
the part that says which. */
.kick-event.stream {
justify-content: flex-start;
border: 1px solid var(--outline-medium);
border-radius: var(--radius-pill);
padding-inline: var(--spacing-m);
background: var(--surface-container-high);
}
.kick-event.stream.live .kick-event-badge {
color: var(--danger);
}
.kick-event.stream.offline .kick-event-badge {
color: var(--text-muted);
}
.kick-event.raid {
justify-content: flex-start;
border: 1px solid var(--outline-medium);
border-radius: var(--radius-pill);
padding-inline: var(--spacing-m);
background: var(--surface-container-high);
}
.kick-event.raid .kick-event-badge {
color: var(--text-muted);
}
.kick-event-main {
display: flex;
flex-direction: column;
gap: var(--spacing-xs);
min-width: 0;
}
.kick-event-line {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--spacing-xs);
}
.kick-event-name {
font-weight: var(--weight-bold);
}
.kick-event-verb {
color: var(--text-muted);
}
.kick-event-amount {
font-size: var(--font-size-large, 1.15em);
font-variant-numeric: tabular-nums;
}
.kick-event-message {
color: var(--surface-text);
overflow-wrap: anywhere;
}
.kick-event-recipients {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--spacing-xs);
}
.kick-event-recipient {
padding: 0 var(--spacing-s);
border-radius: var(--radius-pill);
background: var(--surface-container-highest, var(--surface-hover));
font-weight: var(--weight-medium);
}
.kick-event-badge {
display: inline-flex;
flex: none;
align-items: center;
justify-content: center;
color: var(--kick-accent);
}
.kicks-mark {
display: inline-flex;
flex: none;
align-items: center;
justify-content: center;
border-radius: 50%;
background: var(--kick-accent);
color: #0b0e0a;
font-weight: 900;
line-height: 1;
}
.message-row.comfy {
align-items: flex-start;
padding-top: var(--spacing-xxs);
@@ -1590,7 +1792,8 @@ button.video-tile {
gap: var(--spacing-m);
}
.message-row.comfy:not(.bubbles):not(.grouped):not(.system) {
.message-row.comfy:not(.bubbles):not(.grouped):not(.system),
.message-row.comfy:not(.bubbles):not(.grouped).has-kick-event {
margin-top: var(--spacing-l);
}
@@ -2343,6 +2546,45 @@ img.composer-emoji {
opacity: 0.45;
}
.nick-row.comfy {
gap: var(--spacing-s);
padding: 4px var(--spacing-s);
}
/* The name over what they are doing, in one column that gives way to the
badge at the right rather than pushing it off. */
.nick-text,
.buffer-text {
display: flex;
flex-direction: column;
flex: 1;
min-width: 0;
line-height: 1.25;
}
/* A game, a track, or words they wrote: small, under the name, with a picture
only where there is a kind of thing to show. */
.activity-line {
display: flex;
align-items: center;
gap: 4px;
min-width: 0;
font-size: var(--font-size-small);
}
.activity-line .icon {
flex: none;
}
/* Steam draws a sticker as a picture of its own, about the size it is in Steam's
own chat. Qualified with the element because `img.custom-emoji` sizes every
emoji to the line, and wins over a bare class. */
img.custom-emoji.steam-sticker {
height: 128px;
width: auto;
vertical-align: middle;
}
.nick-prefix {
color: var(--surface-variant-text);
flex: none;
@@ -2483,6 +2725,13 @@ img.composer-emoji {
width: 100%;
}
.field-row > .grow {
flex: 1;
min-width: 0;
align-self: center;
overflow-wrap: anywhere;
}
.field.port {
flex: 0 0 80px;
}
@@ -5386,6 +5635,18 @@ video.lightbox-media {
color: var(--surface-text);
}
/* A conversation over the heading that will take it: the whole category is lit, heading and
rows, since the heading is where it is going to be and not what it is going to be above. */
.category.drop-into {
border-radius: var(--corner-radius-small);
background: color-mix(in srgb, var(--primary) 16%, transparent);
box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--primary) 55%, transparent);
}
.category.drop-into .category-head {
color: var(--surface-text);
}
/* A channel being carried. Faded like the heading, and for the same reason:
the row stays in place so the list does not reflow under the cursor and
move the heading being aimed at. */
@@ -6661,7 +6922,12 @@ video.lightbox-media {
}
.header-nameplate .main-header-title {
flex: 1;
flex: 0 1 auto;
min-width: 0;
}
.header-nameplate .header-status {
flex: 1 1 0;
min-width: 0;
}
@@ -7464,6 +7730,35 @@ video.lightbox-media {
/* Label and value on one line, labels aligned, so the card is read down its
left edge rather than hunted through. */
.profile-status {
display: flex;
flex-direction: column;
gap: var(--spacing-xxs);
padding: var(--spacing-s);
margin-bottom: var(--spacing-s);
border-radius: var(--corner-radius-small);
background: var(--surface-container-high);
}
.profile-section-title {
text-transform: uppercase;
letter-spacing: 0.04em;
font-size: var(--font-size-xs, 11px);
}
.profile-status-presence {
display: flex;
align-items: center;
gap: var(--spacing-xs);
}
.profile-status-dot {
width: 10px;
height: 10px;
border-radius: 50%;
flex: none;
}
.profile-rows {
display: flex;
flex-direction: column;
@@ -9163,6 +9458,57 @@ video.lightbox-media {
overflow-wrap: anywhere;
}
/* A warning the service put on the conversation, over it, in red, until it is
dismissed. Louder than the interruption banner above: that is about the
connection, and this is about who is on the other end. */
.notice-banner {
display: flex;
align-items: center;
gap: var(--spacing-s);
padding: var(--spacing-s) var(--spacing-m);
border-bottom: 1px solid var(--danger);
background: color-mix(in srgb, var(--danger) 22%, var(--surface));
font-size: var(--font-size-small);
}
.notice-banner .icon {
flex: none;
color: var(--danger-text);
}
.notice-banner-text {
flex: 1 1 auto;
min-width: 0;
overflow-wrap: anywhere;
font-weight: var(--weight-semibold);
}
.notice-banner-dismiss {
flex: none;
padding: var(--spacing-xs) var(--spacing-m);
border-radius: var(--corner-radius-small);
background: var(--danger);
color: var(--on-accent);
font-weight: var(--weight-bold);
}
.notice-banner-dismiss:hover {
background: var(--danger-hover);
}
/* The same warning, said in the log where it stays: red, so it is not scrolled
past, and not the italic grey of an ordinary system line. */
.message-row.warning {
background: color-mix(in srgb, var(--danger) 18%, transparent);
box-shadow: inset 3px 0 0 var(--danger);
}
.message-row.warning .message-body {
color: var(--danger-text);
font-style: normal;
font-weight: var(--weight-semibold);
}
/* A rail entry whose service has not answered yet - on start, or after an
outage. The face dims and a spinner sits over it until it connects. */
.rail-tile.connecting .rail-face {
@@ -10405,3 +10751,165 @@ html[data-reduce-motion] *::after {
flex-wrap: wrap;
gap: var(--spacing-xs);
}
/* GIFs to browse and send. */
.gif-picker {
position: fixed;
z-index: var(--z-picker);
width: min(420px, calc(100vw - 8px));
height: min(480px, calc(100vh - 8px));
display: flex;
flex-direction: column;
gap: var(--spacing-xs);
padding: var(--spacing-s);
overflow: hidden;
border-radius: var(--corner-radius);
background: var(--surface-container-high);
border: 1px solid var(--outline-medium);
box-shadow: var(--shadow-2);
animation: overlay-in var(--motion) var(--ease);
}
.gif-search {
display: flex;
align-items: center;
gap: var(--spacing-xs);
padding: 0 var(--spacing-xs);
color: var(--surface-variant-text);
}
.gif-search .text-field {
flex: 1;
min-width: 0;
}
.gif-scroll {
flex: 1;
min-height: 0;
overflow-y: auto;
}
.gif-categories {
display: flex;
flex-wrap: wrap;
gap: var(--spacing-xs);
padding-bottom: var(--spacing-s);
}
.gif-category {
padding: var(--spacing-xxs) var(--spacing-s);
border-radius: var(--radius-pill);
background: var(--surface-hover);
color: var(--surface-text);
font-size: var(--font-size-small);
text-transform: capitalize;
}
.gif-category:hover {
background: var(--surface-selected);
}
.gif-empty {
padding: var(--spacing-l);
text-align: center;
}
.gif-grid {
display: flex;
gap: var(--spacing-xs);
align-items: flex-start;
}
.gif-column {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: var(--spacing-xs);
}
.gif-cell {
display: block;
width: 100%;
padding: 0;
overflow: hidden;
border-radius: var(--radius-s, 6px);
background: var(--surface-container);
cursor: pointer;
}
.gif-cell:hover,
.gif-cell:focus-visible {
outline: 2px solid var(--primary);
}
.gif-cell video,
.gif-cell img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
/* The names somebody has had, on their card: newest first, each with when. */
.profile-name-history {
display: flex;
flex-direction: column;
gap: var(--spacing-xs);
margin: 0;
padding: 0;
list-style: none;
width: 100%;
}
.profile-name-history li {
display: flex;
justify-content: space-between;
gap: var(--spacing-s);
min-width: 0;
}
/* A Steam chat group's settings: tabs over a scrolling body, as a room's are. */
.steam-group {
width: 560px;
max-width: calc(100vw - var(--spacing-xl));
max-height: 80vh;
display: flex;
flex-direction: column;
gap: var(--spacing-s);
padding: var(--spacing-m);
border: 1px solid var(--outline-medium);
border-radius: var(--corner-radius);
background: var(--surface-container-high);
box-shadow: var(--shadow-3);
}
.steam-group-body {
padding-top: var(--spacing-s);
}
.steam-group-row {
align-items: center;
}
.steam-group-person {
display: flex;
flex-direction: column;
gap: var(--spacing-xs);
padding-bottom: var(--spacing-xs);
border-bottom: 1px solid var(--outline-medium);
}
.steam-group-perms {
display: flex;
flex-direction: column;
gap: var(--spacing-xs);
padding: var(--spacing-xs) 0 var(--spacing-xs) var(--spacing-m);
}
.steam-group-x {
margin-left: var(--spacing-xs);
color: inherit;
cursor: pointer;
}
+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<!-- Steam's mark, drawn as a plain silhouette: a disc, the small gear on its
arm, and the cut-out ring for the larger one. -->
<path fill="#fff" fill-rule="evenodd" d="M12 1.5A10.5 10.5 0 0 0 1.55 11.1l5.6 2.3a3 3 0 0 1 1.7-.5h.2l2.5-3.6v-.05a4 4 0 1 1 4 4h-.1l-3.55 2.55a3 3 0 0 1-5.95.5L1.8 14.9A10.5 10.5 0 1 0 12 1.5zm-4 17.1-1.3-.55a2.25 2.25 0 1 0 1.25-3.1l1.35.55a1.65 1.65 0 1 1-1.3 3.1zm7.05-6.2a2.65 2.65 0 1 0-2.65-2.65 2.65 2.65 0 0 0 2.65 2.65zm0-.95a1.7 1.7 0 1 1 1.7-1.7 1.7 1.7 0 0 1-1.7 1.7z"/>
</svg>

After

Width:  |  Height:  |  Size: 615 B

+282 -2
View File
@@ -1,8 +1,9 @@
import { useMediaUrl } from '../lib/route'
import { SwitchRow } from './Switch'
import { useEffect, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import { Icon, IconButton, ServiceMark } from './Icon'
import { MatrixAccountTools } from './MatrixAccountTools'
import { SteamAccountTools } from './SteamAccountTools'
import { IgnoreList } from './IgnoreList'
import { TunnelAllSwitch } from './settings/Tunnel'
import { useChat, useConnectionDetail, useMapPref, usePref, useStore } from '../state/hooks'
@@ -23,7 +24,7 @@ import type { Account } from '../../../shared/wire'
* that gains a backend appears here as soon as it gains a form, and one the
* daemon stops offering disappears without this file being touched.
*/
const FORMS = ['irc', 'discord', 'sneedchat', 'matrix', 'kick'] as const
const FORMS = ['irc', 'discord', 'sneedchat', 'matrix', 'kick', 'steam'] as const
type AddableService = (typeof FORMS)[number]
/** What `listProtocols` answers with. */
@@ -134,6 +135,7 @@ export function AccountsPanel(): JSX.Element {
{adding === 'sneedchat' && <SneedChatForm />}
{adding === 'matrix' && <MatrixForm />}
{adding === 'kick' && <KickForm onDone={() => setAdding(null)} />}
{adding === 'steam' && <SteamForm onDone={() => setAdding(null)} />}
{adding && (
<button type="button" className="button subtle small" onClick={() => setAdding(null)}>
Cancel
@@ -456,6 +458,8 @@ function AccountRow({ account }: { account: Account }): JSX.Element {
{account.service === 'matrix' && <MatrixAccountTools account={account} />}
{account.service === 'steam' && <SteamAccountTools account={account} />}
{account.service === 'sneedchat' && (
<>
<RouteLevel account={account} onChange={(level) => call('setAccountRoute', { accountId: account.id, level })} />
@@ -1192,6 +1196,282 @@ function KickForm({ onDone }: { onDone: () => void }): JSX.Element {
)
}
/** What Steam can ask for to let a sign-in through; any one of them will do. */
interface SteamOption {
kind: 'deviceCode' | 'emailCode' | 'approval' | 'emailApproval'
hint?: string
}
/**
* Signing in to Steam.
*
* A conversation rather than a request, because Steam may want something from
* the person's phone or inbox: the daemon answers with a login id and the rest
* arrives as events (see nobilis backend/steam/login.rs). So the form has
* three shapes - the credentials, then whatever Steam is waiting for, then
* nothing, because the account exists and the form closes itself.
*
* The password is typed here, goes to the daemon once, and is forgotten when
* this form is: the account keeps the token Steam hands back, never the
* password.
*/
function SteamForm({ onDone }: { onDone: () => void }): JSX.Element {
const store = useStore()
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [useTor, setUseTor] = useState(false)
const [busy, setBusy] = useState(false)
const [loginId, setLoginId] = useState('')
const [detail, setDetail] = useState('')
const [needs, setNeeds] = useState<{ options: SteamOption[]; error?: string } | null>(null)
const [code, setCode] = useState('')
// The picture of the code a phone scans, while a sign-in by scanning waits.
const [qr, setQr] = useState<{ path: string; at: number } | null>(null)
// The id lives in a ref as well as state, because the first event can be
// handled before the render that follows the answer to the request that
// started the sign-in. Nothing else is signing in from this form, so an
// event arriving before the id is known can only be this one's.
const current = useRef('')
const setId = (id: string): void => {
current.current = id
setLoginId(id)
}
useEffect(() => {
const off = window.moho.onEvent((e) => {
const d = e.data as {
loginId?: string
detail?: string
options?: SteamOption[]
error?: string
success?: boolean
path?: string
}
if (!e.event.startsWith('steamLogin')) return
if (current.current && d.loginId !== current.current) return
if (e.event === 'steamLoginQr' && d.path) {
// The same file is written again when the code is replaced, so the
// moment is part of what is drawn.
setQr({ path: d.path, at: Date.now() })
} else if (e.event === 'steamLoginStatus') {
setDetail(d.detail || '')
} else if (e.event === 'steamLoginNeeds') {
setNeeds({ options: d.options ?? [], error: d.error })
setCode('')
} else if (e.event === 'steamLoginResult') {
setNeeds(null)
setQr(null)
setId('')
setBusy(false)
setDetail('')
if (d.success) {
setPassword('')
void store.refreshAccounts()
onDone()
} else {
store.toast('error', d.error || 'Steam sign-in failed')
}
}
})
return off
}, [onDone, store])
// Closing the form on a sign-in that is still waiting tells the daemon
// nobody is, so it stops asking Steam and frees what it was holding.
useEffect(
() => () => {
if (current.current) void window.moho.rpc('cancelSteamLogin', { loginId: current.current }).catch(() => {})
},
[]
)
const begin = (): void => {
setBusy(true)
setDetail('')
setNeeds(null)
current.current = ''
void window.moho
.rpc<{ loginId: string }>('addSteamAccount', { username, password, useTor })
.then((r) => setId(r.loginId))
.catch((e: Error) => {
setBusy(false)
store.toast('error', e.message)
})
}
// Signing in by scanning a code with the Steam app: nothing is typed.
const beginQr = (): void => {
setBusy(true)
setDetail('')
setNeeds(null)
setQr(null)
current.current = ''
void window.moho
.rpc<{ loginId: string }>('addSteamAccountQr', { useTor })
.then((r) => setId(r.loginId))
.catch((e: Error) => {
setBusy(false)
store.toast('error', e.message)
})
}
const send = (): void => {
const typed = code.trim()
if (!typed || !loginId) return
void window.moho
.rpc('submitSteamGuardCode', { loginId, code: typed })
.then(() => setDetail('checking the code'))
.catch((e: Error) => store.toast('error', e.message))
}
const cancel = (): void => {
if (current.current) void window.moho.rpc('cancelSteamLogin', { loginId: current.current }).catch(() => {})
setId('')
setQr(null)
setNeeds(null)
setDetail('')
setBusy(false)
}
if (qr) {
return (
<div className="add-form">
<p>Scan this with the Steam app on your phone.</p>
<p className="small muted">
In the app, open Steam Guard and choose the scan option (the QR icon), point the phone
at the code, and approve the sign-in. moho keeps only the token Steam hands back.
</p>
<img className="qr-image" src={resolveMediaUrl(`file://${qr.path}#${qr.at}`)} alt="Steam sign-in QR code" />
{detail && <p className="small muted">{detail}…</p>}
<div className="field-row">
<button type="button" className="button" onClick={cancel}>
Cancel sign-in
</button>
</div>
</div>
)
}
const takesCode = !!needs?.options.some((o) => o.kind === 'deviceCode' || o.kind === 'emailCode')
const approvals = needs?.options.filter((o) => o.kind === 'approval' || o.kind === 'emailApproval') ?? []
if (needs) {
return (
<div className="add-form">
<p>Steam wants to check that this is you.</p>
{approvals.map((o) => (
<p key={o.kind} className="small muted">
{o.kind === 'approval'
? `Approve the sign-in in the Steam app on your phone${o.hint ? ` (${o.hint})` : ''}.`
: `Approve the sign-in from the email Steam sent${o.hint ? ` to ${o.hint}` : ''}.`}
</p>
))}
{takesCode && (
<label className="field">
<span className="small muted">
{needs.options.some((o) => o.kind === 'deviceCode')
? 'Code from your Steam Guard authenticator'
: 'Code Steam emailed you'}
</span>
<input
className="text-field"
autoFocus
autoComplete="off"
spellCheck={false}
value={code}
onChange={(e) => setCode(e.target.value.toUpperCase())}
onKeyDown={(e) => {
if (e.key === 'Enter') send()
}}
/>
</label>
)}
{needs.error && (
<div className="warning-note">
<Icon name="warning" size={16} />
<span>{needs.error}</span>
</div>
)}
{detail && <p className="small muted">{detail}…</p>}
<div className="field-row">
{takesCode && (
<button type="button" className="button primary" disabled={!code.trim()} onClick={send}>
Submit code
</button>
)}
<button type="button" className="button" onClick={cancel}>
Cancel sign-in
</button>
</div>
</div>
)
}
return (
<div className="add-form">
<p className="small muted">
Sign in with your Steam account name — the one you type at the Steam login, not the
display name your friends see. moho signs in as the Steam mobile app's chat, so it runs
beside the Steam launcher without signing it out. Your password goes to Steam and is not
kept; moho keeps only the token Steam hands back.
</p>
<TorSwitch service="steam" on={useTor} onChange={setUseTor} />
<div className="field-row">
<label className="field">
<span className="small muted">Account name</span>
<input
className="text-field"
autoComplete="off"
spellCheck={false}
value={username}
disabled={busy}
onChange={(e) => setUsername(e.target.value)}
/>
</label>
<label className="field">
<span className="small muted">Password</span>
<input
className="text-field"
type="password"
value={password}
disabled={busy}
onChange={(e) => setPassword(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && username.trim() && password && !busy) begin()
}}
/>
</label>
</div>
<div className="field-row">
<button
type="button"
className="button primary"
disabled={busy || !username.trim() || !password}
onClick={begin}
>
{busy ? 'Signing in…' : 'Sign in'}
</button>
<button
type="button"
className="button subtle"
disabled={busy}
title="Sign in by scanning a code with the Steam app on your phone, with no password typed here"
onClick={beginQr}
>
Sign in with a QR code
</button>
{busy && (
<button type="button" className="button" onClick={cancel}>
Cancel
</button>
)}
</div>
{busy && detail && <p className="small muted">{detail}…</p>}
</div>
)
}
/**
* Whether an account's connections go through Tor or a SOCKS5 proxy.
*
@@ -0,0 +1,18 @@
import { Icon } from './Icon'
import { activityIcon } from '../lib/activity'
import type { Activity } from '../../../shared/wire'
/**
* What somebody is doing, as the small line under their name: a gamepad and a
* game, a note and a track, or - with no picture at all - words they wrote
* themselves, which is how Discord draws a custom status.
*/
export function ActivityLine({ activity }: { activity: Activity }): JSX.Element {
const icon = activityIcon(activity)
return (
<span className="activity-line small muted">
{icon && <Icon name={icon} size={13} />}
<span className="ellipsis">{activity.text}</span>
</span>
)
}
+172 -36
View File
@@ -6,19 +6,25 @@ import { ContextMenu, useContextMenu, type MenuEntry } from './ContextMenu'
import { bufferMenuEntries } from '../lib/buffermenu'
import { UserFooter } from './UserFooter'
import { VoiceChannels } from './VoiceChannels'
import { SteamVoiceRooms } from './SteamVoiceRooms'
import { VoicePanel } from './VoicePanel'
import { presenceClass, presenceLabel } from '../lib/presence'
import { useChat, useIdSetPref, useMapPref, usePref, useStore } from '../state/hooks'
import { activityLabel, dmActivity } from '../lib/activity'
import { ActivityLine } from './ActivityLine'
import { steamCategoryId, parseSteamCategory } from '../lib/steamgroups'
import { NamePrompt } from './NamePrompt'
import { useChat, useComfy, useIdSetPref, useInvitations, useMapPref, usePref, useStore } from '../state/hooks'
import {
compareInBand,
dmGroup,
DM_GROUP_ID,
isDirectMessage,
isMutedBuffer,
INVITE_PREFIX,
INVITATIONS_GROUP_ID,
MENTIONS_GROUP_ID,
PINNED_GROUP_ID,
pinnedGroup,
waitingCount,
visibleGroups,
type RailGroup
} from '../lib/groups'
@@ -33,6 +39,7 @@ import {
} from '../lib/util'
import type { Account, Member } from '../../../shared/wire'
import { Avatar } from './Avatar'
import { currentInvitation } from '../lib/invitations'
import {
categoryKey,
reorderCategories,
@@ -71,6 +78,7 @@ export function BufferList(): JSX.Element {
const voiceSessions = useChat((s) => s.voiceSessions)
const presence = useChat((s) => s.presenceByBuffer)
const popouts = useChat((s) => s.popouts)
const activeInvitationKey = useChat((s) => s.activeInvitationKey)
const [pinned, togglePin, isPinned] = useIdSetPref('pinnedBuffers')
const [muted, toggleMute] = useIdSetPref('mutedBuffers')
@@ -128,12 +136,15 @@ export function BufferList(): JSX.Element {
return isDirectMessage(open) ? DM_GROUP_ID : open.groupId
}, [buffers, activeBufferId])
// An invitation is selected the same way the mentions page is: a rail entry
// with no group behind it. Without this the lookup below fails to find it,
// falls back to some real group, and the effect writes that back - so
// choosing an invitation landed on whichever server happened to be first,
// which is exactly what it looked like.
const onInvite = activeGroupId.startsWith(INVITE_PREFIX)
// The invitations page is selected the same way the mentions page is: a rail
// entry with no group behind it. Without this the lookup below fails to find
// it, falls back to some real group, and the effect writes that back - so
// choosing it landed on whichever server happened to be first. Only while
// something is waiting: with nothing left the page has nothing to say, and
// falling back is the way off it.
const invitations = useInvitations()
const onInvite = activeGroupId === INVITATIONS_GROUP_ID && invitations.length > 0
const shownInvitation = currentInvitation(invitations, activeInvitationKey)
const activeGroup =
onMentionsPage || onInvite
@@ -157,6 +168,8 @@ export function BufferList(): JSX.Element {
const isPinnedPage = activeGroup?.id === PINNED_GROUP_ID
const isDmPage = activeGroup?.id === DM_GROUP_ID
// A Steam account's own page: its friends sit under the folders Steam keeps for the account.
const steamPage = activeGroup?.kind === 'account' && accounts.find((a) => a.id === activeGroup.accountId)?.service === 'steam'
/**
* Whose identity the plaque shows.
*
@@ -177,6 +190,7 @@ export function BufferList(): JSX.Element {
onMentionsPage && voiceSessions.length === 0
? undefined
: (accounts.find((a) => a.id === activeGroup?.accountId) ??
(onInvite ? accounts.find((a) => a.id === shownInvitation?.accountId) : undefined) ??
accounts.find((a) => a.id === activeBuffer?.accountId) ??
accounts[0])
@@ -230,10 +244,48 @@ export function BufferList(): JSX.Element {
* since that is the order the server arranged them in and the reason it
* supplies one. The gathered pages keep the order they were sorted into.
*/
/**
* The headings this page draws under its own, and where each conversation is filed.
*
* A Steam account's own page has Steam's folders for the account, as its own client lists them
* (without the "Steam - " some carry), and each friend is under the one Steam has them in:
* what Steam says wins over anything filed here, and a change made here is made on Steam. Every
* other page has the headings somebody made.
*/
const [naming, setNaming] = useState<{ id: string; name: string } | null>(null)
const [makingFolder, setMakingFolder] = useState(false)
const steamGroups = useChat((s) => s.steamGroups)
const steamFolders = useMemo<CustomCategory[]>(
() =>
steamPage && activeGroup
? (steamGroups[activeGroup.accountId] ?? [])
.map((g) => ({ id: steamCategoryId(activeGroup.accountId, g.id), name: g.name.replace(/^Steam - /, '').trim() }))
.sort((a, b) => a.name.localeCompare(b.name))
: [],
[steamPage, activeGroup, steamGroups]
)
const myCategories = steamPage ? steamFolders : activeGroup ? (customCats[activeGroup.id] ?? []) : []
const viewAssignment = useMemo(() => {
if (!steamPage || !activeGroup) return assignment
const folders = [...(steamGroups[activeGroup.accountId] ?? [])].sort((a, b) => a.id - b.id)
const next = { ...assignment }
for (const b of groupBuffers) {
if (b.kind !== 'dm' || !b.remoteId) continue
const home = folders.find((g) => g.members.includes(b.remoteId!))
if (home) next[b.id] = steamCategoryId(activeGroup.accountId, home.id)
else delete next[b.id]
}
return next
}, [steamPage, activeGroup, steamGroups, assignment, groupBuffers])
/** Files a conversation under a heading: on Steam for a Steam page, in the preferences for the rest. */
const fileBuffer = (bufferId: string, categoryId: string): void => {
if (steamPage) store.moveSteamFriend(bufferId, parseSteamCategory(categoryId)?.groupId ?? null)
else setAssignment(bufferId, categoryId)
}
const grouped = useMemo(() => {
if (!activeGroup) return null
const mine = customCats[activeGroup.id] ?? []
const list = sections(groupBuffers, mine, assignment, categoryOrder[activeGroup.id] ?? [])
const list = sections(groupBuffers, myCategories, viewAssignment, categoryOrder[activeGroup.id] ?? [])
if (!isPinnedPage && !isDmPage) {
for (const s of list) {
s.buffers.sort((a, b) => (a.position || 0) - (b.position || 0))
@@ -243,19 +295,22 @@ export function BufferList(): JSX.Element {
// they just made it, and a heading that vanishes until something is put
// in it cannot have anything put in it.
return list.filter((s) => s.custom || s.buffers.length > 0)
}, [activeGroup, isPinnedPage, isDmPage, groupBuffers, customCats, assignment, categoryOrder])
}, [activeGroup, isPinnedPage, isDmPage, steamPage, groupBuffers, myCategories, viewAssignment, categoryOrder])
// The menu still toggles a buffer's *own* flag independently of a muted
// rail entry above it, the same way muting a channel inside an
// already-muted Slack workspace works.
/** The call that sets a mute on the account itself, for a service that keeps one. */
const accountMute = (accountId: string): string | null => {
const service = accounts.find((a) => a.id === accountId)?.service
return service === 'matrix' ? 'setMatrixRoomMuted' : service === 'discord' ? 'setDiscordChannelMuted' : service === 'steam' ? 'steamSetFriendMuted' : null
}
const isEffectivelyMuted = (buffer: BufferEntry): boolean =>
isMutedBuffer(buffer, muted, mutedGroups)
const [naming, setNaming] = useState<{ id: string; name: string } | null>(null)
const { menu: groupMenu, open: openGroupMenuAt, close: closeGroupMenu } = useContextMenu()
const [catMenu, setCatMenu] = useState<{ x: number; y: number; section: CategorySection } | null>(null)
const myCategories = activeGroup ? (customCats[activeGroup.id] ?? []) : []
const writeCategories = (next: CustomCategory[]): void => {
if (activeGroup) setCustomCats(activeGroup.id, next)
}
@@ -304,15 +359,23 @@ export function BufferList(): JSX.Element {
onTogglePin={() => togglePin(b.id)}
onToggleMute={() => {
toggleMute(b.id)
// On Matrix the account itself can hold the answer, so muting here
// mutes on a phone too. Everywhere else this stays what it always
// was: a preference belonging to this window.
if (accounts.find((a) => a.id === b.accountId)?.service === 'matrix') {
// On Matrix and Discord the account itself can hold the answer, so
// muting here mutes on a phone too. Everywhere else this stays what
// it always was: a preference belonging to this window.
const writeBack = accountMute(b.accountId)
if (writeBack)
void window.moho
.rpc('setMatrixRoomMuted', { bufferId: b.id, muted: !isEffectivelyMuted(b) })
.rpc(writeBack, { bufferId: b.id, muted: !isEffectivelyMuted(b) })
.catch((e: Error) => store.toast('error', e.message))
}
}}
onUnmuteAccount={
accountMute(b.accountId)
? () =>
void window.moho
.rpc(accountMute(b.accountId)!, { bufferId: b.id, muted: false })
.catch((e: Error) => store.toast('error', e.message))
: undefined
}
onToggleAutojoin={
b.kind === 'channel' && accounts.find((a) => a.id === b.accountId)?.service === 'irc'
? () => store.toggleAutojoin(b.accountId, bufferDisplayName(b.name))
@@ -340,7 +403,7 @@ export function BufferList(): JSX.Element {
status={dmStatus(b, presence, buffers)}
onCall={() => void store.callBuffer(b.id)}
onHangUp={() => void store.leaveVoice(b.accountId)}
onFile={(categoryId) => setAssignment(b.id, categoryId)}
onFile={(categoryId) => fileBuffer(b.id, categoryId)}
poppedOut={popouts.open.includes(b.id)}
onPopOut={() => store.popOut(b.id)}
onDock={() => store.dock(b.id)}
@@ -404,7 +467,7 @@ export function BufferList(): JSX.Element {
return
}
if (!section.custom) return
setAssignment(held.id, section.key)
fileBuffer(held.id, section.key)
}
const hideBuffer = (id: string): void => {
@@ -423,10 +486,31 @@ export function BufferList(): JSX.Element {
{/* Not on the mentions page, which is deliberately server-less: the
pane is empty there because there is nothing to list, not because
something still needs picking. */}
{accounts.length > 0 && !activeGroup && !onMentionsPage && (
{accounts.length > 0 && !activeGroup && !onMentionsPage && !onInvite && (
<div className="bufferlist-empty muted small">Select a server on the left.</div>
)}
{onInvite && (
<>
<div className="group-title">
<span className="ellipsis group-title-name">Invitations</span>
</div>
{invitations.map((invitation) => (
<button
key={invitation.key}
type="button"
className={classes('buffer-row', invitation.key === shownInvitation?.key && 'active', 'unread')}
title={`${invitation.name} — ${invitation.detail}`}
onClick={() => store.selectInvitation(invitation.key)}
>
<Avatar name={invitation.name} url={invitation.avatarUrl ?? undefined} size={22} accountId={invitation.accountId} />
<span className="ellipsis buffer-name">{invitation.name}</span>
<ServiceMark icon={serviceIcon(invitation.service)} size={15} />
</button>
))}
</>
)}
{activeGroup && (
<>
<div className="group-title">
@@ -519,14 +603,23 @@ export function BufferList(): JSX.Element {
const key = categoryKey(activeGroup.id, section)
const folded = isCollapsed(key)
return (
<div key={section.key} className="category">
<div
key={section.key}
// A conversation held over a heading that will take it lights the whole
// category, so what is about to happen is the heading and its people
// being added to - not a line that could be read as "put it above".
className={classes('category', dragging?.kind === 'buffer' && overCategory === section.key && 'drop-into')}
>
{naming?.id === section.key ? (
<CategoryNameField
value={naming.name}
onChange={(name) => setNaming({ id: naming.id, name })}
onCommit={() => {
const name = naming.name.trim()
if (name) {
if (name && steamPage && activeGroup) {
const group = parseSteamCategory(naming.id)?.groupId
if (group !== undefined) store.renameSteamFolder(activeGroup.accountId, group, name)
} else if (name) {
writeCategories(
myCategories.map((c) => (c.id === naming.id ? { ...c, name } : c))
)
@@ -543,7 +636,7 @@ export function BufferList(): JSX.Element {
'category-head',
'small',
dragging?.kind === 'category' && dragging.id === section.key && 'lifted',
overCategory === section.key && 'drop-target'
overCategory === section.key && dragging?.kind !== 'buffer' && 'drop-target'
)}
onClick={() => toggleCollapsed(key)}
onContextMenu={(e) => openCategoryMenu(e, section)}
@@ -585,12 +678,12 @@ export function BufferList(): JSX.Element {
// What is waiting in what is folded away, which is
// the thing worth knowing about a closed heading;
// how many channels it has is the fallback.
const waiting = section.buffers.filter((b) => b.unread > 0 && (!isEffectivelyMuted(b) || b.highlight))
const unread = waiting.reduce((n, b) => n + b.unread, 0)
const waiting = section.buffers.filter((b) => waitingCount(b, isEffectivelyMuted(b)) > 0)
const unread = waiting.reduce((n, b) => n + waitingCount(b, isEffectivelyMuted(b)), 0)
return unread > 0 ? (
<span
className={classes('unread-badge category-count', waiting.some((b) => b.highlight) && 'highlight')}
title={`${unread} unread in ${waiting.length} ${waiting.length === 1 ? 'channel' : 'channels'}`}
title={`${unread} ${unread === 1 ? 'mention' : 'mentions'} in ${waiting.length} ${waiting.length === 1 ? 'channel' : 'channels'}`}
>
{unread > 99 ? '99+' : unread}
</span>
@@ -626,6 +719,7 @@ export function BufferList(): JSX.Element {
{/* Below the text channels, as everywhere else that has both. */}
<VoiceChannels group={activeGroup} />
<SteamVoiceRooms group={activeGroup} />
</>
)}
</div>
@@ -651,6 +745,11 @@ export function BufferList(): JSX.Element {
label: 'New category',
icon: 'create_new_folder',
onClick: () => {
// On Steam it is made on Steam, once it has a name.
if (steamPage) {
setMakingFolder(true)
return
}
const id = `cat-${Date.now().toString(36)}`
// At the top, not the end. The command was given from the
// group's own title at the top of this list, and a heading
@@ -699,7 +798,11 @@ export function BufferList(): JSX.Element {
danger: true,
// The channels stay; only the heading goes, and they fall back
// to wherever the service filed them.
onClick: () => writeCategories(myCategories.filter((c) => c.id !== catMenu.section.key))
onClick: () => {
const group = parseSteamCategory(catMenu.section.key)
if (steamPage && activeGroup && group) store.deleteSteamFolder(activeGroup.accountId, group.groupId)
else writeCategories(myCategories.filter((c) => c.id !== catMenu.section.key))
}
}
] as MenuEntry[])
: [])
@@ -708,6 +811,20 @@ export function BufferList(): JSX.Element {
/>
)}
{makingFolder && activeGroup && (
<NamePrompt
title="New category"
detail="Made on Steam, so it is on this account in every Steam client. Steam's own client only reads its folders when it signs in, so it shows a folder or a move made here after it is restarted."
placeholder="Name"
confirmLabel="Create"
onCancel={() => setMakingFolder(false)}
onConfirm={(name) => {
setMakingFolder(false)
store.createSteamFolder(activeGroup.accountId, name)
}}
/>
)}
{/* Outside the group above, so a call stays visible and hangable-up
wherever you navigate. */}
<VoicePanel />
@@ -829,6 +946,8 @@ interface BufferRowProps {
onSelect: () => void
onTogglePin: () => void
onToggleMute: () => void
/** Matrix rooms muted on the account: take that mute off. */
onUnmuteAccount?: () => void
/** IRC channels only: rejoin this on every connect, or stop doing so. */
onToggleAutojoin?: () => void
/** Kick channels only: watch the stream where streams are watched. */
@@ -878,6 +997,7 @@ function BufferRow({
onSelect,
onTogglePin,
onToggleMute,
onUnmuteAccount,
onToggleAutojoin,
autojoins,
onOpenInBrowser,
@@ -920,6 +1040,12 @@ function BufferRow({
// Whether this channel's stream is the one in the window. Selected down to
// a boolean for the same reason as `live` above.
const watched = useChat((s) => s.watching?.bufferId === buffer.id)
// What the person is doing: under their name in comfy, and in the tooltip
// either way. Selected as the one object rather than a copy of it, so the row
// redraws when it changes and not on every presence update in the window.
const activity = useChat((s) => dmActivity(buffer, s.presenceByBuffer))
const comfy = useComfy()
const doing = activity ? activityLabel(activity) : undefined
// Under an account header the row's own kind is what's worth showing (a
// channel vs a DM vs the server buffer). A pinned row has no header above
@@ -963,7 +1089,7 @@ function BufferRow({
// Calling from the row it belongs to, as well as from the header of the
// conversation once it is open - the list is where you look for somebody
// you want to reach, so it is where reaching them should be offered.
const canCall = account?.service === 'discord' && buffer.kind === 'dm'
const canCall = (account?.service === 'discord' || account?.service === 'steam') && buffer.kind === 'dm'
// The same entries the header's nameplate opens - see lib/buffermenu.ts for
// why they live there rather than here.
@@ -982,6 +1108,7 @@ function BufferRow({
spaces,
onTogglePin,
onToggleMute,
onUnmuteAccount,
onToggleAutojoin,
onSpace,
onWatch,
@@ -997,7 +1124,9 @@ function BufferRow({
onMarkRead: () => void store.markBuffersRead([buffer.id]),
onMarkUnread: account?.service === 'matrix' ? onMarkUnread : undefined,
onTag: account?.service === 'matrix' ? onTag : undefined,
markedUnread: buffer.markedUnread
markedUnread: buffer.markedUnread,
onSteamFriend: account?.service === 'steam' && buffer.kind === 'dm' && buffer.remoteId ? (what) => store.askSteamFriend(what, buffer.id) : undefined,
onProfile: account?.service === 'steam' && buffer.kind === 'dm' && buffer.remoteId ? () => store.showProfile(buffer.id, buffer.name, buffer.remoteId) : undefined
})
return (
@@ -1025,10 +1154,17 @@ function BufferRow({
onDragStart()
}}
onDragEnd={onDragEnd}
title={link ? `${buffer.name} — ${link.detail}` : draggable ? `${buffer.name} — drag onto a heading to file it` : buffer.name}
title={link ? `${buffer.name} — ${link.detail}` : draggable ? `${buffer.name} — drag onto a heading to file it` : doing ? `${buffer.name} — ${doing}` : buffer.name}
>
{leading}
<span className="ellipsis buffer-name">{rowName}</span>
{comfy && activity ? (
<span className="buffer-text">
<span className="ellipsis buffer-name">{rowName}</span>
<ActivityLine activity={activity} />
</span>
) : (
<span className="ellipsis buffer-name">{rowName}</span>
)}
{/* So a conversation with no unread count and no traffic in it is
explained rather than merely quiet: it is being read elsewhere. */}
{/* Still filling in - a Matrix room between joining it and the server
@@ -1050,9 +1186,9 @@ function BufferRow({
arrive is worse than either on its own. */}
{live ? (
<span className="live-badge">LIVE</span>
) : buffer.unread > 0 && (!muted || buffer.highlight) ? (
<span className={classes('unread-badge', buffer.highlight && 'highlight')}>
{buffer.unread > 99 ? '99+' : buffer.unread}
) : waitingCount(buffer, muted) > 0 ? (
<span className={classes('unread-badge', (buffer.highlight || muted) && 'highlight')}>
{waitingCount(buffer, muted) > 99 ? '99+' : waitingCount(buffer, muted)}
</span>
) : (
// Left unread on purpose, with nothing new in it. A dot rather than
+81 -11
View File
@@ -9,6 +9,7 @@ import torMark from '../assets/tor.svg'
import { PollComposer } from './PollComposer'
import { Avatar } from './Avatar'
import { COMMON_EMOJI, emojiToken, EmojiPicker, type StickerEntry } from './EmojiPicker'
import { GifPicker } from './GifPicker'
import { PlaceField } from './PlaceField'
import { VoiceRecorder } from './VoiceRecorder'
import { useActiveBuffer, useChat, useStore } from '../state/hooks'
@@ -24,6 +25,7 @@ import {
} from '../lib/mentions'
import { STAGE_FILES, type StagedFile } from '../lib/staging'
import { withTone } from '../lib/skintone'
import { STEAM_FILE_TYPES, steamFileRefusal } from '../lib/steamfiles'
import { usePref } from '../state/hooks'
import { rankShortcodes, shortcodeQuery, unicodeTargets, type ShortcodeTarget } from '../lib/shortcodes'
@@ -36,7 +38,7 @@ interface StagedAttachment {
preview?: string
/** In bytes, once it has been asked. */
size?: number | null
/** Sent hidden behind a spoiler: Discord only. */
/** Sent hidden behind a spoiler: Discord and Steam. */
spoiler: boolean
}
@@ -133,6 +135,7 @@ export function Composer({ thread = false }: { thread?: boolean } = {}): JSX.Ele
/** The account's sticker packs, fetched when the picker is first opened. */
const [stickers, setStickers] = useState<StickerEntry[]>([])
const [stickerPicker, setStickerPicker] = useState(false)
const [gifPicker, setGifPicker] = useState(false)
/**
* What to do with files dropped on the window: they land in the tray, to be
* looked over and sent with the next message rather than going out on the
@@ -218,6 +221,7 @@ export function Composer({ thread = false }: { thread?: boolean } = {}): JSX.Ele
const [roles, setRoles] = useState<{ id: string; name: string; colour?: string }[]>([])
const emojiButtonRef = useRef<HTMLButtonElement>(null)
const stickerButtonRef = useRef<HTMLButtonElement>(null)
const gifButtonRef = useRef<HTMLButtonElement>(null)
const plusButtonRef = useRef<HTMLButtonElement>(null)
/** The "+" menu, where it opened. */
const [plusMenu, setPlusMenu] = useState<{ x: number; y: number } | null>(null)
@@ -236,7 +240,7 @@ export function Composer({ thread = false }: { thread?: boolean } = {}): JSX.Ele
const route = useChat((s) => s.route)
const routed = tunnelAll || !!account?.useTor
const media = useMediaUrl(account?.id)
const hasStickers = service === 'matrix' || service === 'discord'
const hasStickers = service === 'matrix' || service === 'discord' || service === 'steam'
const formats = formatsFor(service)
/**
* The account's stickers, asked for when the picker opens - from either
@@ -246,7 +250,7 @@ export function Composer({ thread = false }: { thread?: boolean } = {}): JSX.Ele
const loadStickers = (): void => {
if (!hasStickers || !buffer) return
void window.moho
.rpc<StickerEntry[]>(service === 'discord' ? 'listDiscordStickers' : 'listMatrixStickers', { bufferId: buffer.id })
.rpc<StickerEntry[]>(service === 'discord' ? 'listDiscordStickers' : service === 'steam' ? 'listSteamStickers' : 'listMatrixStickers', { bufferId: buffer.id })
.then(setStickers)
.catch(() => setStickers([]))
}
@@ -254,8 +258,9 @@ export function Composer({ thread = false }: { thread?: boolean } = {}): JSX.Ele
// of an attachment at all, so a file there is uploaded and the link sent -
// which is what people do by hand on IRC anyway, and is why it is offered
// here rather than left as the one service where the button is dead.
// Steam takes a picture or a short video, and says which and how big.
const supportsAttachments =
service === 'discord' || service === 'sneedchat' || service === 'matrix' || service === 'irc'
service === 'discord' || service === 'sneedchat' || service === 'matrix' || service === 'irc' || service === 'steam'
// Starting a reply puts the cursor in the box: the next thing anybody does
// is write the answer.
@@ -433,12 +438,29 @@ export function Composer({ thread = false }: { thread?: boolean } = {}): JSX.Ele
const stage = (path: string, file?: File): void => {
const name = fileNameOf(path)
// Steam refuses most files, and what it takes is known: said now, at the
// box, rather than once the message has gone and failed.
if (service === 'steam') {
const why = steamFileRefusal(name)
if (why) {
store.toast('error', why)
return
}
}
const id = ++seqRef.current
const isImage = isImageFile(name)
const preview = file && isImage ? URL.createObjectURL(file) : undefined
setStaged((s) => [...s, { id, path, name, isImage, spoiler: false, preview }])
// Its size is the main process's to read; the card says it when it comes.
void window.moho.fileSize(path).then((size) => setStaged((s) => s.map((a) => (a.id === id ? { ...a, size } : a))))
void window.moho.fileSize(path).then((size) => {
const tooBig = service === 'steam' ? steamFileRefusal(name, size ?? undefined) : null
if (tooBig) {
store.toast('error', tooBig)
setStaged((s) => s.filter((a) => a.id !== id))
return
}
setStaged((s) => s.map((a) => (a.id === id ? { ...a, size } : a)))
})
}
takeFiles.current = (files) => {
if (!supportsAttachments) {
@@ -449,7 +471,10 @@ export function Composer({ thread = false }: { thread?: boolean } = {}): JSX.Ele
inputRef.current?.focus()
}
const pickAndStage = (): void => void window.moho.pickFile().then((p) => p && stage(p))
// Steam takes a short list of kinds of file, so the dialog offers those and
// nothing else.
const pickAndStage = (): void =>
void window.moho.pickFile(service === 'steam' ? STEAM_FILE_TYPES : undefined).then((p) => p && stage(p))
/**
* What the "+" holds. A file everywhere it can go; and on Matrix the things
* that are a message of their own kind rather than text - a place, a poll.
@@ -524,6 +549,15 @@ export function Composer({ thread = false }: { thread?: boolean } = {}): JSX.Ele
batch.filter((att) => att.spoiler).map((att) => att.path)
)
}
} else if (service === 'steam') {
// Steam sends the words and then each file as messages of their own,
// all of them from one request, so one upload to watch and a caption
// that always comes first.
void post(
body,
staged.map((att) => att.path),
staged.filter((att) => att.spoiler).map((att) => att.path)
)
} else {
staged.forEach((att, i) => {
void post(i === 0 ? body : '', att.path)
@@ -1014,7 +1048,7 @@ export function Composer({ thread = false }: { thread?: boolean } = {}): JSX.Ele
{/* On the card's corner, and there only while it is pointed at
or focused - they would be a dozen buttons otherwise. */}
<div className="staged-actions">
{service === 'discord' && (
{(service === 'discord' || service === 'steam') && (
<button
type="button"
className={classes('staged-action', att.spoiler && 'on')}
@@ -1259,6 +1293,7 @@ export function Composer({ thread = false }: { thread?: boolean } = {}): JSX.Ele
title="Emoji"
onClick={() => {
setStickerPicker(false)
setGifPicker(false)
if (!pickerOpen) loadStickers()
setPickerOpen(!pickerOpen)
}}
@@ -1266,11 +1301,30 @@ export function Composer({ thread = false }: { thread?: boolean } = {}): JSX.Ele
<Icon name="mood" size={18} />
</button>
{/* GIFs, wherever there is a Discord account to ask for them: the
picker borrows that account's way of looking, and what it finds can
be sent in any conversation. */}
{!thread && service !== 'steam' && accounts.some((a) => a.service === 'discord') && (
<button
ref={gifButtonRef}
type="button"
className="icon-button"
title="GIFs"
onClick={() => {
setPickerOpen(false)
setStickerPicker(false)
setGifPicker(!gifPicker)
}}
>
<Icon name="gif_box" size={18} />
</button>
)}
{/* Its own button beside the emoji one, because it is its own
gesture: an emoji goes into the line being written and a sticker
is the message. Only where the service has them: Matrix, where a
pack supplies them, and Discord, where each guild has its own. */}
{!thread && (service === 'matrix' || service === 'discord') && (
{!thread && (service === 'matrix' || service === 'discord' || service === 'steam') && (
<button
ref={stickerButtonRef}
type="button"
@@ -1279,6 +1333,7 @@ export function Composer({ thread = false }: { thread?: boolean } = {}): JSX.Ele
onClick={() => {
const opening = !stickerPicker
setPickerOpen(false)
setGifPicker(false)
setStickerPicker(opening)
if (opening) loadStickers()
}}
@@ -1323,6 +1378,16 @@ export function Composer({ thread = false }: { thread?: boolean } = {}): JSX.Ele
{polling && <PollComposer bufferId={buffer.id} onClose={() => setPolling(false)} />}
{gifPicker && (
<GifPicker
anchor={gifButtonRef.current}
bufferId={buffer.id}
accountId={buffer.accountId}
discord={service === 'discord'}
onClose={() => setGifPicker(false)}
/>
)}
{(pickerOpen || stickerPicker) && (
<EmojiPicker
// Remounted when the other button is pressed, so it opens on that
@@ -1333,14 +1398,19 @@ export function Composer({ thread = false }: { thread?: boolean } = {}): JSX.Ele
// Only where the service has stickers, which is what decides
// whether there is a Stickers tab at all.
stickers={hasStickers ? stickers : undefined}
// Steam gives an account a short set of its own and takes nothing else.
fixedSet={service === 'steam'}
onSticker={
hasStickers
? (sticker) => {
setStickerPicker(false)
setPickerOpen(false)
const sent = sticker.id
? window.moho.rpc('sendDiscordSticker', { bufferId: buffer.id, stickerId: sticker.id })
: window.moho.rpc('sendMatrixSticker', { bufferId: buffer.id, mxc: sticker.mxc, body: sticker.body })
const sent =
service === 'steam'
? window.moho.rpc('sendSteamSticker', { bufferId: buffer.id, name: sticker.name })
: sticker.id
? window.moho.rpc('sendDiscordSticker', { bufferId: buffer.id, stickerId: sticker.id })
: window.moho.rpc('sendMatrixSticker', { bufferId: buffer.id, mxc: sticker.mxc, body: sticker.body })
void sent.catch((e: Error) => store.toast('error', e.message))
}
: undefined
@@ -6,6 +6,7 @@ import { ReasonPrompt } from './ReasonPrompt'
import { Avatar } from './Avatar'
import { bufferMenuEntries } from '../lib/buffermenu'
import { dmStatus } from './BufferList'
import { activityLabel, dmActivity } from '../lib/activity'
import { bufferDisplayName, classes } from '../lib/util'
import { useChat, useStore } from '../state/hooks'
import { useIdSetPref, useMapPref, usePref } from '../state/hooks'
@@ -51,6 +52,8 @@ export function ConversationMenu({ buffer }: { buffer: BufferEntry }): JSX.Eleme
const account = accounts.find((a) => a.id === buffer.accountId)
const name = bufferDisplayName(buffer.name)
const activity = dmActivity(buffer, presence)
const statusText = activity ? activityLabel(activity) : undefined
const entries: MenuEntry[] = [
...bufferMenuEntries({
@@ -61,7 +64,7 @@ export function ConversationMenu({ buffer }: { buffer: BufferEntry }): JSX.Eleme
filed: !!assignment[buffer.id],
inCall: voiceSessions.some((s) => s.bufferId === buffer.id),
poppedOut: popouts.open.includes(buffer.id),
canCall: account?.service === 'discord' && buffer.kind === 'dm',
canCall: (account?.service === 'discord' || account?.service === 'steam') && buffer.kind === 'dm',
live,
watched,
autojoins: store.autojoins(buffer.accountId, name),
@@ -69,12 +72,19 @@ export function ConversationMenu({ buffer }: { buffer: BufferEntry }): JSX.Eleme
onTogglePin: () => togglePin(buffer.id),
onToggleMute: () => {
toggleMute(buffer.id)
if (account?.service === 'matrix') {
if (account?.service === 'matrix' || account?.service === 'steam') {
void window.moho
.rpc('setMatrixRoomMuted', { bufferId: buffer.id, muted: !isMuted(buffer.id) })
.rpc(account.service === 'steam' ? 'steamSetFriendMuted' : 'setMatrixRoomMuted', { bufferId: buffer.id, muted: !isMuted(buffer.id) })
.catch((e: Error) => store.toast('error', e.message))
}
},
onUnmuteAccount:
account?.service === 'matrix' || account?.service === 'steam'
? () =>
void window.moho
.rpc(account.service === 'steam' ? 'steamSetFriendMuted' : 'setMatrixRoomMuted', { bufferId: buffer.id, muted: false })
.catch((e: Error) => store.toast('error', e.message))
: undefined,
onToggleAutojoin:
buffer.kind === 'channel' && account?.service === 'irc'
? () => store.toggleAutojoin(buffer.accountId, name)
@@ -101,7 +111,9 @@ export function ConversationMenu({ buffer }: { buffer: BufferEntry }): JSX.Eleme
account?.service === 'matrix'
? (tag, on) => void store.setRoomTag(buffer.id, tag, on)
: undefined,
markedUnread: buffer.markedUnread
markedUnread: buffer.markedUnread,
onSteamFriend: account?.service === 'steam' && buffer.kind === 'dm' && buffer.remoteId ? (what) => store.askSteamFriend(what, buffer.id) : undefined,
onProfile: account?.service === 'steam' && buffer.kind === 'dm' && buffer.remoteId ? () => store.showProfile(buffer.id, buffer.name, buffer.remoteId) : undefined
}),
{ separator: true },
// Last, and on its own. It is the one entry here that starts something
@@ -159,6 +171,9 @@ export function ConversationMenu({ buffer }: { buffer: BufferEntry }): JSX.Eleme
/>
) : null}
<span className="main-header-title ellipsis">{name}</span>
{/* What they are doing, beside the name: the game, or a state the dot's
colour does not tell apart. */}
{statusText && <span className="header-status small muted ellipsis">{statusText}</span>}
</button>
{buffer.topic && <HeaderTopic topic={buffer.topic} />}
@@ -0,0 +1,27 @@
import { Icon } from './Icon'
import { useChat, useStore } from '../state/hooks'
/**
* A warning the service has put on a conversation, over the top of it, in red,
* until the person dismisses it.
*
* Steam's "this person may not be who they appear to be" is the one there is.
* Said in the log as well, where it stays in its place; this is what stops it
* being missed by somebody who opens the conversation scrolled to the bottom.
* Dismissing tells the service, which does not raise it again - and if it does
* raise one, the banner is back, because that is a new warning.
*/
export function ConversationNotice({ bufferId }: { bufferId: string }): JSX.Element | null {
const notice = useChat((s) => s.buffers.find((b) => b.id === bufferId)?.notice)
const store = useStore()
if (!notice) return null
return (
<div className="notice-banner" role="alert">
<Icon name="warning" size={18} />
<span className="notice-banner-text">{notice.text}</span>
<button type="button" className="notice-banner-dismiss" onClick={() => void store.dismissNotice(bufferId)}>
Dismiss
</button>
</div>
)
}
@@ -615,6 +615,7 @@ export function ConversationTools({ buffer }: { buffer: BufferEntry }): JSX.Elem
// to a name half written.
const filterMenu = suggestions(query)
const isMatrix = buffer.accountId.startsWith('matrix:')
const isSteam = buffer.accountId.startsWith('steam:')
const stream = useChat((s) => s.kickStreams)[buffer.id]
// Whether this window is the one playing this channel. Per window rather
// than per channel: a popped-out chat is its own window with its own
@@ -949,7 +950,7 @@ export function ConversationTools({ buffer }: { buffer: BufferEntry }): JSX.Elem
/>
)}
{isDiscord && isDm && (
{(isDiscord || isSteam) && isDm && (
<IconButton
name={inCall ? 'call_end' : 'call'}
title={inCall ? 'Hang up' : `Call ${buffer.name}`}
+15 -6
View File
@@ -2,7 +2,7 @@ import React, { createContext, useContext, useEffect, useLayoutEffect, useMemo,
import { createPortal } from 'react-dom'
import { useMediaUrl } from '../lib/route'
import { Icon } from './Icon'
import { discordEmojiUrl, emojiPreview, type SmilieEntry } from '../lib/format'
import { discordEmojiUrl, emojiPreview, sourcePick, type SmilieEntry } from '../lib/format'
import { drawableEmoteUrl, onLocalEmotes } from '../lib/emotecache'
import { LottieSticker } from './LottieSticker'
import type { CustomEmoji } from '../../../shared/wire'
@@ -72,6 +72,8 @@ export const COMMON_EMOJI: { emoji: string; name: string }[] = [
* round and flags animation. Neither is negotiable - the server parses it.
*/
export function emojiToken(e: CustomEmoji): string {
// Steam's, named rather than numbered: the id carries the service.
if (e.id.startsWith('steam:')) return `[steam:emote:${e.id.slice(6)}]`
if (e.url) return `[emote:${e.id}:${e.name}]`
return `<${e.animated ? 'a' : ''}:${e.name}:${e.id}>`
}
@@ -205,6 +207,12 @@ interface Props {
accountId?: string
onSelect: (text: string) => void
onClose: () => void
/**
* The service has a short set of its own and nothing else is accepted - Steam
* - so there is no Unicode emoji to offer, only what the account was given.
* Recent picks that are not from that set are left out too.
*/
fixedSet?: boolean
}
export function EmojiPicker({
@@ -217,7 +225,8 @@ export function EmojiPicker({
accountId,
onSelect,
onSticker,
onClose
onClose,
fixedSet = false
}: Props): JSX.Element {
// The account's emoji and stickers through its route when it is strictly
// routed (#257) - Discord's come straight off its CDN otherwise.
@@ -248,7 +257,7 @@ export function EmojiPicker({
/** The cell the arrow keys are on: the search box keeps the focus. */
const keyed = useRef<HTMLElement | null>(null)
const [pos, setPos] = useState({ left: 0, top: 0 })
const [recent, setRecent] = useState<string[]>(() => readRecent(accountId))
const [recent, setRecent] = useState<string[]>(() => readRecent(accountId).filter((r) => !fixedSet || r.startsWith('[steam:')))
// Everything this account can send, wherever it came from. Asked of the
// daemon rather than assembled here, because the answer depends on things
// only it knows - a Nitro subscription, a Kick channel's standing.
@@ -350,8 +359,8 @@ export function EmojiPicker({
const q = query.trim().toLowerCase()
const unicode = useMemo(
() => (q ? COMMON_EMOJI.filter((e) => e.name.includes(q) || e.emoji === q) : COMMON_EMOJI),
[q]
() => (fixedSet ? [] : q ? COMMON_EMOJI.filter((e) => e.name.includes(q) || e.emoji === q) : COMMON_EMOJI),
[q, fixedSet]
)
const custom = useMemo(
() => (q ? customEmoji.filter((e) => e.name.toLowerCase().includes(q)) : customEmoji),
@@ -802,7 +811,7 @@ export function EmojiPicker({
className={`emoji-cell${why ? ' locked' : ''}${art ? '' : ' emoji-token'}`}
disabled={!!why}
title={why || e.name}
onClick={() => pick(e.id)}
onClick={() => pick(sourcePick(src.service, e))}
>
{art ? <img src={media(art)} alt={e.name} loading="lazy" /> : e.name}
</button>
+238
View File
@@ -0,0 +1,238 @@
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { Icon } from './Icon'
import { useEscapeLayer } from '../lib/layers'
import { useMediaUrl } from '../lib/route'
import { useStore } from '../state/hooks'
/** One of the GIFs the daemon lists: what to play, and what to send. */
export interface GifEntry {
id: string
title: string
/** The page on Tenor or Klipy, which is what Discord is sent. */
url: string
/** The video, to play in the grid. */
src: string
/** The file, which is what everything that is not Discord is sent. */
gifSrc: string
preview: string
width: number
height: number
}
interface GifCategory {
name: string
src: string
}
/** How long after the last keystroke before a search is made. */
const SEARCH_DELAY = 450
/**
* GIFs to browse and send, as Discord's own picker has them: what is trending,
* a search, and a row of categories to start from.
*
* They come from Discord - any account will do, whichever conversation this is
* open in - and go anywhere: to a Discord conversation as the link Discord's
* own client sends, so that Discord unfurls it; to every other service as the
* file itself, which a window of this kind draws as the GIF and any other
* client shows as a link.
*/
export function GifPicker({
anchor,
bufferId,
accountId,
discord,
onClose
}: {
anchor: HTMLElement | null
bufferId: string
accountId: string
/** Whether the conversation is on Discord, which decides what is sent. */
discord: boolean
onClose: () => void
}): JSX.Element {
const store = useStore()
const media = useMediaUrl(accountId)
const ref = useRef<HTMLDivElement>(null)
const scroll = useRef<HTMLDivElement>(null)
const [pos, setPos] = useState({ left: 0, top: 0 })
const [query, setQuery] = useState('')
const [gifs, setGifs] = useState<GifEntry[]>([])
const [categories, setCategories] = useState<GifCategory[]>([])
const [state, setState] = useState<'loading' | 'ready' | 'failed'>('loading')
const [error, setError] = useState('')
useEscapeLayer(onClose)
// Above and right-aligned to its button, and kept in view, as the emoji
// picker is.
useLayoutEffect(() => {
const el = ref.current
if (!el || !anchor) return
const place = (): void => {
const a = anchor.getBoundingClientRect()
const r = el.getBoundingClientRect()
const left = Math.max(4, Math.min(a.right - r.width, window.innerWidth - r.width - 4))
const top = Math.max(4, Math.min(a.top - r.height - 6, window.innerHeight - r.height - 4))
setPos((was) => (was.left === left && was.top === top ? was : { left, top }))
}
place()
const ro = new ResizeObserver(place)
ro.observe(el)
window.addEventListener('resize', place)
return () => {
ro.disconnect()
window.removeEventListener('resize', place)
}
}, [anchor])
// Pressing anywhere else closes it; pressing inside, or on its button, does not.
useEffect(() => {
const onDown = (e: MouseEvent): void => {
const target = e.target as Node
if (ref.current?.contains(target) || anchor?.contains(target)) return
onClose()
}
window.addEventListener('mousedown', onDown, true)
return () => window.removeEventListener('mousedown', onDown, true)
}, [anchor, onClose])
// What is trending when it opens, and a search once typing has stopped. An
// answer that arrives after a newer question was asked is not shown.
useEffect(() => {
// The harness has no Discord to ask, so it can leave the answer here. Only
// a window it started has the hook it is read from.
const fixture = (window as unknown as { __mohoShots?: unknown; __gifFixture?: { gifs: GifEntry[]; categories: GifCategory[] } })
if (fixture.__mohoShots && fixture.__gifFixture) {
const wanted = query.trim().toLowerCase()
setGifs(fixture.__gifFixture.gifs.filter((g) => !wanted || g.title.toLowerCase().includes(wanted)))
setCategories(fixture.__gifFixture.categories)
setState('ready')
return
}
let current = true
setState('loading')
const wait = setTimeout(
() => {
window.moho
.rpc<{ gifs: GifEntry[]; categories: GifCategory[] }>('listGifs', { query: query.trim() })
.then((answer) => {
if (!current) return
setGifs(answer.gifs)
setCategories(answer.categories)
setState('ready')
})
.catch((e: Error) => {
if (!current) return
setError(e.message)
setState('failed')
})
},
query.trim() ? SEARCH_DELAY : 0
)
return () => {
current = false
clearTimeout(wait)
}
}, [query])
const pick = (gif: GifEntry): void => {
onClose()
// Discord's own client sends the link, which Discord turns into the GIF.
// Everything else is sent the file, since a page address would be only
// that.
void store.sendMessage(bufferId, discord ? gif.url : gif.gifSrc)
}
// Two columns, each GIF into whichever is shorter, so differently shaped ones
// fit together the way Discord's do.
const columns: GifEntry[][] = [[], []]
const heights = [0, 0]
for (const gif of gifs) {
const into = heights[0] <= heights[1] ? 0 : 1
columns[into].push(gif)
heights[into] += gif.width && gif.height ? gif.height / gif.width : 0.75
}
return createPortal(
<div ref={ref} className="gif-picker" style={{ left: pos.left, top: pos.top }} role="dialog" aria-label="GIFs">
<div className="gif-search">
<Icon name="search" size={18} />
<input
autoFocus
className="text-field"
value={query}
placeholder="Search for a GIF"
onChange={(e) => setQuery(e.target.value)}
/>
</div>
<div className="gif-scroll" ref={scroll}>
{!query.trim() && categories.length > 0 && (
<div className="gif-categories">
{categories.map((c) => (
<button key={c.name} type="button" className="gif-category" onClick={() => setQuery(c.name)}>
{c.name}
</button>
))}
</div>
)}
{state === 'failed' && <div className="gif-empty muted">{error || 'GIFs could not be loaded'}</div>}
{state === 'loading' && gifs.length === 0 && <div className="gif-empty muted">Loading…</div>}
{state === 'ready' && gifs.length === 0 && <div className="gif-empty muted">No GIFs found</div>}
{gifs.length > 0 && (
<div className="gif-grid">
{columns.map((column, i) => (
<div key={i} className="gif-column">
{column.map((gif) => (
<GifCell key={gif.id} gif={gif} media={media} root={scroll} onPick={pick} />
))}
</div>
))}
</div>
)}
</div>
</div>,
document.body
)
}
/**
* One GIF. Played only while it is on screen: a grid of forty videos all
* running is a great deal of work for a list nobody is looking at the bottom
* of, so out of view it is a still picture and nothing more.
*/
function GifCell({
gif,
media,
root,
onPick
}: {
gif: GifEntry
media: (url: string) => string
root: React.RefObject<HTMLDivElement | null>
onPick: (gif: GifEntry) => void
}): JSX.Element {
const cell = useRef<HTMLButtonElement>(null)
const [visible, setVisible] = useState(false)
useEffect(() => {
const el = cell.current
if (!el) return
const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting), { root: root.current, rootMargin: '80px' })
observer.observe(el)
return () => observer.disconnect()
}, [root])
const ratio = gif.width && gif.height ? `${gif.width} / ${gif.height}` : '4 / 3'
return (
<button ref={cell} type="button" className="gif-cell" title={gif.title} style={{ aspectRatio: ratio }} onClick={() => onPick(gif)}>
{visible ? (
<video src={media(gif.src)} poster={gif.preview ? media(gif.preview) : undefined} autoPlay loop muted playsInline />
) : gif.preview ? (
<img src={media(gif.preview)} alt="" draggable={false} />
) : null}
</button>
)
}
@@ -37,11 +37,25 @@ export function IncomingCallPanel({ silent = false }: { silent?: boolean } = {})
const store = useStore()
const calls = useChat((s) => s.incomingCalls)
const matrix = useChat((s) => s.ringingCall)
const steamRings = useChat((s) => s.steamRings)
const buffers = useChat((s) => s.buffers)
const accounts = useChat((s) => s.accounts)
const ringtone = useRef<Ringtone>()
const rings: Ring[] = [
...steamRings.map((ring): Ring => {
const buffer = buffers.find((b) => b.accountId === ring.accountId && b.remoteId === ring.steamid)
const account = accounts.find((a) => a.id === ring.accountId)
return {
key: `s:${ring.voiceChatId}`,
name: buffer ? bufferDisplayName(buffer.name) : 'Someone',
avatarUrl: buffer?.avatarUrl,
accountId: ring.accountId,
detail: `Incoming call${account ? ` · ${account.displayName || account.id}` : ''}`,
answer: () => void store.answerSteamCall(ring),
decline: () => void store.declineSteamCall(ring)
}
}),
...calls.map((call): Ring => {
const buffer = buffers.find((b) => b.id === call.bufferId)
const account = accounts.find((a) => a.id === call.accountId)
+29 -30
View File
@@ -1,44 +1,36 @@
import { Avatar } from './Avatar'
import { useChat, useStore } from '../state/hooks'
import { readInviteGroupId } from '../lib/groups'
import { useChat, useInvitations, useStore } from '../state/hooks'
import { currentInvitation } from '../lib/invitations'
import { serviceLabel } from '../lib/util'
/**
* A room somebody has asked you into, and the two answers to it.
* The invitation being looked at, and the two answers to it.
*
* Shown where the conversation would be, because that is what is being
* offered: the tile in the rail says one has arrived, and this says what it
* is and who from. Both disappear together the moment it is answered - an
* invitation is the one thing in the rail that stops existing once it has
* been dealt with.
* offered: the list on the left says which have arrived, and this says what
* the chosen one is and who from. Accepting turns this pane into the
* conversation it was offering; declining takes the invitation away. Either
* way it disappears from the list - an invitation is the one thing here that
* stops existing once it has been dealt with.
*/
export function InvitePanel({ groupId }: { groupId: string }): JSX.Element | null {
export function InvitePanel(): JSX.Element | null {
const store = useStore()
const invites = useChat((s) => s.matrixInvites)
const accounts = useChat((s) => s.accounts)
const named = readInviteGroupId(groupId)
if (!named) return null
const key = useChat((s) => s.activeInvitationKey)
const invitation = currentInvitation(useInvitations(), key)
// Answered, here or in another client. The page leaves with the last one.
if (!invitation) return null
const invite = (invites[named.accountId] || []).find((i) => i.roomId === named.roomId)
// Answered, here or in another client. The tile goes with it, so this is
// only ever seen for the moment between the two.
if (!invite) return null
const account = accounts.find((a) => a.id === named.accountId)
const answer = (accept: boolean): void => {
store.answerMatrixInvite(named.accountId, named.roomId, accept)
// Back to the account the invitation was for: accepting puts the room in
// its list a moment later, and declining leaves nothing to look at here.
if (account) store.selectGroup(`account:${account.id}`)
}
const account = accounts.find((a) => a.id === invitation.accountId)
const answer = (accept: boolean): void => void store.answerInvitation(invitation, accept)
return (
<div className="invite-panel">
<Avatar name={invite.name} url={invite.avatarUrl ?? undefined} size={64} />
<h2 className="invite-panel-name ellipsis">{invite.name}</h2>
<Avatar name={invitation.name} url={invitation.avatarUrl ?? undefined} size={64} />
<h2 className="invite-panel-name ellipsis">{invitation.name}</h2>
<p className="small muted">
{invite.inviter ? `${invite.inviter} invited you` : 'You have been invited'}
{invite.isDirect ? ' to a direct message' : ' to this room'}
{account ? ` · ${account.displayName || account.id}` : ''}
{invitation.detail}
{account ? ` · ${serviceLabel(account.service)} · ${account.displayName || account.id}` : ''}
</p>
<div className="button-row">
<button type="button" className="button primary" onClick={() => answer(true)}>
@@ -49,8 +41,15 @@ export function InvitePanel({ groupId }: { groupId: string }): JSX.Element | nul
</button>
</div>
<p className="small muted invite-panel-note">
Accepting joins the room and starts syncing it. Declining leaves it, and the invitation
goes away for good.
{invitation.kind === 'friend'
? 'Accepting makes you friends: the conversation with them opens here, and they can see when you are online. Declining removes the request.'
: invitation.kind === 'verification'
? 'Accepting starts the check: you will be shown emoji to compare with the other side. Only accept one you started or expected. Declining cancels it.'
: invitation.direct
? 'Accepting starts the conversation and opens it here. Declining leaves it, and the invitation goes away for good.'
: invitation.service === 'steam'
? 'Accepting joins the group chat and opens it here. Declining takes the invitation off this list; the message that carried it stays in your conversation with them.'
: 'Accepting joins the room and starts syncing it. Declining leaves it, and the invitation goes away for good.'}
</p>
</div>
)
+280 -118
View File
@@ -6,6 +6,7 @@ import { ContextMenu } from './ContextMenu'
import { RoomSearch } from './RoomSearch'
import { useChat, useStore } from '../state/hooks'
import { classes, serviceLabel } from '../lib/util'
import { steamGroupInviteCode } from '../lib/steamchat'
import type { Account, DiscordFriend } from '../../../shared/wire'
/**
@@ -44,15 +45,6 @@ const ON_DISCORD_ONLY: { label: string; icon: string; why: string }[] = [
}
]
/** A room this account has been invited to and not yet answered. */
type MatrixInvite = {
roomId: string
name: string
inviter: string | null
avatarUrl: string | null
isDirect: boolean
}
/**
* Per-protocol join pages rather than one generic "join by name" field: each
* service's mechanism is genuinely different (IRC joins by channel name,
@@ -84,11 +76,13 @@ export function JoinPanel(): JSX.Element {
return <KickJoin account={account} />
case 'sneedchat':
return <SneedchatRooms account={account} />
case 'steam':
return <SteamJoin account={account} />
default:
return <div className="panel muted">Joining isn&apos;t supported for this service yet.</div>
}
})()
const joinable = all.filter((a) => ['irc', 'matrix', 'discord', 'kick', 'sneedchat'].includes(a.service))
const joinable = all.filter((a) => ['irc', 'matrix', 'discord', 'kick', 'sneedchat', 'steam'].includes(a.service))
return (
<div className="join-frame">
@@ -367,6 +361,274 @@ function KickJoin({ account }: { account: Account }): JSX.Element {
)
}
/** One person in a friend request. */
interface SteamPerson {
steamid: string
name: string | null
avatarUrl?: string | null
}
interface SteamRequests {
incoming: SteamPerson[]
outgoing: SteamPerson[]
}
/**
* Friends on Steam: asking somebody, and taking a request back.
*
* Steam makes you friends by one side asking and the other agreeing. Those who
* have asked you are not here: each waits as a tile in the server list, beside
* a Matrix room's invitations, and is answered there. What is here is the asking,
* and the requests still waiting on the other side.
*/
function SteamJoin({ account }: { account: Account }): JSX.Element {
const store = useStore()
const [target, setTarget] = useState('')
const [busy, setBusy] = useState(false)
const [requests, setRequests] = useState<SteamRequests>({ incoming: [], outgoing: [] })
const [blocked, setBlocked] = useState<{ steamid: string; name: string }[]>([])
const [links, setLinks] = useState<{ token: string; link: string; created: number }[] | null>(null)
const connected = account.state === 'connected'
useEffect(() => {
let live = true
void window.moho
.rpc<SteamRequests>('steamFriendRequests', { accountId: account.id })
.then((r) => live && setRequests(r))
.catch(() => {})
const off = window.moho.onEvent((e) => {
if (e.event !== 'steamFriendRequests') return
const d = e.data as { accountId?: string; requests?: SteamRequests }
if (d.accountId === account.id && d.requests) setRequests(d.requests)
})
// Who is blocked, and what links have been given out: neither has a place
// in the conversation list, so they are here, where friends are added.
void window.moho
.rpc<{ steamid: string; name: string }[]>('steamBlockedList', { accountId: account.id })
.then((b) => live && setBlocked(b))
.catch(() => {})
const offBlocked = window.moho.onEvent((e) => {
if (e.event !== 'steamBlocked') return
const d = e.data as { accountId?: string; blocked?: { steamid: string; name: string }[] }
if (d.accountId === account.id && d.blocked) setBlocked(d.blocked)
})
return () => {
live = false
off()
offBlocked()
}
}, [account.id])
// The links, once the account is connected: they come from Steam's website.
useEffect(() => {
if (!connected) return
let live = true
void window.moho
.rpc<{ token: string; link: string; created: number }[]>('steamInviteLinks', { accountId: account.id, action: 'list' })
.then((l) => live && setLinks(l))
.catch(() => live && setLinks([]))
return () => {
live = false
}
}, [account.id, connected])
const changeLinks = (action: 'create' | 'revoke', token?: string): void => {
void window.moho
.rpc<{ token: string; link: string; created: number }[]>('steamInviteLinks', { accountId: account.id, action, token })
.then(setLinks)
.catch((e: Error) => store.toast('error', e.message))
}
const copy = (text: string): void => {
// Through the main process, as everywhere else in moho: the page's own clipboard is refused here.
void window.moho
.copyText(text)
.then(() => store.toast('info', 'Copied'))
.catch(() => store.toast('error', 'Could not copy'))
}
const unblock = (p: { steamid: string; name: string }): void => {
void window.moho
.rpc('steamUnblock', { accountId: account.id, steamid: p.steamid })
.then(() => store.toast('info', `Unblocked ${p.name}`))
.catch((e: Error) => store.toast('error', e.message))
}
const label = (p: SteamPerson): string => p.name || p.steamid
const [groupLink, setGroupLink] = useState('')
const [groupName, setGroupName] = useState('')
const joinGroup = (): void => {
const typed = groupLink.trim()
if (!typed) return
setBusy(true)
void window.moho
.rpc<{ groupId: string; name?: string }>('steamChatGroupAction', { accountId: account.id, action: 'join', invite: typed })
.then((r) => {
setGroupLink('')
store.toast('info', `Joined ${r.name || 'the group'}`)
store.selectGroup(r.groupId)
})
.catch((e: Error) => store.toast('error', e.message))
.finally(() => setBusy(false))
}
const makeGroup = (): void => {
const typed = groupName.trim()
if (!typed) return
setBusy(true)
void window.moho
.rpc<{ groupId: string }>('steamChatGroupAction', { accountId: account.id, action: 'create', name: typed })
.then((r) => {
setGroupName('')
store.selectGroup(r.groupId)
})
.catch((e: Error) => store.toast('error', e.message))
.finally(() => setBusy(false))
}
const ask = (): void => {
const typed = target.trim()
if (!typed) return
// A link to a group, pasted where a friend goes, is joined as the group it is.
if (steamGroupInviteCode(typed)) {
setGroupLink(typed)
setTarget('')
return
}
setBusy(true)
void window.moho
.rpc<{ steamid: string; name: string | null }>('steamAddFriend', { accountId: account.id, target: typed })
.then((r) => {
setTarget('')
store.toast('info', `Friend request sent to ${r.name || typed}`)
})
.catch((e: Error) => store.toast('error', e.message))
.finally(() => setBusy(false))
}
const withdraw = (p: SteamPerson): void => {
void window.moho
.rpc('steamRemoveFriend', { accountId: account.id, steamid: p.steamid })
.catch((e: Error) => store.toast('error', e.message))
}
return (
<div className="panel join-panel">
<span className="small muted">Add a friend</span>
<div className="field-row">
<input
className="text-field"
placeholder="Account name, Steam id, friend code or invite link"
spellCheck={false}
autoComplete="off"
value={target}
disabled={!connected || busy}
onChange={(e) => setTarget(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') ask()
}}
/>
<button type="button" className="button" disabled={!connected || busy || !target.trim()} onClick={ask}>
Add friend
</button>
</div>
{!connected && <p className="small muted">Friends can be added once this account is connected.</p>}
<span className="small muted">Join a group</span>
<div className="field-row">
<input
className="text-field"
placeholder="An invite link, like s.team/chat/…"
spellCheck={false}
autoComplete="off"
value={groupLink}
disabled={!connected || busy}
onChange={(e) => setGroupLink(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') joinGroup()
}}
/>
<button type="button" className="button" disabled={!connected || busy || !groupLink.trim()} onClick={joinGroup}>
Join
</button>
</div>
<span className="small muted">Start a group</span>
<div className="field-row">
<input
className="text-field"
placeholder="A name for it"
value={groupName}
disabled={!connected || busy}
onChange={(e) => setGroupName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') makeGroup()
}}
/>
<button type="button" className="button" disabled={!connected || busy || !groupName.trim()} onClick={makeGroup}>
Create
</button>
</div>
{requests.outgoing.length > 0 && (
<>
<span className="small muted">Waiting for them to accept</span>
{requests.outgoing.map((p) => (
<div key={p.steamid} className="field-row">
<span className="grow">{label(p)}</span>
<button type="button" className="button subtle small" onClick={() => withdraw(p)}>
Cancel request
</button>
</div>
))}
</>
)}
{/* A link anybody can add this account by, even if it takes no requests
from strangers: good for a month, and taken back here. */}
{connected && links !== null && (
<>
<span className="small muted">Your invite links</span>
{links.length === 0 && <p className="small muted">None yet. A link lets whoever has it add you, for thirty days.</p>}
{links.map((l) => (
<div key={l.token} className="field-row">
<span className="grow ellipsis" title={l.link}>
{l.link}
</span>
<button type="button" className="button subtle small" onClick={() => copy(l.link)}>
Copy
</button>
<button type="button" className="button subtle small" onClick={() => changeLinks('revoke', l.token)}>
Revoke
</button>
</div>
))}
<div className="field-row">
<button type="button" className="button subtle small" onClick={() => changeLinks('create')}>
Make a link
</button>
</div>
</>
)}
{blocked.length > 0 && (
<>
<span className="small muted">Blocked</span>
{blocked.map((p) => (
<div key={p.steamid} className="field-row">
<span className="grow ellipsis" title={p.steamid}>
{p.name}
</span>
<button type="button" className="button subtle small" disabled={!connected} onClick={() => unblock(p)}>
Unblock
</button>
</div>
))}
</>
)}
</div>
)
}
/**
* Making a room, or a space.
*
@@ -465,101 +727,10 @@ function CreateMatrixRoom({ account }: { account: Account }): JSX.Element {
)
}
/**
* Rooms somebody has asked this account to join.
*
* Shown above the join field because it is the one thing here that arrived
* on its own: everything else on this page is a room you already know the
* name of and went looking for. An invite was invisible until recently -
* the daemon never read them out of sync - so it is worth being plain about
* who sent it, since a room with no name of its own shows as its raw id and
* the inviter is the only part that makes it answerable.
*/
function MatrixInvites({ account }: { account: Account }): JSX.Element | null {
const store = useStore()
const [invites, setInvites] = useState<MatrixInvite[]>([])
const [answering, setAnswering] = useState<string | null>(null)
useEffect(() => {
const load = (): void => {
void window.moho
.rpc<MatrixInvite[]>('listMatrixInvites', { accountId: account.id })
// An older daemon has no such method, and no invites to show.
.then(setInvites)
.catch(() => setInvites([]))
}
load()
// The daemon pushes the whole set whenever it changes, so accepting from
// another client empties this without anybody refreshing.
return window.moho.onEvent((frame) => {
if (frame.event !== 'matrixInvites') return
const data = frame.data as { accountId: string; invites: MatrixInvite[] }
if (data.accountId === account.id) setInvites(data.invites ?? [])
})
}, [account.id])
if (invites.length === 0) return null
const answer = (invite: MatrixInvite, accept: boolean): void => {
setAnswering(invite.roomId)
void window.moho
.rpc(accept ? 'acceptMatrixInvite' : 'declineMatrixInvite', {
accountId: account.id,
roomId: invite.roomId
})
// Not removed from the list here: the next sync stops listing it,
// which is what actually confirms the server agreed.
.catch((e: Error) => store.toast('error', e.message))
.finally(() => setAnswering(null))
}
return (
<div className="field">
<span className="small muted">
{invites.length === 1 ? 'You have been invited to' : `You have ${invites.length} invitations`}
</span>
<div className="invite-list">
{invites.map((invite) => (
<div className="invite-row" key={invite.roomId}>
<div className="invite-what">
<span className="invite-name ellipsis">{invite.name}</span>
{invite.inviter && (
<span className="small muted ellipsis">
from {invite.inviter}
{invite.isDirect ? ' · direct message' : ''}
</span>
)}
</div>
<div className="invite-actions">
<button
type="button"
className="button primary"
disabled={answering === invite.roomId}
onClick={() => answer(invite, true)}
>
Accept
</button>
<button
type="button"
className="button"
disabled={answering === invite.roomId}
onClick={() => answer(invite, false)}
>
Decline
</button>
</div>
</div>
))}
</div>
</div>
)
}
function MatrixJoin({ account }: { account: Account }): JSX.Element {
const store = useStore()
return (
<div className="panel join-panel">
<MatrixInvites account={account} />
<SubmitField
label="Join a room or space"
// A Space is just a room with an m.space creation type, joined through
@@ -762,11 +933,12 @@ function DiscordJoin({ account }: { account: Account }): JSX.Element {
if (live) setFriends(live)
}, [live])
// Requests are their own list above the friends. They are not people you
// can message and they are the thing somebody opened this panel to deal
// with, so filtering them by whether they happen to be online - which is
// what the toggle below does - would hide the ones that matter most.
const waiting = friends.filter((f) => f.kind === 'incoming' || f.kind === 'outgoing')
// Requests this account has sent are their own list above the friends: not
// people you can message yet, so filtering them by whether they happen to be
// online - which is what the toggle below does - would hide them. The ones
// sent to this account are not here: they wait on the Invitations tile in
// the server list with every other question that wants a yes or a no.
const waiting = friends.filter((f) => f.kind === 'outgoing')
const settled = friends.filter((f) => !f.kind || f.kind === 'friend')
const shown = onlineOnly ? settled.filter((f) => f.status && f.status !== 'offline') : settled
@@ -822,7 +994,7 @@ function DiscordJoin({ account }: { account: Account }): JSX.Element {
{waiting.length > 0 && (
<>
<div className="join-friends-header">
<span className="setting-text">Requests</span>
<span className="setting-text">Waiting for them to accept</span>
</div>
{waiting.map((f) => (
<div key={f.userId} className="friend-row request">
@@ -832,18 +1004,8 @@ function DiscordJoin({ account }: { account: Account }): JSX.Element {
<span className="friend-avatar placeholder">{(f.globalName || f.username).slice(0, 1)}</span>
)}
<span className="ellipsis">{f.globalName || f.username}</span>
<span className="small muted">
{f.kind === 'incoming' ? 'wants to be friends' : 'asked, waiting'}
</span>
{f.kind === 'incoming' && (
<button type="button" className="button" onClick={() => answer(f.userId, true)}>
Accept
</button>
)}
{/* Refusing one and taking back your own are the same call, and
read differently enough to be worth different words. */}
<button type="button" className="button subtle" onClick={() => answer(f.userId, false)}>
{f.kind === 'incoming' ? 'Decline' : 'Cancel'}
Cancel request
</button>
</div>
))}
@@ -0,0 +1,194 @@
import { Icon } from './Icon'
import { embedColor } from '../lib/format'
import { nickColor } from '../lib/util'
import type { Embed } from '../../../shared/wire'
/** The embed kinds the daemon draws as these cards instead of as a link preview. */
export const KICK_EVENT_KINDS = ['kicks', 'gift-sub', 'raid', 'redeem', 'subscribe', 'moderation', 'stream']
export function isKickEvent(embed: Embed): boolean {
return !!embed.kind && KICK_EVENT_KINDS.includes(embed.kind)
}
/** Kick's own mark: a K on a disc. Drawn rather than fetched - it is a few shapes. */
function KicksMark({ size = 16 }: { size?: number }): JSX.Element {
return (
<span className="kicks-mark" style={{ width: size, height: size, fontSize: size * 0.68 }} aria-hidden="true">
K
</span>
)
}
/**
* What somebody did on a Kick stream, as the card Kick draws it - a bar down
* the edge, a mark for what it was, who did it in bold, and the words - on this
* client's own surfaces and tokens rather than Kick's page.
*
* Every kind of event a Kick channel has, all from the daemon
* (nobilis/src/backend/kick/chat.rs): KICKs sent, a subscription and one gifted
* to somebody, a raid, a channel reward redeemed - which keeps the colour the
* streamer gave it - a ban, a timeout or a chat cleared, and the stream going
* live or ending.
*/
export function KickEventCard({ embed }: { embed: Embed }): JSX.Element | null {
const who = embed.author
if (!who) return null
const name = (colour?: string): JSX.Element => (
<strong className="kick-event-name" style={{ color: colour ?? embed.authorColor ?? nickColor(who) }}>
{who}
</strong>
)
const accent = embedColor(embed.color) || undefined
const tint = accent ? ({ '--kick-accent': accent } as React.CSSProperties) : undefined
if (embed.kind === 'kicks') {
return (
<div className="kick-event kicks selectable" style={tint}>
<div className="kick-event-main">
<div className="kick-event-line">
{name()}
<span className="kick-event-verb">sent</span>
<KicksMark />
<strong className="kick-event-amount">{embed.title}</strong>
{embed.provider && <span className="kick-event-gift small muted">{embed.provider}</span>}
</div>
{embed.description && <div className="kick-event-message">{embed.description}</div>}
</div>
<span className="kick-event-badge">
<KicksMark size={30} />
</span>
</div>
)
}
if (embed.kind === 'raid') {
return (
<div className="kick-event raid selectable">
<span className="kick-event-badge lead">
<Icon name="groups" size={20} />
</span>
<div className="kick-event-main">
<div className="kick-event-line">
{name()}
<span className="kick-event-verb">
{embed.title ? 'has raided with' : 'has raided the channel'}
</span>
{embed.title && (
<>
<strong className="kick-event-amount">{embed.title}</strong>
<span className="kick-event-verb">{embed.title === '1' ? 'viewer.' : 'viewers.'}</span>
</>
)}
</div>
{embed.description && <div className="kick-event-message">{embed.description}</div>}
</div>
</div>
)
}
if (embed.kind === 'redeem') {
return (
<div className="kick-event redeem selectable" style={tint}>
<span className="kick-event-badge lead">
<Icon name="stars" size={22} />
</span>
<div className="kick-event-main">
{name(accent)}
<div className="kick-event-line">
<span className="kick-event-verb">has redeemed</span>
<strong>{embed.title}</strong>
</div>
{embed.description && <div className="kick-event-message">{embed.description}</div>}
</div>
</div>
)
}
if (embed.kind === 'subscribe') {
return (
<div className="kick-event subscribe selectable">
<span className="kick-event-badge lead">
<Icon name="workspace_premium" size={22} />
</span>
<div className="kick-event-line">
{name()}
<span className="kick-event-verb">subscribed</span>
{embed.title && (
<>
<span className="kick-event-verb">-</span>
<strong>{embed.title}</strong>
<span className="kick-event-verb">months</span>
</>
)}
</div>
</div>
)
}
if (embed.kind === 'moderation') {
return (
<div className="kick-event moderation selectable">
<span className="kick-event-badge lead">
<Icon name="gavel" size={20} />
</span>
<div className="kick-event-line">
<strong className="kick-event-name">{who}</strong>
<span className="kick-event-verb">{embed.title}</span>
{embed.description && (
<>
<span className="kick-event-verb">by</span>
<strong>{embed.description}</strong>
</>
)}
</div>
</div>
)
}
if (embed.kind === 'stream') {
const live = embed.icon === 'live'
return (
<div className={`kick-event stream selectable ${live ? 'live' : 'offline'}`}>
<span className="kick-event-badge lead">
<Icon name={live ? 'sensors' : 'sensors_off'} size={20} />
</span>
<div className="kick-event-line">
<strong className="kick-event-name">{who}</strong>
<span className="kick-event-verb">{embed.title}</span>
</div>
</div>
)
}
const count = Number(embed.title) || 1
const recipients = (embed.description ?? '').split('\n').filter(Boolean)
return (
<div className="kick-event gift selectable">
<span className="kick-event-badge lead">
<Icon name="redeem" size={22} />
</span>
<div className="kick-event-main">
<div className="kick-event-line">
{name()}
<span className="kick-event-verb">gifted {count === 1 ? 'a sub' : `${count} subs`}</span>
{recipients.length === 1 && (
<>
<span className="kick-event-verb">to</span>
<strong style={{ color: nickColor(recipients[0]) }}>{recipients[0]}</strong>
</>
)}
</div>
{recipients.length > 1 && (
<div className="kick-event-recipients">
<span className="kick-event-verb">to</span>
{recipients.map((r) => (
<strong key={r} className="kick-event-recipient" style={{ color: nickColor(r) }}>
{r}
</strong>
))}
</div>
)}
</div>
</div>
)
}
+14 -3
View File
@@ -113,7 +113,7 @@ export function MediaEmbed({
const [seen, setSeen] = useState<{ width: number; height: number } | null>(null)
const [playing, setPlaying] = useState(false)
// Hidden until it is clicked, as Discord does with a file sent as a spoiler.
const spoiler = !!attachment?.filename?.startsWith(SPOILER_PREFIX)
const spoiler = !!attachment?.filename?.startsWith(SPOILER_PREFIX) || !!item?.spoiler
const [revealed, setRevealed] = useState(false)
const hidden = spoiler && !revealed
// What it is called, less the marker: that is not part of the name.
@@ -433,11 +433,22 @@ export function MediaEmbed({
className="media-embed"
style={ratio}
src={media(fullSrc)}
controls
// A GIF is silent, runs on its own and goes round, and has no
// player to operate: it plays when it is shown if autoplay is on,
// and otherwise while the pointer is over it. Any other video is a
// video, with its controls.
{...(attachment?.gif
? {
muted: true,
autoPlay: autoplay,
loop: true,
onMouseEnter: (e: React.MouseEvent<HTMLVideoElement>) => !autoplay && void e.currentTarget.play().catch(() => {}),
onMouseLeave: (e: React.MouseEvent<HTMLVideoElement>) => !autoplay && e.currentTarget.pause()
}
: { controls: true, loop })}
// Enough to draw the first frame and know how long it is, without
// pulling megabytes for every video in a scrolled-past backlog.
preload="metadata"
loop={loop}
playsInline
onError={() => setFailed(true)}
/>
+69 -14
View File
@@ -7,6 +7,7 @@ import { CallView } from './CallView'
import { CallStage, RoomCallBar } from './CallStage'
import { StreamStage } from './StreamStage'
import { ServiceBanner } from './ServiceBanner'
import { ConversationNotice } from './ConversationNotice'
import { RouteAccount, useStrictRoute } from '../lib/route'
import { useChat, usePref, useStore } from '../state/hooks'
import { bufferDisplayName, dayLabel, isChatKind, startsNewDay } from '../lib/util'
@@ -52,6 +53,9 @@ const REANCHOR_THRESHOLD = 100
*/
const SCROLL_JITTER = 2
/** How far down from the top edge to look for the row being read, nearest first. */
const PLACE_PROBES = [1, 24, 48, 80, 120, 180]
/**
* How long after the reader last touched the list a scroll still counts as
* theirs.
@@ -162,6 +166,16 @@ const RENDER_WINDOW = 120
const RENDER_STEP = 120
/** Rows kept below a jumped-to message, so it has somewhere to sit. */
const JUMP_MARGIN = 40
/**
* The most unread a conversation can have and still open at its first unread
* message. Discord's rule, and for the same reason: its first screenful of
* history is fifty messages, so an unread run that fits in it is somewhere to
* start reading, and one that does not is somewhere nobody wants to be taken -
* hundreds or thousands of messages up, with the conversation they came for
* a long scroll away. Past it the log opens at its end, as any other does,
* and the bar across the top says how much there is and goes back to it.
*/
const OPEN_AT_UNREAD_LIMIT = 50
export function MessageList(): JSX.Element {
const store = useStore()
@@ -363,17 +377,29 @@ export function MessageList(): JSX.Element {
*
* By hit test rather than by walking the rows: this runs on every scroll,
* and a list of two thousand is not a thing to scan that often.
*
* Every element under the point, not the topmost one, and a few points down
* the page rather than one. The "N new messages since" bar is laid over the
* top of the log, so asking what was at the edge was answered with the bar
* for as long as it was up - and the place stopped being kept, which the
* next thing to change size then put the view back to. A date line or the
* gap between two groups at the edge gave the same non-answer for a moment.
*/
const notePlace = useCallback(() => {
const el = scrollRef.current
if (!el) return
const box = el.getBoundingClientRect()
const hit = document.elementFromPoint(box.left + 8, box.top + 1)
const row = hit?.closest?.('[data-msg-id]') as HTMLElement | null
if (!row) return
placeRef.current = {
id: row.dataset.msgId ?? '',
offset: row.getBoundingClientRect().top - box.top
for (const down of PLACE_PROBES) {
for (const hit of document.elementsFromPoint(box.left + 8, box.top + down)) {
if (!el.contains(hit)) continue
const row = hit.closest?.('[data-msg-id]') as HTMLElement | null
if (!row) continue
placeRef.current = {
id: row.dataset.msgId ?? '',
offset: row.getBoundingClientRect().top - box.top
}
return
}
}
}, [])
@@ -512,13 +538,21 @@ export function MessageList(): JSX.Element {
// of switching, because what has been read from the daemon may not have
// arrived yet - the line has to be in the drawn part of the log, which is a
// tail, before it can be scrolled to.
// The divider marks the first message newer than the snapshot taken when the
// buffer was opened; it deliberately doesn't move as more arrive.
const dividerIndex = dividerTs > 0 ? messages.findIndex((m) => m.ts > dividerTs) : -1
// Where it is against what is drawn, for the callbacks below that have to
// know whether the line exists on the page or only in the log.
const dividerRef = useRef({ index: -1, start: 0, length: 0 })
dividerRef.current = { index: dividerIndex, start, length: messages.length }
const openedAtRef = useRef('')
useLayoutEffect(() => {
const key = `${bufferId}|${dividerTs}`
if (openedAtRef.current === key || messages.length === 0) return
openedAtRef.current = key
const first = dividerTs > 0 ? messages.findIndex((m) => m.ts > dividerTs) : -1
if (first >= 0 && messages.length - first > 8) {
if (first >= 0 && messages.length - first > 8 && messages.length - first <= OPEN_AT_UNREAD_LIMIT) {
wantDividerRef.current = true
setShown((n) => Math.max(n, messages.length - first + JUMP_MARGIN))
}
@@ -528,8 +562,13 @@ export function MessageList(): JSX.Element {
const measureDivider = useCallback(() => {
const el = scrollRef.current
const line = el?.querySelector<HTMLElement>('.new-divider')
if (!el || !line) {
setDividerAbove(false)
if (!el) return
if (!line) {
// Not drawn is not the same as not there. A conversation opened with a
// long unread run is at its end, and its line is up in the log beyond
// what is built - which is exactly when the bar is wanted.
const { index, start } = dividerRef.current
setDividerAbove(index >= 0 && index < start)
return
}
// Clearly above, not merely just off the top: with the line a few pixels
@@ -541,7 +580,18 @@ export function MessageList(): JSX.Element {
const toDivider = useCallback((smooth: boolean) => {
const el = scrollRef.current
const line = el?.querySelector<HTMLElement>('.new-divider')
if (!el || !line) return
if (!el) return
if (!line) {
// In the log and not on the page: build the log back to it, and the
// layout effect below scrolls to it once it is there.
const { index, length } = dividerRef.current
if (index < 0) return
anchor(false)
setMissedCount(0)
wantDividerRef.current = true
setShown((n) => Math.max(n, length - index + JUMP_MARGIN))
return
}
anchor(false)
// Going back to the line is not missing anything: what is below is what
// was already there, not news.
@@ -551,6 +601,13 @@ export function MessageList(): JSX.Element {
el.scrollTo({ top: Math.max(0, target), behavior: smooth ? 'smooth' : 'auto' })
}, [anchor, messages])
// Whether the line is out of sight, asked as the log changes as well as when
// it is scrolled: a conversation opened at its end never scrolls, and is
// the one with the most to say about what is above it.
useLayoutEffect(() => {
measureDivider()
}, [bufferId, dividerTs, messages.length, shown, measureDivider])
// Once the line is drawn, start there.
useLayoutEffect(() => {
if (!wantDividerRef.current) return
@@ -713,10 +770,6 @@ export function MessageList(): JSX.Element {
return () => window.removeEventListener('moho:jump-to-present', go)
}, [])
// The divider marks the first message newer than the snapshot taken when the
// buffer was opened; it deliberately doesn't move as more arrive.
const dividerIndex = dividerTs > 0 ? messages.findIndex((m) => m.ts > dividerTs) : -1
return (
// Whose conversation this is, for everything drawn inside it: a strictly
// routed account's media goes through its route (#257). The attribute is
@@ -726,6 +779,8 @@ export function MessageList(): JSX.Element {
{/* First, because it explains everything under it: a conversation that
is not receiving looks like a quiet one otherwise. */}
<ServiceBanner bufferId={bufferId} />
{/* A warning the service put on this conversation, in red, until it is dismissed. */}
<ConversationNotice bufferId={bufferId} />
{/* Above the log and outside the scroller. Who is talking is only
useful while it can be seen, and a panel that scrolled away with
the backlog would be gone the moment anybody read anything. */}
+93 -13
View File
@@ -1,3 +1,4 @@
import { steamRoomIds } from '../lib/steamchat'
import { memo, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { Icon } from './Icon'
@@ -7,7 +8,8 @@ import { EventSource } from './EventSource'
import { ForwardPicker } from './ForwardPicker'
import { ContextMenu, useContextMenu, type MenuEntry } from './ContextMenu'
import { MediaEmbed } from './MediaEmbed'
import { COMMON_EMOJI, EmojiPicker, readRecent } from './EmojiPicker'
import { KickEventCard, isKickEvent } from './KickEventCard'
import { COMMON_EMOJI, EmojiPicker, readRecent, type StickerEntry } from './EmojiPicker'
import { reactionLabel, reactorsSentence } from '../lib/reactions'
import { UploadMeter } from './UploadMeter'
import { RichText } from '../lib/richtext'
@@ -17,6 +19,7 @@ import { useSniffedTypes, sniffUrl } from '../lib/sniff'
import { useMediaUrl, useStrictRoute } from '../lib/route'
import type { ChatMessage } from '../state/store'
import type {
Attachment,
CustomEmoji,
MessageBadge,
MessageComponent,
@@ -28,6 +31,7 @@ import {
embedColor,
extractCodeBlocks,
extractMedia,
markSpoilered,
extractQuoteBlocks,
formatMessage,
normalizeBBCode,
@@ -38,6 +42,8 @@ import {
stripEmbeddedUrls,
stripQuoteBlocks,
discordEmojiUrl,
steamPictureUrl,
steamTokenOf,
type ChannelIndex
} from '../lib/format'
import {
@@ -49,6 +55,7 @@ import {
hasDirectMessages,
isChatKind,
isNotice,
isWarning,
isReward,
isWhisper,
nickColor
@@ -382,7 +389,16 @@ function MessageRowBody({
// messages; IRC has no such concept.
const canEditDelete =
!!message.isOwn && (service === 'discord' || service === 'sneedchat' || service === 'matrix')
const canReact = service === 'discord' || service === 'matrix'
const canReact = service === 'discord' || service === 'matrix' || service === 'steam'
// Steam's stickers, asked for when the reaction picker opens: it reacts with them too.
const [steamStickers, setSteamStickers] = useState<StickerEntry[]>([])
useEffect(() => {
if (!pickerOpen || service !== 'steam') return
void window.moho
.rpc<StickerEntry[]>('listSteamStickers', { bufferId })
.then(setSteamStickers)
.catch(() => setSteamStickers([]))
}, [pickerOpen, service, bufferId])
// Read again after the picker has been used, which is when it changes.
const quick = useMemo(
() => quickReactions(store.accountFor(bufferId)?.id),
@@ -405,6 +421,9 @@ function MessageRowBody({
// label on.
const [highlightNotices] = usePref<boolean>('matrix.highlightNotices', true)
const reward = isReward(message.kind)
// KICKs sent, or subscriptions gifted: the daemon says which and to whom in
// a card, and the line of text is what a copy or a search finds.
const kickEvent = (message.embeds ?? []).find(isKickEvent)
// Both of the modes that draw an avatar column. Bubbles is otherwise
// nothing like comfy, but it wants the same picture beside the same first
// line of a group.
@@ -418,7 +437,24 @@ function MessageRowBody({
*/
const own = bubbles && !isSystem && !!message.isOwn
const attachments = message.attachments ?? []
// A GIF that was linked is a picture to play, and goes where pictures go:
// the same sizing, the same autoplay and loop settings, the same viewer.
const gifs = useMemo(
() =>
(message.embeds ?? [])
.filter((e) => e.kind === 'gif' && e.mediaUrl)
.map((e): Attachment => ({
// As the daemon said; by the ending only for one that did not.
kind: e.mediaKind ?? (/\.(mp4|webm|mov|mkv|ogv)(\?|$)/i.test(e.mediaUrl!) ? 'video' : 'image'),
gif: true,
url: e.mediaUrl,
width: e.width,
height: e.height,
filename: 'gif'
})),
[message.embeds]
)
const attachments = useMemo(() => [...(message.attachments ?? []), ...gifs], [message.attachments, gifs])
// The ones that go in a grid, and the ones that stay in the row, each with
// its place in the message so its key stays the same whichever it is.
const indexed = attachments.map((att, i) => ({ att, i }))
@@ -437,18 +473,23 @@ function MessageRowBody({
// this function again and neither of which is re-stored.
const raw = clearnetLinks(message.body || '')
const normalized = normalizeBBCode(raw)
const media = extractMedia(normalized, {
const media = markSpoilered(extractMedia(normalized, {
contentSniffing,
sniffed,
onNeedSniff: (url) => sniffUrl(url, strictRoute),
// Read from the un-normalised body: the pairing lives in the BBCode,
// and normalising unwraps both tags into two unrelated bare URLs.
thumbnails: thumbnailLinks(raw)
})
}), normalized)
const codeBlocks = extractCodeBlocks(normalized)
const quoteBlocks = extractQuoteBlocks(stripCodeBlocks(normalized))
let body = stripEmbeddedUrls(normalized, media)
// The page a GIF was linked from is not shown as well as the GIF: it is the
// same thing said twice, and is how a posted GIF read as an address.
const gifPages = (message.embeds ?? [])
.filter((e) => e.kind === 'gif' && e.url)
.map((e) => ({ url: e.url!, kind: 'image' as const }))
let body = stripEmbeddedUrls(normalized, [...media, ...gifPages])
body = stripCodeBlocks(body)
body = stripQuoteBlocks(body)
@@ -529,7 +570,8 @@ function MessageRowBody({
}
] as MenuEntry[])
: []),
{ label: 'Reply', icon: 'reply', onClick: () => reply() },
// Steam chat has no replies - a message is a line of text and nothing points at another.
...(service === 'steam' ? [] : ([{ label: 'Reply', icon: 'reply', onClick: () => reply() }] as MenuEntry[])),
// What was selected when the menu opened, first: right-clicking on
// highlighted text and finding no Copy is the one thing this menu must not
// do, having replaced the one the window would have given.
@@ -619,6 +661,17 @@ function MessageRowBody({
}
] as MenuEntry[])
: []),
// Your own words in a room of a Steam group can be taken back.
...(service === 'steam' && message.isOwn && steamRoomIds(store.getSnapshot().buffers.find((b) => b.id === bufferId))
? ([
{
label: 'Delete',
icon: 'delete',
danger: true,
onClick: () => void store.deleteMessage(bufferId, message.id)
}
] as MenuEntry[])
: []),
...(permissions.canRedactOthers && !message.isOwn
? ([
{
@@ -759,10 +812,12 @@ function MessageRowBody({
message.isHighlight && 'highlight',
whispered && 'whisper',
notice && highlightNotices && 'notice',
isWarning(message.kind, message.id) && 'warning',
message.pending && 'pending',
message.failed && 'failed',
isSystem && 'system',
reward && 'reward',
kickEvent && 'has-kick-event',
grouped && 'grouped',
fresh && 'fresh',
comfy && 'comfy',
@@ -805,7 +860,7 @@ function MessageRowBody({
{/* A join, a part, a topic change: not somebody speaking, so no face -
but a small mark in the picture's own column, so the line's text
starts where every other line's does instead of at the edge. */}
{mode === 'comfy' && isSystem && (
{mode === 'comfy' && isSystem && !kickEvent && (
<span className="message-avatar system-mark" aria-hidden>
<Icon name={SYSTEM_MARKS[message.kind] ?? 'info'} size={16} />
</span>
@@ -1035,6 +1090,8 @@ function MessageRowBody({
</div>
)}
</div>
) : kickEvent ? (
<KickEventCard embed={kickEvent} />
) : (
parts.html && (
<span className="message-body selectable">
@@ -1077,7 +1134,8 @@ function MessageRowBody({
</pre>
))}
{(message.embeds || []).map((embed, i) => (
{(message.embeds || []).map((embed, i) =>
embed.kind === 'gif' || isKickEvent(embed) ? null : (
<div
key={`e${i}`}
className={classes('rich-embed selectable', embed.kind === 'notice' && 'notice')}
@@ -1170,7 +1228,8 @@ function MessageRowBody({
</div>
)}
</div>
))}
)
)}
{/* Pictures and videos that came together are laid out together:
two side by side, three with the first tall, four in a square,
@@ -1336,7 +1395,10 @@ function MessageRowBody({
answer. */}
{!isSystem && !message.pending && !message.failed && (
<div className="hover-toolbar">
{/* Steam reacts with its own emoticons and stickers, so the
one-click row of Unicode emoji is not offered there. */}
{canReact &&
service !== 'steam' &&
quick.map((emoji) => (
<button
key={emoji}
@@ -1359,9 +1421,11 @@ function MessageRowBody({
<Icon name="add_reaction" size={15} />
</button>
)}
<button type="button" className="toolbar-button" title="Reply" onClick={reply}>
<Icon name="reply" size={15} />
</button>
{service !== 'steam' && (
<button type="button" className="toolbar-button" title="Reply" onClick={reply}>
<Icon name="reply" size={15} />
</button>
)}
{canEditDelete && (
<button
type="button"
@@ -1397,6 +1461,19 @@ function MessageRowBody({
anchor={reactButtonRef.current}
customEmoji={bufferEmoji}
accountId={store.accountFor(bufferId)?.id}
// Steam reacts with what the account was given and nothing else: its
// emoticons, and its stickers on their own tab.
bufferId={service === 'steam' ? bufferId : undefined}
fixedSet={service === 'steam'}
stickers={service === 'steam' ? steamStickers : undefined}
onSticker={
service === 'steam'
? (sticker) => {
void store.toggleReaction(bufferId, message.id, `[steam:sticker:${sticker.name}]`, true)
setPickerOpen(false)
}
: undefined
}
onSelect={(emoji) => {
void store.toggleReaction(bufferId, message.id, emoji, true)
setPickerOpen(false)
@@ -1532,6 +1609,9 @@ function ReactionPill({
*/
function ReactionEmoji({ emoji }: { emoji: string }): JSX.Element {
const media = useMediaUrl()
// Steam's, held as a token naming the emoticon or sticker.
const steam = steamTokenOf(emoji)
if (steam) return <img className="reaction-emoji" src={steamPictureUrl(steam.kind, steam.name)} alt={steam.name} />
const custom = emoji.match(/^<?a?:?([A-Za-z0-9_~]{2,32}):(\d+)>?$/)
if (!custom) return <span>{emoji}</span>
return <img className="reaction-emoji" src={media(discordEmojiUrl(custom[2]))} alt={custom[1]} />
@@ -0,0 +1,63 @@
import { useEffect, useRef, useState } from 'react'
import { Modal } from './Modal'
/**
* A name asked for before something is made: a folder on a service that keeps
* its own, which is made the moment it has one. Enter makes it, Escape leaves.
*
* A dialog and not a field in the list, because what is made is not a heading
* of ours that can be renamed afterwards for free - it is a change to the
* account on the service, and one that is called "New category" because the
* field lost focus is a folder every other client of the account then shows.
*/
export function NamePrompt({
title,
detail,
placeholder,
confirmLabel,
icon = 'create_new_folder',
onConfirm,
onCancel
}: {
title: string
detail: string
placeholder: string
confirmLabel: string
icon?: string
onConfirm: (name: string) => void
onCancel: () => void
}): JSX.Element {
const [name, setName] = useState('')
const box = useRef<HTMLInputElement>(null)
useEffect(() => {
box.current?.focus()
}, [])
const ready = name.trim().length > 0
return (
<Modal title={title} icon={icon} onClose={onCancel} className="reason-prompt">
<p className="small muted">{detail}</p>
<input
ref={box}
className="reason-prompt-box"
value={name}
placeholder={placeholder}
maxLength={64}
onChange={(e) => setName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && ready) {
e.preventDefault()
onConfirm(name.trim())
}
}}
/>
<div className="reason-prompt-actions">
<button type="button" className="button subtle" onClick={onCancel}>
Cancel
</button>
<button type="button" className="button" disabled={!ready} onClick={() => onConfirm(name.trim())}>
{confirmLabel}
</button>
</div>
</Modal>
)
}
+70 -17
View File
@@ -1,12 +1,15 @@
import { activityLabel } from '../lib/activity'
import { ActivityLine } from './ActivityLine'
import { useEffect, useMemo, useState } from 'react'
import { Avatar } from './Avatar'
import { Icon, IconButton } from './Icon'
import { ContextMenu, useContextMenu, type MenuEntry } from './ContextMenu'
import { useActiveBuffer, useChat, useIdSetPref, useStore } from '../state/hooks'
import { useActiveBuffer, useChat, useComfy, useIdSetPref, useStore } from '../state/hooks'
import { classes, hasDirectMessages, nickColor } from '../lib/util'
import { KickPoints } from './KickPoints'
import { ReasonPrompt } from './ReasonPrompt'
import type { Member } from '../../../shared/wire'
import { steamRoomIds, type SteamChatGroup } from '../lib/steamchat'
/**
* The member list for the active channel. Two grouping modes, both driven off
@@ -48,6 +51,7 @@ export type ModerationAction = 'kick' | 'ban' | 'mute' | 'op' | 'deop' | 'voice'
*/
function memberTitle(member: Member): string {
const lines = [member.nick]
if (member.activity) lines.push(activityLabel(member.activity))
if (member.account) lines.push(`identified as ${member.account}`)
if (member.host) lines.push(member.host)
if (lines.length === 1 && member.userId) return member.userId
@@ -126,6 +130,7 @@ interface DiscordPowers {
export function NickList(): JSX.Element {
const store = useStore()
const comfy = useComfy()
const buffer = useActiveBuffer()
const presenceByBuffer = useChat((s) => s.presenceByBuffer)
const accounts = useChat((s) => s.accounts)
@@ -174,8 +179,28 @@ export function NickList(): JSX.Element {
})
}, [account?.service, account?.id, buffer?.id])
// Steam answers from the group: what the account's roles allow there.
const [steamPowers, setSteamPowers] = useState<Record<string, boolean>>({})
const steamRoom = account?.service === 'steam' ? steamRoomIds(buffer) : null
useEffect(() => {
setSteamPowers({})
if (!steamRoom || !account) return
let live = true
void window.moho
.rpc<SteamChatGroup[]>('steamChatGroups', { accountId: account.id, groupId: steamRoom.group })
.then((g) => live && g[0] && setSteamPowers({ canKick: g[0].mayModerate, canBan: g[0].mayModerate, canMute: false }))
.catch(() => {
/* advisory only: no answer means no moderation entries */
})
return () => {
live = false
}
}, [account?.id, steamRoom?.group])
const perms =
account?.service === 'irc'
account?.service === 'steam'
? steamPowers
: account?.service === 'irc'
? ircPermissions(members, account.currentNick)
: account?.service === 'kick'
? kickPermissions(members, account.currentNick)
@@ -263,6 +288,7 @@ export function NickList(): JSX.Element {
<MemberRow
key={member.userId || member.nick}
member={member}
comfy={comfy}
blockKey={`${buffer?.accountId}|${member.nick}`}
blocked={isBlocked(`${buffer?.accountId}|${member.nick}`)}
canOpenDm={hasDirectMessages(account?.service)}
@@ -353,6 +379,24 @@ export function NickList(): JSX.Element {
.catch((e: Error) => store.toast('error', e.message))
return
}
if (account.service === 'steam') {
const group = steamRoomIds(buffer)?.group
if (!group || !member.userId || (action !== 'kick' && action !== 'ban' && action !== 'mute')) return
// Mute is ten minutes, as it is on Discord; kick and ban are
// the group's own.
void window.moho
.rpc('steamChatGroupAction', {
accountId: account.id,
groupId: group,
action,
steamid: member.userId,
seconds: action === 'mute' ? 600 : 3600,
banned: true
})
.then(() => store.toast('info', `${action === 'ban' ? 'Banned' : action === 'mute' ? 'Muted' : 'Removed'} ${member.nick}`))
.catch((e: Error) => store.toast('error', e.message))
return
}
if (account.service === 'discord') {
// Discord's own three, and "mute" is a timeout there -
// the same word this menu uses everywhere, meaning what
@@ -440,6 +484,12 @@ export function NickList(): JSX.Element {
interface MemberRowProps {
member: Member
/**
* Comfy draws the list as Discord does - a face on everybody, with what
* they are doing under their name - on every service. Classic draws names,
* as IRC and Sneedchat always have.
*/
comfy: boolean
blockKey: string
blocked: boolean
/** The protocol can start a conversation from a member list. */
@@ -487,6 +537,7 @@ interface MemberRowProps {
function MemberRow({
member,
comfy,
blockKey,
blocked,
canOpenDm,
@@ -638,24 +689,17 @@ function MemberRow({
<>
<button
type="button"
className={classes('nick-row', member.away && 'away', blocked && 'blocked')}
className={classes('nick-row', comfy && 'comfy', member.away && 'away', blocked && 'blocked')}
onContextMenu={open}
// Who they are is the click, as in Discord, Slack and Element;
// mentioning is Shift+click and the menu's own entry.
onClick={(e) => (onProfile && !e.shiftKey ? onProfile() : onMention())}
title={memberTitle(member)}
>
{/* A face and a dot, where the service has presence to report. The
others - IRC, Sneedchat, Kick - are lists of names, and a column
of initials on those would be decoration. */}
{member.status !== undefined && (
<Avatar
name={member.nick}
url={member.avatarUrl}
size={24}
status={member.status}
/>
)}
{/* A face on everybody in comfy, with a dot where the service has
presence to report; classic is a list of names, and a column of
initials on those would be decoration. */}
{comfy && <Avatar name={member.nick} url={member.avatarUrl} size={32} status={member.status} />}
{/* IRC's rank is one character and sits in a fixed slot before the
name. Kick's is a word - "moderator", "subscriber" - which
overflowed that eight-pixel slot and painted straight over the
@@ -664,9 +708,18 @@ function MemberRow({
{member.prefix && member.prefix.length === 1 && (
<span className="nick-prefix">{member.prefix}</span>
)}
<span className="ellipsis" style={{ color: nickColor(member.nick) }}>
{member.nick}
</span>
{comfy ? (
<span className="nick-text">
<span className="ellipsis" style={{ color: nickColor(member.nick) }}>
{member.nick}
</span>
{member.activity && <ActivityLine activity={member.activity} />}
</span>
) : (
<span className="ellipsis" style={{ color: nickColor(member.nick) }}>
{member.nick}
</span>
)}
{member.prefix && member.prefix.length > 1 && (
<span className={`sender-badge small ${member.prefix}`} title={member.prefix}>
{shortBadge(member.prefix)}
+46 -4
View File
@@ -2,8 +2,10 @@ import { Modal } from './Modal'
import { Avatar } from './Avatar'
import { Icon, IconButton } from './Icon'
import { useChat, useStore } from '../state/hooks'
import { formatFullTime } from '../lib/util'
import { formatFullTime, serviceLabel } from '../lib/util'
import { presenceColor, presenceLabel } from '../lib/presence'
import { profileActivity } from '../lib/activity'
import { ActivityLine } from './ActivityLine'
/**
* Who somebody is, whichever service they belong to.
@@ -20,13 +22,20 @@ import { presenceColor, presenceLabel } from '../lib/presence'
*/
export function ProfileCard(): JSX.Element | null {
const profile = useChat((s) => s.profile)
const presence = useChat((s) => s.presenceByBuffer)
const buffers = useChat((s) => s.buffers)
const store = useStore()
if (!profile) return null
// Their status, as its own section: how they are showing and what they are
// doing. An away message is words they wrote for this, so it stands in for
// an activity where the service gave none.
const activity = profileActivity(profile, presence, buffers) ?? (profile.away ? ({ kind: 'custom', text: profile.away } as const) : undefined)
const hasStatus = !!profile.status || !!activity
const rows: [string, string][] = []
if (profile.handle && profile.handle !== profile.name) rows.push(['Address', profile.handle])
if (profile.away) rows.push(['Away', profile.away])
if (profile.createdTs) rows.push(['Account made', formatFullTime(profile.createdTs)])
if (profile.joinedTs) rows.push([joinedLabel(profile.service), formatFullTime(profile.joinedTs)])
if (profile.lastActiveTs) rows.push(['Last seen', formatFullTime(profile.lastActiveTs)])
@@ -40,7 +49,7 @@ export function ProfileCard(): JSX.Element | null {
<div className="profile-title">
<span className="profile-name ellipsis">{profile.name}</span>
<span className="small muted">
{profile.status ? presenceLabel(profile.status) : profile.service}
{serviceLabel(profile.service)}
{profile.isModerator ? ' · moderator here' : ''}
</span>
</div>
@@ -65,6 +74,21 @@ export function ProfileCard(): JSX.Element | null {
</div>
)}
{/* Status, first of the facts: it is the one that changes while the
card is open, and the one somebody opens it to see. */}
{hasStatus && (
<section className="profile-status" aria-label="Status">
<span className="small muted profile-section-title">Status</span>
{profile.status && (
<span className="profile-status-presence">
<span className="profile-status-dot" style={{ background: presenceColor(profile.status) }} />
{presenceLabel(profile.status)}
</span>
)}
{activity && <ActivityLine activity={activity} />}
</section>
)}
<dl className="profile-rows">
{rows.map(([label, value]) => (
<div key={label + value} className="profile-row">
@@ -76,6 +100,24 @@ export function ProfileCard(): JSX.Element | null {
))}
</dl>
{/* What they have been called, where the service keeps it: Steam does,
and a friend who renamed is otherwise somebody you no longer recognise. */}
{!!profile.nameHistory?.length && (
<section className="profile-status" aria-label="Previous names">
<span className="small muted profile-section-title">Previous names</span>
<ul className="profile-name-history">
{profile.nameHistory.map((n) => (
<li key={n.name + n.when}>
<span className="ellipsis" title={n.name}>
{n.name}
</span>
{n.when && <span className="small muted">{n.when}</span>}
</li>
))}
</ul>
</section>
)}
{/* Shared channels are the useful half of an IRC lookup, and on a
well-connected nick there are dozens - so they wrap. */}
{!!profile.channels?.length && (
@@ -121,7 +163,7 @@ export function ProfileCard(): JSX.Element | null {
</p>
)}
{!profile.pending && rows.length === 0 && !profile.roles?.length && !profile.channels?.length && (
{!profile.pending && rows.length === 0 && !hasStatus && !profile.roles?.length && !profile.channels?.length && (
<p className="small muted">
<Icon name="info" size={14} /> {profile.service} keeps nothing else about them.
</p>
@@ -2,7 +2,8 @@ import { useEffect, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { Avatar } from './Avatar'
import { Icon } from './Icon'
import { useChat, useStore } from '../state/hooks'
import { useChat, useIdSetPref, usePref, useStore } from '../state/hooks'
import { isMutedBuffer, waitingCount } from '../lib/groups'
import { rankBuffers, whereText } from '../lib/switcher'
import { bufferKindGlyph, classes } from '../lib/util'
@@ -18,6 +19,8 @@ export function QuickSwitcher(): JSX.Element | null {
const store = useStore()
const buffers = useChat((s) => s.buffers)
const accounts = useChat((s) => s.accounts)
const [muted] = useIdSetPref('mutedBuffers')
const [mutedGroups] = usePref<string[]>('mutedGroups', [])
const [open, setOpen] = useState(false)
const [query, setQuery] = useState('')
const [index, setIndex] = useState(0)
@@ -103,6 +106,7 @@ export function QuickSwitcher(): JSX.Element | null {
{hits.length === 0 && <div className="switcher-empty muted">Nothing by that name.</div>}
{hits.map((hit, i) => {
const b = hit.buffer
const waiting = waitingCount(b, isMutedBuffer(b, muted, mutedGroups))
return (
<button
key={b.id}
@@ -122,9 +126,9 @@ export function QuickSwitcher(): JSX.Element | null {
</span>
<span className="switcher-title ellipsis">{hit.title}</span>
<span className="switcher-where muted small ellipsis">{hit.where}</span>
{b.unread > 0 && (
{waiting > 0 && (
<span className={classes('unread-badge', b.highlight && 'highlight')}>
{b.unread > 99 ? '99+' : b.unread}
{waiting > 99 ? '99+' : waiting}
</span>
)}
</button>
+62 -32
View File
@@ -8,13 +8,15 @@ import { Modal } from './Modal'
import { Avatar } from './Avatar'
import { LeaveConfirm } from './LeaveConfirm'
import { ircNetworkFor } from '../lib/networks'
import { useChat, usePref, useStore } from '../state/hooks'
import { useChat, useInvitations, usePref, useStore } from '../state/hooks'
import { RAIL_TIP, hideRailTip, showRailTip, type RailTipDetail } from '../lib/railtip'
import { bufferDisplayName, classes, nickColor, resolveMediaUrl, serviceIcon } from '../lib/util'
import { SpaceRooms } from './SpaceRooms'
import { SteamGroupSettings } from './SteamGroupSettings'
import { steamGroupOfRail } from '../lib/steamchat'
import {
isFixedEntry,
inviteGroup,
invitationsGroup,
orderedGroups,
railEntries,
fileInFolder,
@@ -28,7 +30,8 @@ import {
reorderFolder,
FOLDER_DRAG_PREFIX,
visibleGroups,
countsTowardRail,
countedFor,
isMutedBuffer,
dmGroup,
DM_GROUP_ID,
isDirectMessage,
@@ -60,6 +63,8 @@ interface TileProps {
active: boolean
unread: number
highlight: boolean
/** How many unread messages mention this account: the number the tile shows. */
mentions: number
draggable: boolean
dropTarget: boolean
/** Being dragged right now: it leaves a gap where it was. */
@@ -72,6 +77,8 @@ interface TileProps {
onLeave?: () => void
/** Only a Matrix space has rooms to look through. */
onBrowse?: () => void
/** Only a Steam chat group keeps settings of its own: rooms, roles, invite links. */
onSettings?: () => void
onSelect: () => void
onDragStart: () => void
onDragOver: (merge: boolean) => void
@@ -104,7 +111,7 @@ function GroupFace({ group, customIcon }: { group: RailGroup; customIcon?: strin
// An invitation reads as one rather than as an unfamiliar server: the room
// usually has no picture and often no name, and initials taken off a raw
// room id say nothing at all.
if (group.kind === 'invite') return <Icon name="mark_email_unread" size={22} />
if (group.kind === 'invitations') return <Icon name="mark_email_unread" size={22} />
if (group.iconUrl) return <img className="rail-icon" src={media(group.iconUrl)} alt="" draggable={false} />
if (group.kind === 'dms') return <Icon name="forum" size={22} />
if (group.kind === 'account' && service.mark && service.colour) {
@@ -179,7 +186,7 @@ function isMerge(e: React.DragEvent): boolean {
}
function RailTile(props: TileProps): JSX.Element {
const { group, active, unread, highlight, draggable, dropTarget, customIcon, muted, lifted, mergeTarget } = props
const { group, active, unread, highlight, mentions, draggable, dropTarget, customIcon, muted, lifted, mergeTarget } = props
const { menu, open, close } = useContextMenu()
const store = useStore()
// What is waiting inside this server, for "Mark as read".
@@ -281,6 +288,15 @@ function RailTile(props: TileProps): JSX.Element {
} as const
]
: []),
...(props.onSettings
? [
{
label: 'Group settings',
icon: 'settings',
onClick: props.onSettings
} as const
]
: []),
// Only where there is something to leave. An account's own entry
// stands for the connection itself, which is disconnected from
// the accounts pane rather than left.
@@ -299,15 +315,17 @@ function RailTile(props: TileProps): JSX.Element {
onClose={close}
/>
)}
{/* A mention waiting in here says how many are waiting, in the corner
the service mark sits in - the mark gives way, since a count is what
somebody scanning this column came to see. */}
{highlight && unread > 0 && (
<span className="rail-count highlight" title={`${unread} unread, with a mention`}>
{unread > 99 ? '99+' : unread}
{/* Mentions say how many are waiting, in the corner the service mark sits
in - the mark gives way, since a count is what somebody scanning this
column came to see. Only mentions: how many messages there are in a
busy channel is not what this column is for, and the pill beside the
tile already says there is something to read. */}
{mentions > 0 && (
<span className="rail-count highlight" title={`${mentions} mention${mentions === 1 ? '' : 's'}`}>
{mentions > 99 ? '99+' : mentions}
</span>
)}
{badge && !(highlight && unread > 0) && (
{badge && mentions === 0 && (
<span className={`rail-service${highlight ? ' highlight' : ''}`}>
{badge.colour && badge.mark ? (
<img src={badge.mark} alt="" draggable={false} />
@@ -364,7 +382,7 @@ export function ServerRail(): JSX.Element | null {
// the selector's result by identity, so returning a new object each render
// reports a change every time and loops until React gives up.
const groups = useChat((s) => s.groups)
const matrixInvites = useChat((s) => s.matrixInvites)
const invitations = useInvitations()
const activeGroupId = useChat((s) => s.activeGroupId)
const activeBufferId = useChat((s) => s.activeBufferId)
const buffers = useChat((s) => s.buffers)
@@ -399,9 +417,12 @@ export function ServerRail(): JSX.Element | null {
// The tile a drop would merge into, as opposed to land beside.
const [merging, setMerging] = useState('')
/** The rail entry a leave has been asked about, pending confirmation. */
const [leaving, setLeaving] = useState<RailGroup | null>(null)
const leaving = useChat((s) => s.leaveRequest)
const setLeaving = (g: { id: string; name: string; kind: string } | null): void => store.requestLeave(g)
/** The space whose contents are being looked through, if any. */
const [browsing, setBrowsing] = useState<RailGroup | null>(null)
/** The Steam chat group whose settings are open, if any. */
const [configuring, setConfiguring] = useState<RailGroup | null>(null)
/** Hovering the space below the column, which means "put it last". */
const [tailTarget, setTailTarget] = useState(false)
@@ -419,18 +440,24 @@ export function ServerRail(): JSX.Element | null {
// Unread rolls up from the buffers under each entry, so a guild whose
// channels are all collapsed away still shows it has something waiting.
const totals = new Map<string, { unread: number; highlight: boolean }>()
const totals = new Map<string, { unread: number; highlight: boolean; mentions: number }>()
// A direct message counts for every unread message in it - all of them are
// for you - and anywhere else for its mentions (see countedFor).
const bump = (key: string, b: BufferEntry): void => {
const t = totals.get(key) || { unread: 0, highlight: false }
t.unread += b.unread
t.highlight = t.highlight || b.highlight
const waiting = countedFor(b, muted, hidden, mutedGroups)
// What a muted conversation says is only that your name was used in it:
// its unread messages are not asking for anything.
const quiet = isMutedBuffer(b, muted, mutedGroups)
const t = totals.get(key) || { unread: 0, highlight: false, mentions: 0 }
t.unread += quiet ? 0 : b.unread
t.highlight = t.highlight || (quiet ? waiting > 0 : b.highlight)
t.mentions += waiting
totals.set(key, t)
}
const all = buffers as BufferEntry[]
for (const b of all) {
// Only what the pane below would show: a hidden buffer has no row to
// reach, and a muted one is not asking for attention.
if (!countsTowardRail(b, muted, hidden, mutedGroups)) continue
// A hidden buffer has no row to reach.
if (hidden.includes(b.id)) continue
// A buffer can count on more than one tile: where it lives, and on any
// aggregate page that also lists it. Both are places the user would look.
if (b.groupId) bump(b.groupId, b)
@@ -446,11 +473,9 @@ export function ServerRail(): JSX.Element | null {
// inbox in the header, which is where the unread count already is, and a
// permanent tile for it only competed with the servers this column is for.
if (pinned.length > 0) extras.push(pinnedGroup())
// An invitation arrives as its own tile and leaves when it is answered -
// it behaves like a new conversation, not like a mark on an account.
for (const [accountId, list] of Object.entries(matrixInvites)) {
for (const invite of list) extras.push(inviteGroup(accountId, invite))
}
// Invitations from every service share one tile, which is there while
// anything waits on an answer and gone once nothing does.
if (invitations.length > 0) extras.push(invitationsGroup(invitations.length))
const ordered = orderedGroups([...shown, ...extras], railOrder)
// The rail always draws, even with nothing in it.
@@ -520,7 +545,7 @@ export function ServerRail(): JSX.Element | null {
*/
const unreadDms = all
.filter(
(b) => isDirectMessage(b) && b.unread > 0 && countsTowardRail(b, muted, hidden, mutedGroups)
(b) => isDirectMessage(b) && countedFor(b, muted, hidden, mutedGroups) > 0
)
.sort((a, b) => (b.lastActivityTs || 0) - (a.lastActivityTs || 0))
@@ -550,8 +575,10 @@ export function ServerRail(): JSX.Element | null {
g.kind === 'guild' || g.kind === 'space' ? () => setLeaving(g) : undefined
}
onBrowse={g.kind === 'space' ? () => setBrowsing(g) : undefined}
onSettings={steamGroupOfRail(g.id) ? () => setConfiguring(g) : undefined}
unread={t?.unread ?? 0}
highlight={t?.highlight ?? false}
mentions={t?.mentions ?? 0}
// Direct messages and pinned lead the rail by definition, so
// there is nowhere for them to be dragged to.
draggable={!isFixedEntry(g)}
@@ -599,6 +626,7 @@ export function ServerRail(): JSX.Element | null {
open={open}
unread={entry.members.reduce((n, m) => n + (totals.get(m.id)?.unread ?? 0), 0)}
highlight={entry.members.some((m) => totals.get(m.id)?.highlight)}
mentions={entry.members.reduce((n, m) => n + (totals.get(m.id)?.mentions ?? 0), 0)}
onToggle={() => toggleFolder(entry.id)}
lifted={dragging === `${FOLDER_DRAG_PREFIX}${entry.id}`}
onDragStart={() => beginDrag(`${FOLDER_DRAG_PREFIX}${entry.id}`)}
@@ -721,6 +749,7 @@ export function ServerRail(): JSX.Element | null {
/>
)}
{configuring && <SteamGroupSettings accountId={configuring.accountId} railId={configuring.id} onClose={() => setConfiguring(null)} />}
{browsing && (
<SpaceRooms
accountId={browsing.accountId}
@@ -788,6 +817,7 @@ function FolderTile(props: {
/** What is waiting in the servers inside, so a closed folder can say so. */
unread: number
highlight: boolean
mentions: number
onToggle: () => void
onContextMenu: (e: React.MouseEvent) => void
onDragStart: () => void
@@ -795,7 +825,7 @@ function FolderTile(props: {
onDrop: () => void
onDragEnd: () => void
}): JSX.Element {
const { folder, members, customIcons, dropTarget, lifted, open, unread, highlight } = props
const { folder, members, customIcons, dropTarget, lifted, open, unread, mentions } = props
// Open, its servers show their own; closed, what is inside would be
// invisible without this.
const waiting = !open && unread > 0
@@ -862,14 +892,14 @@ function FolderTile(props: {
{/* Once the face is a grid of other people's icons, nothing says it is
a folder any more - so it takes the same corner badge a guild uses
to name its service. An empty folder is already unmistakably one. */}
{members.length > 0 && !(waiting && highlight) && (
{members.length > 0 && !(!open && mentions > 0) && (
<span className="rail-service">
<Icon name="folder" size={11} />
</span>
)}
{waiting && highlight && (
<span className="rail-count highlight" title={`${unread} unread, with a mention`}>
{unread > 99 ? '99+' : unread}
{!open && mentions > 0 && (
<span className="rail-count highlight" title={`${mentions} mention${mentions === 1 ? '' : 's'}`}>
{mentions > 99 ? '99+' : mentions}
</span>
)}
</button>
+4 -3
View File
@@ -6,6 +6,7 @@ import { useEscapeLayer } from '../lib/layers'
import { presenceClass } from '../lib/presence'
import { classes } from '../lib/util'
import type { Account } from '../../../shared/wire'
import { statusName, supportsStatus } from '../lib/status'
import type { Status } from './UserFooter'
/** The statuses that can be chosen, with the dot each is drawn with. Signing out is separate, below them. */
@@ -89,7 +90,7 @@ export function StatusPopout({
aria-label="Set your status"
style={pos ? { left: pos.left, bottom: pos.bottom } : { visibility: 'hidden' }}
>
{CHOICES.map((c) => (
{CHOICES.filter((c) => supportsStatus(account.service, c.id)).map((c) => (
<button
key={c.id}
type="button"
@@ -100,8 +101,8 @@ export function StatusPopout({
>
<span className={classes('status-dot', presenceClass(c.dot))} />
<span className="status-choice-text">
<span>{c.label}</span>
{c.hint && <span className="small muted">{c.hint}</span>}
<span>{statusName(account.service, c.id)}</span>
{c.hint && <span className="small muted">{account.service === 'matrix' ? 'Your presence is set to offline' : c.hint}</span>}
</span>
{c.id === status && <Icon name="check" size={16} className="status-check" />}
</button>
@@ -0,0 +1,162 @@
import { useEffect, useState } from 'react'
import { Icon } from './Icon'
import { useStore } from '../state/hooks'
import { formatFullTime } from '../lib/util'
import type { Account } from '../../../shared/wire'
/** What Steam says of the account, as the daemon sends it. */
interface Facts {
limited?: boolean
familyView?: { enabled: boolean; holdsFriendsBack: boolean } | null
textFilter?: { on: boolean; setting: string; ignoreFriends: boolean; words: number } | null
privacy?: { profile?: string; inventory?: string; games?: string; playtime?: string; friends?: string } | null
}
interface Session {
tokenId: string
description: string
platform: number
lastSeen: number
place: string
current: boolean
}
/** Which kind of place a session is, in the words Steam's own list uses. */
function platformLabel(platform: number): string {
return platform === 3 ? 'Mobile app' : platform === 2 ? 'Web browser' : platform === 1 ? 'Steam client' : 'Signed in'
}
function privacyWord(state?: string | null): string {
return state === 'public' ? 'public' : state === 'friends' ? 'friends only' : state === 'private' ? 'private' : 'not said'
}
/**
* What the account is, and where it is signed in.
*
* Steam holds things back from an account without saying so where it matters: a
* limited account cannot write to everybody, Family View can hold the friends
* list back. Said here in words, with the privacy the account has set, the text
* filter it uses, and the places it is signed in - any of which, other than the
* one in use, can be signed out.
*/
export function SteamAccountTools({ account }: { account: Account }): JSX.Element {
const store = useStore()
const [facts, setFacts] = useState<Facts | null>(null)
const [sessions, setSessions] = useState<Session[] | null>(null)
const [confirming, setConfirming] = useState('')
const connected = account.state === 'connected'
useEffect(() => {
let live = true
void window.moho
.rpc<Facts>('steamAccountFacts', { accountId: account.id })
.then((f) => live && setFacts(f))
.catch(() => {})
const off = window.moho.onEvent((e) => {
if (e.event !== 'steamAccountFacts') return
const d = e.data as { accountId?: string; facts?: Facts }
if (d.accountId === account.id && d.facts) setFacts(d.facts)
})
return () => {
live = false
off()
}
}, [account.id, connected])
const loadSessions = (): void => {
void window.moho
.rpc<Session[]>('steamSessions', { accountId: account.id })
.then(setSessions)
.catch((e: Error) => store.toast('error', e.message))
}
const signOut = (s: Session): void => {
setConfirming('')
void window.moho
.rpc<Session[]>('steamRevokeSession', { accountId: account.id, tokenId: s.tokenId })
.then((list) => {
setSessions(list)
store.toast('info', `Signed out ${s.description}`)
})
.catch((e: Error) => store.toast('error', e.message))
}
const notes: string[] = []
if (facts?.limited) {
notes.push('This is a limited account: Steam stops it from messaging anyone who is not a friend, and from sending files or many links, until it has spent enough on Steam.')
}
if (facts?.familyView?.enabled) {
notes.push(
facts.familyView.holdsFriendsBack
? 'Family View is on and holds friends and chat back. Unlock it in Steam to chat from here.'
: 'Family View is on. It does not hold friends and chat back.'
)
}
return (
<div className="sasl-block">
<span className="small muted">What Steam says about this account</span>
{!facts && <p className="small muted">{connected ? 'Asking Steam…' : 'Connect the account to read this.'}</p>}
{notes.map((n) => (
<div key={n} className="warning-note">
<Icon name="info" size={16} />
<span>{n}</span>
</div>
))}
{facts && !facts.limited && !facts.familyView?.enabled && <p className="small muted">Not limited, and Family View is off.</p>}
{facts?.privacy && (
<p className="small muted">
Privacy: profile {privacyWord(facts.privacy.profile)}, games {privacyWord(facts.privacy.games)}, friends list{' '}
{privacyWord(facts.privacy.friends)}, inventory {privacyWord(facts.privacy.inventory)}. Changed on Steam, not here.
</p>
)}
{facts?.textFilter && (
<p className="small muted">
Text filter: {facts.textFilter.setting}
{facts.textFilter.on
? `. ${facts.textFilter.words > 0 ? `The ${facts.textFilter.words} words you added are hidden` : 'No words of your own are added'}${facts.textFilter.ignoreFriends ? ', for people who are not friends' : ''}. Steam's own list of what to hide is not applied here.`
: '.'}
</p>
)}
<span className="small muted">Where this account is signed in</span>
{sessions === null ? (
<div className="field-row">
<button type="button" className="button subtle small" disabled={!connected} onClick={loadSessions}>
Show where it is signed in
</button>
</div>
) : (
sessions.map((s) => (
<div key={s.tokenId} className="field-row">
<span className="grow">
{s.description}
<span className="small muted">
{' '}
· {platformLabel(s.platform)}
{s.place ? ` · ${s.place}` : ''}
{s.lastSeen ? ` · ${formatFullTime(s.lastSeen)}` : ''}
</span>
</span>
{s.current ? (
<span className="small muted">this one</span>
) : confirming === s.tokenId ? (
<>
<button type="button" className="button danger small" onClick={() => signOut(s)}>
Sign it out
</button>
<button type="button" className="button subtle small" onClick={() => setConfirming('')}>
Keep
</button>
</>
) : (
<button type="button" className="button subtle small" onClick={() => setConfirming(s.tokenId)}>
Sign out
</button>
)}
</div>
))
)}
</div>
)
}
@@ -0,0 +1,52 @@
import { Modal } from './Modal'
import { ReasonPrompt } from './ReasonPrompt'
import { useChat, useStore } from '../state/hooks'
import { bufferDisplayName } from '../lib/util'
/**
* The questions about a Steam friend that want an answer before anything is
* done: what to call them, and the two that cannot be quietly undone.
*
* One place, mounted once, because the menus that ask them are in two places -
* a conversation's row and its header - and a dialog belongs to neither.
*/
export function SteamFriendDialogs(): JSX.Element | null {
const store = useStore()
const dialog = useChat((s) => s.steamDialog)
const buffer = useChat((s) => s.buffers.find((b) => b.id === dialog?.bufferId))
if (!dialog || !buffer) return null
const name = bufferDisplayName(buffer.name)
if (dialog.what === 'nickname') {
return (
<ReasonPrompt
title={`Nickname for ${name}`}
detail="What you call them. It is kept by Steam for your account, so it is the name on your other devices too. Leave it empty to go back to the name they chose."
placeholder="A name for them"
confirmLabel="Save"
optional
onCancel={() => store.closeSteamDialog()}
onConfirm={(nickname) => void store.doSteamFriend('nickname', dialog.bufferId, nickname)}
/>
)
}
const removing = dialog.what === 'remove'
return (
<Modal title={removing ? `Remove ${name}?` : `Block ${name}?`} icon="warning" iconColor="var(--warning)" onClose={() => store.closeSteamDialog()}>
<p className="small">
{removing
? `${name} will no longer be on your friends list, and you will no longer see when they are online. They can ask again.`
: `${name} will be removed from your friends and will not be able to message you or ask to be your friend again, until you unblock them in Steam.`}
</p>
<div className="leave-confirm-actions">
<button type="button" className="button subtle" autoFocus onClick={() => store.closeSteamDialog()}>
Cancel
</button>
<button type="button" className="button danger" onClick={() => void store.doSteamFriend(dialog.what, dialog.bufferId)}>
{removing ? 'Remove friend' : 'Block'}
</button>
</div>
</Modal>
)
}
@@ -0,0 +1,500 @@
import { useCallback, useEffect, useState } from 'react'
import { Modal } from './Modal'
import { Icon } from './Icon'
import { Switch, SwitchRow } from './Switch'
import { ConfirmButton } from './ConfirmButton'
import { useStore } from '../state/hooks'
import { STEAM_KICK_LENGTHS, STEAM_NOTIFY_LEVELS, steamGroupOfRail, type SteamChatGroup } from '../lib/steamchat'
/**
* Asks the daemon; or, in a window the screenshot harness started, takes the
* answer it left in `__rpcFixture`, since the harness has no Steam to ask.
*/
function ask<T>(method: string, params: Record<string, unknown>): Promise<T> {
const w = window as unknown as { __mohoShots?: unknown; __rpcFixture?: Record<string, (p: Record<string, unknown>) => unknown> }
const stub = w.__mohoShots ? w.__rpcFixture?.[method] : undefined
return stub ? Promise.resolve(stub(params) as T) : window.moho.rpc<T>(method, params)
}
type Tab = 'general' | 'rooms' | 'people' | 'roles' | 'invites'
interface Link {
code: string
link: string
expires?: number | null
}
/** What a role may do, by the names the daemon gives each permission. */
type Permissions = Record<string, boolean>
const LINK_LIFETIMES: { label: string; seconds: number }[] = [
{ label: 'An hour', seconds: 3600 },
{ label: 'A day', seconds: 86400 },
{ label: 'A week', seconds: 604800 }
]
/**
* Everything about one Steam chat group that the group itself keeps: its name
* and tagline, its rooms, who is in it and what they may do, and the links
* that let people in.
*
* Read from the daemon each time it is opened and after every change, so what
* is shown is what Steam holds rather than what this thought it asked for.
* What the account may not change is shown but not offered; Steam checks again
* and refuses, which is said in its own words.
*/
export function SteamGroupSettings({
accountId,
railId,
onClose
}: {
accountId: string
railId: string
onClose: () => void
}): JSX.Element {
const store = useStore()
const groupId = steamGroupOfRail(railId) ?? ''
const [group, setGroup] = useState<SteamChatGroup | null>(null)
const [tab, setTab] = useState<Tab>('general')
const [busy, setBusy] = useState(false)
const reload = useCallback(async () => {
const all = await ask<SteamChatGroup[]>('steamChatGroups', { accountId, groupId })
setGroup(all[0] ?? null)
}, [accountId, groupId])
useEffect(() => {
void reload().catch((e: Error) => store.toast('error', e.message))
}, [reload, store])
/** One change, then the group read again; the error is Steam's own. */
const act = useCallback(
async <T,>(action: string, extra: Record<string, unknown> = {}): Promise<T | undefined> => {
setBusy(true)
try {
const done = await ask<T>('steamChatGroupAction', { accountId, groupId, action, ...extra })
await reload()
return done
} catch (e) {
store.toast('error', (e as Error).message)
return undefined
} finally {
setBusy(false)
}
},
[accountId, groupId, reload, store]
)
if (!group) {
return (
<Modal title="Group" icon="groups" onClose={onClose} className="steam-group">
<p className="small muted">
<span className="spinner" /> Asking Steam…
</p>
</Modal>
)
}
const tabs: [Tab, string][] = [
['general', 'General'],
['rooms', 'Rooms'],
['people', 'People'],
['roles', 'Roles'],
['invites', 'Invites']
]
return (
<Modal title={group.name || 'Group'} icon="groups" onClose={onClose} className="steam-group">
<div className="room-settings-tabs" role="tablist">
{tabs.map(([id, label]) => (
<button
key={id}
type="button"
role="tab"
aria-selected={tab === id}
className={`room-settings-tab${tab === id ? ' active' : ''}`}
onClick={() => setTab(id)}
>
{label}
</button>
))}
</div>
<div className="room-settings-body steam-group-body">
{tab === 'general' && <General group={group} busy={busy} act={act} onLeft={onClose} />}
{tab === 'rooms' && <Rooms group={group} busy={busy} act={act} />}
{tab === 'people' && <People group={group} busy={busy} act={act} />}
{tab === 'roles' && <Roles group={group} busy={busy} act={act} />}
{tab === 'invites' && <Invites group={group} act={act} />}
</div>
</Modal>
)
}
type Act = <T>(action: string, extra?: Record<string, unknown>) => Promise<T | undefined>
function General({ group, busy, act, onLeft }: { group: SteamChatGroup; busy: boolean; act: Act; onLeft: () => void }): JSX.Element {
const store = useStore()
const [name, setName] = useState(group.name)
const [tagline, setTagline] = useState(group.tagline)
const mayChange = group.mayManage
return (
<>
<div className="field">
<span className="small muted">Picture</span>
<div className="field-row steam-group-row">
<span className="grow small muted">{group.mayManage ? 'Shown on the rail and in the channel list.' : 'Only those who may change the group can change it.'}</span>
{/* Sent to Steam's site and then named to the group; the new picture
arrives on the rail when Steam says the group changed. */}
<button
type="button"
className="button subtle small"
disabled={!group.mayManage || busy}
onClick={() => {
void window.moho.pickFile(['jpg', 'jpeg', 'png', 'gif']).then((path) => path && void act('avatar', { path }))
}}
>
Change picture
</button>
</div>
</div>
<div className="field">
<span className="small muted">Name</span>
<div className="field-row">
<input className="text-field" value={name} disabled={!mayChange || busy} onChange={(e) => setName(e.target.value)} />
<button type="button" className="button" disabled={!mayChange || busy || !name.trim() || name === group.name} onClick={() => void act('rename', { name })}>
Save
</button>
</div>
</div>
<div className="field">
<span className="small muted">Tagline</span>
<div className="field-row">
<input className="text-field" value={tagline} disabled={!mayChange || busy} onChange={(e) => setTagline(e.target.value)} />
<button type="button" className="button" disabled={!mayChange || busy || tagline === group.tagline} onClick={() => void act('tagline', { text: tagline })}>
Save
</button>
</div>
</div>
{!mayChange && <p className="small muted">Only {group.myRankWord === 'Member' ? 'its officers' : 'someone with more say'} can change these.</p>}
<div className="field">
<span className="small muted">Tell me about</span>
<div className="segmented" role="radiogroup" aria-label="Notifications">
{STEAM_NOTIFY_LEVELS.map((l) => (
<button key={l.value} type="button" role="radio" aria-checked={group.notify === l.value} className={group.notify === l.value ? 'active' : ''} disabled={busy} onClick={() => void act('notify', { level: l.value })}>
{l.label}
</button>
))}
</div>
{/* Separate from the level, as Steam keeps them: being told of everything shows the marker again. */}
{group.notify !== 4 && <SwitchRow title="Show unread messages" description="The marker on the group when something was written in it" checked={!group.muted} disabled={busy} onChange={(show) => void act('notify', { muted: !show })} />}
<p className="small muted">Kept by Steam for your account, so it is the same on your other devices.</p>
</div>
<div className="field">
<span className="small muted">You are</span>
<span>{group.myRankWord}</span>
</div>
<div className="leave-confirm-actions">
<ConfirmButton
label="Leave group"
question={`Leave ${group.name}?`}
confirmLabel="Leave"
danger
onConfirm={() => {
// The window's own leave: it takes the rail entry away with it.
void store.leaveGroup(group.railId).then((left) => left && onLeft())
}}
/>
</div>
</>
)
}
function Rooms({ group, busy, act }: { group: SteamChatGroup; busy: boolean; act: Act }): JSX.Element {
const [fresh, setFresh] = useState('')
const [withVoice, setWithVoice] = useState(false)
const [editing, setEditing] = useState<{ id: string; name: string } | null>(null)
return (
<>
{group.rooms.map((r) => (
<div key={r.id} className="field-row steam-group-row">
{editing?.id === r.id ? (
<>
<input className="text-field grow" autoFocus value={editing.name} onChange={(e) => setEditing({ id: r.id, name: e.target.value })} />
<button
type="button"
className="button small"
disabled={busy}
onClick={() => void act('renameRoom', { roomId: r.id, name: editing.name }).then(() => setEditing(null))}
>
Save
</button>
<button type="button" className="button subtle small" onClick={() => setEditing(null)}>
Cancel
</button>
</>
) : (
<>
<Icon name={r.voice ? 'volume_up' : 'tag'} size={16} />
<span className="grow ellipsis">{r.name || 'General'}</span>
{r.voice && <span className="small muted">voice</span>}
{group.mayManage && (
<>
<button type="button" className="button subtle small" onClick={() => setEditing({ id: r.id, name: r.name })}>
Rename
</button>
{group.rooms.length > 1 && (
<ConfirmButton label="Delete" question={`Delete ${r.name || 'General'} and what was said in it?`} confirmLabel="Delete" danger onConfirm={() => void act('deleteRoom', { roomId: r.id })} />
)}
</>
)}
</>
)}
</div>
))}
{group.mayManage && (
<>
<div className="field-row">
<input className="text-field" placeholder="A new room" value={fresh} onChange={(e) => setFresh(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && fresh.trim() && void act('createRoom', { name: fresh, voice: withVoice }).then(() => setFresh(''))} />
<button type="button" className="button" disabled={busy || !fresh.trim()} onClick={() => void act('createRoom', { name: fresh, voice: withVoice }).then(() => setFresh(''))}>
Add room
</button>
</div>
<SwitchRow title="With voice" description="People in it can talk, as well as write; it is chosen when the room is made" checked={withVoice} onChange={setWithVoice} />
</>
)}
</>
)
}
function People({ group, busy, act }: { group: SteamChatGroup; busy: boolean; act: Act }): JSX.Element {
const store = useStore()
const [bans, setBans] = useState<{ steamid: string; name: string }[] | null>(null)
const [kickFor, setKickFor] = useState(3600)
const roleName = (id: string): string => group.roles.find((r) => r.id === id)?.name ?? id
const loadBans = (): void => {
void act<{ bans: { steamid: string; name: string }[] }>('bans').then((r) => r && setBans(r.bans))
}
return (
<>
{group.members.map((m) => {
const own = m.steamid === group.owner
return (
<div key={m.steamid} className="steam-group-person">
<div className="field-row steam-group-row">
<span className="grow ellipsis" title={m.steamid}>
{m.name}
</span>
<span className="small muted">{m.rankWord}</span>
{group.mayModerate && !own && (
<>
<button type="button" className="button subtle small" disabled={busy} onClick={() => void act('mute', { steamid: m.steamid, seconds: 600 }).then(() => store.toast('info', `Muted ${m.name} for 10 minutes`))}>
Mute 10 min
</button>
<select className="text-field small" value={kickFor} aria-label="How long a removal lasts" onChange={(e) => setKickFor(Number(e.target.value))}>
{STEAM_KICK_LENGTHS.map((l) => (
<option key={l.seconds} value={l.seconds}>
{l.label}
</option>
))}
</select>
<ConfirmButton label="Remove" question={`Remove ${m.name} for ${STEAM_KICK_LENGTHS.find((l) => l.seconds === kickFor)?.label.toLowerCase()}?`} confirmLabel="Remove" danger onConfirm={() => void act('kick', { steamid: m.steamid, seconds: kickFor })} />
<ConfirmButton label="Ban" question={`Ban ${m.name}?`} confirmLabel="Ban" danger onConfirm={() => void act('ban', { steamid: m.steamid, banned: true }).then(() => store.toast('info', `Banned ${m.name}`))} />
</>
)}
</div>
{m.roles.length > 0 && (
<div className="profile-roles">
{m.roles.map((r) => (
<span key={r} className="profile-role small">
{roleName(r)}
{group.mayAssignRoles && !own && r !== group.defaultRole && (
<button type="button" className="steam-group-x" aria-label={`Take ${roleName(r)} from ${m.name}`} onClick={() => void act('takeRole', { steamid: m.steamid, roleId: r })}>
×
</button>
)}
</span>
))}
</div>
)}
{group.mayAssignRoles && group.roles.some((r) => r.id !== group.defaultRole && !m.roles.includes(r.id)) && (
<select
className="text-field small"
value=""
aria-label={`Give ${m.name} a role`}
onChange={(e) => e.target.value && void act('giveRole', { steamid: m.steamid, roleId: e.target.value })}
>
<option value="">Give a role…</option>
{group.roles
.filter((r) => r.id !== group.defaultRole && !m.roles.includes(r.id))
.map((r) => (
<option key={r.id} value={r.id}>
{r.name}
</option>
))}
</select>
)}
</div>
)
})}
{group.mayModerate && (
<>
<span className="small muted">Banned</span>
{bans === null ? (
<button type="button" className="button subtle small" onClick={loadBans}>
Show who is banned
</button>
) : bans.length === 0 ? (
<p className="small muted">Nobody.</p>
) : (
bans.map((b) => (
<div key={b.steamid} className="field-row steam-group-row">
<span className="grow ellipsis">{b.name}</span>
<button type="button" className="button subtle small" onClick={() => void act('ban', { steamid: b.steamid, banned: false }).then(loadBans)}>
Unban
</button>
</div>
))
)}
</>
)}
</>
)
}
function Roles({ group, busy, act }: { group: SteamChatGroup; busy: boolean; act: Act }): JSX.Element {
const [fresh, setFresh] = useState('')
const [open, setOpen] = useState<string | null>(null)
const [perms, setPerms] = useState<Permissions | null>(null)
const [name, setName] = useState('')
const expand = (id: string, current: string): void => {
if (open === id) {
setOpen(null)
return
}
setOpen(id)
setPerms(null)
setName(current)
void act<Permissions>('roleActions', { roleId: id }).then((p) => p && setPerms(p))
}
return (
<>
{group.roles.map((r) => (
<div key={r.id} className="steam-group-person">
<div className="field-row steam-group-row">
<Icon name="shield" size={16} />
<span className="grow ellipsis">{r.name}</span>
<button type="button" className="button subtle small" onClick={() => expand(r.id, r.name)}>
{open === r.id ? 'Close' : 'Edit'}
</button>
</div>
{open === r.id && (
<div className="steam-group-perms">
{group.mayChangeRoles && r.id !== group.defaultRole && (
<div className="field-row">
<input className="text-field" value={name} onChange={(e) => setName(e.target.value)} />
<button type="button" className="button small" disabled={busy || !name.trim() || name === r.name} onClick={() => void act('renameRole', { roleId: r.id, name })}>
Rename
</button>
<ConfirmButton label="Delete" question={`Delete ${r.name}?`} confirmLabel="Delete" danger onConfirm={() => void act('deleteRole', { roleId: r.id }).then(() => setOpen(null))} />
</div>
)}
{perms === null ? (
<p className="small muted">
<span className="spinner" /> Asking Steam…
</p>
) : (
group.permissions.map((p) => (
<div key={p.key} className="switch-row">
<span className="switch-text">
<span>{p.label}</span>
</span>
<Switch
checked={!!perms[p.key]}
label={p.label}
disabled={!group.mayChangeRoles || busy}
onChange={(next) => {
const updated = { ...perms, [p.key]: next }
setPerms(updated)
void act('setRoleActions', { roleId: r.id, actions: updated })
}}
/>
</div>
))
)}
</div>
)}
</div>
))}
{group.mayChangeRoles && (
<div className="field-row">
<input className="text-field" placeholder="A new role" value={fresh} onChange={(e) => setFresh(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && fresh.trim() && void act('createRole', { name: fresh }).then(() => setFresh(''))} />
<button type="button" className="button" disabled={busy || !fresh.trim()} onClick={() => void act('createRole', { name: fresh }).then(() => setFresh(''))}>
Add role
</button>
</div>
)}
</>
)
}
function Invites({ group, act }: { group: SteamChatGroup; act: Act }): JSX.Element {
const store = useStore()
const [links, setLinks] = useState<Link[] | null>(null)
const [seconds, setSeconds] = useState(86400)
const load = useCallback(() => {
void act<{ links: Link[] }>('links').then((r) => r && setLinks(r.links))
// act reads the group again, which is not needed here but is harmless.
}, [act])
useEffect(() => {
load()
// Once per opening of the tab.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const copy = (text: string): void => {
// Through the main process, as everywhere else in moho: the page's own clipboard is refused here.
void window.moho
.copyText(text)
.then(() => store.toast('info', 'Copied'))
.catch(() => store.toast('error', 'Could not copy'))
}
return (
<>
{links === null && (
<p className="small muted">
<span className="spinner" /> Asking Steam…
</p>
)}
{links?.length === 0 && <p className="small muted">No links. Make one to let people in.</p>}
{links?.map((l) => (
<div key={l.code} className="field-row steam-group-row">
<span className="grow ellipsis" title={l.link}>
{l.link}
</span>
{l.expires ? <span className="small muted">until {new Date(l.expires * 1000).toLocaleString()}</span> : null}
<button type="button" className="button subtle small" onClick={() => copy(l.link)}>
Copy
</button>
{group.mayInvite && (
<button type="button" className="button subtle small" onClick={() => void act('revokeInvite', { code: l.code }).then(load)}>
Revoke
</button>
)}
</div>
))}
{group.mayInvite && (
<div className="field-row">
<select className="text-field" value={seconds} aria-label="How long a link lasts" onChange={(e) => setSeconds(Number(e.target.value))}>
{LINK_LIFETIMES.map((l) => (
<option key={l.seconds} value={l.seconds}>
{l.label}
</option>
))}
</select>
<button type="button" className="button" onClick={() => void act('makeInvite', { seconds }).then(load)}>
Make a link
</button>
</div>
)}
</>
)
}
@@ -0,0 +1,109 @@
import { useEffect, useState } from 'react'
import { Avatar } from './Avatar'
import { Icon, IconButton } from './Icon'
import { useChat, useIdSetPref, useStore } from '../state/hooks'
import { classes } from '../lib/util'
import { steamGroupOfRail } from '../lib/steamchat'
import type { RailGroup } from '../lib/groups'
/**
* The rooms of a Steam group that have voice, listed under its text ones the
* way a Discord server's voice channels are, with who is in each shown before
* you join: that is what anyone decides on.
*
* Steam keeps who is in a room's voice chat with the room, so the list is what
* the daemon last said, and joining is this window's: see lib/steamvoice.ts.
*/
export function SteamVoiceRooms({ group }: { group: RailGroup }): JSX.Element | null {
const store = useStore()
const groupId = steamGroupOfRail(group.id)
const rooms = useChat((s) => (groupId ? s.steamVoiceRooms[`${group.accountId}|${groupId}`] : undefined)) ?? []
const now = useChat((s) => s.steamVoiceNow)
const [, toggleFolded, isFolded] = useIdSetPref('collapsedCategories')
const foldKey = `steamvoice|${group.id}`
const here = (roomId: string): boolean => now?.target.kind === 'room' && now.accountId === group.accountId && now.target.groupId === groupId && now.target.roomId === roomId
const inThisGroup = rooms.some((r) => here(r.roomId))
const live = useLive(inThisGroup)
useEffect(() => {
if (groupId) void store.refreshSteamVoiceRooms(group.accountId, groupId)
}, [store, group.accountId, groupId])
if (!groupId || rooms.length === 0) return null
return (
<>
<button
type="button"
className="bufferlist-section category-head"
onClick={() => toggleFolded(foldKey)}
title={isFolded(foldKey) ? 'Show voice rooms' : 'Hide voice rooms'}
>
<Icon name="expand_more" size={14} className={classes('fold-chevron', isFolded(foldKey) && 'folded')} />
<span>Voice</span>
</button>
{rooms
.filter((r) => !isFolded(foldKey) || here(r.roomId))
.map((r) => {
const connected = here(r.roomId)
return (
<div key={r.roomId} className={`voice-channel${connected ? ' active' : ''}`}>
<div className="voice-channel-row">
<button
type="button"
className="voice-channel-main"
title={connected ? `Connected to ${r.name}` : `Join ${r.name}`}
onClick={() => (connected ? void store.leaveVoice(group.accountId) : void store.joinSteamVoice(group.accountId, groupId, r.roomId))}
>
<Icon name="volume_up" size={16} />
<span className="ellipsis">{r.name}</span>
{connected && now?.phase !== 'connected' && <span className="spinner" />}
</button>
{connected && <IconButton name="call_end" size={16} title="Disconnect" onClick={() => void store.leaveVoice(group.accountId)} />}
</div>
{r.members.map((m) => {
const status = live.statuses.get(m.userId)
return (
<div key={m.userId} className={classes('voice-member small', live.speakers.has(m.userId) && 'speaking')}>
<span className="voice-member-face">
<Avatar name={m.nick} url={m.avatarUrl ?? undefined} size={20} accountId={group.accountId} />
</span>
<span className="ellipsis">{m.nick}</span>
{m.isSelf && <span className="muted voice-you">you</span>}
{status?.outputMuted ? (
<span className="voice-state" title={`${m.nick} has deafened themselves`}>
<Icon name="headset_off" size={13} />
</span>
) : (
(status?.micMuted || status?.noMic) && (
<span className="voice-state" title={status?.noMic ? `${m.nick} has no microphone` : `${m.nick} is muted`}>
<Icon name="mic_off" size={13} />
</span>
)
)}
</div>
)
})}
</div>
)
})}
</>
)
}
/** Who is audible and how each person says they are, read from the call this window holds. */
function useLive(inCall: boolean): { speakers: Set<string>; statuses: Map<string, { micMuted: boolean; outputMuted: boolean; noMic: boolean }> } {
const store = useStore()
const [, tick] = useState(0)
useEffect(() => {
if (!inCall) return
// Often enough that the ring follows speech; not while nobody can see it.
const timer = setInterval(() => {
if (document.visibilityState === 'visible') tick((n) => n + 1)
}, 200)
return () => clearInterval(timer)
}, [inCall])
const v = store.steamVoiceLive
return { speakers: inCall ? v.speakers : new Set(), statuses: inCall ? v.statuses : new Map() }
}
+9 -6
View File
@@ -4,6 +4,7 @@ import { Icon } from './Icon'
import { Avatar } from './Avatar'
import { useStore, useChat } from '../state/hooks'
import { presenceLabel } from '../lib/presence'
import { statusName } from '../lib/status'
import { serviceLabel } from '../lib/util'
import type { Account } from '../../../shared/wire'
@@ -34,8 +35,10 @@ export function effectiveStatus(account: Account): Status | 'connecting' {
return (account.status as Status) || 'online'
}
function label(status: Status | 'connecting'): string {
return status === 'connecting' ? 'Connecting…' : presenceLabel(status)
function label(status: Status | 'connecting', service: string, auto = false): string {
if (status === 'connecting') return 'Connecting…'
if (status === 'idle' && auto) return 'Idle (away)'
return status === 'invisible' ? statusName(service, 'invisible') : presenceLabel(status)
}
export function UserFooter({ account }: { account?: Account }): JSX.Element {
@@ -59,7 +62,7 @@ export function UserFooter({ account }: { account?: Account }): JSX.Element {
// Mute and deafen are the whole client's, for whatever call is up - so
// shown on a service that has calls, or anywhere while one is running,
// and not beside an IRC or Kick account with nothing to apply them to.
const showVoice = account.service === 'discord' || account.service === 'matrix' || inACall
const showVoice = account.service === 'discord' || account.service === 'matrix' || account.service === 'steam' || inACall
return (
<>
@@ -71,12 +74,12 @@ export function UserFooter({ account }: { account?: Account }): JSX.Element {
aria-haspopup="menu"
aria-expanded={open}
onClick={() => setOpen(!open)}
title={detail ? `${name} — ${label(status)}\n${detail}` : `${name} — ${label(status)}`}
title={detail ? `${name} — ${label(status, account.service, account.autoIdle)}\n${detail}` : `${name} — ${label(status, account.service, account.autoIdle)}`}
>
<Avatar name={name} url={account.avatarUrl} size={28} status={status} accountId={account.id} />
<span className="user-identity">
<span className="ellipsis user-name">{name}</span>
<span className="ellipsis small muted">{watching ? 'Watching, signed out' : label(status)}</span>
<span className="ellipsis small muted">{watching ? 'Watching, signed out' : label(status, account.service, account.autoIdle)}</span>
</span>
</button>
@@ -117,7 +120,7 @@ export function UserFooter({ account }: { account?: Account }): JSX.Element {
</div>
{open && (
<StatusPopout account={account} status={status} anchor={identity.current} onClose={() => setOpen(false)} />
<StatusPopout account={account} status={account.autoIdle ? 'online' : status} anchor={identity.current} onClose={() => setOpen(false)} />
)}
</>
)
@@ -16,7 +16,8 @@ import { useChat, useStore } from '../state/hooks'
*/
export function VerificationDialog(): JSX.Element | null {
const active = useChat((s) => s.matrixVerification)
if (!active) return null
// Waiting on an answer, it is on the Invitations tile: this is for the check itself.
if (!active || active.incoming) return null
// Keyed on the verification so its QR code is fetched afresh for a new one,
// rather than a picture of the last session being shown against this one.
+8 -2
View File
@@ -42,6 +42,12 @@ export function VoicePanel(): JSX.Element | null {
setRtt(staged.rttMs)
return
}
// A Steam call is held by this window, which is where its level is.
if (session.accountId.startsWith('steam:')) {
setLevel(store.steamVoiceLive.level)
setRtt(store.steamVoiceLive.rttMs)
return
}
try {
const levels = await window.moho.rpc<{ accountId: string; micPeak: number; rttMs?: number | null }[]>(
'getVoiceLevels'
@@ -60,13 +66,13 @@ export function VoicePanel(): JSX.Element | null {
if (document.visibilityState === 'visible') void tick()
}, 150)
return () => clearInterval(timer)
}, [session])
}, [session, store])
if (!session) return null
// A one-to-one call has no guild to go back to; its home is the
// conversation itself, which the DM page holds.
const groupId = session.guildId ? `${session.accountId}|guild:${session.guildId}` : DM_GROUP_ID
const groupId = session.railId ?? (session.guildId ? `${session.accountId}|guild:${session.guildId}` : DM_GROUP_ID)
const guildName = session.isDirect ? '' : (groups.find((g) => g.id === groupId)?.name ?? '')
const fill = levelFill(level)
const quality = rtt === null ? null : rtt < 80 ? 'good' : rtt < 160 ? 'fair' : 'poor'
@@ -855,6 +855,27 @@ function GeneralSettings(): JSX.Element {
<GlobalHighlightKeywords />
</SettingsSection>
<SettingsSection title="Presence">
<ToggleSetting
settingKey="presence.autoIdle"
label="Go idle when I step away"
description="Shows you as Idle on Discord and IRC after a while with nothing touched, and back to Online when you return. Only while your status is Online: Idle, Do not disturb and Invisible stay where you put them until you set Online again. Not while you are in a call. moho looks only at how long it has been since the keyboard or mouse was used - never at what you do. Where the system will not say (some Wayland desktops), it goes by your use of moho's own windows."
defaultValue={true}
/>
<SelectionSetting
settingKey="presence.autoIdleMinutes"
label="Idle after"
defaultValue="10"
options={[
{ label: '5 min', value: '5' },
{ label: '10 min', value: '10' },
{ label: '15 min', value: '15' },
{ label: '30 min', value: '30' },
{ label: '1 hour', value: '60' }
]}
/>
</SettingsSection>
<SettingsSection title="Updates">
<ToggleSetting
settingKey="updates.notify"
+58
View File
@@ -0,0 +1,58 @@
import { describe, expect, it } from 'vitest'
import type { Member } from '../../../shared/wire'
import type { BufferEntry } from '../state/store'
import { activityIcon, activityLabel, dmActivity, profileActivity } from './activity'
const dm = { id: 'steam:me|Gabe', kind: 'dm', accountId: 'steam:me', name: 'Gabe' } as BufferEntry
const member = (extra: Partial<Member>): Member => ({ nick: 'Gabe', status: 'online', ...extra }) as Member
describe('what somebody is doing, under their name', () => {
it('has a gamepad for a game, a note for a track, and nothing for words they wrote', () => {
expect(activityIcon({ kind: 'game', text: 'Resident Evil 4' })).toBe('sports_esports')
expect(activityIcon({ kind: 'music', text: 'Ramones' })).toBe('music_note')
expect(activityIcon({ kind: 'custom', text: 'ask questions' })).toBeUndefined()
})
it('reads as a sentence where there is no room for a picture', () => {
expect(activityLabel({ kind: 'game', text: 'Dota 2' })).toBe('Playing Dota 2')
expect(activityLabel({ kind: 'music', text: 'Ramones' })).toBe('Listening to Ramones')
expect(activityLabel({ kind: 'custom', text: 'ask questions' })).toBe('ask questions')
})
it('is the one person of a direct message, and nobody else', () => {
const playing = { kind: 'game', text: 'Dota 2' } as const
expect(dmActivity(dm, { [dm.id]: [member({ activity: playing })] })).toEqual(playing)
expect(dmActivity(dm, { [dm.id]: [member({ activity: null })] })).toBeUndefined()
expect(dmActivity(dm, { [dm.id]: [member({})] })).toBeUndefined()
expect(dmActivity(dm, {})).toBeUndefined()
const room = { ...dm, kind: 'channel' } as BufferEntry
expect(dmActivity(room, { [room.id]: [member({ activity: playing })] })).toBeUndefined()
expect(dmActivity(dm, { [dm.id]: [member({ activity: playing }), member({ nick: 'x', activity: playing })] })).toBeUndefined()
})
})
describe('what a profile card says somebody is doing', () => {
const playing = { kind: 'game', text: 'Dota 2' } as const
const buffers = [
{ id: 'discord:1|#a', accountId: 'discord:1', kind: 'channel', name: '#a' },
{ id: 'discord:2|#b', accountId: 'discord:2', kind: 'channel', name: '#b' }
] as BufferEntry[]
const who = { accountId: 'discord:1', id: '42', name: 'Gabe', handle: 'gabe#1' }
it('is what the lookup said, first', () => {
expect(profileActivity({ ...who, activity: { kind: 'custom', text: 'brb' } }, {}, buffers)).toEqual({ kind: 'custom', text: 'brb' })
})
it('is otherwise what the member lists already say, found by id or by name', () => {
const byId = { 'discord:1|#a': [member({ nick: 'someone else', userId: '42', activity: playing })] }
expect(profileActivity(who, byId, buffers)).toEqual(playing)
const byName = { 'discord:1|#a': [member({ nick: 'GABE', activity: playing })] }
expect(profileActivity(who, byName, buffers)).toEqual(playing)
})
it('does not borrow it from another account, nor from somebody else', () => {
expect(profileActivity(who, { 'discord:2|#b': [member({ nick: 'Gabe', userId: '42', activity: playing })] }, buffers)).toBeUndefined()
expect(profileActivity(who, { 'discord:1|#a': [member({ nick: 'Other', userId: '7', activity: playing })] }, buffers)).toBeUndefined()
expect(profileActivity(who, { 'discord:1|#a': [member({ nick: 'Gabe', userId: '42' })] }, buffers)).toBeUndefined()
})
})

Some files were not shown because too many files have changed in this diff Show More