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 465 additions and 191 deletions
......@@ -44,7 +44,7 @@ type Props = Omit<
};
export default function Category(props: Props) {
let { text, action, ...otherProps } = props;
const { text, action, ...otherProps } = props;
return (
<CategoryBase {...otherProps}>
......
......@@ -4,12 +4,12 @@ import styled, { css } from "styled-components";
import { Children } from "../../types/Preact";
const CheckboxBase = styled.label`
margin-top: 20px;
gap: 4px;
z-index: 1;
display: flex;
border-radius: 4px;
margin-top: 20px;
align-items: center;
border-radius: var(--border-radius);
cursor: pointer;
font-size: 18px;
......@@ -57,9 +57,9 @@ const Checkmark = styled.div<{ checked: boolean }>`
height: 24px;
display: grid;
flex-shrink: 0;
border-radius: 4px;
place-items: center;
transition: 0.2s ease all;
border-radius: var(--border-radius);
background: var(--secondary-background);
svg {
......
......@@ -55,7 +55,11 @@ const SwatchesBase = styled.div`
div {
width: 8px;
height: 68px;
background: linear-gradient(to right, var(--primary-background), transparent);
background: linear-gradient(
to right,
var(--primary-background),
transparent
);
}
}
`;
......@@ -63,7 +67,7 @@ const SwatchesBase = styled.div`
const Swatch = styled.div<{ type: "small" | "large"; colour: string }>`
flex-shrink: 0;
cursor: pointer;
border-radius: 4px;
border-radius: var(--border-radius);
background-color: ${(props) => props.colour};
display: grid;
......@@ -127,8 +131,10 @@ export default function ColourSwatches({ value, onChange }: Props) {
<Palette size={32} />
</Swatch>
<div class="overlay"><div /></div>
<div class="overlay">
<div />
</div>
<Rows>
{presets.map((row, i) => (
<div key={i}>
......@@ -144,8 +150,6 @@ export default function ColourSwatches({ value, onChange }: Props) {
</div>
))}
</Rows>
</SwatchesBase>
);
}
import styled from "styled-components";
export default styled.select`
width: 100%;
padding: 10px;
border-radius: 6px;
cursor: pointer;
border-radius: var(--border-radius);
font-family: inherit;
font-size: var(--text-size);
color: var(--secondary-foreground);
background: var(--secondary-background);
font-size: var(--text-size);
border: none;
outline: 2px solid transparent;
transition: outline-color 0.2s ease-in-out;
transition: box-shadow 0.2s ease-in-out;
cursor: pointer;
width: 100%;
transition: outline-color 0.2s ease-in-out;
&:focus {
box-shadow: 0 0 0 1.5pt var(--accent);
......
......@@ -12,8 +12,8 @@ const Base = styled.div<{ unread?: boolean }>`
time {
margin-top: -2px;
font-size: .6875rem;
line-height: .6875rem;
font-size: 0.6875rem;
line-height: 0.6875rem;
padding: 2px 0 2px 0;
padding-inline-end: 5px;
color: var(--tertiary-foreground);
......
......@@ -6,9 +6,9 @@ interface Props {
export default styled.input<Props>`
z-index: 1;
padding: 8px 16px;
border-radius: 6px;
font-size: 1rem;
padding: 8px 16px;
border-radius: var(--border-radius);
font-family: inherit;
color: var(--foreground);
......
/* 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";
import { Children } from "../../types/Preact";
import Button, { ButtonProps } from "./Button";
import { internalSubscribe } from "../../lib/eventEmitter";
const open = keyframes`
0% {opacity: 0;}
......@@ -52,7 +54,7 @@ const ModalBase = styled.div`
&.closing {
animation-name: ${close};
}
&.closing > div {
animation-name: ${zoomOut};
}
......@@ -60,8 +62,8 @@ const ModalBase = styled.div`
const ModalContainer = styled.div`
overflow: hidden;
border-radius: 8px;
max-width: calc(100vw - 20px);
border-radius: var(--border-radius);
animation-name: ${zoomIn};
animation-duration: 0.25s;
......@@ -71,8 +73,8 @@ const ModalContainer = styled.div`
const ModalContent = styled.div<
{ [key in "attachment" | "noBackground" | "border" | "padding"]?: boolean }
>`
border-radius: 8px;
text-overflow: ellipsis;
border-radius: var(--border-radius);
h3 {
margin-top: 0;
......@@ -98,13 +100,13 @@ const ModalContent = styled.div<
${(props) =>
props.attachment &&
css`
border-radius: 8px 8px 0 0;
border-radius: var(--border-radius) var(--border-radius) 0 0;
`}
${(props) =>
props.border &&
css`
border-radius: 10px;
border-radius: var(--border-radius);
border: 2px solid var(--secondary-background);
`}
`;
......@@ -133,7 +135,7 @@ interface Props {
dontModal?: boolean;
padding?: boolean;
onClose: () => void;
onClose?: () => void;
actions?: Action[];
disabled?: boolean;
border?: boolean;
......@@ -145,7 +147,7 @@ export let isModalClosing = false;
export default function Modal(props: Props) {
if (!props.visible) return null;
let content = (
const content = (
<ModalContent
attachment={!!props.actions}
noBackground={props.noBackground}
......@@ -162,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;
......@@ -180,16 +182,16 @@ export default function Modal(props: Props) {
document.body.addEventListener("keydown", keyDown);
return () => document.body.removeEventListener("keydown", keyDown);
}, [props.disallowClosing, props.onClose]);
}, [props.disallowClosing, onClose]);
let confirmationAction = props.actions?.find(
const confirmationAction = props.actions?.find(
(action) => action.confirmation,
);
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) {
......@@ -203,14 +205,19 @@ export default function Modal(props: Props) {
}, [confirmationAction]);
return createPortal(
<ModalBase className={animateClose ? 'closing' : undefined}
<ModalBase
className={animateClose ? "closing" : undefined}
onClick={(!props.disallowClosing && props.onClose) || undefined}>
<ModalContainer onClick={(e) => (e.cancelBubble = true)}>
{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 &&
......
......@@ -27,8 +27,8 @@ const RadioBase = styled.label<BaseProps>`
font-size: 1rem;
font-weight: 600;
user-select: none;
border-radius: 4px;
transition: 0.2s ease all;
border-radius: var(--border-radius);
&:hover {
background: var(--hover);
......
......@@ -30,7 +30,7 @@ export default styled.textarea<TextAreaProps>`
${(props) =>
!props.hideBorder &&
css`
border-radius: 4px;
border-radius: var(--border-radius);
transition: border-color 0.2s ease-in-out;
border: var(--input-border-width) solid transparent;
`}
......@@ -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;
......
......@@ -22,8 +22,8 @@ export const TipBase = styled.div<Props>`
align-items: center;
font-size: 14px;
border-radius: 7px;
background: var(--primary-header);
border-radius: var(--border-radius);
border: 2px solid var(--secondary-header);
a {
......@@ -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";
......@@ -24,6 +24,7 @@ export enum Language {
AZERBAIJANI = "az",
CZECH = "cs",
GERMAN = "de",
GREEK = "el",
SPANISH = "es",
FINNISH = "fi",
FRENCH = "fr",
......@@ -31,6 +32,7 @@ export enum Language {
CROATIAN = "hr",
HUNGARIAN = "hu",
INDONESIAN = "id",
ITALIAN = "it",
LITHUANIAN = "lt",
MACEDONIAN = "mk",
DUTCH = "nl",
......@@ -40,6 +42,7 @@ export enum Language {
RUSSIAN = "ru",
SERBIAN = "sr",
SWEDISH = "sv",
TOKIPONA = "tokipona",
TURKISH = "tr",
UKRANIAN = "uk",
CHINESE_SIMPLIFIED = "zh_Hans",
......@@ -56,7 +59,7 @@ export interface LanguageEntry {
i18n: string;
dayjs?: string;
rtl?: boolean;
alt?: boolean;
cat?: "const" | "alt";
}
export const Languages: { [key in Language]: LanguageEntry } = {
......@@ -71,13 +74,15 @@ export const Languages: { [key in Language]: LanguageEntry } = {
az: { display: "Azərbaycan dili", emoji: "🇦🇿", i18n: "az" },
cs: { display: "Čeština", emoji: "🇨🇿", i18n: "cs" },
de: { display: "Deutsch", emoji: "🇩🇪", i18n: "de" },
el: { display: "Ελληνικά", emoji: "🇬🇷", i18n: "el" },
es: { display: "Español", emoji: "🇪🇸", i18n: "es" },
fi: { display: "suomi", emoji: "🇫🇮", i18n: "fi" },
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" },
......@@ -101,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",
},
};
......@@ -136,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(
......@@ -175,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,13 +328,12 @@ function Theme({ children, options }: Props) {
window.addEventListener("resize", resize);
return () => window.removeEventListener("resize", resize);
}, []);
}, [root]);
return (
<ThemeContext.Provider value={theme}>
<Helmet>
<meta name="theme-color" content={theme["background"]}
/>
<meta name="theme-color" content={theme["background"]} />
</Helmet>
<GlobalTheme theme={theme} />
{theme.css && (
......
import { Channel } from "revolt.js/dist/maps/Channels";
import { createContext } from "preact";
import { useContext, useEffect, useMemo, useRef, useState } from "preact/hooks";
import {
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from "preact/hooks";
import type { ProduceType, VoiceUser } from "../lib/vortex/Types";
import type VoiceClient from "../lib/vortex/VoiceClient";
import { Children } from "../types/Preact";
import { SoundContext } from "./Settings";
import { AppContext } from "./revoltjs/RevoltClient";
import { useForceUpdate } from "./revoltjs/hooks";
export enum VoiceStatus {
LOADING = 0,
......@@ -22,7 +29,7 @@ export enum VoiceStatus {
}
export interface VoiceOperations {
connect: (channelId: string) => Promise<void>;
connect: (channel: Channel) => Promise<Channel>;
disconnect: () => void;
isProducing: (type: ProduceType) => boolean;
startProducing: (type: ProduceType) => Promise<void>;
......@@ -44,20 +51,22 @@ type Props = {
};
export default function Voice({ children }: Props) {
const revoltClient = useContext(AppContext);
const [client, setClient] = useState<VoiceClient | undefined>(undefined);
const [state, setState] = useState<VoiceState>({
status: VoiceStatus.LOADING,
participants: new Map(),
});
function setStatus(status: VoiceStatus, roomId?: string) {
setState({
status,
roomId: roomId ?? client?.roomId,
participants: client?.participants ?? new Map(),
});
}
const setStatus = useCallback(
(status: VoiceStatus, roomId?: string) => {
setState({
status,
roomId: roomId ?? client?.roomId,
participants: client?.participants ?? new Map(),
});
},
[client?.participants, client?.roomId],
);
useEffect(() => {
import("../lib/vortex/VoiceClient")
......@@ -75,32 +84,30 @@ export default function Voice({ children }: Props) {
console.error("Failed to load voice library!", err);
setStatus(VoiceStatus.UNAVAILABLE);
});
}, []);
}, [setStatus]);
const isConnecting = useRef(false);
const operations: VoiceOperations = useMemo(() => {
return {
connect: async (channelId) => {
connect: async (channel) => {
if (!client?.supported()) throw new Error("RTC is unavailable");
isConnecting.current = true;
setStatus(VoiceStatus.CONNECTING, channelId);
setStatus(VoiceStatus.CONNECTING, channel._id);
try {
const call = await revoltClient.channels.joinCall(
channelId,
);
const call = await channel.joinCall();
if (!isConnecting.current) {
setStatus(VoiceStatus.READY);
return;
return channel;
}
// ! FIXME: use configuration to check if voso is enabled
// ! TODO: use configuration to check if voso is enabled
// await client.connect("wss://voso.revolt.chat/ws");
await client.connect(
"wss://voso.revolt.chat/ws",
channelId,
channel._id,
);
setStatus(VoiceStatus.AUTHENTICATING);
......@@ -112,11 +119,12 @@ export default function Voice({ children }: Props) {
} catch (error) {
console.error(error);
setStatus(VoiceStatus.READY);
return;
return channel;
}
setStatus(VoiceStatus.CONNECTED);
isConnecting.current = false;
return channel;
},
disconnect: () => {
if (!client?.supported()) throw new Error("RTC is unavailable");
......@@ -138,9 +146,9 @@ export default function Voice({ children }: Props) {
switch (type) {
case "audio": {
if (client?.audioProducer !== undefined)
return console.log("No audio producer."); // ! FIXME: let the user know
return console.log("No audio producer."); // ! TODO: let the user know
if (navigator.mediaDevices === undefined)
return console.log("No media devices."); // ! FIXME: let the user know
return console.log("No media devices."); // ! TODO: let the user know
const mediaStream =
await navigator.mediaDevices.getUserMedia({
audio: true,
......@@ -158,44 +166,49 @@ export default function Voice({ children }: Props) {
return client?.stopProduce(type);
},
};
}, [client]);
}, [client, setStatus]);
const { forceUpdate } = useForceUpdate();
const playSound = useContext(SoundContext);
useEffect(() => {
if (!client?.supported()) return;
// ! FIXME: message for fatal:
// ! TODO: message for fatal:
// ! get rid of these force updates
// ! handle it through state or smth
client.on("startProduce", forceUpdate);
client.on("stopProduce", forceUpdate);
function stateUpdate() {
setStatus(state.status);
}
client.on("startProduce", stateUpdate);
client.on("stopProduce", stateUpdate);
client.on("userJoined", () => {
playSound("call_join");
forceUpdate();
stateUpdate();
});
client.on("userLeft", () => {
playSound("call_leave");
forceUpdate();
stateUpdate();
});
client.on("userStartProduce", forceUpdate);
client.on("userStopProduce", forceUpdate);
client.on("close", forceUpdate);
client.on("userStartProduce", stateUpdate);
client.on("userStopProduce", stateUpdate);
client.on("close", stateUpdate);
return () => {
client.removeListener("startProduce", forceUpdate);
client.removeListener("stopProduce", forceUpdate);
client.removeListener("userJoined", forceUpdate);
client.removeListener("userLeft", forceUpdate);
client.removeListener("userStartProduce", forceUpdate);
client.removeListener("userStopProduce", forceUpdate);
client.removeListener("close", forceUpdate);
client.removeListener("startProduce", stateUpdate);
client.removeListener("stopProduce", stateUpdate);
client.removeListener("userJoined", stateUpdate);
client.removeListener("userLeft", stateUpdate);
client.removeListener("userStartProduce", stateUpdate);
client.removeListener("userStopProduce", stateUpdate);
client.removeListener("close", stateUpdate);
};
}, [client, state]);
}, [client, state, playSound, setStatus]);
return (
<VoiceContext.Provider value={state}>
......
import { Prompt } from "react-router";
import { useHistory } from "react-router-dom";
import {
Attachment,
Channels,
EmbedImage,
Servers,
Users,
} from "revolt.js/dist/api/objects";
import type { Attachment } from "revolt-api/types/Autumn";
import type { EmbedImage } from "revolt-api/types/January";
import { Channel } from "revolt.js/dist/maps/Channels";
import { Message } from "revolt.js/dist/maps/Messages";
import { Server } from "revolt.js/dist/maps/Servers";
import { User } from "revolt.js/dist/maps/Users";
import { createContext } from "preact";
import { useContext, useEffect, useMemo, useState } from "preact/hooks";
......@@ -32,21 +31,21 @@ export type Screen =
actions: Action[];
}
| ({ id: "special_prompt" } & (
| { type: "leave_group"; target: Channels.GroupChannel }
| { type: "close_dm"; target: Channels.DirectMessageChannel }
| { type: "leave_server"; target: Servers.Server }
| { type: "delete_server"; target: Servers.Server }
| { type: "delete_channel"; target: Channels.TextChannel }
| { type: "delete_message"; target: Channels.Message }
| { type: "leave_group"; target: Channel }
| { type: "close_dm"; target: Channel }
| { type: "leave_server"; target: Server }
| { type: "delete_server"; target: Server }
| { type: "delete_channel"; target: Channel }
| { type: "delete_message"; target: Message }
| {
type: "create_invite";
target: Channels.TextChannel | Channels.GroupChannel;
target: Channel;
}
| { type: "kick_member"; target: Servers.Server; user: string }
| { type: "ban_member"; target: Servers.Server; user: string }
| { type: "unfriend_user"; target: Users.User }
| { type: "block_user"; target: Users.User }
| { type: "create_channel"; target: Servers.Server }
| { type: "kick_member"; target: Server; user: User }
| { type: "ban_member"; target: Server; user: User }
| { type: "unfriend_user"; target: User }
| { type: "block_user"; target: User }
| { type: "create_channel"; target: Server }
))
| ({ id: "special_input" } & (
| {
......@@ -58,7 +57,7 @@ export type Screen =
}
| {
type: "create_role";
server: string;
server: Server;
callback: (id: string) => void;
}
))
......@@ -81,8 +80,8 @@ export type Screen =
| { id: "image_viewer"; attachment?: Attachment; embed?: EmbedImage }
| { id: "modify_account"; field: "username" | "email" | "password" }
| { id: "profile"; user_id: string }
| { id: "channel_info"; channel_id: string }
| { id: "pending_requests"; users: string[] }
| { id: "channel_info"; channel: Channel }
| { id: "pending_requests"; users: User[] }
| {
id: "user_picker";
omit?: string[];
......@@ -90,13 +89,16 @@ export type Screen =
};
export const IntermediateContext = createContext({
screen: { id: "none" } as Screen,
screen: { id: "none" },
focusTaken: false,
});
export const IntermediateActionsContext = createContext({
openScreen: (screen: Screen) => {},
writeClipboard: (text: string) => {},
export const IntermediateActionsContext = createContext<{
openScreen: (screen: Screen) => void;
writeClipboard: (text: string) => void;
}>({
openScreen: null!,
writeClipboard: null!,
});
interface Props {
......@@ -131,12 +133,20 @@ export default function Intermediate(props: Props) {
const navigate = (path: string) => history.push(path);
const subs = [
internalSubscribe("Intermediate", "openProfile", openProfile),
internalSubscribe("Intermediate", "navigate", navigate),
internalSubscribe(
"Intermediate",
"openProfile",
openProfile as (...args: unknown[]) => void,
),
internalSubscribe(
"Intermediate",
"navigate",
navigate as (...args: unknown[]) => void,
),
];
return () => subs.map((unsub) => unsub());
}, []);
}, [history]);
return (
<IntermediateContext.Provider value={value}>
......
import { isModalClosing } from "../../components/ui/Modal";
import { internalEmit } from "../../lib/eventEmitter";
import { isModalClosing } from "../../components/ui/Modal";
import { Screen } from "./Intermediate";
import { ClipboardModal } from "./modals/Clipboard";
import { ErrorModal } from "./modals/Error";
......@@ -10,11 +12,14 @@ import { SignedOutModal } from "./modals/SignedOut";
export interface Props {
screen: Screen;
openScreen: (id: any) => void;
openScreen: (screen: Screen) => void;
}
export default function Modals({ screen, openScreen }: Props) {
const onClose = () => isModalClosing ? openScreen({ id: "none" }) : internalEmit('Modal', 'close');
const onClose = () =>
isModalClosing || screen.id === "onboarding"
? openScreen({ id: "none" })
: internalEmit("Modal", "close");
switch (screen.id) {
case "_prompt":
......
import { useContext } from "preact/hooks";
import { isModalClosing } from "../../components/ui/Modal";
import { internalEmit } from "../../lib/eventEmitter";
import { isModalClosing } from "../../components/ui/Modal";
import { IntermediateContext, useIntermediate } from "./Intermediate";
import { SpecialInputModal } from "./modals/Input";
import { SpecialPromptModal } from "./modals/Prompt";
......@@ -16,7 +18,10 @@ export default function Popovers() {
const { screen } = useContext(IntermediateContext);
const { openScreen } = useIntermediate();
const onClose = () => isModalClosing ? openScreen({ id: "none" }) : internalEmit('Modal', 'close');
const onClose = () =>
isModalClosing
? openScreen({ id: "none" })
: internalEmit("Modal", "close");
switch (screen.id) {
case "profile":
......
import { useHistory } from "react-router";
import { Server } from "revolt.js/dist/maps/Servers";
import { ulid } from "ulid";
import { Text } from "preact-i18n";
......@@ -81,7 +82,7 @@ type SpecialProps = { onClose: () => void } & (
| "set_custom_status"
| "add_friend";
}
| { type: "create_role"; server: string; callback: (id: string) => void }
| { type: "create_role"; server: Server; callback: (id: string) => void }
);
export function SpecialInputModal(props: SpecialProps) {
......@@ -134,10 +135,7 @@ export function SpecialInputModal(props: SpecialProps) {
}
field={<Text id="app.settings.permissions.role_name" />}
callback={async (name) => {
const role = await client.servers.createRole(
props.server,
name,
);
const role = await props.server.createRole(name);
props.callback(role.id);
}}
/>
......@@ -151,7 +149,7 @@ export function SpecialInputModal(props: SpecialProps) {
field={<Text id="app.context_menu.custom_status" />}
defaultValue={client.user?.status?.text}
callback={(text) =>
client.users.editUser({
client.users.edit({
status: {
...client.user?.status,
text: text.trim().length > 0 ? text : undefined,
......@@ -166,7 +164,14 @@ export function SpecialInputModal(props: SpecialProps) {
<InputModal
onClose={onClose}
question={"Add Friend"}
callback={(username) => client.users.addFriend(username)}
callback={(username) =>
client
.req(
"PUT",
`/users/${username}/friend` as "/users/id/friend",
)
.then(undefined)
}
/>
);
}
......
......@@ -26,7 +26,7 @@
margin: auto;
display: block;
max-height: 420px;
border-radius: 8px;
border-radius: var(--border-radius);
}
input {
......