Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
No results found
Show changes
Showing
with 950 additions and 522 deletions
......@@ -9,7 +9,7 @@ export interface MarkdownProps {
export default function Markdown(props: MarkdownProps) {
return (
// @ts-expect-error
// @ts-expect-error Typings mis-match.
<Suspense fallback={props.content}>
<Renderer {...props} />
</Suspense>
......
/* eslint-disable react-hooks/rules-of-hooks */
import MarkdownKatex from "@traptitech/markdown-it-katex";
import MarkdownSpoilers from "@traptitech/markdown-it-spoiler";
import "katex/dist/katex.min.css";
import MarkdownIt from "markdown-it";
// @ts-ignore
// @ts-expect-error No typings.
import MarkdownEmoji from "markdown-it-emoji/dist/markdown-it-emoji-bare";
// @ts-ignore
// @ts-expect-error No typings.
import MarkdownSub from "markdown-it-sub";
// @ts-ignore
// @ts-expect-error No typings.
import MarkdownSup from "markdown-it-sup";
import Prism from "prismjs";
import "prismjs/themes/prism-tomorrow.css";
import { RE_MENTIONS } from "revolt.js";
import styles from "./Markdown.module.scss";
import { useCallback, useContext, useRef } from "preact/hooks";
import { useCallback, useContext } from "preact/hooks";
import { internalEmit } from "../../lib/eventEmitter";
......@@ -67,6 +68,8 @@ export const md: MarkdownIt = MarkdownIt({
throwOnError: false,
maxExpand: 0,
maxSize: 10,
strict: false,
errorColor: "var(--error)",
});
// TODO: global.d.ts file for defining globals
......@@ -82,6 +85,9 @@ md.renderer.rules.emoji = function (token, idx) {
const RE_TWEMOJI = /:(\w+):/g;
// ! FIXME: Move to library
const RE_CHANNELS = /<#([A-z0-9]{26})>/g;
export default function Renderer({ content, disallowBigEmoji }: MarkdownProps) {
const client = useContext(AppContext);
if (typeof content === "undefined") return null;
......@@ -89,10 +95,9 @@ export default function Renderer({ content, disallowBigEmoji }: MarkdownProps) {
// We replace the message with the mention at the time of render.
// We don't care if the mention changes.
const newContent = content.replace(
RE_MENTIONS,
(sub: string, ...args: any[]) => {
const id = args[0],
const newContent = content
.replace(RE_MENTIONS, (sub: string, ...args: unknown[]) => {
const id = args[0] as string,
user = client.users.get(id);
if (user) {
......@@ -100,8 +105,17 @@ export default function Renderer({ content, disallowBigEmoji }: MarkdownProps) {
}
return sub;
},
);
})
.replace(RE_CHANNELS, (sub: string, ...args: unknown[]) => {
const id = args[0] as string,
channel = client.channels.get(id);
if (channel?.channel_type === "TextChannel") {
return `[#${channel.name}](/server/${channel.server_id}/channel/${id})`;
}
return sub;
});
const useLargeEmojis = disallowBigEmoji
? false
......
import { Wrench } from "@styled-icons/boxicons-solid";
import styled from "styled-components";
import UpdateIndicator from "../common/UpdateIndicator";
const TitlebarBase = styled.div`
height: var(--titlebar-height);
display: flex;
user-select: none;
align-items: center;
.drag {
flex-grow: 1;
-webkit-app-region: drag;
margin-top: 10px;
height: 100%;
}
.quick {
color: var(--secondary-foreground);
> div,
> div > div {
width: var(--titlebar-height) !important;
}
&.disabled {
color: var(--error);
}
&.unavailable {
background: var(--error);
}
}
.title {
-webkit-app-region: drag;
/*height: var(--titlebar-height);*/
font-size: 16px;
font-weight: 600;
margin-inline-start: 10px;
margin-top: 10px;
gap: 6px;
display: flex;
align-items: center;
justify-content: flex-start;
z-index: 90000;
color: var(--titlebar-logo-color);
svg {
margin-bottom: 10px;
}
svg:first-child {
height: calc(var(--titlebar-height) / 3);
}
}
.actions {
z-index: 100;
display: flex;
align-items: center;
margin-inline-start: 6px;
div {
width: calc(
var(--titlebar-height) + var(--titlebar-action-padding)
);
height: var(--titlebar-height);
display: grid;
place-items: center;
transition: 0.2s ease color;
transition: 0.2s ease background-color;
&:hover {
background: var(--primary-background);
}
&.error:hover {
background: var(--error);
}
}
}
`;
export function Titlebar() {
return (
<TitlebarBase>
<div class="title">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 193.733 37.438">
<path
d="M23.393,1.382c0,2.787-1.52,4.46-4.764,4.46H13.258V-2.977H18.63C21.873-2.977,23.393-1.254,23.393,1.382Zm-24-11.555,5.2,7.213V25.4h8.666V11.973h2.078l7.4,13.43h9.781l-8.21-14.089A10.355,10.355,0,0,0,32.212,1.027c0-6.183-4.358-11.2-13.075-11.2Zm60.035,0H37.634V25.4H59.426V18.46H46.3v-7.8H57.906V3.966H46.3V-2.969H59.426Zm20.981,26.86-8.818-26.86H62.365L74.984,25.4H85.83L98.449-10.173H89.276Zm56.659-9.173c0-10.693-8.058-18.194-18.194-18.194-10.085,0-18.3,7.5-18.3,18.194a17.9,17.9,0,0,0,18.3,18.244A17.815,17.815,0,0,0,137.066,7.514Zm-27.62,0c0-6.335,3.649-10.338,9.426-10.338,5.676,0,9.376,4,9.376,10.338,0,6.233-3.7,10.338-9.376,10.338C113.095,17.852,109.446,13.747,109.446,7.514ZM141.88-10.173V25.4H161.9v-6.95H150.545V-10.173Zm22.248,7.2h9.426V25.4h8.666V-2.975h9.426v-7.2H164.128Z"
transform="translate(1.586 11.18)"
fill="var(--titlebar-logo-color)"
stroke="var(--titlebar-logo-color)"
stroke-width="1"
/>
</svg>
{window.native.getConfig().build === "dev" && (
<Wrench size="12.5" />
)}
</div>
{/*<div class="actions quick">
<Tooltip
content="Mute"
placement="bottom">
<div onClick={window.native.min}>
<Microphone size={15}/>
</div>
</Tooltip>
<Tooltip
content="Deafen"
placement="bottom">
<div onClick={window.native.min}>
<VolumeFull size={15}/>
</div>
</Tooltip>
</div>*/}
<div class="drag" />
<UpdateIndicator style="titlebar" />
<div class="actions">
<div onClick={window.native.min}>
<svg
aria-hidden="false"
width="12"
height="12"
viewBox="0 0 12 12">
<rect
fill="currentColor"
width="10"
height="1"
x="1"
y="6"
/>
</svg>
</div>
<div onClick={window.native.max}>
<svg
aria-hidden="false"
width="12"
height="12"
viewBox="0 0 12 12">
<rect
width="9"
height="9"
x="1.5"
y="1.5"
fill="none"
stroke="currentColor"
/>
</svg>
</div>
<div onClick={window.native.close} class="error">
<svg
aria-hidden="false"
width="12"
height="12"
viewBox="0 0 12 12">
<polygon
fill="currentColor"
stroke-width="1"
fill-rule="evenodd"
points="11 1.576 6.583 6 11 10.424 10.424 11 6 6.583 1.576 11 1 10.424 5.417 6 1 1.576 1.576 1 6 5.417 10.424 1"
style="stroke:currentColor;stroke-width:0.4"
/>
</svg>
</div>
</div>
</TitlebarBase>
);
}
import { Search } from "@styled-icons/boxicons-regular";
import { Message, Group, Inbox } from "@styled-icons/boxicons-solid";
import { Message, Group } from "@styled-icons/boxicons-solid";
import { observer } from "mobx-react-lite";
import { useHistory, useLocation } from "react-router";
import styled, { css } from "styled-components";
......@@ -8,7 +8,7 @@ import ConditionalLink from "../../lib/ConditionalLink";
import { connectState } from "../../redux/connector";
import { LastOpened } from "../../redux/reducers/last_opened";
import { useSelf } from "../../context/revoltjs/hooks";
import { useClient } from "../../context/revoltjs/RevoltClient";
import UserIcon from "../common/user/UserIcon";
import IconButton from "../ui/IconButton";
......@@ -51,8 +51,10 @@ interface Props {
lastOpened: LastOpened;
}
export function BottomNavigation({ lastOpened }: Props) {
const user = useSelf();
export const BottomNavigation = observer(({ lastOpened }: Props) => {
const client = useClient();
const user = client.users.get(client.user!._id);
const history = useHistory();
const path = useLocation().pathname;
......@@ -114,7 +116,7 @@ export function BottomNavigation({ lastOpened }: Props) {
</Navbar>
</Base>
);
}
});
export default connectState(BottomNavigation, (state) => {
return {
......
import { X, Crown } from "@styled-icons/boxicons-regular";
import { Channels, Users } from "revolt.js/dist/api/objects";
import { observer } from "mobx-react-lite";
import { Presence } from "revolt-api/types/Users";
import { Channel } from "revolt.js/dist/maps/Channels";
import { User } from "revolt.js/dist/maps/Users";
import styles from "./Item.module.scss";
import classNames from "classnames";
......@@ -14,6 +17,7 @@ import { useIntermediate } from "../../../context/intermediate/Intermediate";
import ChannelIcon from "../../common/ChannelIcon";
import Tooltip from "../../common/Tooltip";
import UserIcon from "../../common/user/UserIcon";
import { Username } from "../../common/user/UserShort";
import UserStatus from "../../common/user/UserStatus";
import IconButton from "../../ui/IconButton";
......@@ -29,12 +33,12 @@ type CommonProps = Omit<
};
type UserProps = CommonProps & {
user: Users.User;
context?: Channels.Channel;
channel?: Channels.DirectMessageChannel;
user: User;
context?: Channel;
channel?: Channel;
};
export function UserButton(props: UserProps) {
export const UserButton = observer((props: UserProps) => {
const { active, alert, alertCount, user, context, channel, ...divProps } =
props;
const { openScreen } = useIntermediate();
......@@ -47,8 +51,7 @@ export function UserButton(props: UserProps) {
data-alert={typeof alert === "string"}
data-online={
typeof channel !== "undefined" ||
(user.online &&
user.status?.presence !== Users.Presence.Invisible)
(user.online && user.status?.presence !== Presence.Invisible)
}
onContextMenu={attachContextMenu("Menu", {
user: user._id,
......@@ -63,11 +66,13 @@ export function UserButton(props: UserProps) {
status
/>
<div className={styles.name}>
<div>{user.username}</div>
<div>
<Username user={user} />
</div>
{
<div className={styles.subText}>
{channel?.last_message && alert ? (
channel.last_message.short
(channel.last_message as { short: string }).short
) : (
<UserStatus user={user} />
)}
......@@ -76,7 +81,7 @@ export function UserButton(props: UserProps) {
</div>
<div className={styles.button}>
{context?.channel_type === "Group" &&
context.owner === user._id && (
context.owner_id === user._id && (
<Localizer>
<Tooltip
content={<Text id="app.main.groups.owner" />}>
......@@ -106,15 +111,15 @@ export function UserButton(props: UserProps) {
</div>
</div>
);
}
});
type ChannelProps = CommonProps & {
channel: Channels.Channel & { unread?: string };
user?: Users.User;
channel: Channel & { unread?: string };
user?: User;
compact?: boolean;
};
export function ChannelButton(props: ChannelProps) {
export const ChannelButton = observer((props: ChannelProps) => {
const { active, alert, alertCount, channel, user, compact, ...divProps } =
props;
......@@ -131,7 +136,7 @@ export function ChannelButton(props: ChannelProps) {
{...divProps}
data-active={active}
data-alert={typeof alert === "string"}
aria-label={{}} /*FIXME: ADD ARIA LABEL*/
aria-label={channel.name}
className={classNames(styles.item, { [styles.compact]: compact })}
onContextMenu={attachContextMenu("Menu", {
channel: channel._id,
......@@ -147,12 +152,12 @@ export function ChannelButton(props: ChannelProps) {
{channel.channel_type === "Group" && (
<div className={styles.subText}>
{channel.last_message && alert ? (
channel.last_message.short
(channel.last_message as { short: string }).short
) : (
<Text
id="quantities.members"
plural={channel.recipients.length}
fields={{ count: channel.recipients.length }}
plural={channel.recipients!.length}
fields={{ count: channel.recipients!.length }}
/>
)}
</div>
......@@ -180,7 +185,7 @@ export function ChannelButton(props: ChannelProps) {
</div>
</div>
);
}
});
type ButtonProps = CommonProps & {
onClick?: () => void;
......
......@@ -4,9 +4,9 @@ import {
Wrench,
Notepad,
} from "@styled-icons/boxicons-solid";
import { observer } from "mobx-react-lite";
import { Link, Redirect, useLocation, useParams } from "react-router-dom";
import { Channels } from "revolt.js/dist/api/objects";
import { Users as UsersNS } from "revolt.js/dist/api/objects";
import { RelationshipStatus } from "revolt-api/types/Users";
import { Text } from "preact-i18n";
import { useContext, useEffect } from "preact/hooks";
......@@ -21,11 +21,6 @@ import { Unreads } from "../../../redux/reducers/unreads";
import { useIntermediate } from "../../../context/intermediate/Intermediate";
import { AppContext } from "../../../context/revoltjs/RevoltClient";
import {
useDMs,
useForceUpdate,
useUsers,
} from "../../../context/revoltjs/hooks";
import Category from "../../ui/Category";
import placeholderSVG from "../items/placeholder.svg";
......@@ -39,16 +34,21 @@ type Props = {
unreads: Unreads;
};
function HomeSidebar(props: Props) {
const HomeSidebar = observer((props: Props) => {
const { pathname } = useLocation();
const client = useContext(AppContext);
const { channel } = useParams<{ channel: string }>();
const { openScreen } = useIntermediate();
const ctx = useForceUpdate();
const channels = useDMs(ctx);
const channels = [...client.channels.values()]
.filter(
(x) =>
x.channel_type === "DirectMessage" ||
x.channel_type === "Group",
)
.map((x) => mapChannelWithUnread(x, props.unreads));
const obj = channels.find((x) => x?._id === channel);
const obj = client.channels.get(channel);
if (channel && !obj) return <Redirect to="/" />;
if (obj) useUnreads({ ...props, channel: obj });
......@@ -62,21 +62,7 @@ function HomeSidebar(props: Props) {
});
}, [channel]);
const channelsArr = channels
.filter((x) => x.channel_type !== "SavedMessages")
.map((x) => mapChannelWithUnread(x, props.unreads));
const users = useUsers(
(
channelsArr as (
| Channels.DirectMessageChannel
| Channels.GroupChannel
)[]
).reduce((prev: any, cur) => [...prev, ...cur.recipients], []),
ctx,
);
channelsArr.sort((b, a) => a.timestamp.localeCompare(b.timestamp));
channels.sort((b, a) => a.timestamp.localeCompare(b.timestamp));
return (
<GenericSidebarBase padding>
......@@ -98,10 +84,10 @@ function HomeSidebar(props: Props) {
<ButtonItem
active={pathname === "/friends"}
alert={
typeof users.find(
typeof [...client.users.values()].find(
(user) =>
user?.relationship ===
UsersNS.Relationship.Incoming,
RelationshipStatus.Incoming,
) !== "undefined"
? "unread"
: undefined
......@@ -143,18 +129,18 @@ function HomeSidebar(props: Props) {
})
}
/>
{channelsArr.length === 0 && <img src={placeholderSVG} />}
{channelsArr.map((x) => {
{channels.length === 0 && (
<img src={placeholderSVG} loading="eager" />
)}
{channels.map((x) => {
let user;
if (x.channel_type === "DirectMessage") {
if (!x.active) return null;
const recipient = client.channels.getRecipient(x._id);
user = users.find((x) => x?._id === recipient);
if (x.channel.channel_type === "DirectMessage") {
if (!x.channel.active) return null;
user = x.channel.recipient;
if (!user) {
console.warn(
`Skipped DM ${x._id} because user was missing.`,
`Skipped DM ${x.channel._id} because user was missing.`,
);
return null;
}
......@@ -162,14 +148,15 @@ function HomeSidebar(props: Props) {
return (
<ConditionalLink
active={x._id === channel}
to={`/channel/${x._id}`}>
key={x.channel._id}
active={x.channel._id === channel}
to={`/channel/${x.channel._id}`}>
<ChannelButton
user={user}
channel={x}
channel={x.channel}
alert={x.unread}
alertCount={x.alertCount}
active={x._id === channel}
active={x.channel._id === channel}
/>
</ConditionalLink>
);
......@@ -178,7 +165,7 @@ function HomeSidebar(props: Props) {
</GenericSidebarList>
</GenericSidebarBase>
);
}
});
export default connectState(
HomeSidebar,
......
import { Plus } from "@styled-icons/boxicons-regular";
import { useLocation, useParams } from "react-router-dom";
import { Channel, Servers } from "revolt.js/dist/api/objects";
import { observer } from "mobx-react-lite";
import { useHistory, useLocation, useParams } from "react-router-dom";
import { RelationshipStatus } from "revolt-api/types/Users";
import styled, { css } from "styled-components";
import { attachContextMenu, openContextMenu } from "preact-context-menu";
import { attachContextMenu } from "preact-context-menu";
import ConditionalLink from "../../../lib/ConditionalLink";
import PaintCounter from "../../../lib/PaintCounter";
......@@ -14,14 +15,8 @@ import { LastOpened } from "../../../redux/reducers/last_opened";
import { Unreads } from "../../../redux/reducers/unreads";
import { useIntermediate } from "../../../context/intermediate/Intermediate";
import {
useChannels,
useForceUpdate,
useSelf,
useServers,
} from "../../../context/revoltjs/hooks";
import logoSVG from "../../../assets/logo.svg";
import { useClient } from "../../../context/revoltjs/RevoltClient";
import ServerIcon from "../../common/ServerIcon";
import Tooltip from "../../common/Tooltip";
import UserHover from "../../common/user/UserHover";
......@@ -56,7 +51,7 @@ function Icon({
<circle cx="27" cy="5" r="5" fill={"white"} />
)}
{unread === "mention" && (
<circle cx="27" cy="5" r="5" fill={"red"} />
<circle cx="27" cy="5" r="5" fill={"var(--error)"} />
)}
</svg>
);
......@@ -65,6 +60,7 @@ function Icon({
const ServersBase = styled.div`
width: 56px;
height: 100%;
padding-left: 2px;
display: flex;
flex-direction: column;
......@@ -78,7 +74,8 @@ const ServerList = styled.div`
flex-grow: 1;
display: flex;
overflow-y: scroll;
padding-bottom: 48px;
padding-bottom: 20px;
/*width: 58px;*/
flex-direction: column;
scrollbar-width: none;
......@@ -90,6 +87,11 @@ const ServerList = styled.div`
&::-webkit-scrollbar {
width: 0px;
}
/*${isTouchscreenDevice &&
css`
width: 58px;
`}*/
`;
const ServerEntry = styled.div<{ active: boolean; home?: boolean }>`
......@@ -97,10 +99,13 @@ const ServerEntry = styled.div<{ active: boolean; home?: boolean }>`
display: flex;
align-items: center;
:focus {
outline: 3px solid blue;
}
> div {
height: 42px;
padding-left: 4px;
padding-right: 6px;
padding-inline-start: 6px;
display: grid;
place-items: center;
......@@ -132,11 +137,7 @@ const ServerEntry = styled.div<{ active: boolean; home?: boolean }>`
`}
svg {
width: 57px;
height: 117px;
margin-top: 4px;
display: relative;
margin-top: 5px;
pointer-events: none;
// outline: 1px solid red;
}
......@@ -153,13 +154,22 @@ function Swoosh() {
return (
<span>
<svg
xmlns="http://www.w3.org/2000/svg"
width="57"
height="117"
fill="var(--sidebar-active)">
<path d="M27.746 86.465c14 0 28 11.407 28 28s.256-56 .256-56-42.256 28-28.256 28z" />
<path d="M56 58.465c0 15.464-12.536 28-28 28s-28-12.536-28-28 12.536-28 28-28 28 12.536 28 28z" />
<path d="M28.002 30.465c14 0 28-11.407 28-28s0 56 0 56-42-28-28-28z" />
width="54"
height="106"
viewBox="0 0 54 106"
xmlns="http://www.w3.org/2000/svg">
<path
d="M54 53C54 67.9117 41.9117 80 27 80C12.0883 80 0 67.9117 0 53C0 38.0883 12.0883 26 27 26C41.9117 26 54 38.0883 54 53Z"
fill="var(--sidebar-active)"
/>
<path
d="M27 80C4.5 80 54 53 54 53L54.0001 106C54.0001 106 49.5 80 27 80Z"
fill="var(--sidebar-active)"
/>
<path
d="M27 26C4.5 26 54 53 54 53L53.9999 0C53.9999 0 49.5 26 27 26Z"
fill="var(--sidebar-active)"
/>
</svg>
</span>
);
......@@ -170,28 +180,32 @@ interface Props {
lastOpened: LastOpened;
}
export function ServerListSidebar({ unreads, lastOpened }: Props) {
const ctx = useForceUpdate();
const self = useSelf(ctx);
const activeServers = useServers(undefined, ctx) as Servers.Server[];
const channels = (useChannels(undefined, ctx) as Channel[]).map((x) =>
export const ServerListSidebar = observer(({ unreads, lastOpened }: Props) => {
const client = useClient();
const { server: server_id } = useParams<{ server?: string }>();
const server = server_id ? client.servers.get(server_id) : undefined;
const activeServers = [...client.servers.values()];
const channels = [...client.channels.values()].map((x) =>
mapChannelWithUnread(x, unreads),
);
const unreadChannels = channels.filter((x) => x.unread).map((x) => x._id);
const unreadChannels = channels
.filter((x) => x.unread)
.map((x) => x.channel?._id);
const servers = activeServers.map((server) => {
let alertCount = 0;
for (const id of server.channels) {
const channel = channels.find((x) => x._id === id);
for (const id of server.channel_ids) {
const channel = channels.find((x) => x.channel?._id === id);
if (channel?.alertCount) {
alertCount += channel.alertCount;
}
}
return {
...server,
unread: (typeof server.channels.find((x) =>
server,
unread: (typeof server.channel_ids.find((x) =>
unreadChannels.includes(x),
) !== "undefined"
? alertCount > 0
......@@ -202,18 +216,17 @@ export function ServerListSidebar({ unreads, lastOpened }: Props) {
};
});
const history = useHistory();
const path = useLocation().pathname;
const { server: server_id } = useParams<{ server?: string }>();
const server = servers.find((x) => x!._id == server_id);
const { openScreen } = useIntermediate();
let homeUnread: "mention" | "unread" | undefined;
let alertCount = 0;
for (const x of channels) {
if (
((x.channel_type === "DirectMessage" && x.active) ||
x.channel_type === "Group") &&
(x.channel?.channel_type === "DirectMessage"
? x.channel?.active
: x.channel?.channel_type === "Group") &&
x.unread
) {
homeUnread = "unread";
......@@ -221,6 +234,14 @@ export function ServerListSidebar({ unreads, lastOpened }: Props) {
}
}
if (
[...client.users.values()].find(
(x) => x.relationship === RelationshipStatus.Incoming,
)
) {
alertCount++;
}
if (alertCount > 0) homeUnread = "mention";
const homeActive =
typeof server === "undefined" && !path.startsWith("/invite");
......@@ -233,52 +254,50 @@ export function ServerListSidebar({ unreads, lastOpened }: Props) {
to={lastOpened.home ? `/channel/${lastOpened.home}` : "/"}>
<ServerEntry home active={homeActive}>
<Swoosh />
{isTouchscreenDevice ? (
<Icon size={42} unread={homeUnread}>
<img
style={{ width: 32, height: 32 }}
src={logoSVG}
/>
</Icon>
) : (
<div
onContextMenu={attachContextMenu("Status")}
onClick={() =>
homeActive && openContextMenu("Status")
}>
<UserHover user={self}>
<Icon size={42} unread={homeUnread}>
<UserIcon
target={self}
size={32}
status
/>
</Icon>
</UserHover>
</div>
)}
<div
onContextMenu={attachContextMenu("Status")}
onClick={() =>
homeActive && history.push("/settings")
}>
<UserHover user={client.user}>
<Icon size={42} unread={homeUnread}>
<UserIcon
target={client.user}
size={32}
status
hover
/>
</Icon>
</UserHover>
</div>
</ServerEntry>
</ConditionalLink>
<LineDivider />
{servers.map((entry) => {
const active = entry!._id === server?._id;
const id = lastOpened[entry!._id];
const active = entry.server._id === server?._id;
const id = lastOpened[entry.server._id];
return (
<ConditionalLink
key={entry.server._id}
active={active}
to={`/server/${entry!._id}${
to={`/server/${entry.server._id}${
id ? `/channel/${id}` : ""
}`}>
<ServerEntry
active={active}
onContextMenu={attachContextMenu("Menu", {
server: entry!._id,
server: entry.server._id,
})}>
<Swoosh />
<Tooltip content={entry.name} placement="right">
<Tooltip
content={entry.server.name}
placement="right">
<Icon size={42} unread={entry.unread}>
<ServerIcon size={32} target={entry} />
<ServerIcon
size={32}
target={entry.server}
/>
</Icon>
</Tooltip>
</ServerEntry>
......@@ -294,11 +313,20 @@ export function ServerListSidebar({ unreads, lastOpened }: Props) {
}>
<Plus size={36} />
</IconButton>
{/*<IconButton
onClick={() =>
openScreen({
id: "special_input",
type: "create_server",
})
}>
<Compass size={36} />
</IconButton>*/}
<PaintCounter small />
</ServerList>
</ServersBase>
);
}
});
export default connectState(ServerListSidebar, (state) => {
return {
......
import { observer } from "mobx-react-lite";
import { Redirect, useParams } from "react-router";
import { Channels } from "revolt.js/dist/api/objects";
import styled from "styled-components";
import styled, { css } from "styled-components";
import { attachContextMenu } from "preact-context-menu";
import { useEffect } from "preact/hooks";
import ConditionalLink from "../../../lib/ConditionalLink";
import PaintCounter from "../../../lib/PaintCounter";
import { isTouchscreenDevice } from "../../../lib/isTouchscreenDevice";
import { dispatch } from "../../../redux";
import { connectState } from "../../../redux/connector";
import { Unreads } from "../../../redux/reducers/unreads";
import {
useChannels,
useForceUpdate,
useServer,
} from "../../../context/revoltjs/hooks";
import { useClient } from "../../../context/revoltjs/RevoltClient";
import CollapsibleSection from "../../common/CollapsibleSection";
import ServerHeader from "../../common/ServerHeader";
......@@ -37,10 +34,13 @@ const ServerBase = styled.div`
flex-shrink: 0;
flex-direction: column;
background: var(--secondary-background);
border-start-start-radius: 8px;
border-end-start-radius: 8px;
overflow: hidden;
${isTouchscreenDevice &&
css`
padding-bottom: 50px;
`}
`;
const ServerList = styled.div`
......@@ -53,23 +53,17 @@ const ServerList = styled.div`
}
`;
function ServerSidebar(props: Props) {
const ServerSidebar = observer((props: Props) => {
const client = useClient();
const { server: server_id, channel: channel_id } =
useParams<{ server?: string; channel?: string }>();
const ctx = useForceUpdate();
useParams<{ server: string; channel?: string }>();
const server = useServer(server_id, ctx);
const server = client.servers.get(server_id);
if (!server) return <Redirect to="/" />;
const channels = (
useChannels(server.channels, ctx).filter(
(entry) => typeof entry !== "undefined",
) as Readonly<Channels.TextChannel | Channels.VoiceChannel>[]
).map((x) => mapChannelWithUnread(x, props.unreads));
const channel = channels.find((x) => x?._id === channel_id);
const channel = channel_id ? client.channels.get(channel_id) : undefined;
if (channel_id && !channel) return <Redirect to={`/server/${server_id}`} />;
if (channel) useUnreads({ ...props, channel }, ctx);
if (channel) useUnreads({ ...props, channel });
useEffect(() => {
if (!channel_id) return;
......@@ -79,13 +73,13 @@ function ServerSidebar(props: Props) {
parent: server_id!,
child: channel_id!,
});
}, [channel_id]);
}, [channel_id, server_id]);
const uncategorised = new Set(server.channels);
const uncategorised = new Set(server.channel_ids);
const elements = [];
function addChannel(id: string) {
const entry = channels.find((x) => x._id === id);
const entry = client.channels.get(id);
if (!entry) return;
const active = channel?._id === entry._id;
......@@ -98,7 +92,8 @@ function ServerSidebar(props: Props) {
<ChannelButton
channel={entry}
active={active}
alert={entry.unread}
// ! FIXME: pull it out directly
alert={mapChannelWithUnread(entry, props.unreads).unread}
compact
/>
</ConditionalLink>
......@@ -130,7 +125,7 @@ function ServerSidebar(props: Props) {
return (
<ServerBase>
<ServerHeader server={server} ctx={ctx} />
<ServerHeader server={server} />
<ConnectionStatus />
<ServerList
onContextMenu={attachContextMenu("Menu", {
......@@ -141,7 +136,7 @@ function ServerSidebar(props: Props) {
<PaintCounter small />
</ServerBase>
);
}
});
export default connectState(ServerSidebar, (state) => {
return {
......
import { Channel } from "revolt.js";
import { reaction } from "mobx";
import { Channel } from "revolt.js/dist/maps/Channels";
import { useLayoutEffect } from "preact/hooks";
import { dispatch } from "../../../redux";
import { Unreads } from "../../../redux/reducers/unreads";
import { HookContext, useForceUpdate } from "../../../context/revoltjs/hooks";
type UnreadProps = {
channel: Channel;
unreads: Unreads;
};
export function useUnreads(
{ channel, unreads }: UnreadProps,
context?: HookContext,
) {
const ctx = useForceUpdate(context);
export function useUnreads({ channel, unreads }: UnreadProps) {
useLayoutEffect(() => {
function checkUnread(target?: Channel) {
function checkUnread(target: Channel) {
if (!target) return;
if (target._id !== channel._id) return;
if (
......@@ -41,19 +35,16 @@ export function useUnreads(
message,
});
ctx.client.req(
"PUT",
`/channels/${channel._id}/ack/${message}` as "/channels/id/ack/id",
);
channel.ack(message);
}
}
}
checkUnread(channel);
ctx.client.channels.addListener("mutation", checkUnread);
return () =>
ctx.client.channels.removeListener("mutation", checkUnread);
return reaction(
() => channel.last_message,
() => checkUnread(channel),
);
}, [channel, unreads]);
}
......@@ -63,12 +54,12 @@ export function mapChannelWithUnread(channel: Channel, unreads: Unreads) {
channel.channel_type === "DirectMessage" ||
channel.channel_type === "Group"
) {
last_message_id = channel.last_message?._id;
last_message_id = (channel.last_message as { _id: string })?._id;
} else if (channel.channel_type === "TextChannel") {
last_message_id = channel.last_message;
last_message_id = channel.last_message as string;
} else {
return {
...channel,
channel,
unread: undefined,
alertCount: undefined,
timestamp: channel._id,
......@@ -85,7 +76,7 @@ export function mapChannelWithUnread(channel: Channel, unreads: Unreads) {
unread = "mention";
} else if (
u.last_id &&
last_message_id.localeCompare(u.last_id) > 0
(last_message_id as string).localeCompare(u.last_id) > 0
) {
unread = "unread";
}
......@@ -95,7 +86,7 @@ export function mapChannelWithUnread(channel: Channel, unreads: Unreads) {
}
return {
...channel,
channel,
timestamp: last_message_id ?? channel._id,
unread,
alertCount,
......
/* eslint-disable react-hooks/rules-of-hooks */
import { useRenderState } from "../../../lib/renderer/Singleton";
interface Props {
......
import { useParams } from "react-router";
import { Link } from "react-router-dom";
import { User } from "revolt.js";
import { Channels, Message, Servers, Users } from "revolt.js/dist/api/objects";
import { ClientboundNotification } from "revolt.js/dist/websocket/notifications";
/* eslint-disable react-hooks/rules-of-hooks */
import { observer } from "mobx-react-lite";
import { Link, useParams } from "react-router-dom";
import { Presence } from "revolt-api/types/Users";
import { Channel } from "revolt.js/dist/maps/Channels";
import { Message } from "revolt.js/dist/maps/Messages";
import { Text } from "preact-i18n";
import { useContext, useEffect, useState } from "preact/hooks";
......@@ -11,18 +12,13 @@ import { getState } from "../../../redux";
import { useIntermediate } from "../../../context/intermediate/Intermediate";
import {
AppContext,
ClientStatus,
StatusContext,
useClient,
} from "../../../context/revoltjs/RevoltClient";
import {
HookContext,
useChannel,
useForceUpdate,
useUsers,
} from "../../../context/revoltjs/hooks";
import CollapsibleSection from "../../common/CollapsibleSection";
import Button from "../../ui/Button";
import Category from "../../ui/Category";
import InputBox from "../../ui/InputBox";
import Preloader from "../../ui/Preloader";
......@@ -32,36 +28,30 @@ import { GenericSidebarBase, GenericSidebarList } from "../SidebarBase";
import { UserButton } from "../items/ButtonItem";
import { ChannelDebugInfo } from "./ChannelDebugInfo";
interface Props {
ctx: HookContext;
}
export default function MemberSidebar(props: { channel?: Channels.Channel }) {
const ctx = useForceUpdate();
const { channel: cid } = useParams<{ channel: string }>();
const channel = props.channel ?? useChannel(cid, ctx);
export default function MemberSidebar({ channel: obj }: { channel?: Channel }) {
const { channel: channel_id } = useParams<{ channel: string }>();
const client = useClient();
const channel = obj ?? client.channels.get(channel_id);
switch (channel?.channel_type) {
case "Group":
return <GroupMemberSidebar channel={channel} ctx={ctx} />;
return <GroupMemberSidebar channel={channel} />;
case "TextChannel":
return <ServerMemberSidebar channel={channel} ctx={ctx} />;
return <ServerMemberSidebar channel={channel} />;
default:
return null;
}
}
export function GroupMemberSidebar({
channel,
ctx,
}: Props & { channel: Channels.GroupChannel }) {
const { openScreen } = useIntermediate();
const users = useUsers(undefined, ctx);
const members = channel.recipients
.map((x) => users.find((y) => y?._id === x))
.filter((x) => typeof x !== "undefined") as User[];
/*const voice = useContext(VoiceContext);
export const GroupMemberSidebar = observer(
({ channel }: { channel: Channel }) => {
const { openScreen } = useIntermediate();
const members = channel.recipients?.filter(
(x) => typeof x !== "undefined",
);
/*const voice = useContext(VoiceContext);
const voiceActive = voice.roomId === channel._id;
let voiceParticipants: User[] = [];
......@@ -76,34 +66,34 @@ export function GroupMemberSidebar({
voiceParticipants.sort((a, b) => a.username.localeCompare(b.username));
}*/
members.sort((a, b) => {
// ! FIXME: should probably rewrite all this code
const l =
+(
(a.online && a.status?.presence !== Users.Presence.Invisible) ??
false
) | 0;
const r =
+(
(b.online && b.status?.presence !== Users.Presence.Invisible) ??
false
) | 0;
const n = r - l;
if (n !== 0) {
return n;
}
return a.username.localeCompare(b.username);
});
members?.sort((a, b) => {
// ! FIXME: should probably rewrite all this code
const l =
+(
(a!.online && a!.status?.presence !== Presence.Invisible) ??
false
) | 0;
const r =
+(
(b!.online && b!.status?.presence !== Presence.Invisible) ??
false
) | 0;
const n = r - l;
if (n !== 0) {
return n;
}
return (
<GenericSidebarBase>
<GenericSidebarList>
<ChannelDebugInfo id={channel._id} />
<Search channel={channel._id} />
return a!.username.localeCompare(b!.username);
});
return (
<GenericSidebarBase>
<GenericSidebarList>
<ChannelDebugInfo id={channel._id} />
<Search channel={channel} />
{/*voiceActive && voiceParticipants.length !== 0 && (
{/*voiceActive && voiceParticipants.length !== 0 && (
<Fragment>
<Category
type="members"
......@@ -128,142 +118,31 @@ export function GroupMemberSidebar({
)}
</Fragment>
)*/}
<CollapsibleSection
sticky
id="members"
defaultValue
summary={
<Category
variant="uniform"
text={
<span>
<Text id="app.main.categories.members" />{" "}
{channel.recipients.length}
</span>
}
/>
}>
{members.length === 0 && <img src={placeholderSVG} />}
{members.map(
(user) =>
user && (
<UserButton
key={user._id}
user={user}
context={channel}
onClick={() =>
openScreen({
id: "profile",
user_id: user._id,
})
}
/>
),
)}
</CollapsibleSection>
</GenericSidebarList>
</GenericSidebarBase>
);
}
export function ServerMemberSidebar({
channel,
ctx,
}: Props & { channel: Channels.TextChannel }) {
const [members, setMembers] = useState<Servers.Member[] | undefined>(
undefined,
);
const users = useUsers(members?.map((x) => x._id.user) ?? []).filter(
(x) => typeof x !== "undefined",
ctx,
) as Users.User[];
const { openScreen } = useIntermediate();
const status = useContext(StatusContext);
const client = useContext(AppContext);
useEffect(() => {
if (status === ClientStatus.ONLINE && typeof members === "undefined") {
client.servers.members
.fetchMembers(channel.server)
.then((members) => setMembers(members));
}
}, [status]);
// ! FIXME: temporary code
useEffect(() => {
function onPacket(packet: ClientboundNotification) {
if (!members) return;
if (packet.type === "ServerMemberJoin") {
if (packet.id !== channel.server) return;
setMembers([
...members,
{ _id: { server: packet.id, user: packet.user } },
]);
} else if (packet.type === "ServerMemberLeave") {
if (packet.id !== channel.server) return;
setMembers(
members.filter(
(x) =>
!(
x._id.user === packet.user &&
x._id.server === packet.id
),
),
);
}
}
client.addListener("packet", onPacket);
return () => client.removeListener("packet", onPacket);
}, [members]);
// copy paste from above
users.sort((a, b) => {
// ! FIXME: should probably rewrite all this code
const l =
+(
(a.online && a.status?.presence !== Users.Presence.Invisible) ??
false
) | 0;
const r =
+(
(b.online && b.status?.presence !== Users.Presence.Invisible) ??
false
) | 0;
const n = r - l;
if (n !== 0) {
return n;
}
return a.username.localeCompare(b.username);
});
return (
<GenericSidebarBase>
<GenericSidebarList>
<ChannelDebugInfo id={channel._id} />
<Search channel={channel._id} />
<div>{!members && <Preloader type="ring" />}</div>
{members && (
<CollapsibleSection
//sticky //will re-add later, need to fix css
sticky
id="members"
defaultValue
summary={
<span>
<Text id="app.main.categories.members" />{" "}
{users.length}
</span>
<Category
variant="uniform"
text={
<span>
<Text id="app.main.categories.members" />{" "}
{channel.recipients?.length ?? 0}
</span>
}
/>
}>
{users.length === 0 && <img src={placeholderSVG} />}
{users.map(
{members?.length === 0 && (
<img src={placeholderSVG} loading="eager" />
)}
{members?.map(
(user) =>
user && (
<UserButton
key={user._id}
user={user}
context={channel}
context={channel!}
onClick={() =>
openScreen({
id: "profile",
......@@ -274,25 +153,104 @@ export function ServerMemberSidebar({
),
)}
</CollapsibleSection>
)}
</GenericSidebarList>
</GenericSidebarBase>
);
}
</GenericSidebarList>
</GenericSidebarBase>
);
},
);
export const ServerMemberSidebar = observer(
({ channel }: { channel: Channel }) => {
const client = useClient();
const { openScreen } = useIntermediate();
const status = useContext(StatusContext);
useEffect(() => {
if (status === ClientStatus.ONLINE) {
channel.server!.fetchMembers();
}
}, [status, channel.server]);
const users = [...client.members.keys()]
.map((x) => JSON.parse(x))
.filter((x) => x.server === channel.server_id)
.map((y) => client.users.get(y.user)!)
.filter((z) => typeof z !== "undefined");
// copy paste from above
users.sort((a, b) => {
// ! FIXME: should probably rewrite all this code
const l =
+(
(a.online && a.status?.presence !== Presence.Invisible) ??
false
) | 0;
const r =
+(
(b.online && b.status?.presence !== Presence.Invisible) ??
false
) | 0;
const n = r - l;
if (n !== 0) {
return n;
}
return a.username.localeCompare(b.username);
});
return (
<GenericSidebarBase>
<GenericSidebarList>
<ChannelDebugInfo id={channel._id} />
<Search channel={channel} />
<div>{users.length === 0 && <Preloader type="ring" />}</div>
{users.length > 0 && (
<CollapsibleSection
//sticky //will re-add later, need to fix css
id="members"
defaultValue
summary={
<span>
<Text id="app.main.categories.members" />{" "}
{users?.length ?? 0}
</span>
}>
{users.map(
(user) =>
user && (
<UserButton
key={user._id}
user={user}
context={channel}
onClick={() =>
openScreen({
id: "profile",
user_id: user._id,
})
}
/>
),
)}
</CollapsibleSection>
)}
</GenericSidebarList>
</GenericSidebarBase>
);
},
);
function Search({ channel }: { channel: string }) {
function Search({ channel }: { channel: Channel }) {
if (!getState().experiments.enabled?.includes("search")) return null;
const client = useContext(AppContext);
type Sort = "Relevance" | "Latest" | "Oldest";
const [sort, setSort] = useState<Sort>("Relevance");
const [query, setV] = useState("");
const [results, setResults] = useState<Message[]>([]);
async function search() {
const data = await client.channels.searchWithUsers(
channel,
{ query, sort: "Relevance" },
true,
);
const data = await channel.searchWithUsers({ query, sort });
setResults(data.messages);
}
......@@ -301,7 +259,25 @@ function Search({ channel }: { channel: string }) {
sticky
id="search"
defaultValue={false}
summary={"Search (BETA)"}>
summary={
<>
<Text id="app.main.channel.search.title" /> (BETA)
</>
}>
<div style={{ display: "flex" }}>
{["Relevance", "Latest", "Oldest"].map((key) => (
<Button
key={key}
style={{ flex: 1, minWidth: 0 }}
compact
error={sort === key}
onClick={() => setSort(key as Sort)}>
<Text
id={`app.main.channel.search.sort.${key.toLowerCase()}`}
/>
</Button>
))}
</div>
<InputBox
style={{ width: "100%" }}
onKeyDown={(e) => e.key === "Enter" && search()}
......@@ -317,25 +293,21 @@ function Search({ channel }: { channel: string }) {
}}>
{results.map((message) => {
let href = "";
const channel = client.channels.get(message.channel);
if (channel?.channel_type === "TextChannel") {
href += `/server/${channel.server}`;
href += `/server/${channel.server_id}`;
}
href += `/channel/${message.channel}/${message._id}`;
href += `/channel/${message.channel_id}/${message._id}`;
return (
<Link to={href}>
<Link to={href} key={message._id}>
<div
style={{
margin: "2px",
padding: "6px",
background: "var(--primary-background)",
}}>
<b>
@
{client.users.get(message.author)?.username}
</b>
<b>@{message.author?.username}</b>
<br />
{message.content}
</div>
......
......@@ -6,6 +6,7 @@ interface Props {
readonly contrast?: boolean;
readonly plain?: boolean;
readonly error?: boolean;
readonly gold?: boolean;
readonly iconbutton?: boolean;
}
......@@ -125,4 +126,22 @@ export default styled.button<Props>`
background: var(--error);
}
`}
${(props) =>
props.gold &&
css`
color: black;
font-weight: 600;
background: goldenrod;
&:hover {
filter: brightness(1.2);
background: goldenrod;
}
&:disabled {
cursor: not-allowed;
background: goldenrod;
}
`}
`;
/* eslint-disable react-hooks/rules-of-hooks */
import styled, { css, keyframes } from "styled-components";
import { createPortal, useEffect, useState } from "preact/compat";
import { createPortal, useCallback, useEffect, useState } from "preact/compat";
import { internalSubscribe } from "../../lib/eventEmitter";
......@@ -134,7 +135,7 @@ interface Props {
dontModal?: boolean;
padding?: boolean;
onClose: () => void;
onClose?: () => void;
actions?: Action[];
disabled?: boolean;
border?: boolean;
......@@ -163,12 +164,12 @@ export default function Modal(props: Props) {
const [animateClose, setAnimateClose] = useState(false);
isModalClosing = animateClose;
function onClose() {
const onClose = useCallback(() => {
setAnimateClose(true);
setTimeout(() => props.onClose(), 2e2);
}
setTimeout(() => props.onClose?.(), 2e2);
}, [setAnimateClose, props]);
useEffect(() => internalSubscribe("Modal", "close", onClose), []);
useEffect(() => internalSubscribe("Modal", "close", onClose), [onClose]);
useEffect(() => {
if (props.disallowClosing) return;
......@@ -181,7 +182,7 @@ export default function Modal(props: Props) {
document.body.addEventListener("keydown", keyDown);
return () => document.body.removeEventListener("keydown", keyDown);
}, [props.disallowClosing, props.onClose]);
}, [props.disallowClosing, onClose]);
const confirmationAction = props.actions?.find(
(action) => action.confirmation,
......@@ -190,7 +191,7 @@ export default function Modal(props: Props) {
useEffect(() => {
if (!confirmationAction) return;
// ! FIXME: this may be done better if we
// ! TODO: this may be done better if we
// ! can focus the button although that
// ! doesn't seem to work...
function keyDown(e: KeyboardEvent) {
......@@ -211,8 +212,12 @@ export default function Modal(props: Props) {
{content}
{props.actions && (
<ModalActions>
{props.actions.map((x) => (
<Button {...x} disabled={props.disabled} />
{props.actions.map((x, index) => (
<Button
key={index}
{...x}
disabled={props.disabled}
/>
))}
</ModalActions>
)}
......
......@@ -8,13 +8,19 @@ type Props = Omit<JSX.HTMLAttributes<HTMLDivElement>, "children" | "as"> & {
error?: string;
block?: boolean;
spaced?: boolean;
noMargin?: boolean;
children?: Children;
type?: "default" | "subtle" | "error";
};
const OverlineBase = styled.div<Omit<Props, "children" | "error">>`
display: inline;
margin: 0.4em 0;
${(props) =>
!props.noMargin &&
css`
margin: 0.4em 0;
`}
${(props) =>
props.spaced &&
......
......@@ -48,7 +48,7 @@ export default styled.textarea<TextAreaProps>`
${(props) =>
props.code
? css`
font-family: var(--monoscape-font), monospace;
font-family: var(--monospace-font), monospace;
`
: css`
font-family: inherit;
......
......@@ -55,14 +55,16 @@ export const TipBase = styled.div<Props>`
`}
`;
export default function Tip(props: Props & { children: Children }) {
const { children, ...tipProps } = props;
export default function Tip(
props: Props & { children: Children; hideSeparator?: boolean },
) {
const { children, hideSeparator, ...tipProps } = props;
return (
<>
<Separator />
{!hideSeparator && <Separator />}
<TipBase {...tipProps}>
<InfoCircle size={20} />
<span>{props.children}</span>
<span>{children}</span>
</TipBase>
</>
);
......
import { ChevronRight, LinkExternal } from "@styled-icons/boxicons-regular";
import styled, { css } from "styled-components";
import { Children } from "../../../types/Preact";
interface BaseProps {
readonly hover?: boolean;
readonly account?: boolean;
readonly disabled?: boolean;
readonly largeDescription?: boolean;
}
const CategoryBase = styled.div<BaseProps>`
/*height: 54px;*/
padding: 9.8px 12px;
border-radius: 6px;
margin-bottom: 10px;
color: var(--foreground);
background: var(--secondary-header);
gap: 12px;
display: flex;
align-items: center;
flex-direction: row;
> svg {
flex-shrink: 0;
}
.content {
display: flex;
flex-grow: 1;
flex-direction: column;
font-weight: 600;
font-size: 14px;
.title {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
}
.description {
${(props) =>
props.largeDescription
? css`
font-size: 14px;
`
: css`
font-size: 11px;
`}
font-weight: 400;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
overflow: hidden;
a:hover {
text-decoration: underline;
}
}
}
${(props) =>
props.hover &&
css`
cursor: pointer;
opacity: 1;
transition: 0.1s ease background-color;
&:hover {
background: var(--secondary-background);
}
`}
${(props) =>
props.disabled &&
css`
opacity: 0.4;
/*.content,
.action {
color: var(--tertiary-foreground);
}*/
.action {
font-size: 14px;
}
`}
${(props) =>
props.account &&
css`
height: 54px;
.content {
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
.title {
text-transform: uppercase;
font-size: 12px;
color: var(--secondary-foreground);
}
.description {
font-size: 15px;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
}
`}
`;
interface Props extends BaseProps {
icon?: Children;
children?: Children;
description?: Children;
onClick?: () => void;
action?: "chevron" | "external" | Children;
}
export default function CategoryButton({
icon,
children,
description,
account,
disabled,
onClick,
hover,
action,
}: Props) {
return (
<CategoryBase
hover={hover || typeof onClick !== "undefined"}
onClick={onClick}
disabled={disabled}
account={account}>
{icon}
<div class="content">
<div className="title">{children}</div>
<div className="description">{description}</div>
</div>
<div class="action">
{typeof action === "string" ? (
action === "chevron" ? (
<ChevronRight size={24} />
) : (
<LinkExternal size={20} />
)
) : (
action
)}
</div>
</CategoryBase>
);
}
......@@ -5,7 +5,7 @@ import update from "dayjs/plugin/updateLocale";
import defaultsDeep from "lodash.defaultsdeep";
import { IntlProvider } from "preact-i18n";
import { useEffect, useState } from "preact/hooks";
import { useCallback, useEffect, useState } from "preact/hooks";
import { connectState } from "../redux/connector";
......@@ -32,6 +32,7 @@ export enum Language {
CROATIAN = "hr",
HUNGARIAN = "hu",
INDONESIAN = "id",
ITALIAN = "it",
LITHUANIAN = "lt",
MACEDONIAN = "mk",
DUTCH = "nl",
......@@ -41,6 +42,7 @@ export enum Language {
RUSSIAN = "ru",
SERBIAN = "sr",
SWEDISH = "sv",
TOKIPONA = "tokipona",
TURKISH = "tr",
UKRANIAN = "uk",
CHINESE_SIMPLIFIED = "zh_Hans",
......@@ -57,7 +59,7 @@ export interface LanguageEntry {
i18n: string;
dayjs?: string;
rtl?: boolean;
alt?: boolean;
cat?: "const" | "alt";
}
export const Languages: { [key in Language]: LanguageEntry } = {
......@@ -78,8 +80,9 @@ export const Languages: { [key in Language]: LanguageEntry } = {
fr: { display: "Français", emoji: "🇫🇷", i18n: "fr" },
hi: { display: "हिन्दी", emoji: "🇮🇳", i18n: "hi" },
hr: { display: "Hrvatski", emoji: "🇭🇷", i18n: "hr" },
hu: { display: "magyar", emoji: "🇭🇺", i18n: "hu" },
hu: { display: "Magyar", emoji: "🇭🇺", i18n: "hu" },
id: { display: "bahasa Indonesia", emoji: "🇮🇩", i18n: "id" },
it: { display: "Italiano", emoji: "🇮🇹", i18n: "it" },
lt: { display: "Lietuvių", emoji: "🇱🇹", i18n: "lt" },
mk: { display: "Македонски", emoji: "🇲🇰", i18n: "mk" },
nl: { display: "Nederlands", emoji: "🇳🇱", i18n: "nl" },
......@@ -103,33 +106,41 @@ export const Languages: { [key in Language]: LanguageEntry } = {
dayjs: "zh",
},
tokipona: {
display: "Toki Pona",
emoji: "🙂",
i18n: "tokipona",
dayjs: "en-gb",
cat: "const",
},
owo: {
display: "OwO",
emoji: "🐱",
i18n: "owo",
dayjs: "en-gb",
alt: true,
cat: "alt",
},
pr: {
display: "Pirate",
emoji: "🏴‍☠️",
i18n: "pr",
dayjs: "en-gb",
alt: true,
cat: "alt",
},
bottom: {
display: "Bottom",
emoji: "🥺",
i18n: "bottom",
dayjs: "en-gb",
alt: true,
cat: "alt",
},
piglatin: {
display: "Pig Latin",
emoji: "🐖",
i18n: "piglatin",
dayjs: "en-gb",
alt: true,
cat: "alt",
},
};
......@@ -138,32 +149,62 @@ interface Props {
locale: Language;
}
export interface Dictionary {
dayjs?: {
defaults?: {
twelvehour?: "yes" | "no";
separator?: string;
date?: "traditional" | "simplified" | "ISO8601";
};
timeFormat?: string;
};
[key: string]:
| Record<string, Omit<Dictionary, "dayjs">>
| string
| undefined;
}
function Locale({ children, locale }: Props) {
// TODO: create and use LanguageDefinition type here
const [defns, setDefinition] =
useState<Record<string, unknown>>(definition);
const lang = Languages[locale];
const [defns, setDefinition] = useState<Dictionary>(
definition as Dictionary,
);
// Load relevant language information, fallback to English if invalid.
const lang = Languages[locale] ?? Languages.en;
// TODO: clean this up and use the built in Intl API
function transformLanguage(source: { [key: string]: any }) {
function transformLanguage(source: Dictionary) {
// Fallback untranslated strings to English (UK)
const obj = defaultsDeep(source, definition);
const dayjs = obj.dayjs;
const defaults = dayjs.defaults;
const twelvehour = defaults?.twelvehour === "yes" || true;
// Take relevant objects out, dayjs and defaults
// should exist given we just took defaults above.
const { dayjs } = obj;
const { defaults } = dayjs;
// Determine whether we are using 12-hour clock.
const twelvehour = defaults?.twelvehour
? defaults.twelvehour === "yes"
: false;
// Determine what date separator we are using.
const separator: string = defaults?.date_separator ?? "/";
// Determine what date format we are using.
const date: "traditional" | "simplified" | "ISO8601" =
defaults?.date_format ?? "traditional";
// Available date formats.
const DATE_FORMATS = {
traditional: `DD${separator}MM${separator}YYYY`,
simplified: `MM${separator}DD${separator}YYYY`,
ISO8601: "YYYY-MM-DD",
};
dayjs["sameElse"] = DATE_FORMATS[date];
// Replace data in dayjs object, make sure to provide fallbacks.
dayjs["sameElse"] = DATE_FORMATS[date] ?? DATE_FORMATS.traditional;
dayjs["timeFormat"] = twelvehour ? "hh:mm A" : "HH:mm";
// Replace {{time}} format string in dayjs strings with the time format.
Object.keys(dayjs)
.filter((k) => typeof dayjs[k] === "string")
.forEach(
......@@ -177,35 +218,49 @@ function Locale({ children, locale }: Props) {
return obj;
}
useEffect(() => {
if (locale === "en") {
const defn = transformLanguage(definition);
setDefinition(defn);
dayjs.locale("en");
dayjs.updateLocale("en", { calendar: defn.dayjs });
return;
}
import(`../../external/lang/${lang.i18n}.json`).then(
async (lang_file) => {
const defn = transformLanguage(lang_file.default);
const target = lang.dayjs ?? lang.i18n;
const dayjs_locale = await import(
`../../node_modules/dayjs/esm/locale/${target}.js`
);
dayjs.locale(target, dayjs_locale.default);
if (defn.dayjs) {
dayjs.updateLocale(target, { calendar: defn.dayjs });
}
const loadLanguage = useCallback(
(locale: string) => {
if (locale === "en") {
// If English, make sure to restore everything to defaults.
// Use what we already have.
const defn = transformLanguage(definition as Dictionary);
setDefinition(defn);
},
);
}, [locale, lang]);
dayjs.locale("en");
dayjs.updateLocale("en", { calendar: defn.dayjs });
return;
}
import(`../../external/lang/${lang.i18n}.json`).then(
async (lang_file) => {
// Transform the definitions data.
const defn = transformLanguage(lang_file.default);
// Determine and load dayjs locales.
const target = lang.dayjs ?? lang.i18n;
const dayjs_locale = await import(
`../../node_modules/dayjs/esm/locale/${target}.js`
);
// Load dayjs locales.
dayjs.locale(target, dayjs_locale.default);
if (defn.dayjs) {
// Override dayjs calendar locales with our own.
dayjs.updateLocale(target, { calendar: defn.dayjs });
}
// Apply definition to app.
setDefinition(defn);
},
);
},
[lang.dayjs, lang.i18n],
);
useEffect(() => loadLanguage(locale), [locale, lang, loadLanguage]);
useEffect(() => {
// Apply RTL language format.
document.body.style.direction = lang.rtl ? "rtl" : "";
}, [lang.rtl]);
......
......@@ -4,8 +4,6 @@ import { createGlobalStyle } from "styled-components";
import { createContext } from "preact";
import { useEffect } from "preact/hooks";
import { isTouchscreenDevice } from "../lib/isTouchscreenDevice";
import { connectState } from "../redux/connector";
import { Children } from "../types/Preact";
......@@ -57,7 +55,7 @@ export type Fonts =
| "Raleway"
| "Ubuntu"
| "Comic Neue";
export type MonoscapeFonts =
export type MonospaceFonts =
| "Fira Code"
| "Roboto Mono"
| "Source Code Pro"
......@@ -70,7 +68,7 @@ export type Theme = {
light?: boolean;
font?: Fonts;
css?: string;
monoscapeFont?: MonoscapeFonts;
monospaceFont?: MonospaceFonts;
};
export interface ThemeOptions {
......@@ -190,8 +188,8 @@ export const FONTS: Record<Fonts, { name: string; load: () => void }> = {
},
};
export const MONOSCAPE_FONTS: Record<
MonoscapeFonts,
export const MONOSPACE_FONTS: Record<
MonospaceFonts,
{ name: string; load: () => void }
> = {
"Fira Code": {
......@@ -217,7 +215,7 @@ export const MONOSCAPE_FONTS: Record<
};
export const FONT_KEYS = Object.keys(FONTS).sort();
export const MONOSCAPE_FONT_KEYS = Object.keys(MONOSCAPE_FONTS).sort();
export const MONOSPACE_FONT_KEYS = Object.keys(MONOSPACE_FONTS).sort();
export const DEFAULT_FONT = "Open Sans";
export const DEFAULT_MONO_FONT = "Fira Code";
......@@ -311,17 +309,17 @@ function Theme({ children, options }: Props) {
const font = theme.font ?? DEFAULT_FONT;
root.setProperty("--font", `"${font}"`);
FONTS[font].load();
}, [theme.font]);
}, [root, theme.font]);
useEffect(() => {
const font = theme.monoscapeFont ?? DEFAULT_MONO_FONT;
root.setProperty("--monoscape-font", `"${font}"`);
MONOSCAPE_FONTS[font].load();
}, [theme.monoscapeFont]);
const font = theme.monospaceFont ?? DEFAULT_MONO_FONT;
root.setProperty("--monospace-font", `"${font}"`);
MONOSPACE_FONTS[font].load();
}, [root, theme.monospaceFont]);
useEffect(() => {
root.setProperty("--ligatures", options?.ligatures ? "normal" : "none");
}, [options?.ligatures]);
}, [root, options?.ligatures]);
useEffect(() => {
const resize = () =>
......@@ -330,7 +328,7 @@ function Theme({ children, options }: Props) {
window.addEventListener("resize", resize);
return () => window.removeEventListener("resize", resize);
}, []);
}, [root]);
return (
<ThemeContext.Provider value={theme}>
......
This diff is collapsed.