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 387 additions and 280 deletions
import dayjs from "dayjs";
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 { IntlProvider } from "preact-i18n";
import { useEffect, useState } from "preact/hooks";
import { useCallback, useEffect, useState } from "preact/hooks";
import { connectState } from "../redux/connector";
import definition from "../../external/lang/en.json";
export const dayjs = dayJS;
dayjs.extend(calendar);
dayjs.extend(format);
dayjs.extend(update);
......@@ -22,6 +24,7 @@ export enum Language {
AZERBAIJANI = "az",
CZECH = "cs",
GERMAN = "de",
GREEK = "el",
SPANISH = "es",
FINNISH = "fi",
FRENCH = "fr",
......@@ -29,6 +32,7 @@ export enum Language {
CROATIAN = "hr",
HUNGARIAN = "hu",
INDONESIAN = "id",
ITALIAN = "it",
LITHUANIAN = "lt",
MACEDONIAN = "mk",
DUTCH = "nl",
......@@ -38,6 +42,7 @@ export enum Language {
RUSSIAN = "ru",
SERBIAN = "sr",
SWEDISH = "sv",
TOKIPONA = "tokipona",
TURKISH = "tr",
UKRANIAN = "uk",
CHINESE_SIMPLIFIED = "zh_Hans",
......@@ -54,7 +59,7 @@ export interface LanguageEntry {
i18n: string;
dayjs?: string;
rtl?: boolean;
alt?: boolean;
cat?: "const" | "alt";
}
export const Languages: { [key in Language]: LanguageEntry } = {
......@@ -69,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" },
......@@ -99,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",
},
};
......@@ -134,72 +149,118 @@ 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;
// 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 ?? "/";
const twelvehour = defaults?.twelvehour === "yes" || true;
const separator: "/" | "-" | "." = 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) => k !== "defaults")
.filter((k) => typeof dayjs[k] === "string")
.forEach(
(k) =>
(dayjs[k] = dayjs[k].replace(
/{{time}}/g,
twelvehour ? "LT" : "HH:mm",
dayjs["timeFormat"],
)),
);
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`
);
if (defn.dayjs) {
dayjs.updateLocale(target, { calendar: defn.dayjs });
}
dayjs.locale(dayjs_locale.default);
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";
......@@ -234,7 +232,7 @@ export const PRESETS: Record<string, Theme> = {
mention: "rgba(251, 255, 0, 0.40)",
success: "#65E572",
warning: "#FAA352",
error: "#F06464",
error: "#ED4245",
hover: "rgba(0, 0, 0, 0.2)",
"scrollbar-thumb": "#CA525A",
"scrollbar-track": "transparent",
......@@ -261,7 +259,7 @@ export const PRESETS: Record<string, Theme> = {
mention: "rgba(251, 255, 0, 0.06)",
success: "#65E572",
warning: "#FAA352",
error: "#F06464",
error: "#ED4245",
hover: "rgba(0, 0, 0, 0.1)",
"scrollbar-thumb": "#CA525A",
"scrollbar-track": "transparent",
......@@ -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,19 +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={
isTouchscreenDevice
? theme["primary-header"]
: 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 { internalEmit } from "../../lib/eventEmitter";
import { isModalClosing } from "../../components/ui/Modal";
import { Screen } from "./Intermediate";
import { ClipboardModal } from "./modals/Clipboard";
import { ErrorModal } from "./modals/Error";
......@@ -8,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 = () => openScreen({ id: "none" });
const onClose = () =>
isModalClosing || screen.id === "onboarding"
? openScreen({ id: "none" })
: internalEmit("Modal", "close");
switch (screen.id) {
case "_prompt":
......
import { useContext } from "preact/hooks";
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";
......@@ -14,7 +18,10 @@ export default function Popovers() {
const { screen } = useContext(IntermediateContext);
const { openScreen } = useIntermediate();
const onClose = () => openScreen({ id: "none" });
const onClose = () =>
isModalClosing
? openScreen({ id: "none" })
: internalEmit("Modal", "close");
switch (screen.id) {
case "profile":
......
......@@ -17,7 +17,7 @@ export function ClipboardModal({ onClose, text }: Props) {
{
onClick: onClose,
confirmation: true,
text: <Text id="app.special.modals.actions.close" />,
children: <Text id="app.special.modals.actions.close" />,
},
]}>
{location.protocol !== "https:" && (
......
......@@ -17,11 +17,11 @@ export function ErrorModal({ onClose, error }: Props) {
{
onClick: onClose,
confirmation: true,
text: <Text id="app.special.modals.actions.ok" />,
children: <Text id="app.special.modals.actions.ok" />,
},
{
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>
......
import { useHistory } from "react-router";
import { Server } from "revolt.js/dist/maps/Servers";
import { ulid } from "ulid";
import { Text } from "preact-i18n";
......@@ -39,7 +40,7 @@ export function InputModal({
actions={[
{
confirmation: true,
text: <Text id="app.special.modals.actions.ok" />,
children: <Text id="app.special.modals.actions.ok" />,
onClick: () => {
setProcessing(true);
callback(value)
......@@ -51,7 +52,7 @@ export function InputModal({
},
},
{
text: <Text id="app.special.modals.actions.cancel" />,
children: <Text id="app.special.modals.actions.cancel" />,
onClick: onClose,
},
]}
......@@ -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 {
......
......@@ -28,8 +28,8 @@ export function OnboardingModal({ onClose, callback }: Props) {
const onSubmit: SubmitHandler<FormInputs> = ({ username }) => {
setLoading(true);
callback(username, true)
.then(onClose)
.catch((err: any) => {
.then(() => onClose())
.catch((err: unknown) => {
setError(takeError(err));
setLoading(false);
});
......@@ -40,7 +40,7 @@ export function OnboardingModal({ onClose, callback }: Props) {
<div className={styles.header}>
<h1>
<Text id="app.special.modals.onboarding.welcome" />
<img src={wideSVG} />
<img src={wideSVG} loading="eager" />
</h1>
</div>
<div className={styles.form}>
......
......@@ -7,7 +7,7 @@
user-select: all;
font-size: 1.4em;
text-align: center;
font-family: var(--monoscape-font);
font-family: var(--monospace-font);
}
}
......
import { observer } from "mobx-react-lite";
import { useHistory } from "react-router-dom";
import { Channels, Servers, Users } from "revolt.js/dist/api/objects";
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 styles from "./Prompt.module.scss";
......@@ -17,7 +21,7 @@ import Radio from "../../../components/ui/Radio";
import { Children } from "../../../types/Preact";
import { AppContext } from "../../revoltjs/RevoltClient";
import { mapMessage, takeError } from "../../revoltjs/util";
import { takeError } from "../../revoltjs/util";
import { useIntermediate } from "../Intermediate";
interface Props {
......@@ -51,24 +55,24 @@ export function PromptModal({
}
type SpecialProps = { onClose: () => void } & (
| { 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: MessageI }
| {
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 }
);
export function SpecialPromptModal(props: SpecialProps) {
export const SpecialPromptModal = observer((props: SpecialProps) => {
const client = useContext(AppContext);
const [processing, setProcessing] = useState(false);
const [error, setError] = useState<undefined | string>(undefined);
......@@ -92,7 +96,7 @@ export function SpecialPromptModal(props: SpecialProps) {
block_user: ["block_user", "block"],
};
let event = EVENTS[props.type];
const event = EVENTS[props.type];
let name;
switch (props.type) {
case "unfriend_user":
......@@ -100,9 +104,7 @@ export function SpecialPromptModal(props: SpecialProps) {
name = props.target.username;
break;
case "close_dm":
name = client.users.get(
client.channels.getRecipient(props.target._id),
)?.username;
name = props.target.recipient?.username;
break;
default:
name = props.target.name;
......@@ -122,7 +124,7 @@ export function SpecialPromptModal(props: SpecialProps) {
confirmation: true,
contrast: true,
error: true,
text: (
children: (
<Text
id={`app.special.modals.actions.${event[1]}`}
/>
......@@ -133,27 +135,19 @@ export function SpecialPromptModal(props: SpecialProps) {
try {
switch (props.type) {
case "unfriend_user":
await client.users.removeFriend(
props.target._id,
);
await props.target.removeFriend();
break;
case "block_user":
await client.users.blockUser(
props.target._id,
);
await props.target.blockUser();
break;
case "leave_group":
case "close_dm":
case "delete_channel":
await client.channels.delete(
props.target._id,
);
props.target.delete();
break;
case "leave_server":
case "delete_server":
await client.servers.delete(
props.target._id,
);
props.target.delete();
break;
}
......@@ -165,7 +159,7 @@ export function SpecialPromptModal(props: SpecialProps) {
},
},
{
text: (
children: (
<Text id="app.special.modals.actions.cancel" />
),
onClick: onClose,
......@@ -192,18 +186,14 @@ export function SpecialPromptModal(props: SpecialProps) {
confirmation: true,
contrast: true,
error: true,
text: (
children: (
<Text id="app.special.modals.actions.delete" />
),
onClick: async () => {
setProcessing(true);
try {
await client.channels.deleteMessage(
props.target.channel,
props.target._id,
);
props.target.delete();
onClose();
} catch (err) {
setError(takeError(err));
......@@ -212,10 +202,11 @@ export function SpecialPromptModal(props: SpecialProps) {
},
},
{
text: (
children: (
<Text id="app.special.modals.actions.cancel" />
),
onClick: onClose,
plain: true,
},
]}
content={
......@@ -224,7 +215,7 @@ export function SpecialPromptModal(props: SpecialProps) {
id={`app.special.modals.prompt.confirm_delete_message_long`}
/>
<Message
message={mapMessage(props.target)}
message={props.target}
head={true}
contrast
/>
......@@ -242,12 +233,12 @@ export function SpecialPromptModal(props: SpecialProps) {
useEffect(() => {
setProcessing(true);
client.channels
.createInvite(props.target._id)
props.target
.createInvite()
.then((code) => setCode(code))
.catch((err) => setError(takeError(err)))
.finally(() => setProcessing(false));
}, []);
}, [props.target]);
return (
<PromptModal
......@@ -255,12 +246,14 @@ export function SpecialPromptModal(props: SpecialProps) {
question={<Text id={`app.context_menu.create_invite`} />}
actions={[
{
text: <Text id="app.special.modals.actions.ok" />,
children: (
<Text id="app.special.modals.actions.ok" />
),
confirmation: true,
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}`,
......@@ -283,15 +276,15 @@ export function SpecialPromptModal(props: SpecialProps) {
);
}
case "kick_member": {
const user = client.users.get(props.user);
return (
<PromptModal
onClose={onClose}
question={<Text id={`app.context_menu.kick_member`} />}
actions={[
{
text: <Text id="app.special.modals.actions.kick" />,
children: (
<Text id="app.special.modals.actions.kick" />
),
contrast: true,
error: true,
confirmation: true,
......@@ -299,10 +292,13 @@ export function SpecialPromptModal(props: SpecialProps) {
setProcessing(true);
try {
await client.servers.members.kickMember(
props.target._id,
props.user,
);
client.members
.getKey({
server: props.target._id,
user: props.user._id,
})
?.kick();
onClose();
} catch (err) {
setError(takeError(err));
......@@ -311,7 +307,7 @@ export function SpecialPromptModal(props: SpecialProps) {
},
},
{
text: (
children: (
<Text id="app.special.modals.actions.cancel" />
),
onClick: onClose,
......@@ -319,10 +315,10 @@ export function SpecialPromptModal(props: SpecialProps) {
]}
content={
<div className={styles.column}>
<UserIcon target={user} size={64} />
<UserIcon target={props.user} size={64} />
<Text
id="app.special.modals.prompt.confirm_kick"
fields={{ name: user?.username }}
fields={{ name: props.user?.username }}
/>
</div>
}
......@@ -333,7 +329,6 @@ export function SpecialPromptModal(props: SpecialProps) {
}
case "ban_member": {
const [reason, setReason] = useState<string | undefined>(undefined);
const user = client.users.get(props.user);
return (
<PromptModal
......@@ -341,7 +336,9 @@ export function SpecialPromptModal(props: SpecialProps) {
question={<Text id={`app.context_menu.ban_member`} />}
actions={[
{
text: <Text id="app.special.modals.actions.ban" />,
children: (
<Text id="app.special.modals.actions.ban" />
),
contrast: true,
error: true,
confirmation: true,
......@@ -349,11 +346,9 @@ export function SpecialPromptModal(props: SpecialProps) {
setProcessing(true);
try {
await client.servers.banUser(
props.target._id,
props.user,
{ reason },
);
await props.target.banUser(props.user._id, {
reason,
});
onClose();
} catch (err) {
setError(takeError(err));
......@@ -362,7 +357,7 @@ export function SpecialPromptModal(props: SpecialProps) {
},
},
{
text: (
children: (
<Text id="app.special.modals.actions.cancel" />
),
onClick: onClose,
......@@ -370,10 +365,10 @@ export function SpecialPromptModal(props: SpecialProps) {
]}
content={
<div className={styles.column}>
<UserIcon target={user} size={64} />
<UserIcon target={props.user} size={64} />
<Text
id="app.special.modals.prompt.confirm_ban"
fields={{ name: user?.username }}
fields={{ name: props.user?.username }}
/>
<Overline>
<Text id="app.special.modals.prompt.confirm_ban_reason" />
......@@ -404,7 +399,7 @@ export function SpecialPromptModal(props: SpecialProps) {
{
confirmation: true,
contrast: true,
text: (
children: (
<Text id="app.special.modals.actions.create" />
),
onClick: async () => {
......@@ -412,14 +407,11 @@ export function SpecialPromptModal(props: SpecialProps) {
try {
const channel =
await client.servers.createChannel(
props.target._id,
{
type,
name,
nonce: ulid(),
},
);
await props.target.createChannel({
type,
name,
nonce: ulid(),
});
history.push(
`/server/${props.target._id}/channel/${channel._id}`,
......@@ -432,7 +424,7 @@ export function SpecialPromptModal(props: SpecialProps) {
},
},
{
text: (
children: (
<Text id="app.special.modals.actions.cancel" />
),
onClick: onClose,
......@@ -470,4 +462,4 @@ export function SpecialPromptModal(props: SpecialProps) {
default:
return null;
}
}
});
......@@ -16,7 +16,7 @@ export function SignedOutModal({ onClose }: Props) {
{
onClick: onClose,
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 { observer } from "mobx-react-lite";
import { Channel } from "revolt.js/dist/maps/Channels";
import styles from "./ChannelInfo.module.scss";
import Modal from "../../../components/ui/Modal";
import Markdown from "../../../components/markdown/Markdown";
import { useChannel, useForceUpdate } from "../../revoltjs/hooks";
import { getChannelName } from "../../revoltjs/util";
interface Props {
channel_id: string;
channel: Channel;
onClose: () => void;
}
export function ChannelInfo({ channel_id, onClose }: Props) {
const ctx = useForceUpdate();
const channel = useChannel(channel_id, ctx);
if (!channel) return null;
export const ChannelInfo = observer(({ channel, onClose }: Props) => {
if (
channel.channel_type === "DirectMessage" ||
channel.channel_type === "SavedMessages"
......@@ -30,15 +27,15 @@ export function ChannelInfo({ channel_id, onClose }: Props) {
<Modal visible={true} onClose={onClose}>
<div className={styles.info}>
<div className={styles.header}>
<h1>{getChannelName(ctx.client, channel, true)}</h1>
<h1>{getChannelName(channel, true)}</h1>
<div onClick={onClose}>
<X size={36} />
</div>
</div>
<p>
<Markdown content={channel.description} />
<Markdown content={channel.description!} />
</p>
</div>
</Modal>
);
}
});
.viewer {
display: flex;
flex-direction: column;
border-end-end-radius: 4px;
border-end-start-radius: 4px;
overflow: hidden;
img {
width: auto;
height: auto;
max-width: 90vw;
max-height: 90vh;
max-height: 75vh;
border-bottom: thin solid var(--tertiary-foreground);
object-fit: contain;
}
}
import { Attachment, EmbedImage } from "revolt.js/dist/api/objects";
/* 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 { useContext, useEffect } from "preact/hooks";
import AttachmentActions from "../../../components/common/messaging/attachments/AttachmentActions";
import EmbedMediaActions from "../../../components/common/messaging/embed/EmbedMediaActions";
import Modal from "../../../components/ui/Modal";
import { AppContext } from "../../revoltjs/RevoltClient";
import { useClient } from "../../revoltjs/RevoltClient";
interface Props {
onClose: () => void;
......@@ -15,28 +16,42 @@ interface Props {
attachment?: Attachment;
}
type ImageMetadata = AttachmentMetadata & { type: "Image" };
export function ImageViewer({ attachment, embed, onClose }: Props) {
// ! FIXME: temp code
// ! add proxy function to client
function proxyImage(url: string) {
return "https://jan.revolt.chat/proxy?url=" + encodeURIComponent(url);
if (attachment && attachment.metadata.type !== "Image") {
console.warn(
`Attempted to use a non valid attatchment type in the image viewer: ${attachment.metadata.type}`,
);
return null;
}
if (attachment && attachment.metadata.type !== "Image") return null;
const client = useContext(AppContext);
const client = useClient();
return (
<Modal visible={true} onClose={onClose} noBackground>
<div className={styles.viewer}>
{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} />
</>
)}
{embed && (
<>
<img src={proxyImage(embed.url)} />
<img
loading="eager"
src={client.proxyFile(embed.url)}
width={embed.width}
height={embed.height}
/>
<EmbedMediaActions embed={embed} />
</>
)}
......
......@@ -71,7 +71,7 @@ export function ModifyAccountModal({ onClose, field }: Props) {
{
confirmation: true,
onClick: handleSubmit(onSubmit),
text:
children:
field === "email" ? (
<Text id="app.special.modals.actions.send_email" />
) : (
......@@ -80,16 +80,18 @@ export function ModifyAccountModal({ onClose, field }: Props) {
},
{
onClick: onClose,
text: <Text id="app.special.modals.actions.close" />,
children: <Text id="app.special.modals.actions.close" />,
},
]}>
{/* Preact / React typing incompatabilities */}
<form
onSubmit={
onSubmit={(e) => {
e.preventDefault();
handleSubmit(
onSubmit,
) as JSX.GenericEventHandler<HTMLFormElement>
}>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
)(e as any);
}}>
{field === "email" && (
<FormField
type="email"
......
import { observer } from "mobx-react-lite";
import { User } from "revolt.js/dist/maps/Users";
import styles from "./UserPicker.module.scss";
import { Text } from "preact-i18n";
import Modal from "../../../components/ui/Modal";
import { Friend } from "../../../pages/friends/Friend";
import { useUsers } from "../../revoltjs/hooks";
interface Props {
users: string[];
users: User[];
onClose: () => void;
}
export function PendingRequests({ users: ids, onClose }: Props) {
const users = useUsers(ids);
export const PendingRequests = observer(({ users, onClose }: Props) => {
return (
<Modal
visible={true}
title={<Text id="app.special.friends.pending" />}
onClose={onClose}>
<div className={styles.list}>
{users
.filter((x) => typeof x !== "undefined")
.map((x) => (
<Friend user={x!} key={x!._id} />
))}
{users.map((x) => (
<Friend user={x!} key={x!._id} />
))}
</div>
</Modal>
);
}
});
......@@ -4,7 +4,6 @@
max-height: 360px;
overflow-y: scroll;
// ! FIXME: very temporary code
> label {
> span {
align-items: flex-start !important;
......@@ -18,4 +17,4 @@
}
}
}
}
\ No newline at end of file
}