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 1181 additions and 540 deletions
import { IntlProvider } from "preact-i18n"; import dayJS from "dayjs";
import calendar from "dayjs/plugin/calendar";
import format from "dayjs/plugin/localizedFormat";
import update from "dayjs/plugin/updateLocale";
import defaultsDeep from "lodash.defaultsdeep"; import defaultsDeep from "lodash.defaultsdeep";
import { IntlProvider } from "preact-i18n";
import { useCallback, useEffect, useState } from "preact/hooks";
import { connectState } from "../redux/connector"; import { connectState } from "../redux/connector";
import { useEffect, useState } from "preact/hooks";
import definition from "../../external/lang/en.json"; import definition from "../../external/lang/en.json";
import dayjs from "dayjs"; export const dayjs = dayJS;
import calendar from "dayjs/plugin/calendar";
import update from "dayjs/plugin/updateLocale";
import format from "dayjs/plugin/localizedFormat";
dayjs.extend(calendar); dayjs.extend(calendar);
dayjs.extend(format); dayjs.extend(format);
dayjs.extend(update); dayjs.extend(update);
...@@ -19,6 +24,7 @@ export enum Language { ...@@ -19,6 +24,7 @@ export enum Language {
AZERBAIJANI = "az", AZERBAIJANI = "az",
CZECH = "cs", CZECH = "cs",
GERMAN = "de", GERMAN = "de",
GREEK = "el",
SPANISH = "es", SPANISH = "es",
FINNISH = "fi", FINNISH = "fi",
FRENCH = "fr", FRENCH = "fr",
...@@ -26,6 +32,7 @@ export enum Language { ...@@ -26,6 +32,7 @@ export enum Language {
CROATIAN = "hr", CROATIAN = "hr",
HUNGARIAN = "hu", HUNGARIAN = "hu",
INDONESIAN = "id", INDONESIAN = "id",
ITALIAN = "it",
LITHUANIAN = "lt", LITHUANIAN = "lt",
MACEDONIAN = "mk", MACEDONIAN = "mk",
DUTCH = "nl", DUTCH = "nl",
...@@ -35,6 +42,7 @@ export enum Language { ...@@ -35,6 +42,7 @@ export enum Language {
RUSSIAN = "ru", RUSSIAN = "ru",
SERBIAN = "sr", SERBIAN = "sr",
SWEDISH = "sv", SWEDISH = "sv",
TOKIPONA = "tokipona",
TURKISH = "tr", TURKISH = "tr",
UKRANIAN = "uk", UKRANIAN = "uk",
CHINESE_SIMPLIFIED = "zh_Hans", CHINESE_SIMPLIFIED = "zh_Hans",
...@@ -43,7 +51,6 @@ export enum Language { ...@@ -43,7 +51,6 @@ export enum Language {
PIRATE = "pr", PIRATE = "pr",
BOTTOM = "bottom", BOTTOM = "bottom",
PIGLATIN = "piglatin", PIGLATIN = "piglatin",
HARDCORE = "hardcore",
} }
export interface LanguageEntry { export interface LanguageEntry {
...@@ -52,7 +59,7 @@ export interface LanguageEntry { ...@@ -52,7 +59,7 @@ export interface LanguageEntry {
i18n: string; i18n: string;
dayjs?: string; dayjs?: string;
rtl?: boolean; rtl?: boolean;
alt?: boolean; cat?: "const" | "alt";
} }
export const Languages: { [key in Language]: LanguageEntry } = { export const Languages: { [key in Language]: LanguageEntry } = {
...@@ -67,13 +74,15 @@ export const Languages: { [key in Language]: LanguageEntry } = { ...@@ -67,13 +74,15 @@ export const Languages: { [key in Language]: LanguageEntry } = {
az: { display: "Azərbaycan dili", emoji: "🇦🇿", i18n: "az" }, az: { display: "Azərbaycan dili", emoji: "🇦🇿", i18n: "az" },
cs: { display: "Čeština", emoji: "🇨🇿", i18n: "cs" }, cs: { display: "Čeština", emoji: "🇨🇿", i18n: "cs" },
de: { display: "Deutsch", emoji: "🇩🇪", i18n: "de" }, de: { display: "Deutsch", emoji: "🇩🇪", i18n: "de" },
el: { display: "Ελληνικά", emoji: "🇬🇷", i18n: "el" },
es: { display: "Español", emoji: "🇪🇸", i18n: "es" }, es: { display: "Español", emoji: "🇪🇸", i18n: "es" },
fi: { display: "suomi", emoji: "🇫🇮", i18n: "fi" }, fi: { display: "suomi", emoji: "🇫🇮", i18n: "fi" },
fr: { display: "Français", emoji: "🇫🇷", i18n: "fr" }, fr: { display: "Français", emoji: "🇫🇷", i18n: "fr" },
hi: { display: "हिन्दी", emoji: "🇮🇳", i18n: "hi" }, hi: { display: "हिन्दी", emoji: "🇮🇳", i18n: "hi" },
hr: { display: "Hrvatski", emoji: "🇭🇷", i18n: "hr" }, 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" }, id: { display: "bahasa Indonesia", emoji: "🇮🇩", i18n: "id" },
it: { display: "Italiano", emoji: "🇮🇹", i18n: "it" },
lt: { display: "Lietuvių", emoji: "🇱🇹", i18n: "lt" }, lt: { display: "Lietuvių", emoji: "🇱🇹", i18n: "lt" },
mk: { display: "Македонски", emoji: "🇲🇰", i18n: "mk" }, mk: { display: "Македонски", emoji: "🇲🇰", i18n: "mk" },
nl: { display: "Nederlands", emoji: "🇳🇱", i18n: "nl" }, nl: { display: "Nederlands", emoji: "🇳🇱", i18n: "nl" },
...@@ -97,22 +106,41 @@ export const Languages: { [key in Language]: LanguageEntry } = { ...@@ -97,22 +106,41 @@ export const Languages: { [key in Language]: LanguageEntry } = {
dayjs: "zh", dayjs: "zh",
}, },
owo: { display: "OwO", emoji: "🐱", i18n: "owo", dayjs: "en-gb", alt: true }, tokipona: {
pr: { display: "Pirate", emoji: "🏴‍☠️", i18n: "pr", dayjs: "en-gb", alt: true }, display: "Toki Pona",
bottom: { display: "Bottom", emoji: "🥺", i18n: "bottom", dayjs: "en-gb", alt: true }, emoji: "🙂",
i18n: "tokipona",
dayjs: "en-gb",
cat: "const",
},
owo: {
display: "OwO",
emoji: "🐱",
i18n: "owo",
dayjs: "en-gb",
cat: "alt",
},
pr: {
display: "Pirate",
emoji: "🏴‍☠️",
i18n: "pr",
dayjs: "en-gb",
cat: "alt",
},
bottom: {
display: "Bottom",
emoji: "🥺",
i18n: "bottom",
dayjs: "en-gb",
cat: "alt",
},
piglatin: { piglatin: {
display: "Pig Latin", display: "Pig Latin",
emoji: "🐖", emoji: "🐖",
i18n: "piglatin", i18n: "piglatin",
dayjs: "en-gb", dayjs: "en-gb",
alt: true cat: "alt",
},
hardcore: {
display: "Hardcore Mode",
emoji: "🔥",
i18n: "hardcore",
dayjs: "en-gb",
alt: true
}, },
}; };
...@@ -121,40 +149,118 @@ interface Props { ...@@ -121,40 +149,118 @@ interface Props {
locale: Language; 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) { function Locale({ children, locale }: Props) {
const [defns, setDefinition] = useState(definition); const [defns, setDefinition] = useState<Dictionary>(
const lang = Languages[locale]; definition as Dictionary,
);
useEffect(() => { // Load relevant language information, fallback to English if invalid.
if (locale === "en") { const lang = Languages[locale] ?? Languages.en;
setDefinition(definition);
dayjs.locale("en"); function transformLanguage(source: Dictionary) {
return; // Fallback untranslated strings to English (UK)
} const obj = defaultsDeep(source, definition);
if (lang.i18n === "hardcore") { // Take relevant objects out, dayjs and defaults
// eslint-disable-next-line @typescript-eslint/no-explicit-any // should exist given we just took defaults above.
setDefinition({} as any); const { dayjs } = obj;
return; const { defaults } = dayjs;
}
// Determine whether we are using 12-hour clock.
import(`../../external/lang/${lang.i18n}.json`).then( const twelvehour = defaults?.twelvehour
async (lang_file) => { ? defaults.twelvehour === "yes"
const defn = lang_file.default; : false;
const target = lang.dayjs ?? lang.i18n;
const dayjs_locale = await import(`../../node_modules/dayjs/esm/locale/${target}.js`); // Determine what date separator we are using.
const separator: string = defaults?.date_separator ?? "/";
if (defn.dayjs) {
dayjs.updateLocale(target, { calendar: defn.dayjs }); // Determine what date format we are using.
} const date: "traditional" | "simplified" | "ISO8601" =
defaults?.date_format ?? "traditional";
dayjs.locale(dayjs_locale.default);
setDefinition(defaultsDeep(defn, definition)); // Available date formats.
const DATE_FORMATS = {
traditional: `DD${separator}MM${separator}YYYY`,
simplified: `MM${separator}DD${separator}YYYY`,
ISO8601: "YYYY-MM-DD",
};
// 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(
(k) =>
(dayjs[k] = dayjs[k].replace(
/{{time}}/g,
dayjs["timeFormat"],
)),
);
return obj;
}
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);
dayjs.locale("en");
dayjs.updateLocale("en", { calendar: defn.dayjs });
return;
} }
);
}, [locale, lang]); 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(() => { useEffect(() => {
// Apply RTL language format.
document.body.style.direction = lang.rtl ? "rtl" : ""; document.body.style.direction = lang.rtl ? "rtl" : "";
}, [lang.rtl]); }, [lang.rtl]);
...@@ -168,5 +274,5 @@ export default connectState<Omit<Props, "locale">>( ...@@ -168,5 +274,5 @@ export default connectState<Omit<Props, "locale">>(
locale: state.locale, locale: state.locale,
}; };
}, },
true true,
); );
...@@ -6,44 +6,56 @@ ...@@ -6,44 +6,56 @@
// if it does cause problems though. // if it does cause problems though.
// //
// This now also supports Audio stuff. // This now also supports Audio stuff.
import { DEFAULT_SOUNDS, Settings, SoundOptions } from "../redux/reducers/settings";
import { playSound, Sounds } from "../assets/sounds/Audio";
import { connectState } from "../redux/connector";
import defaultsDeep from "lodash.defaultsdeep"; import defaultsDeep from "lodash.defaultsdeep";
import { Children } from "../types/Preact";
import { createContext } from "preact"; import { createContext } from "preact";
import { useMemo } from "preact/hooks"; import { useMemo } from "preact/hooks";
export const SettingsContext = createContext<Settings>({} as any); import { connectState } from "../redux/connector";
export const SoundContext = createContext<(sound: Sounds) => void>({} as any); import {
DEFAULT_SOUNDS,
Settings,
SoundOptions,
} from "../redux/reducers/settings";
import { playSound, Sounds } from "../assets/sounds/Audio";
import { Children } from "../types/Preact";
export const SettingsContext = createContext<Settings>({});
export const SoundContext = createContext<(sound: Sounds) => void>(null!);
interface Props { interface Props {
children?: Children, children?: Children;
settings: Settings settings: Settings;
} }
function Settings({ settings, children }: Props) { function SettingsProvider({ settings, children }: Props) {
const play = useMemo(() => { const play = useMemo(() => {
const enabled: SoundOptions = defaultsDeep(settings.notification?.sounds ?? {}, DEFAULT_SOUNDS); const enabled: SoundOptions = defaultsDeep(
settings.notification?.sounds ?? {},
DEFAULT_SOUNDS,
);
return (sound: Sounds) => { return (sound: Sounds) => {
if (enabled[sound]) { if (enabled[sound]) {
playSound(sound); playSound(sound);
} }
}; };
}, [ settings.notification ]); }, [settings.notification]);
return ( return (
<SettingsContext.Provider value={settings}> <SettingsContext.Provider value={settings}>
<SoundContext.Provider value={play}> <SoundContext.Provider value={play}>
{ children } {children}
</SoundContext.Provider> </SoundContext.Provider>
</SettingsContext.Provider> </SettingsContext.Provider>
) );
} }
export default connectState<Omit<Props, 'settings'>>(Settings, state => { export default connectState<Omit<Props, "settings">>(
return { SettingsProvider,
settings: state.settings (state) => {
} return {
}); settings: state.settings,
};
},
);
import { isTouchscreenDevice } from "../lib/isTouchscreenDevice"; import { Helmet } from "react-helmet";
import { createGlobalStyle } from "styled-components"; import { createGlobalStyle } from "styled-components";
import { createContext } from "preact";
import { useEffect } from "preact/hooks";
import { connectState } from "../redux/connector"; import { connectState } from "../redux/connector";
import { Children } from "../types/Preact"; import { Children } from "../types/Preact";
import { createContext } from "preact";
import { Helmet } from "react-helmet";
export type Variables = export type Variables =
| "accent" | "accent"
...@@ -31,20 +34,194 @@ export type Variables = ...@@ -31,20 +34,194 @@ export type Variables =
| "status-streaming" | "status-streaming"
| "status-invisible"; | "status-invisible";
// While this isn't used, it'd be good to keep this up to date as a reference or for future use
export type HiddenVariables =
| "font"
| "ligatures"
| "app-height"
| "sidebar-active"
| "monospace-font";
export type Fonts =
| "Open Sans"
| "Inter"
| "Atkinson Hyperlegible"
| "Roboto"
| "Noto Sans"
| "Lato"
| "Bree Serif"
| "Montserrat"
| "Poppins"
| "Raleway"
| "Ubuntu"
| "Comic Neue";
export type MonospaceFonts =
| "Fira Code"
| "Roboto Mono"
| "Source Code Pro"
| "Space Mono"
| "Ubuntu Mono";
export type Theme = { export type Theme = {
[variable in Variables]: string; [variable in Variables]: string;
} & { } & {
light?: boolean; light?: boolean;
font?: Fonts;
css?: string; css?: string;
monospaceFont?: MonospaceFonts;
}; };
export interface ThemeOptions { export interface ThemeOptions {
preset?: string; preset?: string;
ligatures?: boolean;
custom?: Partial<Theme>; custom?: Partial<Theme>;
} }
// import aaa from "@fontsource/open-sans/300.css?raw";
// console.info(aaa);
export const FONTS: Record<Fonts, { name: string; load: () => void }> = {
"Open Sans": {
name: "Open Sans",
load: async () => {
await import("@fontsource/open-sans/300.css");
await import("@fontsource/open-sans/400.css");
await import("@fontsource/open-sans/600.css");
await import("@fontsource/open-sans/700.css");
await import("@fontsource/open-sans/400-italic.css");
},
},
Inter: {
name: "Inter",
load: async () => {
await import("@fontsource/inter/300.css");
await import("@fontsource/inter/400.css");
await import("@fontsource/inter/600.css");
await import("@fontsource/inter/700.css");
},
},
"Atkinson Hyperlegible": {
name: "Atkinson Hyperlegible",
load: async () => {
await import("@fontsource/atkinson-hyperlegible/400.css");
await import("@fontsource/atkinson-hyperlegible/700.css");
await import("@fontsource/atkinson-hyperlegible/400-italic.css");
},
},
Roboto: {
name: "Roboto",
load: async () => {
await import("@fontsource/roboto/400.css");
await import("@fontsource/roboto/700.css");
await import("@fontsource/roboto/400-italic.css");
},
},
"Noto Sans": {
name: "Noto Sans",
load: async () => {
await import("@fontsource/noto-sans/400.css");
await import("@fontsource/noto-sans/700.css");
await import("@fontsource/noto-sans/400-italic.css");
},
},
"Bree Serif": {
name: "Bree Serif",
load: () => import("@fontsource/bree-serif/400.css"),
},
Lato: {
name: "Lato",
load: async () => {
await import("@fontsource/lato/300.css");
await import("@fontsource/lato/400.css");
await import("@fontsource/lato/700.css");
await import("@fontsource/lato/400-italic.css");
},
},
Montserrat: {
name: "Montserrat",
load: async () => {
await import("@fontsource/montserrat/300.css");
await import("@fontsource/montserrat/400.css");
await import("@fontsource/montserrat/600.css");
await import("@fontsource/montserrat/700.css");
await import("@fontsource/montserrat/400-italic.css");
},
},
Poppins: {
name: "Poppins",
load: async () => {
await import("@fontsource/poppins/300.css");
await import("@fontsource/poppins/400.css");
await import("@fontsource/poppins/600.css");
await import("@fontsource/poppins/700.css");
await import("@fontsource/poppins/400-italic.css");
},
},
Raleway: {
name: "Raleway",
load: async () => {
await import("@fontsource/raleway/300.css");
await import("@fontsource/raleway/400.css");
await import("@fontsource/raleway/600.css");
await import("@fontsource/raleway/700.css");
await import("@fontsource/raleway/400-italic.css");
},
},
Ubuntu: {
name: "Ubuntu",
load: async () => {
await import("@fontsource/ubuntu/300.css");
await import("@fontsource/ubuntu/400.css");
await import("@fontsource/ubuntu/500.css");
await import("@fontsource/ubuntu/700.css");
await import("@fontsource/ubuntu/400-italic.css");
},
},
"Comic Neue": {
name: "Comic Neue",
load: async () => {
await import("@fontsource/comic-neue/300.css");
await import("@fontsource/comic-neue/400.css");
await import("@fontsource/comic-neue/700.css");
await import("@fontsource/comic-neue/400-italic.css");
},
},
};
export const MONOSPACE_FONTS: Record<
MonospaceFonts,
{ name: string; load: () => void }
> = {
"Fira Code": {
name: "Fira Code",
load: () => import("@fontsource/fira-code/400.css"),
},
"Roboto Mono": {
name: "Roboto Mono",
load: () => import("@fontsource/roboto-mono/400.css"),
},
"Source Code Pro": {
name: "Source Code Pro",
load: () => import("@fontsource/source-code-pro/400.css"),
},
"Space Mono": {
name: "Space Mono",
load: () => import("@fontsource/space-mono/400.css"),
},
"Ubuntu Mono": {
name: "Ubuntu Mono",
load: () => import("@fontsource/ubuntu-mono/400.css"),
},
};
export const FONT_KEYS = Object.keys(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";
// Generated from https://gitlab.insrt.uk/revolt/community/themes // Generated from https://gitlab.insrt.uk/revolt/community/themes
export const PRESETS: { [key: string]: Theme } = { export const PRESETS: Record<string, Theme> = {
light: { light: {
light: true, light: true,
accent: "#FD6671", accent: "#FD6671",
...@@ -55,7 +232,7 @@ export const PRESETS: { [key: string]: Theme } = { ...@@ -55,7 +232,7 @@ export const PRESETS: { [key: string]: Theme } = {
mention: "rgba(251, 255, 0, 0.40)", mention: "rgba(251, 255, 0, 0.40)",
success: "#65E572", success: "#65E572",
warning: "#FAA352", warning: "#FAA352",
error: "#F06464", error: "#ED4245",
hover: "rgba(0, 0, 0, 0.2)", hover: "rgba(0, 0, 0, 0.2)",
"scrollbar-thumb": "#CA525A", "scrollbar-thumb": "#CA525A",
"scrollbar-track": "transparent", "scrollbar-track": "transparent",
...@@ -82,7 +259,7 @@ export const PRESETS: { [key: string]: Theme } = { ...@@ -82,7 +259,7 @@ export const PRESETS: { [key: string]: Theme } = {
mention: "rgba(251, 255, 0, 0.06)", mention: "rgba(251, 255, 0, 0.06)",
success: "#65E572", success: "#65E572",
warning: "#FAA352", warning: "#FAA352",
error: "#F06464", error: "#ED4245",
hover: "rgba(0, 0, 0, 0.1)", hover: "rgba(0, 0, 0, 0.1)",
"scrollbar-thumb": "#CA525A", "scrollbar-thumb": "#CA525A",
"scrollbar-track": "transparent", "scrollbar-track": "transparent",
...@@ -112,43 +289,63 @@ const GlobalTheme = createGlobalStyle<{ theme: Theme }>` ...@@ -112,43 +289,63 @@ const GlobalTheme = createGlobalStyle<{ theme: Theme }>`
} }
`; `;
export const ThemeContext = createContext<Theme>({} as any); // Load the default default them and apply extras later
export const ThemeContext = createContext<Theme>(PRESETS["dark"]);
interface Props { interface Props {
children: Children; children: Children;
options?: ThemeOptions; options?: ThemeOptions;
} }
function Theme(props: Props) { function Theme({ children, options }: Props) {
const theme: Theme = { const theme: Theme = {
...PRESETS["dark"], ...PRESETS["dark"],
...(PRESETS as any)[props.options?.preset as any], ...PRESETS[options?.preset ?? ""],
...props.options?.custom ...options?.custom,
}; };
const root = document.documentElement.style;
useEffect(() => {
const font = theme.font ?? DEFAULT_FONT;
root.setProperty("--font", `"${font}"`);
FONTS[font].load();
}, [root, theme.font]);
useEffect(() => {
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");
}, [root, options?.ligatures]);
useEffect(() => {
const resize = () =>
root.setProperty("--app-height", `${window.innerHeight}px`);
resize();
window.addEventListener("resize", resize);
return () => window.removeEventListener("resize", resize);
}, [root]);
return ( return (
<ThemeContext.Provider value={theme}> <ThemeContext.Provider value={theme}>
<Helmet> <Helmet>
<meta <meta name="theme-color" content={theme["background"]} />
name="theme-color"
content={
isTouchscreenDevice
? theme["primary-header"]
: theme["tertiary-background"]
}
/>
</Helmet> </Helmet>
<GlobalTheme theme={theme} /> <GlobalTheme theme={theme} />
{theme.css && ( {theme.css && (
<style dangerouslySetInnerHTML={{ __html: theme.css }} /> <style dangerouslySetInnerHTML={{ __html: theme.css }} />
)} )}
{props.children} {children}
</ThemeContext.Provider> </ThemeContext.Provider>
); );
} }
export default connectState<{ children: Children }>(Theme, state => { export default connectState<{ children: Children }>(Theme, (state) => {
return { return {
options: state.settings.theme options: state.settings.theme,
}; };
}); });
import { Channel } from "revolt.js/dist/maps/Channels";
import { createContext } from "preact"; import { createContext } from "preact";
import { Children } from "../types/Preact"; import {
import { useForceUpdate } from "./revoltjs/hooks"; useCallback,
import { AppContext } from "./revoltjs/RevoltClient"; useContext,
import type VoiceClient from "../lib/vortex/VoiceClient"; useEffect,
useMemo,
useRef,
useState,
} from "preact/hooks";
import type { ProduceType, VoiceUser } from "../lib/vortex/Types"; import type { ProduceType, VoiceUser } from "../lib/vortex/Types";
import { useContext, useEffect, useMemo, useRef, useState } from "preact/hooks"; import type VoiceClient from "../lib/vortex/VoiceClient";
import { Children } from "../types/Preact";
import { SoundContext } from "./Settings"; import { SoundContext } from "./Settings";
export enum VoiceStatus { export enum VoiceStatus {
...@@ -15,12 +24,12 @@ export enum VoiceStatus { ...@@ -15,12 +24,12 @@ export enum VoiceStatus {
CONNECTING = 4, CONNECTING = 4,
AUTHENTICATING, AUTHENTICATING,
RTC_CONNECTING, RTC_CONNECTING,
CONNECTED CONNECTED,
// RECONNECTING // RECONNECTING
} }
export interface VoiceOperations { export interface VoiceOperations {
connect: (channelId: string) => Promise<void>; connect: (channel: Channel) => Promise<Channel>;
disconnect: () => void; disconnect: () => void;
isProducing: (type: ProduceType) => boolean; isProducing: (type: ProduceType) => boolean;
startProducing: (type: ProduceType) => Promise<void>; startProducing: (type: ProduceType) => Promise<void>;
...@@ -33,31 +42,34 @@ export interface VoiceState { ...@@ -33,31 +42,34 @@ export interface VoiceState {
participants?: Readonly<Map<string, VoiceUser>>; participants?: Readonly<Map<string, VoiceUser>>;
} }
export const VoiceContext = createContext<VoiceState>(undefined as any); // They should be present from first render. - insert's words
export const VoiceOperationsContext = createContext<VoiceOperations>(undefined as any); export const VoiceContext = createContext<VoiceState>(null!);
export const VoiceOperationsContext = createContext<VoiceOperations>(null!);
type Props = { type Props = {
children: Children; children: Children;
}; };
export default function Voice({ children }: Props) { export default function Voice({ children }: Props) {
const revoltClient = useContext(AppContext);
const [client, setClient] = useState<VoiceClient | undefined>(undefined); const [client, setClient] = useState<VoiceClient | undefined>(undefined);
const [state, setState] = useState<VoiceState>({ const [state, setState] = useState<VoiceState>({
status: VoiceStatus.LOADING, status: VoiceStatus.LOADING,
participants: new Map() participants: new Map(),
}); });
function setStatus(status: VoiceStatus, roomId?: string) { const setStatus = useCallback(
setState({ (status: VoiceStatus, roomId?: string) => {
status, setState({
roomId: roomId ?? client?.roomId, status,
participants: client?.participants ?? new Map(), roomId: roomId ?? client?.roomId,
}); participants: client?.participants ?? new Map(),
} });
},
[client?.participants, client?.roomId],
);
useEffect(() => { useEffect(() => {
import('../lib/vortex/VoiceClient') import("../lib/vortex/VoiceClient")
.then(({ default: VoiceClient }) => { .then(({ default: VoiceClient }) => {
const client = new VoiceClient(); const client = new VoiceClient();
setClient(client); setClient(client);
...@@ -68,35 +80,35 @@ export default function Voice({ children }: Props) { ...@@ -68,35 +80,35 @@ export default function Voice({ children }: Props) {
setStatus(VoiceStatus.READY); setStatus(VoiceStatus.READY);
} }
}) })
.catch(err => { .catch((err) => {
console.error('Failed to load voice library!', err); console.error("Failed to load voice library!", err);
setStatus(VoiceStatus.UNAVAILABLE); setStatus(VoiceStatus.UNAVAILABLE);
}) });
}, []); }, [setStatus]);
const isConnecting = useRef(false); const isConnecting = useRef(false);
const operations: VoiceOperations = useMemo(() => { const operations: VoiceOperations = useMemo(() => {
return { return {
connect: async channelId => { connect: async (channel) => {
if (!client?.supported()) if (!client?.supported()) throw new Error("RTC is unavailable");
throw new Error("RTC is unavailable");
isConnecting.current = true; isConnecting.current = true;
setStatus(VoiceStatus.CONNECTING, channelId); setStatus(VoiceStatus.CONNECTING, channel._id);
try { try {
const call = await revoltClient.channels.joinCall( const call = await channel.joinCall();
channelId
);
if (!isConnecting.current) { if (!isConnecting.current) {
setStatus(VoiceStatus.READY); 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");
await client.connect("wss://voso.revolt.chat/ws", channelId); await client.connect(
"wss://voso.revolt.chat/ws",
channel._id,
);
setStatus(VoiceStatus.AUTHENTICATING); setStatus(VoiceStatus.AUTHENTICATING);
...@@ -107,16 +119,16 @@ export default function Voice({ children }: Props) { ...@@ -107,16 +119,16 @@ export default function Voice({ children }: Props) {
} catch (error) { } catch (error) {
console.error(error); console.error(error);
setStatus(VoiceStatus.READY); setStatus(VoiceStatus.READY);
return; return channel;
} }
setStatus(VoiceStatus.CONNECTED); setStatus(VoiceStatus.CONNECTED);
isConnecting.current = false; isConnecting.current = false;
return channel;
}, },
disconnect: () => { disconnect: () => {
if (!client?.supported()) if (!client?.supported()) throw new Error("RTC is unavailable");
throw new Error("RTC is unavailable");
// if (status <= VoiceStatus.READY) return; // if (status <= VoiceStatus.READY) return;
// this will not update in this context // this will not update in this context
...@@ -133,17 +145,18 @@ export default function Voice({ children }: Props) { ...@@ -133,17 +145,18 @@ export default function Voice({ children }: Props) {
startProducing: async (type: ProduceType) => { startProducing: async (type: ProduceType) => {
switch (type) { switch (type) {
case "audio": { case "audio": {
if (client?.audioProducer !== undefined) return console.log('No audio producer.'); // ! FIXME: let the user know if (client?.audioProducer !== undefined)
if (navigator.mediaDevices === undefined) return console.log('No media devices.'); // ! FIXME: let the user know return console.log("No audio producer."); // ! TODO: let the user know
const mediaStream = await navigator.mediaDevices.getUserMedia( if (navigator.mediaDevices === undefined)
{ return console.log("No media devices."); // ! TODO: let the user know
audio: true const mediaStream =
} await navigator.mediaDevices.getUserMedia({
); audio: true,
});
await client?.startProduce( await client?.startProduce(
mediaStream.getAudioTracks()[0], mediaStream.getAudioTracks()[0],
"audio" "audio",
); );
return; return;
} }
...@@ -151,51 +164,56 @@ export default function Voice({ children }: Props) { ...@@ -151,51 +164,56 @@ export default function Voice({ children }: Props) {
}, },
stopProducing: (type: ProduceType) => { stopProducing: (type: ProduceType) => {
return client?.stopProduce(type); return client?.stopProduce(type);
} },
} };
}, [ client ]); }, [client, setStatus]);
const { forceUpdate } = useForceUpdate();
const playSound = useContext(SoundContext); const playSound = useContext(SoundContext);
useEffect(() => { useEffect(() => {
if (!client?.supported()) return; if (!client?.supported()) return;
// ! FIXME: message for fatal: // ! TODO: message for fatal:
// ! get rid of these force updates // ! get rid of these force updates
// ! handle it through state or smth // ! handle it through state or smth
client.on("startProduce", forceUpdate); function stateUpdate() {
client.on("stopProduce", forceUpdate); setStatus(state.status);
}
client.on("startProduce", stateUpdate);
client.on("stopProduce", stateUpdate);
client.on("userJoined", () => { client.on("userJoined", () => {
playSound('call_join'); playSound("call_join");
forceUpdate(); stateUpdate();
}); });
client.on("userLeft", () => { client.on("userLeft", () => {
playSound('call_leave'); playSound("call_leave");
forceUpdate(); stateUpdate();
}); });
client.on("userStartProduce", forceUpdate);
client.on("userStopProduce", forceUpdate); client.on("userStartProduce", stateUpdate);
client.on("close", forceUpdate); client.on("userStopProduce", stateUpdate);
client.on("close", stateUpdate);
return () => { return () => {
client.removeListener("startProduce", forceUpdate); client.removeListener("startProduce", stateUpdate);
client.removeListener("stopProduce", forceUpdate); client.removeListener("stopProduce", stateUpdate);
client.removeListener("userJoined", forceUpdate); client.removeListener("userJoined", stateUpdate);
client.removeListener("userLeft", forceUpdate); client.removeListener("userLeft", stateUpdate);
client.removeListener("userStartProduce", forceUpdate); client.removeListener("userStartProduce", stateUpdate);
client.removeListener("userStopProduce", forceUpdate); client.removeListener("userStopProduce", stateUpdate);
client.removeListener("close", forceUpdate); client.removeListener("close", stateUpdate);
}; };
}, [ client, state ]); }, [client, state, playSound, setStatus]);
return ( return (
<VoiceContext.Provider value={state}> <VoiceContext.Provider value={state}>
<VoiceOperationsContext.Provider value={operations}> <VoiceOperationsContext.Provider value={operations}>
{ children } {children}
</VoiceOperationsContext.Provider> </VoiceOperationsContext.Provider>
</VoiceContext.Provider> </VoiceContext.Provider>
); );
......
import State from "../redux/State";
import { Children } from "../types/Preact";
import { BrowserRouter as Router } from "react-router-dom"; import { BrowserRouter as Router } from "react-router-dom";
import Intermediate from './intermediate/Intermediate'; import State from "../redux/State";
import Client from './revoltjs/RevoltClient';
import Settings from "./Settings"; import { Children } from "../types/Preact";
import Locale from "./Locale"; import Locale from "./Locale";
import Voice from "./Voice"; import Settings from "./Settings";
import Theme from "./Theme"; import Theme from "./Theme";
import Voice from "./Voice";
import Intermediate from "./intermediate/Intermediate";
import Client from "./revoltjs/RevoltClient";
export default function Context({ children }: { children: Children }) { export default function Context({ children }: { children: Children }) {
return ( return (
...@@ -18,9 +19,7 @@ export default function Context({ children }: { children: Children }) { ...@@ -18,9 +19,7 @@ export default function Context({ children }: { children: Children }) {
<Locale> <Locale>
<Intermediate> <Intermediate>
<Client> <Client>
<Voice> <Voice>{children}</Voice>
{children}
</Voice>
</Client> </Client>
</Intermediate> </Intermediate>
</Locale> </Locale>
......
import { Attachment, Channels, EmbedImage, Servers } from "revolt.js/dist/api/objects"; import { Prompt } from "react-router";
import { useHistory } from "react-router-dom";
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"; import { useContext, useEffect, useMemo, useState } from "preact/hooks";
import { internalSubscribe } from "../../lib/eventEmitter"; import { internalSubscribe } from "../../lib/eventEmitter";
import { Action } from "../../components/ui/Modal"; import { Action } from "../../components/ui/Modal";
import { useHistory } from "react-router-dom";
import { Children } from "../../types/Preact"; import { Children } from "../../types/Preact";
import { createContext } from "preact"; import Modals from "./Modals";
import { Prompt } from "react-router";
import Modals from './Modals';
export type Screen = export type Screen =
| { id: "none" } | { id: "none" }
// Modals // Modals
| { id: "signed_out" } | { id: "signed_out" }
| { id: "error"; error: string } | { id: "error"; error: string }
| { id: "clipboard"; text: string } | { id: "clipboard"; text: string }
| { id: "_prompt"; question: Children; content?: Children; actions: Action[] } | {
| ({ id: "special_prompt" } & ( id: "_prompt";
{ type: "leave_group", target: Channels.GroupChannel } | question: Children;
{ type: "close_dm", target: Channels.DirectMessageChannel } | content?: Children;
{ type: "leave_server", target: Servers.Server } | actions: Action[];
{ type: "delete_server", target: Servers.Server } | }
{ type: "delete_channel", target: Channels.TextChannel } | | ({ id: "special_prompt" } & (
{ type: "delete_message", target: Channels.Message } | | { type: "leave_group"; target: Channel }
{ type: "create_invite", target: Channels.TextChannel | Channels.GroupChannel } | | { type: "close_dm"; target: Channel }
{ type: "kick_member", target: Servers.Server, user: string } | | { type: "leave_server"; target: Server }
{ type: "ban_member", target: Servers.Server, user: string } | | { type: "delete_server"; target: Server }
{ type: "create_channel", target: Servers.Server } | { type: "delete_channel"; target: Channel }
)) | | { type: "delete_message"; target: Message }
({ id: "special_input" } & ( | {
{ type: "create_group" | "create_server" | "set_custom_status" | "add_friend" } type: "create_invite";
)) target: Channel;
| { }
id: "_input"; | { type: "kick_member"; target: Server; user: User }
question: Children; | { type: "ban_member"; target: Server; user: User }
field: Children; | { type: "unfriend_user"; target: User }
defaultValue?: string; | { type: "block_user"; target: User }
callback: (value: string) => Promise<void>; | { type: "create_channel"; target: Server }
} ))
| { | ({ id: "special_input" } & (
id: "onboarding"; | {
callback: ( type:
username: string, | "create_group"
loginAfterSuccess?: true | "create_server"
) => Promise<void>; | "set_custom_status"
} | "add_friend";
}
// Pop-overs | {
| { id: "image_viewer"; attachment?: Attachment; embed?: EmbedImage; } type: "create_role";
| { id: "modify_account"; field: "username" | "email" | "password" } server: Server;
| { id: "profile"; user_id: string } callback: (id: string) => void;
| { id: "channel_info"; channel_id: string } }
| { ))
id: "user_picker"; | {
omit?: string[]; id: "_input";
callback: (users: string[]) => Promise<void>; question: Children;
}; field: Children;
defaultValue?: string;
callback: (value: string) => Promise<void>;
}
| {
id: "onboarding";
callback: (
username: string,
loginAfterSuccess?: true,
) => Promise<void>;
}
// Pop-overs
| { id: "image_viewer"; attachment?: Attachment; embed?: EmbedImage }
| { id: "modify_account"; field: "username" | "email" | "password" }
| { id: "profile"; user_id: string }
| { id: "channel_info"; channel: Channel }
| { id: "pending_requests"; users: User[] }
| {
id: "user_picker";
omit?: string[];
callback: (users: string[]) => Promise<void>;
};
export const IntermediateContext = createContext({ export const IntermediateContext = createContext({
screen: { id: "none" } as Screen, screen: { id: "none" },
focusTaken: false focusTaken: false,
}); });
export const IntermediateActionsContext = createContext({ export const IntermediateActionsContext = createContext<{
openScreen: (screen: Screen) => {}, openScreen: (screen: Screen) => void;
writeClipboard: (text: string) => {} writeClipboard: (text: string) => void;
}>({
openScreen: null!,
writeClipboard: null!,
}); });
interface Props { interface Props {
...@@ -77,7 +111,7 @@ export default function Intermediate(props: Props) { ...@@ -77,7 +111,7 @@ export default function Intermediate(props: Props) {
const value = { const value = {
screen, screen,
focusTaken: screen.id !== 'none' focusTaken: screen.id !== "none",
}; };
const actions = useMemo(() => { const actions = useMemo(() => {
...@@ -89,26 +123,35 @@ export default function Intermediate(props: Props) { ...@@ -89,26 +123,35 @@ export default function Intermediate(props: Props) {
} else { } else {
actions.openScreen({ id: "clipboard", text }); actions.openScreen({ id: "clipboard", text });
} }
} },
} };
}, []); }, []);
useEffect(() => { useEffect(() => {
const openProfile = (user_id: string) => openScreen({ id: "profile", user_id }); const openProfile = (user_id: string) =>
openScreen({ id: "profile", user_id });
const navigate = (path: string) => history.push(path); const navigate = (path: string) => history.push(path);
const subs = [ const subs = [
internalSubscribe("Intermediate", "open_profile", openProfile), internalSubscribe(
internalSubscribe("Intermediate", "navigate", navigate) "Intermediate",
] "openProfile",
openProfile as (...args: unknown[]) => void,
return () => subs.map(unsub => unsub()); ),
}, []); internalSubscribe(
"Intermediate",
"navigate",
navigate as (...args: unknown[]) => void,
),
];
return () => subs.map((unsub) => unsub());
}, [history]);
return ( return (
<IntermediateContext.Provider value={value}> <IntermediateContext.Provider value={value}>
<IntermediateActionsContext.Provider value={actions}> <IntermediateActionsContext.Provider value={actions}>
{ screen.id !== 'onboarding' && props.children } {screen.id !== "onboarding" && props.children}
<Modals <Modals
{...value} {...value}
{...actions} {...actions}
...@@ -117,10 +160,19 @@ export default function Intermediate(props: Props) { ...@@ -117,10 +160,19 @@ export default function Intermediate(props: Props) {
} /** By specifying a key, we reset state whenever switching screen. */ } /** By specifying a key, we reset state whenever switching screen. */
/> />
<Prompt <Prompt
when={[ 'modify_account', 'special_prompt', 'special_input', 'image_viewer', 'profile', 'channel_info', 'user_picker' ].includes(screen.id)} when={[
"modify_account",
"special_prompt",
"special_input",
"image_viewer",
"profile",
"channel_info",
"pending_requests",
"user_picker",
].includes(screen.id)}
message={(_, action) => { message={(_, action) => {
if (action === 'POP') { if (action === "POP") {
openScreen({ id: 'none' }); openScreen({ id: "none" });
setTimeout(() => history.push(history.location), 0); setTimeout(() => history.push(history.location), 0);
return false; return false;
......
import { Screen } from "./Intermediate"; 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"; import { ErrorModal } from "./modals/Error";
import { InputModal } from "./modals/Input"; import { InputModal } from "./modals/Input";
import { OnboardingModal } from "./modals/Onboarding";
import { PromptModal } from "./modals/Prompt"; import { PromptModal } from "./modals/Prompt";
import { SignedOutModal } from "./modals/SignedOut"; import { SignedOutModal } from "./modals/SignedOut";
import { ClipboardModal } from "./modals/Clipboard";
import { OnboardingModal } from "./modals/Onboarding";
export interface Props { export interface Props {
screen: Screen; screen: Screen;
openScreen: (id: any) => void; openScreen: (screen: Screen) => void;
} }
export default function Modals({ screen, openScreen }: Props) { export default function Modals({ screen, openScreen }: Props) {
const onClose = () => openScreen({ id: "none" }); const onClose = () =>
isModalClosing || screen.id === "onboarding"
? openScreen({ id: "none" })
: internalEmit("Modal", "close");
switch (screen.id) { switch (screen.id) {
case "_prompt": case "_prompt":
......
import { IntermediateContext, useIntermediate } from "./Intermediate";
import { useContext } from "preact/hooks"; import { useContext } from "preact/hooks";
import { UserPicker } from "./popovers/UserPicker"; import { internalEmit } from "../../lib/eventEmitter";
import { isModalClosing } from "../../components/ui/Modal";
import { IntermediateContext, useIntermediate } from "./Intermediate";
import { SpecialInputModal } from "./modals/Input"; import { SpecialInputModal } from "./modals/Input";
import { SpecialPromptModal } from "./modals/Prompt"; import { SpecialPromptModal } from "./modals/Prompt";
import { UserProfile } from "./popovers/UserProfile";
import { ImageViewer } from "./popovers/ImageViewer";
import { ChannelInfo } from "./popovers/ChannelInfo"; import { ChannelInfo } from "./popovers/ChannelInfo";
import { ImageViewer } from "./popovers/ImageViewer";
import { ModifyAccountModal } from "./popovers/ModifyAccount"; import { ModifyAccountModal } from "./popovers/ModifyAccount";
import { PendingRequests } from "./popovers/PendingRequests";
import { UserPicker } from "./popovers/UserPicker";
import { UserProfile } from "./popovers/UserProfile";
export default function Popovers() { export default function Popovers() {
const { screen } = useContext(IntermediateContext); const { screen } = useContext(IntermediateContext);
const { openScreen } = useIntermediate(); const { openScreen } = useIntermediate();
const onClose = () => openScreen({ id: "none" }); const onClose = () =>
isModalClosing
? openScreen({ id: "none" })
: internalEmit("Modal", "close");
switch (screen.id) { switch (screen.id) {
case "profile": case "profile":
...@@ -24,6 +32,8 @@ export default function Popovers() { ...@@ -24,6 +32,8 @@ export default function Popovers() {
return <ImageViewer {...screen} onClose={onClose} />; return <ImageViewer {...screen} onClose={onClose} />;
case "channel_info": case "channel_info":
return <ChannelInfo {...screen} onClose={onClose} />; return <ChannelInfo {...screen} onClose={onClose} />;
case "pending_requests":
return <PendingRequests {...screen} onClose={onClose} />;
case "modify_account": case "modify_account":
return <ModifyAccountModal onClose={onClose} {...screen} />; return <ModifyAccountModal onClose={onClose} {...screen} />;
case "special_prompt": case "special_prompt":
......
import { Text } from "preact-i18n"; import { Text } from "preact-i18n";
import Modal from "../../../components/ui/Modal"; import Modal from "../../../components/ui/Modal";
interface Props { interface Props {
...@@ -16,10 +17,9 @@ export function ClipboardModal({ onClose, text }: Props) { ...@@ -16,10 +17,9 @@ export function ClipboardModal({ onClose, text }: Props) {
{ {
onClick: onClose, onClick: onClose,
confirmation: true, confirmation: true,
text: <Text id="app.special.modals.actions.close" /> children: <Text id="app.special.modals.actions.close" />,
} },
]} ]}>
>
{location.protocol !== "https:" && ( {location.protocol !== "https:" && (
<p> <p>
<Text id="app.special.modals.clipboard.https" /> <Text id="app.special.modals.clipboard.https" />
......
import { Text } from "preact-i18n"; import { Text } from "preact-i18n";
import Modal from "../../../components/ui/Modal"; import Modal from "../../../components/ui/Modal";
interface Props { interface Props {
...@@ -16,14 +17,13 @@ export function ErrorModal({ onClose, error }: Props) { ...@@ -16,14 +17,13 @@ export function ErrorModal({ onClose, error }: Props) {
{ {
onClick: onClose, onClick: onClose,
confirmation: true, confirmation: true,
text: <Text id="app.special.modals.actions.ok" /> children: <Text id="app.special.modals.actions.ok" />,
}, },
{ {
onClick: () => location.reload(), onClick: () => location.reload(),
text: <Text id="app.special.modals.actions.reload" /> children: <Text id="app.special.modals.actions.reload" />,
} },
]} ]}>
>
<Text id={`error.${error}`}>{error}</Text> <Text id={`error.${error}`}>{error}</Text>
</Modal> </Modal>
); );
......
import { useHistory } from "react-router";
import { Server } from "revolt.js/dist/maps/Servers";
import { ulid } from "ulid"; import { ulid } from "ulid";
import { Text } from "preact-i18n"; import { Text } from "preact-i18n";
import { useHistory } from "react-router"; import { useContext, useState } from "preact/hooks";
import InputBox from "../../../components/ui/InputBox";
import Modal from "../../../components/ui/Modal"; import Modal from "../../../components/ui/Modal";
import Overline from "../../../components/ui/Overline";
import { Children } from "../../../types/Preact"; import { Children } from "../../../types/Preact";
import { takeError } from "../../revoltjs/util";
import { useContext, useState } from "preact/hooks";
import Overline from '../../../components/ui/Overline';
import InputBox from '../../../components/ui/InputBox';
import { AppContext } from "../../revoltjs/RevoltClient"; import { AppContext } from "../../revoltjs/RevoltClient";
import { takeError } from "../../revoltjs/util";
interface Props { interface Props {
onClose: () => void; onClose: () => void;
...@@ -22,7 +26,7 @@ export function InputModal({ ...@@ -22,7 +26,7 @@ export function InputModal({
question, question,
field, field,
defaultValue, defaultValue,
callback callback,
}: Props) { }: Props) {
const [processing, setProcessing] = useState(false); const [processing, setProcessing] = useState(false);
const [value, setValue] = useState(defaultValue ?? ""); const [value, setValue] = useState(defaultValue ?? "");
...@@ -35,38 +39,51 @@ export function InputModal({ ...@@ -35,38 +39,51 @@ export function InputModal({
disabled={processing} disabled={processing}
actions={[ actions={[
{ {
text: <Text id="app.special.modals.actions.ok" />, confirmation: true,
children: <Text id="app.special.modals.actions.ok" />,
onClick: () => { onClick: () => {
setProcessing(true); setProcessing(true);
callback(value) callback(value)
.then(onClose) .then(onClose)
.catch(err => { .catch((err) => {
setError(takeError(err)); setError(takeError(err));
setProcessing(false) setProcessing(false);
}) });
} },
}, },
{ {
text: <Text id="app.special.modals.actions.cancel" />, children: <Text id="app.special.modals.actions.cancel" />,
onClick: onClose onClick: onClose,
} },
]} ]}
onClose={onClose} onClose={onClose}>
> <form>
{ field ? <Overline error={error} block> {field ? (
{field} <Overline error={error} block>
</Overline> : (error && <Overline error={error} type="error" block />) } {field}
<InputBox </Overline>
value={value} ) : (
onChange={e => setValue(e.currentTarget.value)} error && <Overline error={error} type="error" block />
/> )}
<InputBox
value={value}
onChange={(e) => setValue(e.currentTarget.value)}
/>
</form>
</Modal> </Modal>
); );
} }
type SpecialProps = { onClose: () => void } & ( type SpecialProps = { onClose: () => void } & (
{ type: "create_group" | "create_server" | "set_custom_status" | "add_friend" } | {
) type:
| "create_group"
| "create_server"
| "set_custom_status"
| "add_friend";
}
| { type: "create_role"; server: Server; callback: (id: string) => void }
);
export function SpecialInputModal(props: SpecialProps) { export function SpecialInputModal(props: SpecialProps) {
const history = useHistory(); const history = useHistory();
...@@ -75,65 +92,90 @@ export function SpecialInputModal(props: SpecialProps) { ...@@ -75,65 +92,90 @@ export function SpecialInputModal(props: SpecialProps) {
const { onClose } = props; const { onClose } = props;
switch (props.type) { switch (props.type) {
case "create_group": { case "create_group": {
return <InputModal return (
onClose={onClose} <InputModal
question={<Text id="app.main.groups.create" />} onClose={onClose}
field={<Text id="app.main.groups.name" />} question={<Text id="app.main.groups.create" />}
callback={async name => { field={<Text id="app.main.groups.name" />}
const group = await client.channels.createGroup( callback={async (name) => {
{ const group = await client.channels.createGroup({
name, name,
nonce: ulid(), nonce: ulid(),
users: [] users: [],
} });
);
history.push(`/channel/${group._id}`); history.push(`/channel/${group._id}`);
}} }}
/>; />
);
} }
case "create_server": { case "create_server": {
return <InputModal return (
onClose={onClose} <InputModal
question={<Text id="app.main.servers.create" />} onClose={onClose}
field={<Text id="app.main.servers.name" />} question={<Text id="app.main.servers.create" />}
callback={async name => { field={<Text id="app.main.servers.name" />}
const server = await client.servers.createServer( callback={async (name) => {
{ const server = await client.servers.createServer({
name, name,
nonce: ulid() nonce: ulid(),
} });
);
history.push(`/server/${server._id}`); history.push(`/server/${server._id}`);
}} }}
/>; />
);
}
case "create_role": {
return (
<InputModal
onClose={onClose}
question={
<Text id="app.settings.permissions.create_role" />
}
field={<Text id="app.settings.permissions.role_name" />}
callback={async (name) => {
const role = await props.server.createRole(name);
props.callback(role.id);
}}
/>
);
} }
case "set_custom_status": { case "set_custom_status": {
return <InputModal return (
onClose={onClose} <InputModal
question={<Text id="app.context_menu.set_custom_status" />} onClose={onClose}
field={<Text id="app.context_menu.custom_status" />} question={<Text id="app.context_menu.set_custom_status" />}
defaultValue={client.user?.status?.text} field={<Text id="app.context_menu.custom_status" />}
callback={text => defaultValue={client.user?.status?.text}
client.users.editUser({ callback={(text) =>
status: { client.users.edit({
...client.user?.status, status: {
text: text.trim().length > 0 ? text : undefined ...client.user?.status,
} text: text.trim().length > 0 ? text : undefined,
}) },
} })
/>; }
/>
);
} }
case "add_friend": { case "add_friend": {
return <InputModal return (
onClose={onClose} <InputModal
question={"Add Friend"} onClose={onClose}
callback={username => question={"Add Friend"}
client.users.addFriend(username) callback={(username) =>
} client
/>; .req(
"PUT",
`/users/${username}/friend` as "/users/id/friend",
)
.then(undefined)
}
/>
);
} }
default: return null; default:
return null;
} }
} }
...@@ -26,7 +26,7 @@ ...@@ -26,7 +26,7 @@
margin: auto; margin: auto;
display: block; display: block;
max-height: 420px; max-height: 420px;
border-radius: 8px; border-radius: var(--border-radius);
} }
input { input {
......
import { SubmitHandler, useForm } from "react-hook-form";
import styles from "./Onboarding.module.scss";
import { Text } from "preact-i18n"; import { Text } from "preact-i18n";
import { useState } from "preact/hooks"; import { useState } from "preact/hooks";
import { useForm } from "react-hook-form";
import styles from "./Onboarding.module.scss"; import wideSVG from "../../../assets/wide.svg";
import { takeError } from "../../revoltjs/util";
import Button from "../../../components/ui/Button"; import Button from "../../../components/ui/Button";
import FormField from "../../../pages/login/FormField";
import Preloader from "../../../components/ui/Preloader"; import Preloader from "../../../components/ui/Preloader";
import wideSVG from '../../../assets/wide.svg'; import FormField from "../../../pages/login/FormField";
import { takeError } from "../../revoltjs/util";
interface Props { interface Props {
onClose: () => void; onClose: () => void;
callback: (username: string, loginAfterSuccess?: true) => Promise<void>; callback: (username: string, loginAfterSuccess?: true) => Promise<void>;
} }
interface FormInputs {
username: string;
}
export function OnboardingModal({ onClose, callback }: Props) { export function OnboardingModal({ onClose, callback }: Props) {
const { handleSubmit, register } = useForm(); const { handleSubmit, register } = useForm<FormInputs>();
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | undefined>(undefined); const [error, setError] = useState<string | undefined>(undefined);
async function onSubmit({ username }: { username: string }) { const onSubmit: SubmitHandler<FormInputs> = ({ username }) => {
setLoading(true); setLoading(true);
callback(username, true) callback(username, true)
.then(onClose) .then(() => onClose())
.catch((err: any) => { .catch((err: unknown) => {
setError(takeError(err)); setError(takeError(err));
setLoading(false); setLoading(false);
}); });
} };
return ( return (
<div className={styles.onboarding}> <div className={styles.onboarding}>
<div className={styles.header}> <div className={styles.header}>
<h1> <h1>
<Text id="app.special.modals.onboarding.welcome" /> <Text id="app.special.modals.onboarding.welcome" />
<img src={wideSVG} /> <img src={wideSVG} loading="eager" />
</h1> </h1>
</div> </div>
<div className={styles.form}> <div className={styles.form}>
...@@ -45,7 +51,12 @@ export function OnboardingModal({ onClose, callback }: Props) { ...@@ -45,7 +51,12 @@ export function OnboardingModal({ onClose, callback }: Props) {
<p> <p>
<Text id="app.special.modals.onboarding.pick" /> <Text id="app.special.modals.onboarding.pick" />
</p> </p>
<form onSubmit={handleSubmit(onSubmit) as any}> <form
onSubmit={
handleSubmit(
onSubmit,
) as JSX.GenericEventHandler<HTMLFormElement>
}>
<div> <div>
<FormField <FormField
type="username" type="username"
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
user-select: all; user-select: all;
font-size: 1.4em; font-size: 1.4em;
text-align: center; text-align: center;
font-family: "Fira Mono"; font-family: var(--monospace-font);
} }
} }
......
import { observer } from "mobx-react-lite";
import { useHistory } from "react-router-dom";
import { Channel } from "revolt.js/dist/maps/Channels";
import { Message as MessageI } from "revolt.js/dist/maps/Messages";
import { Server } from "revolt.js/dist/maps/Servers";
import { User } from "revolt.js/dist/maps/Users";
import { ulid } from "ulid"; import { ulid } from "ulid";
import styles from "./Prompt.module.scss";
import { Text } from "preact-i18n"; import { Text } from "preact-i18n";
import styles from './Prompt.module.scss'; import { useContext, useEffect, useState } from "preact/hooks";
import { useHistory } from "react-router-dom";
import Radio from "../../../components/ui/Radio"; import { TextReact } from "../../../lib/i18n";
import { Children } from "../../../types/Preact";
import { useIntermediate } from "../Intermediate"; import Message from "../../../components/common/messaging/Message";
import UserIcon from "../../../components/common/user/UserIcon";
import InputBox from "../../../components/ui/InputBox"; import InputBox from "../../../components/ui/InputBox";
import Modal, { Action } from "../../../components/ui/Modal";
import Overline from "../../../components/ui/Overline"; import Overline from "../../../components/ui/Overline";
import Radio from "../../../components/ui/Radio";
import { Children } from "../../../types/Preact";
import { AppContext } from "../../revoltjs/RevoltClient"; import { AppContext } from "../../revoltjs/RevoltClient";
import { mapMessage, takeError } from "../../revoltjs/util"; import { takeError } from "../../revoltjs/util";
import Modal, { Action } from "../../../components/ui/Modal"; import { useIntermediate } from "../Intermediate";
import { Channels, Servers } from "revolt.js/dist/api/objects";
import { useContext, useEffect, useState } from "preact/hooks";
import UserIcon from "../../../components/common/user/UserIcon";
import Message from "../../../components/common/messaging/Message";
interface Props { interface Props {
onClose: () => void; onClose: () => void;
...@@ -24,7 +33,14 @@ interface Props { ...@@ -24,7 +33,14 @@ interface Props {
error?: string; error?: string;
} }
export function PromptModal({ onClose, question, content, actions, disabled, error }: Props) { export function PromptModal({
onClose,
question,
content,
actions,
disabled,
error,
}: Props) {
return ( return (
<Modal <Modal
visible={true} visible={true}
...@@ -32,69 +48,107 @@ export function PromptModal({ onClose, question, content, actions, disabled, err ...@@ -32,69 +48,107 @@ export function PromptModal({ onClose, question, content, actions, disabled, err
actions={actions} actions={actions}
onClose={onClose} onClose={onClose}
disabled={disabled}> disabled={disabled}>
{ error && <Overline error={error} type="error" /> } {error && <Overline error={error} type="error" />}
{ content } {content}
</Modal> </Modal>
); );
} }
type SpecialProps = { onClose: () => void } & ( type SpecialProps = { onClose: () => void } & (
{ type: "leave_group", target: Channels.GroupChannel } | | { type: "leave_group"; target: Channel }
{ type: "close_dm", target: Channels.DirectMessageChannel } | | { type: "close_dm"; target: Channel }
{ type: "leave_server", target: Servers.Server } | | { type: "leave_server"; target: Server }
{ type: "delete_server", target: Servers.Server } | | { type: "delete_server"; target: Server }
{ type: "delete_channel", target: Channels.TextChannel } | | { type: "delete_channel"; target: Channel }
{ type: "delete_message", target: Channels.Message } | | { type: "delete_message"; target: MessageI }
{ type: "create_invite", target: Channels.TextChannel | Channels.GroupChannel } | | {
{ type: "kick_member", target: Servers.Server, user: string } | type: "create_invite";
{ type: "ban_member", target: Servers.Server, user: string } | target: Channel;
{ 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 }
);
export function SpecialPromptModal(props: SpecialProps) { export const SpecialPromptModal = observer((props: SpecialProps) => {
const client = useContext(AppContext); const client = useContext(AppContext);
const [ processing, setProcessing ] = useState(false); const [processing, setProcessing] = useState(false);
const [ error, setError ] = useState<undefined | string>(undefined); const [error, setError] = useState<undefined | string>(undefined);
const { onClose } = props; const { onClose } = props;
switch (props.type) { switch (props.type) {
case 'leave_group': case "leave_group":
case 'close_dm': case "close_dm":
case 'leave_server': case "leave_server":
case 'delete_server': case "delete_server":
case 'delete_channel': { case "delete_channel":
case "unfriend_user":
case "block_user": {
const EVENTS = { const EVENTS = {
'close_dm': 'confirm_close_dm', close_dm: ["confirm_close_dm", "close"],
'delete_server': 'confirm_delete', delete_server: ["confirm_delete", "delete"],
'delete_channel': 'confirm_delete', delete_channel: ["confirm_delete", "delete"],
'leave_group': 'confirm_leave', leave_group: ["confirm_leave", "leave"],
'leave_server': 'confirm_leave' leave_server: ["confirm_leave", "leave"],
unfriend_user: ["unfriend_user", "remove"],
block_user: ["block_user", "block"],
}; };
let event = EVENTS[props.type]; const event = EVENTS[props.type];
let name = props.type === 'close_dm' ? client.users.get(client.channels.getRecipient(props.target._id))?.username : props.target.name; let name;
switch (props.type) {
case "unfriend_user":
case "block_user":
name = props.target.username;
break;
case "close_dm":
name = props.target.recipient?.username;
break;
default:
name = props.target.name;
}
return ( return (
<PromptModal <PromptModal
onClose={onClose} onClose={onClose}
question={<Text question={
id={`app.special.modals.prompt.${event}`} <Text
fields={{ name }} id={`app.special.modals.prompt.${event[0]}`}
/>} fields={{ name }}
/>
}
actions={[ actions={[
{ {
confirmation: true, confirmation: true,
contrast: true, contrast: true,
error: true, error: true,
text: <Text id="app.special.modals.actions.delete" />, children: (
<Text
id={`app.special.modals.actions.${event[1]}`}
/>
),
onClick: async () => { onClick: async () => {
setProcessing(true); setProcessing(true);
try { try {
if (props.type === 'leave_group' || props.type === 'close_dm' || props.type === 'delete_channel') { switch (props.type) {
await client.channels.delete(props.target._id); case "unfriend_user":
} else { await props.target.removeFriend();
await client.servers.delete(props.target._id); break;
case "block_user":
await props.target.blockUser();
break;
case "leave_group":
case "close_dm":
case "delete_channel":
props.target.delete();
break;
case "leave_server":
case "delete_server":
props.target.delete();
break;
} }
onClose(); onClose();
...@@ -102,63 +156,89 @@ export function SpecialPromptModal(props: SpecialProps) { ...@@ -102,63 +156,89 @@ export function SpecialPromptModal(props: SpecialProps) {
setError(takeError(err)); setError(takeError(err));
setProcessing(false); setProcessing(false);
} }
} },
},
{
children: (
<Text id="app.special.modals.actions.cancel" />
),
onClick: onClose,
}, },
{ text: <Text id="app.special.modals.actions.cancel" />, onClick: onClose }
]} ]}
content={<Text id={`app.special.modals.prompt.${event}_long`} />} content={
<TextReact
id={`app.special.modals.prompt.${event[0]}_long`}
fields={{ name: <b>{name}</b> }}
/>
}
disabled={processing} disabled={processing}
error={error} error={error}
/> />
) );
} }
case 'delete_message': { case "delete_message": {
return ( return (
<PromptModal <PromptModal
onClose={onClose} onClose={onClose}
question={<Text id={'app.context_menu.delete_message'} />} question={<Text id={"app.context_menu.delete_message"} />}
actions={[ actions={[
{ {
confirmation: true, confirmation: true,
contrast: true, contrast: true,
error: true, error: true,
text: <Text id="app.special.modals.actions.delete" />, children: (
<Text id="app.special.modals.actions.delete" />
),
onClick: async () => { onClick: async () => {
setProcessing(true); setProcessing(true);
try { try {
await client.channels.deleteMessage(props.target.channel, props.target._id); props.target.delete();
onClose(); onClose();
} catch (err) { } catch (err) {
setError(takeError(err)); setError(takeError(err));
setProcessing(false); setProcessing(false);
} }
} },
},
{
children: (
<Text id="app.special.modals.actions.cancel" />
),
onClick: onClose,
plain: true,
}, },
{ text: <Text id="app.special.modals.actions.cancel" />, onClick: onClose }
]} ]}
content={<> content={
<Text id={`app.special.modals.prompt.confirm_delete_message_long`} /> <>
<Message message={mapMessage(props.target)} head={true} contrast /> <Text
</>} id={`app.special.modals.prompt.confirm_delete_message_long`}
/>
<Message
message={props.target}
head={true}
contrast
/>
</>
}
disabled={processing} disabled={processing}
error={error} error={error}
/> />
) );
} }
case "create_invite": { case "create_invite": {
const [ code, setCode ] = useState('abcdef'); const [code, setCode] = useState("abcdef");
const { writeClipboard } = useIntermediate(); const { writeClipboard } = useIntermediate();
useEffect(() => { useEffect(() => {
setProcessing(true); setProcessing(true);
client.channels.createInvite(props.target._id) props.target
.then(code => setCode(code)) .createInvite()
.catch(err => setError(takeError(err))) .then((code) => setCode(code))
.catch((err) => setError(takeError(err)))
.finally(() => setProcessing(false)); .finally(() => setProcessing(false));
}, []); }, [props.target]);
return ( return (
<PromptModal <PromptModal
...@@ -166,69 +246,89 @@ export function SpecialPromptModal(props: SpecialProps) { ...@@ -166,69 +246,89 @@ export function SpecialPromptModal(props: SpecialProps) {
question={<Text id={`app.context_menu.create_invite`} />} question={<Text id={`app.context_menu.create_invite`} />}
actions={[ actions={[
{ {
text: <Text id="app.special.modals.actions.ok" />, children: (
<Text id="app.special.modals.actions.ok" />
),
confirmation: true, confirmation: true,
onClick: onClose onClick: onClose,
}, },
{ {
text: <Text id="app.context_menu.copy_link" />, children: <Text id="app.context_menu.copy_link" />,
onClick: () => writeClipboard(`${window.location.protocol}//${window.location.host}/invite/${code}`) onClick: () =>
} writeClipboard(
`${window.location.protocol}//${window.location.host}/invite/${code}`,
),
},
]} ]}
content={ content={
processing ? processing ? (
<Text id="app.special.modals.prompt.create_invite_generate" /> <Text id="app.special.modals.prompt.create_invite_generate" />
: <div className={styles.invite}> ) : (
<Text id="app.special.modals.prompt.create_invite_created" /> <div className={styles.invite}>
<code>{code}</code> <Text id="app.special.modals.prompt.create_invite_created" />
<code>{code}</code>
</div> </div>
)
} }
disabled={processing} disabled={processing}
error={error} error={error}
/> />
) );
} }
case "kick_member": { case "kick_member": {
const user = client.users.get(props.user);
return ( return (
<PromptModal <PromptModal
onClose={onClose} onClose={onClose}
question={<Text id={`app.context_menu.kick_member`} />} question={<Text id={`app.context_menu.kick_member`} />}
actions={[ actions={[
{ {
text: <Text id="app.special.modals.actions.kick" />, children: (
<Text id="app.special.modals.actions.kick" />
),
contrast: true, contrast: true,
error: true, error: true,
confirmation: true, confirmation: true,
onClick: async () => { onClick: async () => {
setProcessing(true); setProcessing(true);
try { try {
await client.servers.members.kickMember(props.target._id, props.user); client.members
.getKey({
server: props.target._id,
user: props.user._id,
})
?.kick();
onClose(); onClose();
} catch (err) { } catch (err) {
setError(takeError(err)); setError(takeError(err));
setProcessing(false); setProcessing(false);
} }
} },
},
{
children: (
<Text id="app.special.modals.actions.cancel" />
),
onClick: onClose,
}, },
{ text: <Text id="app.special.modals.actions.cancel" />, onClick: onClose }
]} ]}
content={<div className={styles.column}> content={
<UserIcon target={user} size={64} /> <div className={styles.column}>
<Text <UserIcon target={props.user} size={64} />
id="app.special.modals.prompt.confirm_kick" <Text
fields={{ name: user?.username }} /> id="app.special.modals.prompt.confirm_kick"
</div>} fields={{ name: props.user?.username }}
/>
</div>
}
disabled={processing} disabled={processing}
error={error} error={error}
/> />
) );
} }
case "ban_member": { case "ban_member": {
const [ reason, setReason ] = useState<string | undefined>(undefined); const [reason, setReason] = useState<string | undefined>(undefined);
const user = client.users.get(props.user);
return ( return (
<PromptModal <PromptModal
...@@ -236,40 +336,59 @@ export function SpecialPromptModal(props: SpecialProps) { ...@@ -236,40 +336,59 @@ export function SpecialPromptModal(props: SpecialProps) {
question={<Text id={`app.context_menu.ban_member`} />} question={<Text id={`app.context_menu.ban_member`} />}
actions={[ actions={[
{ {
text: <Text id="app.special.modals.actions.ban" />, children: (
<Text id="app.special.modals.actions.ban" />
),
contrast: true, contrast: true,
error: true, error: true,
confirmation: true, confirmation: true,
onClick: async () => { onClick: async () => {
setProcessing(true); setProcessing(true);
try { try {
await client.servers.banUser(props.target._id, props.user, { reason }); await props.target.banUser(props.user._id, {
reason,
});
onClose(); onClose();
} catch (err) { } catch (err) {
setError(takeError(err)); setError(takeError(err));
setProcessing(false); setProcessing(false);
} }
} },
},
{
children: (
<Text id="app.special.modals.actions.cancel" />
),
onClick: onClose,
}, },
{ text: <Text id="app.special.modals.actions.cancel" />, onClick: onClose }
]} ]}
content={<div className={styles.column}> content={
<UserIcon target={user} size={64} /> <div className={styles.column}>
<Text <UserIcon target={props.user} size={64} />
id="app.special.modals.prompt.confirm_ban" <Text
fields={{ name: user?.username }} /> id="app.special.modals.prompt.confirm_ban"
<Overline><Text id="app.special.modals.prompt.confirm_ban_reason" /></Overline> fields={{ name: props.user?.username }}
<InputBox value={reason ?? ''} onChange={e => setReason(e.currentTarget.value)} /> />
</div>} <Overline>
<Text id="app.special.modals.prompt.confirm_ban_reason" />
</Overline>
<InputBox
value={reason ?? ""}
onChange={(e) =>
setReason(e.currentTarget.value)
}
/>
</div>
}
disabled={processing} disabled={processing}
error={error} error={error}
/> />
) );
} }
case 'create_channel': { case "create_channel": {
const [ name, setName ] = useState(''); const [name, setName] = useState("");
const [ type, setType ] = useState<'Text' | 'Voice'>('Text'); const [type, setType] = useState<"Text" | "Voice">("Text");
const history = useHistory(); const history = useHistory();
return ( return (
...@@ -280,46 +399,67 @@ export function SpecialPromptModal(props: SpecialProps) { ...@@ -280,46 +399,67 @@ export function SpecialPromptModal(props: SpecialProps) {
{ {
confirmation: true, confirmation: true,
contrast: true, contrast: true,
text: <Text id="app.special.modals.actions.create" />, children: (
<Text id="app.special.modals.actions.create" />
),
onClick: async () => { onClick: async () => {
setProcessing(true); setProcessing(true);
try { try {
const channel = await client.servers.createChannel( const channel =
props.target._id, await props.target.createChannel({
{
type, type,
name, name,
nonce: ulid() nonce: ulid(),
} });
history.push(
`/server/${props.target._id}/channel/${channel._id}`,
); );
history.push(`/server/${props.target._id}/channel/${channel._id}`);
onClose(); onClose();
} catch (err) { } catch (err) {
setError(takeError(err)); setError(takeError(err));
setProcessing(false); setProcessing(false);
} }
} },
},
{
children: (
<Text id="app.special.modals.actions.cancel" />
),
onClick: onClose,
}, },
{ text: <Text id="app.special.modals.actions.cancel" />, onClick: onClose }
]} ]}
content={<> content={
<Overline block type="subtle"><Text id="app.main.servers.channel_type" /></Overline> <>
<Radio checked={type === 'Text'} onSelect={() => setType('Text')}> <Overline block type="subtle">
<Text id="app.main.servers.text_channel" /></Radio> <Text id="app.main.servers.channel_type" />
<Radio checked={type === 'Voice'} onSelect={() => setType('Voice')}> </Overline>
<Text id="app.main.servers.voice_channel" /></Radio> <Radio
<Overline block type="subtle"><Text id="app.main.servers.channel_name" /></Overline> checked={type === "Text"}
<InputBox onSelect={() => setType("Text")}>
value={name} <Text id="app.main.servers.text_channel" />
onChange={e => setName(e.currentTarget.value)} /> </Radio>
</>} <Radio
checked={type === "Voice"}
onSelect={() => setType("Voice")}>
<Text id="app.main.servers.voice_channel" />
</Radio>
<Overline block type="subtle">
<Text id="app.main.servers.channel_name" />
</Overline>
<InputBox
value={name}
onChange={(e) => setName(e.currentTarget.value)}
/>
</>
}
disabled={processing} disabled={processing}
error={error} error={error}
/> />
) );
} }
default: return null; default:
return null;
} }
} });
import { Text } from "preact-i18n"; import { Text } from "preact-i18n";
import Modal from "../../../components/ui/Modal"; import Modal from "../../../components/ui/Modal";
interface Props { interface Props {
...@@ -15,8 +16,8 @@ export function SignedOutModal({ onClose }: Props) { ...@@ -15,8 +16,8 @@ export function SignedOutModal({ onClose }: Props) {
{ {
onClick: onClose, onClick: onClose,
confirmation: true, confirmation: true,
text: <Text id="app.special.modals.actions.ok" /> children: <Text id="app.special.modals.actions.ok" />,
} },
]} ]}
/> />
); );
......
import { X } from "@styled-icons/boxicons-regular"; import { X } from "@styled-icons/boxicons-regular";
import { observer } from "mobx-react-lite";
import { Channel } from "revolt.js/dist/maps/Channels";
import styles from "./ChannelInfo.module.scss"; import styles from "./ChannelInfo.module.scss";
import Modal from "../../../components/ui/Modal"; import Modal from "../../../components/ui/Modal";
import { getChannelName } from "../../revoltjs/util";
import Markdown from "../../../components/markdown/Markdown"; import Markdown from "../../../components/markdown/Markdown";
import { useChannel, useForceUpdate } from "../../revoltjs/hooks"; import { getChannelName } from "../../revoltjs/util";
interface Props { interface Props {
channel_id: string; channel: Channel;
onClose: () => void; onClose: () => void;
} }
export function ChannelInfo({ channel_id, onClose }: Props) { export const ChannelInfo = observer(({ channel, onClose }: Props) => {
const ctx = useForceUpdate(); if (
const channel = useChannel(channel_id, ctx); channel.channel_type === "DirectMessage" ||
if (!channel) return null; channel.channel_type === "SavedMessages"
) {
if (channel.channel_type === "DirectMessage" || channel.channel_type === 'SavedMessages') {
onClose(); onClose();
return null; return null;
} }
...@@ -24,15 +27,15 @@ export function ChannelInfo({ channel_id, onClose }: Props) { ...@@ -24,15 +27,15 @@ export function ChannelInfo({ channel_id, onClose }: Props) {
<Modal visible={true} onClose={onClose}> <Modal visible={true} onClose={onClose}>
<div className={styles.info}> <div className={styles.info}>
<div className={styles.header}> <div className={styles.header}>
<h1>{ getChannelName(ctx.client, channel, true) }</h1> <h1>{getChannelName(channel, true)}</h1>
<div onClick={onClose}> <div onClick={onClose}>
<X size={36} /> <X size={36} />
</div> </div>
</div> </div>
<p> <p>
<Markdown content={channel.description} /> <Markdown content={channel.description!} />
</p> </p>
</div> </div>
</Modal> </Modal>
); );
} });
.viewer { .viewer {
display: flex;
flex-direction: column;
border-end-end-radius: 4px;
border-end-start-radius: 4px;
overflow: hidden;
img { img {
width: auto;
height: auto;
max-width: 90vw; max-width: 90vw;
max-height: 90vh; max-height: 75vh;
border-bottom: thin solid var(--tertiary-foreground);
object-fit: contain;
} }
} }
/* eslint-disable react-hooks/rules-of-hooks */
import { Attachment, AttachmentMetadata } from "revolt-api/types/Autumn";
import { EmbedImage } from "revolt-api/types/January";
import styles from "./ImageViewer.module.scss"; import styles from "./ImageViewer.module.scss";
import Modal from "../../../components/ui/Modal";
import { useContext, useEffect } from "preact/hooks";
import { AppContext } from "../../revoltjs/RevoltClient";
import { Attachment, EmbedImage } from "revolt.js/dist/api/objects";
import EmbedMediaActions from "../../../components/common/messaging/embed/EmbedMediaActions";
import AttachmentActions from "../../../components/common/messaging/attachments/AttachmentActions"; import AttachmentActions from "../../../components/common/messaging/attachments/AttachmentActions";
import EmbedMediaActions from "../../../components/common/messaging/embed/EmbedMediaActions";
import Modal from "../../../components/ui/Modal";
import { useClient } from "../../revoltjs/RevoltClient";
interface Props { interface Props {
onClose: () => void; onClose: () => void;
...@@ -12,31 +16,45 @@ interface Props { ...@@ -12,31 +16,45 @@ interface Props {
attachment?: Attachment; attachment?: Attachment;
} }
type ImageMetadata = AttachmentMetadata & { type: "Image" };
export function ImageViewer({ attachment, embed, onClose }: Props) { export function ImageViewer({ attachment, embed, onClose }: Props) {
// ! FIXME: temp code if (attachment && attachment.metadata.type !== "Image") {
// ! add proxy function to client console.warn(
function proxyImage(url: string) { `Attempted to use a non valid attatchment type in the image viewer: ${attachment.metadata.type}`,
return 'https://jan.revolt.chat/proxy?url=' + encodeURIComponent(url); );
return null;
} }
if (attachment && attachment.metadata.type !== "Image") return null; const client = useClient();
const client = useContext(AppContext);
return ( return (
<Modal visible={true} onClose={onClose} noBackground> <Modal visible={true} onClose={onClose} noBackground>
<div className={styles.viewer}> <div className={styles.viewer}>
{ attachment && {attachment && (
<> <>
<img src={client.generateFileURL(attachment)} /> <img
loading="eager"
src={client.generateFileURL(attachment)}
width={(attachment.metadata as ImageMetadata).width}
height={
(attachment.metadata as ImageMetadata).height
}
/>
<AttachmentActions attachment={attachment} /> <AttachmentActions attachment={attachment} />
</> </>
} )}
{ embed && {embed && (
<> <>
<img src={proxyImage(embed.url)} /> <img
loading="eager"
src={client.proxyFile(embed.url)}
width={embed.width}
height={embed.height}
/>
<EmbedMediaActions embed={embed} /> <EmbedMediaActions embed={embed} />
</> </>
} )}
</div> </div>
</Modal> </Modal>
); );
......
import { SubmitHandler, useForm } from "react-hook-form";
import { Text } from "preact-i18n"; import { Text } from "preact-i18n";
import { useForm } from "react-hook-form";
import Modal from "../../../components/ui/Modal";
import { takeError } from "../../revoltjs/util";
import { useContext, useState } from "preact/hooks"; import { useContext, useState } from "preact/hooks";
import FormField from '../../../pages/login/FormField';
import Modal from "../../../components/ui/Modal";
import Overline from "../../../components/ui/Overline"; import Overline from "../../../components/ui/Overline";
import FormField from "../../../pages/login/FormField";
import { AppContext } from "../../revoltjs/RevoltClient"; import { AppContext } from "../../revoltjs/RevoltClient";
import { takeError } from "../../revoltjs/util";
interface Props { interface Props {
onClose: () => void; onClose: () => void;
field: "username" | "email" | "password"; field: "username" | "email" | "password";
} }
interface FormInputs {
password: string;
new_email: string;
new_username: string;
new_password: string;
// TODO: figure out if this is correct or not
// it wasn't in the types before this was typed but the element itself was there
current_password?: string;
}
export function ModifyAccountModal({ onClose, field }: Props) { export function ModifyAccountModal({ onClose, field }: Props) {
const client = useContext(AppContext); const client = useContext(AppContext);
const { handleSubmit, register, errors } = useForm(); const { handleSubmit, register, errors } = useForm<FormInputs>();
const [error, setError] = useState<string | undefined>(undefined); const [error, setError] = useState<string | undefined>(undefined);
async function onSubmit({ const onSubmit: SubmitHandler<FormInputs> = async ({
password, password,
new_username, new_username,
new_email, new_email,
new_password new_password,
}: { }) => {
password: string;
new_username: string;
new_email: string;
new_password: string;
}) {
try { try {
if (field === "email") { if (field === "email") {
await client.req("POST", "/auth/change/email", { await client.req("POST", "/auth/change/email", {
password, password,
new_email new_email,
}); });
onClose(); onClose();
} else if (field === "password") { } else if (field === "password") {
await client.req("POST", "/auth/change/password", { await client.req("POST", "/auth/change/password", {
password, password,
new_password new_password,
}); });
onClose(); onClose();
} else if (field === "username") { } else if (field === "username") {
await client.req("PATCH", "/users/id/username", { await client.req("PATCH", "/users/id/username", {
username: new_username, username: new_username,
password password,
}); });
onClose(); onClose();
} }
} catch (err) { } catch (err) {
setError(takeError(err)); setError(takeError(err));
} }
} };
return ( return (
<Modal <Modal
...@@ -62,20 +71,27 @@ export function ModifyAccountModal({ onClose, field }: Props) { ...@@ -62,20 +71,27 @@ export function ModifyAccountModal({ onClose, field }: Props) {
{ {
confirmation: true, confirmation: true,
onClick: handleSubmit(onSubmit), onClick: handleSubmit(onSubmit),
text: children:
field === "email" ? ( field === "email" ? (
<Text id="app.special.modals.actions.send_email" /> <Text id="app.special.modals.actions.send_email" />
) : ( ) : (
<Text id="app.special.modals.actions.update" /> <Text id="app.special.modals.actions.update" />
) ),
}, },
{ {
onClick: onClose, onClick: onClose,
text: <Text id="app.special.modals.actions.close" /> children: <Text id="app.special.modals.actions.close" />,
} },
]} ]}>
> {/* Preact / React typing incompatabilities */}
<form onSubmit={handleSubmit(onSubmit) as any}> <form
onSubmit={(e) => {
e.preventDefault();
handleSubmit(
onSubmit,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
)(e as any);
}}>
{field === "email" && ( {field === "email" && (
<FormField <FormField
type="email" type="email"
......