Compare commits

..

No commits in common. "main" and "improve-theming" have entirely different histories.

81 changed files with 452 additions and 2716 deletions

View file

@ -8,6 +8,7 @@ steps:
- pnpm build - pnpm build
when: when:
- event: push - event: push
- event: pull_request
- name: container-build-and-publish - name: container-build-and-publish
image: docker image: docker
@ -22,17 +23,3 @@ steps:
when: when:
- branch: main - branch: main
event: push event: push
- name: container-build-and-publish (staging)
image: docker
commands:
- docker login --username radical --password $PASSWORD git.gorb.app
- docker buildx build --platform linux/amd64,linux/arm64 --rm --push -t git.gorb.app/gorb/frontend:staging .
environment:
PASSWORD:
from_secret: docker_password
volumes:
- /var/run/podman/podman.sock:/var/run/docker.sock
when:
- branch: staging
event: push

70
app.vue
View file

@ -1,66 +1,36 @@
<template> <template>
<div> <div>
<Banner v-if="banner" /> <Banner v-if="banner" />
<NuxtPage :keepalive="true" /> <NuxtPage :keepalive="true" />
</div> </div>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import loadPreferredTheme from '~/utils/loadPreferredTheme';
const banner = useState("banner", () => false); const banner = useState("banner", () => false);
onMounted(() => { let currentTheme = "dark" // default theme
loadPreferredTheme() const savedTheme = localStorage.getItem("selectedTheme");
if (savedTheme) {
document.removeEventListener("contextmenu", contextMenuHandler); currentTheme = savedTheme;
document.addEventListener("contextmenu", (e) => {
if (e.target instanceof Element && e.target.classList.contains("default-contextmenu")) return;
contextMenuHandler(e);
});
document.addEventListener("mousedown", (e) => {
if (e.target instanceof HTMLDivElement && e.target.closest("#context-menu")) return;
console.log("click");
console.log("target:", e.target);
console.log(e.target instanceof HTMLDivElement);
removeContextMenu();
if (e.target instanceof HTMLElement && e.target.classList.contains("message-text") && e.target.contentEditable) {
e.target.contentEditable = "false";
}
const destroyOnClick = document.getElementsByClassName("destroy-on-click");
for (const element of destroyOnClick) {
const closest = (e.target as HTMLElement).closest(".destroy-on-click");
if (element != closest) {
unrender(element);
}
}
});
document.addEventListener("keyup", (e) => {
const messageReply = document.getElementById("message-reply") as HTMLDivElement;
if (e.key == "Escape" && messageReply) {
e.preventDefault();
messageReply.remove();
}
});
});
function contextMenuHandler(e: MouseEvent) {
e.preventDefault();
//console.log("Opened context menu");
//createContextMenu(e, [
// { name: "Wah", callback: () => { return } }
//]);
} }
const baseURL = useRuntimeConfig().app.baseURL;
useHead({
link: [
{
rel: "stylesheet",
href: `${baseURL}themes/${currentTheme}.css`
}
]
})
</script> </script>
<style> <style>
html { html,
background-color: #1f1e1d;
}
body { body {
font-family: var(--preferred-font), Arial, Helvetica, sans-serif; font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box; box-sizing: border-box;
color: var(--text-color); color: var(--text-color);
background: var(--optional-body-background); background: var(--optional-body-background);

View file

@ -1,44 +0,0 @@
<template>
<NuxtImg v-if="displayAvatar"
class="display-avatar"
:src="displayAvatar"
:alt="displayName" />
<Icon v-else
name="lucide:user"
:alt="displayName" />
</template>
<script lang="ts" setup>
import { NuxtImg } from '#components';
import type { GuildMemberResponse, UserResponse } from '~/types/interfaces';
const props = defineProps<{
user?: UserResponse,
member?: GuildMemberResponse,
}>();
let displayName: string
let displayAvatar: string | null
const user = props.user || props.member?.user
if (user) {
displayName = getDisplayName(user, props.member)
if (user.avatar) {
displayAvatar = user.avatar
} else if (!isCanvasBlocked()){
displayAvatar = generateDefaultIcon(displayName, user.uuid)
} else {
displayAvatar = null
}
}
</script>
<style scoped>
.display-avatar {
border-radius: var(--pfp-radius);
}
</style>

View file

@ -1,13 +0,0 @@
<template>
<div>
</div>
</template>
<script lang="ts" setup>
</script>
<style>
</style>

View file

@ -1,14 +1,14 @@
<template> <template>
<button @click="props.callback ? props.callback() : null" class="button" :class="props.variant + '-button'"> <div @click="props.callback()" class="button" :class="props.variant + '-button'">
{{ props.text }} {{ props.text }}
</button> </div>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
const props = defineProps<{ const props = defineProps<{
text: string, text: string,
callback?: CallableFunction, callback: CallableFunction,
variant?: "normal" | "scary" | "neutral", variant?: "normal" | "scary" | "neutral",
}>(); }>();
@ -21,15 +21,13 @@ const props = defineProps<{
background-color: var(--primary-color); background-color: var(--primary-color);
color: var(--text-color); color: var(--text-color);
padding: 0.4em 0.75em; padding: 0.7dvh 1.2dvw;
font-size: 1.1em; font-size: 1.1em;
transition: background-color 0.2s; transition: background-color 0.2s;
border-radius: 0.7rem; border-radius: 0.7rem;
text-decoration: none; text-decoration: none;
display: inline-block; display: inline-block;
border: none;
} }
.button:hover { .button:hover {

View file

@ -1,10 +1,10 @@
<template> <template>
<div v-if="isCurrentChannel" class="channel-list-link-container rounded-corners current-channel" tabindex="0" :title="props.name"> <div v-if="isCurrentChannel" class="channel-list-link-container rounded-corners current-channel" tabindex="0">
<NuxtLink class="channel-list-link" :href="props.href" tabindex="-1"> <NuxtLink class="channel-list-link" :href="props.href" tabindex="-1">
# {{ props.name }} # {{ props.name }}
</NuxtLink> </NuxtLink>
</div> </div>
<div v-else class="channel-list-link-container rounded-corners" tabindex="0" :title="props.name"> <div v-else class="channel-list-link-container rounded-corners" tabindex="0">
<NuxtLink class="channel-list-link" :href="props.href" tabindex="-1"> <NuxtLink class="channel-list-link" :href="props.href" tabindex="-1">
# {{ props.name }} # {{ props.name }}
</NuxtLink> </NuxtLink>
@ -23,16 +23,14 @@ const isCurrentChannel = props.uuid == props.currentUuid;
.channel-list-link { .channel-list-link {
text-decoration: none; text-decoration: none;
color: inherit; color: inherit;
padding-left: .25em; padding-left: .5dvw;
padding-right: .25em; padding-right: .5dvw;
overflow: hidden;
text-overflow: ellipsis;
} }
.channel-list-link-container { .channel-list-link-container {
text-align: left; text-align: left;
display: flex; display: flex;
height: 1.5em; height: 4dvh;
white-space: nowrap; white-space: nowrap;
align-items: center; align-items: center;
} }

View file

@ -10,7 +10,6 @@
<script lang="ts" setup> <script lang="ts" setup>
import Cropper from 'cropperjs'; import Cropper from 'cropperjs';
import Button from '../UserInterface/Button.vue';
const props = defineProps({ const props = defineProps({
imageSrc: String, imageSrc: String,

View file

@ -1,46 +0,0 @@
<template>
<div class="dropdown-body">
<div v-for="option of props.options" class="dropdown-option">
<button class="dropdown-button" :data-value="option.value" @click.prevent="option.callback" tabindex="0">{{ option.name }}</button>
</div>
</div>
</template>
<script lang="ts" setup>
import type { DropdownOption } from '~/types/interfaces';
const props = defineProps<{ options: DropdownOption[] }>();
</script>
<style scoped>
.dropdown-body {
position: absolute;
z-index: 100;
left: 4dvw;
bottom: 4dvh;
background-color: var(--chat-background-color);
width: 8rem;
display: flex;
flex-direction: column;
}
.dropdown-option {
border: .09rem solid rgb(70, 70, 70);
}
.dropdown-button {
padding-top: .5dvh;
padding-bottom: .5dvh;
color: var(--text-color);
background-color: transparent;
width: 100%;
border: none;
}
.dropdown-button:hover {
background-color: var(--padding-color);
}
</style>

View file

@ -1,56 +0,0 @@
<template>
<div id="guild-options-menu" class="destroy-on-click">
<div v-for="setting of settings" class="guild-option" tabindex="0">
<button class="guild-option-button" @click="setting.action" tabindex="0">{{ setting.name }}</button>
</div>
</div>
<ModalInvite v-if="showInviteModal" :guild-id="guildId" />
</template>
<script lang="ts" setup>
const settings = [
{ name: "Invite", icon: "lucide:letter", action: openInviteModal }
]
const guildId = useRoute().params.serverId as string;
const showInviteModal = ref(false);
function openInviteModal() {
showInviteModal.value = true;
}
</script>
<style>
#guild-options-menu {
display: flex;
flex-direction: column;
position: relative;
background-color: var(--chat-background-color);
top: 8dvh;
z-index: 10;
width: 100%;
position: absolute;
}
.guild-option {
display: flex;
justify-content: center;
align-items: center;
height: 2em;
box-sizing: border-box;
}
.guild-option:hover {
background-color: var(--padding-color);
}
.guild-option-button {
border: 0;
background-color: transparent;
color: var(--main-text-color);
height: 100%;
width: 100%;
}
</style>

View file

@ -0,0 +1,40 @@
<template>
<div id="invite-popup">
<div v-if="invite">
<p>{{ invite }}</p>
<button @click="copyInvite">Copy Link</button>
</div>
<div v-else>
<button @click="generateInvite">Generate Invite</button>
</div>
</div>
</template>
<script lang="ts" setup>
import type { InviteResponse } from '~/types/interfaces';
const invite = ref<string>();
const route = useRoute();
async function generateInvite(): Promise<void> {
const createdInvite: InviteResponse | undefined = await fetchWithApi(
`/guilds/${route.params.serverId}/invites`,
{ method: "POST", body: { custom_id: "oijewfoiewf" } }
);
invite.value = createdInvite?.id;
return;
}
function copyInvite() {
const inviteUrl = URL.parse(`invite/${invite.value}`, `${window.location.protocol}//${window.location.host}`);
navigator.clipboard.writeText(inviteUrl!.href);
}
</script>
<style>
</style>

View file

@ -1,63 +0,0 @@
<template>
<div style="text-align: left;">
<h3>Add a Friend</h3>
Enter a friend's Gorb username to send them a friend request.
</div>
<div id="add-friend-search-bar">
<input id="add-friend-search-input" ref="inputField"
placeholder="blahaj.enjoyer" maxlength="32" @keypress.enter="sendRequest"/> <!-- REMEMBER TO CHANGE THIS WHEN WE ADD FEDERATION-->
<Button id="friend-request-button" :callback="sendRequest" text="Send Friend Request"></Button>
</div>
</template>
<script lang="ts" setup>
import Button from '~/components/UserInterface/Button.vue';
const inputField = ref<HTMLInputElement>();
const { addFriend } = useApi();
async function sendRequest() {
if (inputField.value) {
try {
await addFriend(inputField.value.value)
alert("Friend request sent!")
} catch {
alert("Request failed :(")
}
}
}
</script>
<style>
#add-friend-search-bar {
display: flex;
text-align: left;
margin-top: .8em;
padding: .3em .3em;
border-radius: 1em;
border: 1px solid var(--accent-color);
}
#add-friend-search-input {
border: none;
box-sizing: border-box;
margin: 0 .2em;
flex-grow: 1;
color: inherit;
background-color: unset;
font-weight: medium;
letter-spacing: .04em;
}
#add-friend-search-input:empty:before {
content: attr(placeholder);
color: gray;
}
</style>

View file

@ -1,44 +0,0 @@
<template>
<ResizableSidebar width="14rem" min-width="8rem" max-width="30rem" border-sides="right" local-storage-name="middleLeftColumn">
<div id="middle-left-column">
<div id="friend-sidebar">
<div>
<h3>Direct Messages</h3>
</div>
<VerticalSpacer />
<NuxtLink class="user-item" :href="`/me`" tabindex="0">
<Icon class="user-avatar" name="lucide:user" />
<span class="user-display-name">Friends</span>
</NuxtLink>
<VerticalSpacer />
<div id="direct-message-list">
<UserEntry v-for="user of friends" :user="user"
:href="`/me/${user.uuid}`"/>
</div>
</div>
</div>
</ResizableSidebar>
</template>
<script lang="ts" setup>
import VerticalSpacer from '~/components/UserInterface/VerticalSpacer.vue';
import ResizableSidebar from '../UserInterface/ResizableSidebar.vue';
const { fetchFriends } = useApi();
const friends = await fetchFriends()
</script>
<style>
#middle-left-column {
background: var(--optional-channel-list-background);
background-color: var(--sidebar-background-color);
}
#friend-sidebar {
padding-left: .5em;
padding-right: .5em;
}
</style>

View file

@ -1,58 +0,0 @@
<template>
<input id="search-friend-bar" placeholder="search"/>
<!-- we aren't checking for the "all" variant, since this is the default and fallback one -->
<p v-if="props.variant === 'online'" style="text-align: left;">Online 0</p>
<p v-else-if="props.variant === 'pending'" style="text-align: left;">Friend Requests 0</p>
<p v-else style="text-align: left;">Friends {{ friends?.length || 0 }}</p>
<div id="friends-list">
<div v-if="props.variant === 'online'">
Not Implemented
</div>
<div v-else-if="props.variant === 'pending'">
Not Implemented
</div>
<div v-else>
<UserEntry v-for="user of friends" :user="user" :name="getDisplayName(user)"
:href="`/me/${user.uuid}`"/>
</div>
</div>
</template>
<script lang="ts" setup>
const { fetchFriends } = useApi();
const friends = sortUsers(await fetchFriends())
const props = defineProps<{
variant: string
}>();
</script>
<style>
#search-friend-bar {
text-align: left;
margin-top: .8em;
padding: .3em .5em;
width: 100%;
border-radius: 1em;
border: 1px solid var(--accent-color);
box-sizing: border-box;
color: inherit;
background-color: unset;
font-weight: medium;
letter-spacing: .04em;
}
#search-friend-bar:empty:before {
content: attr(placeholder);
color: gray;
}
</style>

View file

@ -1,7 +1,8 @@
<template> <template>
<div class="member-item" @click="togglePopup" @blur="hidePopup" tabindex="0"> <div class="member-item" @click="togglePopup" @blur="hidePopup" tabindex="0">
<Avatar :member="props.member" class="member-avatar"/> <img v-if="props.member.user.avatar" class="member-avatar" :src="props.member.user.avatar" :alt="props.member.user.display_name ?? props.member.user.username" />
<span class="member-display-name">{{ getDisplayName(props.member.user, props.member) }}</span> <Icon v-else class="member-avatar" name="lucide:user" />
<span class="member-display-name">{{ props.member.user.display_name ?? props.member.user.username }}</span>
<UserPopup v-if="isPopupVisible" :user="props.member.user" id="profile-popup" /> <UserPopup v-if="isPopupVisible" :user="props.member.user" id="profile-popup" />
</div> </div>
</template> </template>
@ -9,6 +10,7 @@
<script lang="ts" setup> <script lang="ts" setup>
import { ref } from 'vue'; import { ref } from 'vue';
import type { GuildMemberResponse } from '~/types/interfaces'; import type { GuildMemberResponse } from '~/types/interfaces';
import UserPopup from './UserPopup.vue';
const props = defineProps<{ const props = defineProps<{
member: GuildMemberResponse member: GuildMemberResponse

View file

@ -1,75 +1,50 @@
<template> <template>
<div v-if="props.type == 'normal' || props.replyMessage" ref="messageElement" @contextmenu="createContextMenu($event, menuItems)" :id="props.last ? 'last-message' : undefined" <div v-if="props.type == 'normal'" :id="props.last ? 'last-message' : undefined" class="message normal-message">
class="message normal-message" :class="{ 'mentioned': (props.replyMessage || props.isMentioned) && props.message.user.uuid != props.me.uuid && props.replyMessage?.user.uuid == props.me.uuid }" :data-message-id="props.messageId"
:editing.sync="props.editing" :replying-to.sync="props.replyingTo">
<div v-if="props.replyMessage" class="message-reply-svg">
<svg
width="1.5em" height="1.5em"
viewBox="0 0 150 87.5" version="1.1" id="svg1"
style="overflow: visible;">
<defs id="defs1" />
<g id="layer1"
transform="translate(40,-35)">
<g id="g3"
transform="translate(-35,-20)">
<path
style="stroke:var(--reply-text-color);stroke-width:8;stroke-opacity:1"
d="m 120.02168,87.850978 100.76157,2.4e-5"
id="path3-5" />
<path
style="stroke:var(--reply-text-color);stroke-width:8;stroke-opacity:1"
d="M 69.899501,174.963 120.2803,87.700931"
id="path3-5-2" />
</g>
</g>
</svg>
</div>
<MessageReply v-if="props.replyMessage" :id="props.message.uuid"
:author="getDisplayName(props.replyMessage.user)"
:text="props.replyMessage?.message"
:reply-id="props.replyMessage.uuid" max-width="reply" />
<div class="left-column"> <div class="left-column">
<Avatar :user="props.author" class="message-author-avatar"/> <img v-if="props.img" class="message-author-avatar" :src="props.img" :alt="username" />
<Icon v-else name="lucide:user" class="message-author-avatar" />
</div> </div>
<div class="message-data"> <div class="message-data">
<div class="message-metadata"> <div class="message-metadata">
<span class="message-author-username" tabindex="0" :style="`color: ${props.authorColor}`"> <span class="message-author-username" tabindex="0">
{{ getDisplayName(props.author) }} {{ username }}
</span> </span>
<span class="message-date" :title="date.toString()"> <span class="message-date" :title="date.toString()">
<span v-if="getDayDifference(date, currentDate) === 1">Yesterday at</span> <span v-if="getDayDifference(date, currentDate) === 1">Yesterday at</span>
<span v-else-if="getDayDifference(date, currentDate) > 1 ">{{ date.toLocaleDateString(undefined) }},</span> <span v-else-if="getDayDifference(date, currentDate) > 1 ">{{ date.toLocaleDateString(undefined) }},</span>
{{ date.toLocaleTimeString(undefined, { timeStyle: "short" }) }}
{{ date.toLocaleTimeString(undefined, { hour12: props.format == "12", timeStyle: "short" }) }}
</span> </span>
</div> </div>
<div class="message-text" v-html="sanitized" :hidden="hasEmbed" tabindex="0"></div> <div class="message-text" v-html="sanitized" tabindex="0"></div>
</div> </div>
<MessageMedia v-if="mediaLinks.length" :links="mediaLinks" />
</div> </div>
<div v-else ref="messageElement" @contextmenu="createContextMenu($event, menuItems)" :id="props.last ? 'last-message' : undefined" <div v-else ref="messageElement" :id="props.last ? 'last-message' : undefined" class="message grouped-message" :class="{ 'message-margin-bottom': props.marginBottom }">
class="message grouped-message" :class="{ 'message-margin-bottom': props.marginBottom, 'mentioned': props.replyMessage || props.isMentioned }"
:data-message-id="props.messageId" :editing.sync="props.editing" :replying-to.sync="props.replyingTo">
<div class="left-column"> <div class="left-column">
<span :class="{ 'invisible': dateHidden }" class="message-date side-message-date" :title="date.toString()"> <span :class="{ 'invisible': dateHidden }" class="message-date side-message-date" :title="date.toString()">
{{ date.toLocaleTimeString(undefined, { hour12: props.format == "12", timeStyle: "short" }) }} {{ date.toLocaleTimeString(undefined, { timeStyle: "short" }) }}
</span> </span>
</div> </div>
<div class="message-data"> <div class="message-data">
<div class="message-text" :class="$style['message-text']" v-html="sanitized" :hidden="hasEmbed" tabindex="0"></div> <div class="message-text" :class="$style['message-text']" v-html="sanitized" tabindex="0"></div>
</div> </div>
<MessageMedia v-if="mediaLinks.length" :links="mediaLinks" />
</div> </div>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import DOMPurify from 'dompurify'; import DOMPurify from 'dompurify';
import { parse } from 'marked'; import { parse } from 'marked';
import type { MessageProps } from '~/types/props';
import MessageMedia from './MessageMedia.vue';
import MessageReply from './UserInterface/MessageReply.vue';
const props = defineProps<MessageProps>(); const props = defineProps<{
class?: string,
img?: string | null,
username: string,
text: string,
timestamp: number,
format: "12" | "24",
type: "normal" | "grouped",
marginBottom: boolean,
last: boolean
}>();
const messageElement = ref<HTMLDivElement>(); const messageElement = ref<HTMLDivElement>();
@ -78,79 +53,30 @@ const dateHidden = ref<boolean>(true);
const date = new Date(props.timestamp); const date = new Date(props.timestamp);
const currentDate: Date = new Date() const currentDate: Date = new Date()
console.log("[MSG] message to render:", props.message); console.log("message:", props.text);
console.log("author:", props.author); console.log("author:", props.username);
console.log("[MSG] reply message:", props.replyMessage);
const linkRegex = /https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)/g;
const linkMatches = props.message.message.matchAll(linkRegex).map(link => link[0]);
const mediaLinks: string[] = [];
console.log("link matches:", linkMatches);
const hasEmbed = ref(false);
const sanitized = ref<string>(); const sanitized = ref<string>();
onMounted(async () => { onMounted(async () => {
const parsed = await parse(props.text, { gfm: true }); const parsed = await parse(props.text, { gfm: true });
sanitized.value = DOMPurify.sanitize(parsed, { sanitized.value = DOMPurify.sanitize(parsed, { ALLOWED_TAGS: ["strong", "em", "br", "blockquote", "code", "ul", "ol", "li", "a", "h1", "h2", "h3", "h4", "h5", "h6"] });
ALLOWED_TAGS: [
"strong", "em", "br", "blockquote",
"code", "ul", "ol", "li", "a", "h1",
"h2", "h3", "h4", "h5", "h6"
],
ALLOW_DATA_ATTR: false,
ALLOW_SELF_CLOSE_IN_ATTR: false,
ALLOWED_ATTR: ["href"]
});
console.log("adding listeners") console.log("adding listeners")
await nextTick(); await nextTick();
if (messageElement.value?.classList.contains("grouped-message")) { messageElement.value?.addEventListener("mouseenter", (e: Event) => {
messageElement.value?.addEventListener("mouseenter", (e: Event) => { dateHidden.value = false;
dateHidden.value = false; });
});
messageElement.value?.addEventListener("mouseleave", (e: Event) => {
dateHidden.value = true;
});
console.log("added listeners");
}
for (const link of linkMatches) { messageElement.value?.addEventListener("mouseleave", (e: Event) => {
console.log("link:", link); dateHidden.value = true;
try { });
const res = await $fetch.raw(link); console.log("added listeners");
if (res.ok && res.headers.get("content-type")?.match(/^image\/(apng|gif|jpeg|png|webp)$/)) {
console.log("link is image");
mediaLinks.push(link);
}
if (mediaLinks.length) {
hasEmbed.value = true
setTimeout(() => {
scrollToBottom(document.getElementById("messages") as HTMLDivElement);
}, 500);
};
} catch (error) {
console.error(error);
}
}
console.log("media links:", mediaLinks);
}); });
//function toggleTooltip(e: Event) { //function toggleTooltip(e: Event) {
// showHover.value = !showHover.value; // showHover.value = !showHover.value;
//} //}
const menuItems = [
{ name: "Reply", callback: () => { if (messageElement.value) replyToMessage(messageElement.value, props) } }
]
console.log("me:", props.me);
if (props.author?.uuid == props.me.uuid) {
menuItems.push({ name: "Edit", callback: () => { if (messageElement.value) editMessage(messageElement.value, props) } });
}
function getDayDifference(date1: Date, date2: Date) { function getDayDifference(date1: Date, date2: Date) {
const midnight1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()); const midnight1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
const midnight2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate()); const midnight2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
@ -173,12 +99,6 @@ function getDayDifference(date1: Date, date2: Date) {
align-items: center; align-items: center;
column-gap: 1dvw; column-gap: 1dvw;
width: 100%; width: 100%;
overflow-wrap: anywhere;
}
.message-reply-preview {
grid-row: 1;
grid-column: 2;
} }
.message:hover { .message:hover {
@ -210,8 +130,6 @@ function getDayDifference(date1: Date, date2: Date) {
flex-direction: column; flex-direction: column;
height: fit-content; height: fit-content;
width: 100%; width: 100%;
grid-row: 2;
grid-column: 2;
} }
.message-author { .message-author {
@ -221,6 +139,7 @@ function getDayDifference(date1: Date, date2: Date) {
.message-author-avatar { .message-author-avatar {
width: 100%; width: 100%;
border-radius: 50%;
} }
.left-column { .left-column {
@ -229,8 +148,6 @@ function getDayDifference(date1: Date, date2: Date) {
justify-content: center; justify-content: center;
text-align: center; text-align: center;
white-space: nowrap; white-space: nowrap;
grid-row: 2;
grid-column: 1;
} }
.author-username { .author-username {
@ -257,30 +174,16 @@ function getDayDifference(date1: Date, date2: Date) {
width: 20px; width: 20px;
} }
*/ */
.mentioned {
background-color: rgba(0, 255, 166, 0.123);
}
.mentioned:hover {
background-color: rgba(90, 255, 200, 0.233);
}
.message-reply-svg {
display: flex;
justify-content: center;
}
</style> </style>
<style module> <style module>
.message-text ul, h1, h2, h3, h4, h5, h6 { .message-text ul, h1, h2, h3, h4, h5, h6 {
padding-top: .5em; padding-top: 1dvh;
padding-bottom: .5em; padding-bottom: 1dvh;
margin: 0; margin: 0;
} }
.message-text ul { .message-text ul {
padding-left: 1em; padding-left: 2dvw;
} }
</style> </style>

View file

@ -1,57 +1,33 @@
<template> <template>
<div id="message-area"> <div id="message-area">
<div id="messages" ref="messagesElement"> <div id="messages" ref="messagesElement">
<Message v-for="(message, i) of messages" :username="getDisplayName(message.user)" <Message v-for="(message, i) of messages" :username="message.user.display_name ?? message.user.username"
:text="message.message" :timestamp="messageTimestamps[message.uuid]" :img="message.user.avatar" :text="message.message" :timestamp="messageTimestamps[message.uuid]" :img="message.user.avatar"
:format="timeFormat" :type="messagesType[message.uuid]" format="12" :type="messagesType[message.uuid]"
:margin-bottom="(messages[i + 1] && messagesType[messages[i + 1].uuid] == 'normal') ?? false" :margin-bottom="(messages[i + 1] && messagesType[messages[i + 1].uuid] == 'normal') ?? false"
:last="i == messages.length - 1" :message-id="message.uuid" :author="message.user" :me="me" :last="i == messages.length - 1" />
:message="message" :is-reply="message.reply_to"
:author-color="`${generateIrcColor(message.user.uuid)}`"
:reply-message="message.reply_to ? getReplyMessage(message.reply_to) : undefined" />
</div> </div>
<div id="message-box" class="rounded-corners"> <div id="message-box" class="rounded-corners">
<form id="message-form" @submit="sendMessage"> <form id="message-form" @submit="sendMessage">
<div id="message-box-left-elements"> <input v-model="messageInput" id="message-box-input" class="rounded-corners" type="text"
<span class="message-box-button"> name="message-input" autocomplete="off">
<Icon name="lucide:file-plus-2" /> <button id="submit-button" type="submit">
</span> <Icon name="lucide:send" />
</div> </button>
<div id="message-textarea">
<div id="message-textbox-input"
role="textbox" ref="messageTextboxInput"
autocorrect="off" spellcheck="true" contenteditable="true"
@keydown="handleTextboxKeyDown" @input="handleTextboxInput">
</div>
</div>
<div id="message-box-right-elements">
<button class="message-box-button" type="submit">
<Icon name="lucide:send" />
</button>
<span class="message-box-button">
<Icon name="lucide:image-play" />
</span>
</div>
</form> </form>
</div> </div>
</div> </div>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import type { MessageResponse, ScrollPosition, UserResponse } from '~/types/interfaces'; import type { MessageResponse, ScrollPosition } from '~/types/interfaces';
import scrollToBottom from '~/utils/scrollToBottom'; import scrollToBottom from '~/utils/scrollToBottom';
import { generateIrcColor } from '#imports';
const props = defineProps<{ channelUrl: string, amount?: number, offset?: number }>(); const props = defineProps<{ channelUrl: string, amount?: number, offset?: number }>();
const me = await fetchWithApi("/me") as UserResponse;
const messageTimestamps = ref<Record<string, number>>({}); const messageTimestamps = ref<Record<string, number>>({});
const messagesType = ref<Record<string, "normal" | "grouped">>({}); const messagesType = ref<Record<string, "normal" | "grouped">>({});
const messageGroupingMaxDifference = useRuntimeConfig().public.messageGroupingMaxDifference const messageGroupingMaxDifference = useRuntimeConfig().public.messageGroupingMaxDifference
const timeFormat = getPreferredTimeFormat()
const messagesRes: MessageResponse[] | undefined = await fetchWithApi( const messagesRes: MessageResponse[] | undefined = await fetchWithApi(
`${props.channelUrl}/messages`, `${props.channelUrl}/messages`,
@ -121,7 +97,6 @@ if (messagesRes) {
messagesRes.reverse(); messagesRes.reverse();
console.log("messages res:", messagesRes.map(msg => msg.message)); console.log("messages res:", messagesRes.map(msg => msg.message));
for (const message of messagesRes) { for (const message of messagesRes) {
console.log("[MSG] processing message:", message);
groupMessage(message); groupMessage(message);
} }
} }
@ -131,38 +106,11 @@ function pushMessage(message: MessageResponse) {
messages.value.push(message); messages.value.push(message);
} }
function handleTextboxKeyDown(event: KeyboardEvent) {
if (event.key === "Enter" && event.shiftKey && messageTextboxInput.value) {
// this enters a newline, due to not preventing default
} else if (event.key === "Enter") {
event.preventDefault()
sendMessage(event)
}
adjustTextboxHeight()
}
function handleTextboxInput() {
if (messageTextboxInput.value) {
messageInput.value = messageTextboxInput.value.innerText;
}
adjustTextboxHeight()
}
// this technically uses pixel units, but it's still set using dynamic units
function adjustTextboxHeight() {
if (messageTextboxInput.value && messageTextboxDisplay.value) {
messageTextboxInput.value.style.height = "auto"
messageTextboxInput.value.style.height = `${messageTextboxInput.value.scrollHeight}px`
}
}
const messages = ref<MessageResponse[]>([]); const messages = ref<MessageResponse[]>([]);
const messageInput = ref<string>("");
const messageInput = ref<string>();
const messagesElement = ref<HTMLDivElement>(); const messagesElement = ref<HTMLDivElement>();
const messageTextboxInput = ref<HTMLDivElement>();
const messageTextboxDisplay = ref<HTMLDivElement>();
if (messagesRes) messages.value = messagesRes; if (messagesRes) messages.value = messagesRes;
@ -193,7 +141,6 @@ if (accessToken && apiBase) {
console.log("event data:", event.data); console.log("event data:", event.data);
console.log("message uuid:", event.data.uuid); console.log("message uuid:", event.data.uuid);
const parsedData = JSON.parse(event.data); const parsedData = JSON.parse(event.data);
console.log("[MSG] parsed message:", parsedData);
console.log("parsed message type:", messagesType.value[parsedData.uuid]); console.log("parsed message type:", messagesType.value[parsedData.uuid]);
console.log("parsed message timestamp:", messageTimestamps.value[parsedData.uuid]); console.log("parsed message timestamp:", messageTimestamps.value[parsedData.uuid]);
@ -211,39 +158,14 @@ if (accessToken && apiBase) {
function sendMessage(e: Event) { function sendMessage(e: Event) {
e.preventDefault(); e.preventDefault();
if (messageInput.value && messageInput.value.trim() !== "") { const message = {
const message: Record<string, string> = { message: messageInput.value
message: messageInput.value.trim().replace(/\n/g, "<br>") // trim, and replace \n with <br>
}
const messageReply = document.getElementById("message-reply") as HTMLDivElement;
console.log("[MSG] message reply:", messageReply);
if (messageReply && messageReply.dataset.messageId) {
console.log("[MSG] message is a reply");
message.reply_to = messageReply.dataset.messageId;
}
console.log("[MSG] sent message:", message);
ws.send(JSON.stringify(message));
// reset input field
messageInput.value = ""
if (messageTextboxInput.value) {
messageTextboxInput.value.innerText = ""
}
adjustTextboxHeight()
} }
} console.log("message:", message);
if (message.message) {
function getReplyMessage(id: string) { ws.send(JSON.stringify(message));
console.log("[REPLYMSG] id:", id); messageInput.value = "";
const messagesValues = Object.values(messages.value); console.log("MESSAGE SENT!!!");
console.log("[REPLYMSG] messages values:", messagesValues);
for (const message of messagesValues) {
console.log("[REPLYMSG] message:", message);
console.log("[REPLYMSG] IDs match?", message.uuid == id);
if (message.uuid == id) return message;
} }
} }
@ -251,10 +173,7 @@ const route = useRoute();
onMounted(async () => { onMounted(async () => {
if (import.meta.server) return; if (import.meta.server) return;
console.log("[MSG] messages keys:", Object.values(messages.value));
if (messagesElement.value) { if (messagesElement.value) {
await nextTick();
await nextTick();
scrollToBottom(messagesElement.value); scrollToBottom(messagesElement.value);
let fetched = false; let fetched = false;
const amount = messages.value.length; const amount = messages.value.length;
@ -322,64 +241,39 @@ router.beforeEach((to, from, next) => {
<style scoped> <style scoped>
#message-area { #message-area {
display: flex; display: grid;
flex-direction: column; grid-template-rows: 8fr 1fr;
padding-left: 1dvw; padding-left: 1dvw;
padding-right: 1dvw; padding-right: 1dvw;
overflow: hidden; overflow: hidden;
flex-grow: 1;
} }
#message-box { #message-box {
margin-top: auto; /* force it to the bottom of the screen */ display: flex;
margin-bottom: 2dvh; flex-direction: column;
justify-content: center;
align-content: center;
border: 1px solid var(--padding-color);
padding-bottom: 1dvh;
padding-top: 1dvh;
margin-bottom: 1dvh;
margin-left: 1dvw; margin-left: 1dvw;
margin-right: 1dvw; margin-right: 1dvw;
background: var(--optional-message-box-background);
padding-left: 2%;
padding-right: 2%;
align-items: center;
color: var(--text-color);
border: 1px solid var(--padding-color);
background-color: var(--chatbox-background-color);
} }
#message-form { #message-form {
display: flex; display: flex;
flex-direction: row; justify-content: center;
gap: .55em;
} }
#message-textarea { #message-box-input {
flex-grow: 1; width: 80%;
min-height: 2.35em;
}
#message-textbox-input {
width: 100%;
max-height: 50dvh;
padding: 0.5em 0;
user-select: text;
font-family: inherit;
font-size: inherit;
line-height: normal;
border: none; border: none;
background-color: #40404000; /* completely transparent colour */ color: inherit;
padding-left: 1dvw;
text-align: left; padding-right: 1dvw;
word-break: break-word; background-color: var(--chatbox-background-color);
overflow-wrap: break-word;
overflow-y: auto;
}
#message-box-left-elements, #message-box-right-elements {
display: flex;
align-items: end;
} }
#messages { #messages {
@ -390,7 +284,7 @@ router.beforeEach((to, from, next) => {
padding-right: 1dvw; padding-right: 1dvw;
} }
.message-box-button { #submit-button {
background-color: inherit; background-color: inherit;
border: none; border: none;
color: var(--primary-color); color: var(--primary-color);
@ -398,7 +292,7 @@ router.beforeEach((to, from, next) => {
font-size: 1.5em; font-size: 1.5em;
} }
.message-box-button:hover { #submit-button:hover {
color: var(--primary-highlighted-color); color: var(--primary-highlighted-color);
cursor: pointer; cursor: pointer;
} }

View file

@ -1,47 +0,0 @@
<template>
<div class="media-container">
<NuxtImg v-for="link of props.links" class="media-item" :src="link" @click.prevent="createModal(link)" />
</div>
</template>
<script lang="ts" setup>
import { ModalBase } from '#components';
import { render } from 'vue';
const props = defineProps<{ links: string[] }>();
function createModal(link: string) {
const div = document.createElement("div");
const modal = h(ModalBase, {
obscure: true,
onClose: () => unrender(div),
onCancel: () => unrender(div),
},
[
h("img", {
src: link,
class: "default-contextmenu"
})
]);
document.body.appendChild(div);
render(modal, div);
}
</script>
<style scoped>
.media-container {
grid-column: 2;
grid-row: 3;
margin-left: .5dvw;
}
.media-item {
cursor: pointer;
max-width: 15dvw;
}
</style>

View file

@ -1,84 +0,0 @@
<template>
<dialog ref="dialog" class="modal" :class="props.obscure ? 'modal-obscure' : 'modal-regular'">
<span class="modal-exit-button-container" style="position: absolute; right: 2em; top: .2em; width: .5em; height: .5em;">
<Button text="X" variant="neutral" :callback="() => dialog?.remove()" />
</span>
<div class="modal-content">
<h1 class="modal-title">{{ title }}</h1>
<slot />
</div>
</dialog>
</template>
<script lang="ts" setup>
import type { ModalProps } from '~/types/interfaces';
import Button from '~/components/UserInterface/Button.vue';
const props = defineProps<ModalProps>();
const dialog = ref<HTMLDialogElement>();
console.log("props:", props);
onMounted(() => {
if (dialog.value) {
dialog.value.showModal();
if (props.onClose) {
dialog.value.addEventListener("close", props.onClose);
}
if (props.onCancel) {
dialog.value.addEventListener("cancel", props.onCancel);
}
}
});
</script>
<style>
.modal {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
gap: 1em;
opacity: 100%;
padding: 1%;
background-color: var(--sidebar-highlighted-background-color);
color: var(--text-color);
overflow: hidden;
}
.modal-regular::backdrop {
background-color: var(--chat-background-color);
opacity: 0%;
}
.modal-obscure::backdrop {
background-color: var(--chat-background-color);
opacity: 80%;
}
.modal-top-container {
position: fixed;
display: flex;
justify-content: center;
align-items: center;
height: 100%;
width: 100%;
}
.modal-title {
font-size: 1.5rem;
padding: 0;
}
.modal-content {
display: flex;
flex-direction: column;
align-items: center;
gap: 1em;
margin: 1em;
width: 100%;
}
</style>

View file

@ -1,70 +0,0 @@
<template>
<ModalBase v-bind="props" :title="props.title || 'Create an invite'">
<div v-if="invite" id="invite-body">
<div id="invite-label">{{ invite }}</div>
<div id="invite-buttons">
<Button text="Copy as link" variant="neutral" :callback="() => copyInvite('link')" />
<Button text="Copy as code" variant="neutral" :callback="() => copyInvite('code')" />
</div>
</div>
<div v-else>
<Button text="Generate Invite" variant="normal" :callback="generateInvite">Generate Invite</Button>
</div>
</ModalBase>
</template>
<script lang="ts" setup>
import type { InviteResponse, ModalProps } from '~/types/interfaces';
import Button from '~/components/UserInterface/Button.vue';
const props = defineProps<ModalProps & { guildId: string }>();
const invite = ref<string>();
async function generateInvite(): Promise<void> {
const chars = "ABCDEFGHIJKLMNOQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"
let randCode = "";
for (let i = 0; i < 6; i++) {
randCode += chars[Math.floor(Math.random() * chars.length)];
}
const createdInvite: InviteResponse | undefined = await fetchWithApi(
`/guilds/${props.guildId}/invites`,
{ method: "POST", body: { custom_id: randCode } }
);
invite.value = createdInvite?.id;
return;
}
function copyInvite(type: "link" | "code") {
if (!invite.value) return;
if (type == "link") {
const inviteUrl = URL.parse(`invite/${invite.value}`, `${window.location.protocol}//${window.location.host}`);
if (inviteUrl) {
navigator.clipboard.writeText(inviteUrl.href);
}
} else {
navigator.clipboard.writeText(invite.value);
}
}
</script>
<style scoped>
#invite-body, #invite-buttons {
display: flex;
gap: 1em;
}
#invite-body {
flex-direction: column;
}
#invite-label {
text-align: center;
color: aquamarine;
}
</style>

View file

@ -17,28 +17,19 @@
</div> </div>
</div> </div>
<!-- <p class="subtitle">Icons</p> <p class="subtitle">ICONS</p>
<div class="icons"> <div class="themes">
</div> -->
<p class="subtitle">TIME FORMAT</p>
<div class="icons">
<RadioButtons :button-count="3" :text-strings="timeFormatTextStrings"
:default-button-index="settingsLoad().timeFormat?.index ?? 0" :callback="onTimeFormatClicked"></RadioButtons>
</div> </div>
</div> </div>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import RadioButtons from '~/components/UserInterface/RadioButtons.vue';
import type { TimeFormat } from '~/types/settings';
import loadPreferredTheme from '~/utils/loadPreferredTheme';
import settingSave from '~/utils/settingSave';
const runtimeConfig = useRuntimeConfig() const runtimeConfig = useRuntimeConfig()
const defaultThemes = runtimeConfig.public.defaultThemes const defaultThemes = runtimeConfig.public.defaultThemes
const baseURL = runtimeConfig.app.baseURL; const baseURL = runtimeConfig.app.baseURL;
const timeFormatTextStrings = ["Auto", "12-Hour", "24-Hour"] let themeLinkElement: HTMLLinkElement | null = null;
const themes: Array<Theme> = [] const themes: Array<Theme> = []
@ -51,8 +42,20 @@ interface Theme {
} }
function changeTheme(id: string, url: string) { function changeTheme(id: string, url: string) {
settingSave("selectedThemeId", id) if (themeLinkElement && themeLinkElement.getAttribute('href') === `${baseURL}themes/${url}`) {
loadPreferredTheme() return;
}
localStorage.setItem("selectedTheme", id);
// if the theme didn't originally load for some reason, create it
if (!themeLinkElement) {
themeLinkElement = document.createElement('link');
themeLinkElement.rel = 'stylesheet';
document.head.appendChild(themeLinkElement);
}
themeLinkElement.href = `${baseURL}themes/${url}`;
} }
async function fetchThemes() { async function fetchThemes() {
@ -65,21 +68,6 @@ async function fetchThemes() {
} }
await fetchThemes() await fetchThemes()
async function onTimeFormatClicked(index: number) {
let format: "auto" | "12" | "24" = "auto"
if (index == 0) {
format = "auto"
} else if (index == 1) {
format = "12"
} else if (index == 2) {
format = "24"
}
const timeFormat: TimeFormat = {index, format}
settingSave("timeFormat", timeFormat)
}
</script> </script>
<style scoped> <style scoped>

View file

@ -1,11 +0,0 @@
import Appearance from './Appearance.vue';
import Notifications from './Notifications.vue';
import Keybinds from './Keybinds.vue';
import Language from './Language.vue';
export {
Appearance,
Notifications,
Keybinds,
Language,
}

View file

@ -17,7 +17,7 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import Button from '~/components/UserInterface/Button.vue'; import Button from '~/components/Button.vue';
import type { UserResponse } from '~/types/interfaces'; import type { UserResponse } from '~/types/interfaces';
const { fetchUser } = useAuth(); const { fetchUser } = useAuth();
@ -43,14 +43,6 @@ async function changeEmail() {
body: formData body: formData
}) })
const apiBase = useCookie("api_base").value;
if (apiBase) {
const stats = await useApi().fetchInstanceStats(apiBase);
if (stats.email_verification_required) {
return window.location.reload();
}
}
alert('success!!') alert('success!!')
} catch (error: any) { } catch (error: any) {
if (error?.response?.status !== 200) { if (error?.response?.status !== 200) {

View file

@ -5,6 +5,7 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import Button from '~/components/Button.vue';
</script> </script>
<style scoped> <style scoped>

View file

@ -33,16 +33,12 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import CropPopup from '~/components/Popups/CropPopup.vue';
import UserPopup from '~/components/User/UserPopup.vue';
import Button from '~/components/UserInterface/Button.vue';
import type { UserResponse } from '~/types/interfaces'; import type { UserResponse } from '~/types/interfaces';
let newPfpFile: File; let newPfpFile: File;
const isCropPopupVisible = ref(false); const isCropPopupVisible = ref(false);
const cropImageSrc = ref("") const cropImageSrc = ref("")
;
const { fetchUser } = useAuth(); const { fetchUser } = useAuth();
const user: UserResponse | undefined = await fetchUser() const user: UserResponse | undefined = await fetchUser()

View file

@ -1,13 +0,0 @@
import Profile from './Profile.vue';
import Account from './Account.vue';
import Privacy from './Privacy.vue';
import Devices from './Devices.vue';
import Connections from './Connections.vue';
export {
Profile,
Account,
Privacy,
Devices,
Connections,
}

View file

@ -1,48 +0,0 @@
<template>
<NuxtLink class="user-item" :href="`/me/${user.uuid}`" tabindex="0">
<Avatar :user="props.user" class="user-avatar"/>
<span class="user-display-name">{{ getDisplayName(props.user) }}</span>
</NuxtLink>
</template>
<script lang="ts" setup>
import type { UserResponse } from '~/types/interfaces';
const props = defineProps<{
user: UserResponse
}>();
</script>
<style>
.user-item {
display: flex;
align-items: center;
text-align: left;
margin-top: .5em;
margin-bottom: .5em;
gap: .5em;
text-decoration: none;
color: inherit;
}
.user-item:hover {
background-color: #00000020
}
.user-avatar {
min-width: 2.3em;
max-width: 2.3em;
min-width: 2.3em;
max-height: 2.3em;
}
.user-display-name {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
</style>

20
components/UserArea.vue Normal file
View file

@ -0,0 +1,20 @@
<template>
<div id="user-panel">
HELLO!!
</div>
</template>
<script lang="ts" setup>
import type { UserResponse } from '~/types/interfaces';
const props = defineProps<{
user: UserResponse,
}>();
</script>
<style scoped>
#user-panel {
width: 100%;
}
</style>

View file

@ -1,44 +0,0 @@
<template>
<div v-for="item of props.menuItems" class="context-menu-item" @click="runCallback(item)">
{{ item.name }}
</div>
</template>
<script lang="ts" setup>
import type { ContextMenuItem } from '~/types/interfaces';
const props = defineProps<{ menuItems: ContextMenuItem[], pointerX: number, pointerY: number }>();
onMounted(() => {
const contextMenu = document.getElementById("context-menu");
if (contextMenu) {
contextMenu.style.left = props.pointerX.toString() + "px";
contextMenu.style.top = props.pointerY.toString() + "px";
}
});
function runCallback(item: ContextMenuItem) {
removeContextMenu();
item.callback();
}
</script>
<style>
#context-menu {
position: absolute;
display: flex;
flex-direction: column;
width: 10dvw;
border: .15rem solid cyan;
background-color: var(--background-color);
text-align: center;
}
.context-menu-item:hover {
background-color: rgb(50, 50, 50);
}
</style>

View file

@ -1,92 +0,0 @@
<template>
<div :id="props.maxWidth == 'full' ? 'message-reply' : undefined" :class="{ 'message-reply-preview' : props.maxWidth == 'reply' }"
:data-message-id="props.id" @click="scrollToReply">
<span id="reply-text">Replying to <span id="reply-author-field">{{ props.author }}:</span> <span v-html="sanitized"></span></span>
<!-- <span id="message-reply-cancel"><Icon name="lucide:x" /></span> -->
</div>
</template>
<script lang="ts" setup>
import DOMPurify from "dompurify";
import { parse } from "marked";
const props = defineProps<{ author: string, text: string, id: string, replyId: string, maxWidth: "full" | "reply" }>();
const existingReply = document.getElementById("message-reply");
if (existingReply) {
existingReply.remove();
}
console.log("text:", props.text);
const sanitized = ref<string>();
onMounted(async () => {
const parsed = await parse(props.text.trim().replaceAll("<br>", " "), { gfm: true });
sanitized.value = DOMPurify.sanitize(parsed, {
ALLOWED_TAGS: [],
ALLOW_DATA_ATTR: false,
ALLOW_SELF_CLOSE_IN_ATTR: false,
ALLOWED_ATTR: [],
KEEP_CONTENT: true
});
console.log("sanitized:", sanitized.value);
const messageBoxInput = document.getElementById("message-textbox-input") as HTMLDivElement;
if (messageBoxInput) {
messageBoxInput.focus();
}
});
function scrollToReply(e: MouseEvent) {
e.preventDefault();
console.log("clicked on reply box");
const reply = document.querySelector(`.message[data-message-id="${props.replyId}"]`);
if (reply) {
console.log("reply:", reply);
console.log("scrolling into view");
reply.scrollIntoView({ behavior: "smooth", block: "center" });
}
}
</script>
<style scoped>
#message-reply, .message-reply-preview {
display: flex;
text-align: left;
margin-bottom: .5rem;
cursor: pointer;
overflow: hidden;
}
#message-reply {
width: 100%;
}
.message-reply-preview {
margin-left: .5dvw;
}
#reply-text {
color: var(--reply-text-color);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
margin-bottom: 0;
margin-top: .2rem;
border-bottom: 1px solid var(--padding-color);
}
#reply-author-field {
color: var(--text-color);
}
</style>

View file

@ -1,111 +0,0 @@
<template>
<div class="radio-buttons-container" ref="radioButtonsContainer">
<div v-for="index in indices" :key="index" class="radio-button" @click="onClick(index)">
<span class="radio-button-radio"></span>
<span class="radio-button-text">{{ textStrings[index] }}</span>
</div>
</div>
</template>
<script lang="ts" setup>
const radioButtonsContainer = ref<HTMLDivElement>()
const props = defineProps<{
textStrings: string[],
buttonCount: number,
defaultButtonIndex: number,
callback: CallableFunction,
}>();
// makes an array from 0 to buttonCount - 1
const indices = Array.from({ length: props.buttonCount }, (_, i) => i)
// select default selected button
onMounted(async () => {
await nextTick()
if (props.defaultButtonIndex != undefined && radioButtonsContainer.value) {
const children = radioButtonsContainer.value.children
const defaultButton = children.item(props.defaultButtonIndex)
defaultButton?.classList.add("selected-radio-button")
defaultButton?.children.item(0)?.classList.add("selected-radio-button-radio")
}
})
function onClick(clickedIndex: number) {
// remove selected-radio-button class from all buttons except the clicked one
if (radioButtonsContainer.value) {
const children = radioButtonsContainer.value.children
for (let i = 0; i < children.length; i++) {
children.item(i)?.classList.remove("selected-radio-button")
children.item(i)?.children.item(0)?.classList.remove("selected-radio-button-radio")
}
children.item(clickedIndex)?.classList.add("selected-radio-button")
children.item(clickedIndex)?.children.item(0)?.classList.add("selected-radio-button-radio")
}
props.callback(clickedIndex)
}
</script>
<style scoped>
.radio-buttons-container {
display: flex;
flex-direction: column;
}
.radio-button {
cursor: pointer;
display: flex;
align-items: center;
border-radius: .66em;
background-color: unset;
color: var(--text-color);
padding: 0.4em 0.75em;
margin: 0.4em 0em;
font-size: 1.1em;
transition: background-color 0.2s;
}
.radio-button:hover {
background-color: var(--secondary-highlighted-color);
}
.selected-radio-button {
background-color: var(--accent-color);
}
.selected-radio-button:hover {
background-color: var(--accent-highlighted-color);
}
.radio-button-radio, .selected-radio-button-radio {
position: relative;
display: inline-block;
border-radius: 1em;
}
.radio-button-radio {
height: 1em;
width: 1em;
border: .15em solid var(--primary-color);
}
.selected-radio-button-radio {
height: 1em;
width: 1em;
border: 0.15em solid var(--primary-color);
background-color: var(--primary-highlighted-color);
}
.radio-button-text {
margin-left: .5em;
}
</style>

View file

@ -1,140 +0,0 @@
<template>
<div ref="resizableSidebar" class="resizable-sidebar"
:style="{
'width': storedWidth ? `${storedWidth}px` : props.width,
'min-width': props.minWidth,
'max-width': props.maxWidth,
'border': props.borderSides == 'all' ? borderStyling : undefined,
'border-top': props.borderSides?.includes('top') ? borderStyling : undefined,
'border-bottom': props.borderSides?.includes('bottom') ? borderStyling : undefined,
}">
<div v-if="props.borderSides != 'right'" class="width-resizer-bar">
<div ref="widthResizer" class="width-resizer"></div>
</div>
<div class="sidebar-content">
<slot />
</div>
<div v-if="props.borderSides == 'right'" class="width-resizer-bar">
<div ref="widthResizer" class="width-resizer"></div>
</div>
</div>
</template>
<script lang="ts" setup>
import type { ContextMenuItem } from '~/types/interfaces';
const props = defineProps<{ width?: string, minWidth: string, maxWidth: string, borderSides: "all" | "top" | "right" | "bottom" | "left" | ("top" | "right" | "bottom" | "left")[], localStorageName?: string }>();
const borderStyling = ".1rem solid var(--padding-color)";
const resizableSidebar = ref<HTMLDivElement>();
const widthResizer = ref<HTMLDivElement>();
const storedWidth = ref<number>();
const menuItems: ContextMenuItem[] = [
{ name: "Reset", callback: () => { resizableSidebar.value!.style.width = props.width ?? props.minWidth } }
]
onMounted(() => {
loadStoredWidth();
if (resizableSidebar.value && widthResizer.value) {
widthResizer.value.addEventListener("pointerdown", (e) => {
e.preventDefault();
if (e.button == 2) {
createContextMenu(e, menuItems);
return
};
document.body.style.cursor = "ew-resize";
function handleMove(pointer: PointerEvent) {
if (resizableSidebar.value) {
console.log("moving");
console.log("pointer:", pointer);
console.log("width:", resizableSidebar.value.style.width);
let delta = 0;
if (props.borderSides == 'right') {
delta = resizableSidebar.value.getBoundingClientRect().left;
console.log("delta:", delta);
resizableSidebar.value.style.width = `${pointer.clientX - delta}px`;
} else {
delta = resizableSidebar.value.getBoundingClientRect().right;
console.log("delta:", delta);
resizableSidebar.value.style.width = `${delta - pointer.clientX}px`;
}
}
}
document.addEventListener("pointermove", handleMove);
document.addEventListener("pointerup", () => {
console.log("pointer up");
document.removeEventListener("pointermove", handleMove);
console.log("removed pointermove event listener");
document.body.style.cursor = "";
if (resizableSidebar.value && props.localStorageName) {
localStorage.setItem(props.localStorageName, resizableSidebar.value.style.width);
}
}, { once: true });
});
}
});
onActivated(() => {
console.log("[res] activated");
loadStoredWidth();
});
function loadStoredWidth() {
if (props.localStorageName) {
const storedWidthValue = localStorage.getItem(props.localStorageName);
if (storedWidthValue) {
storedWidth.value = parseInt(storedWidthValue) || undefined;
console.log("[res] loaded stored width");
}
}
}
</script>
<style>
.resizable-sidebar > * {
box-sizing: border-box;
}
.resizable-sidebar {
display: flex;
background: var(--optional-channel-list-background);
background-color: var(--sidebar-background-color);
height: 100%;
flex: 0 0 auto;
}
.width-resizer {
width: .5rem;
cursor: col-resize;
position: absolute;
height: 100%;
}
.width-resizer-bar {
display: flex;
justify-content: center;
position: relative;
height: 100%;
width: 1px;
background-color: var(--padding-color);
}
.sidebar-content {
width: 100%;
padding-left: .25em;
padding-right: .25em;
}
.sidebar-content > :first-child {
width: 100%;
height: 100%;
overflow-y: scroll;
overflow-x: hidden;
}
</style>

View file

@ -1,12 +0,0 @@
<template>
<span class="spacer"></span>
</template>
<style scoped>
.spacer {
height: 0.2dvh;
display: block;
margin: 0.8dvh 0.2dvw;
background-color: var(--padding-color);
}
</style>

View file

@ -1,11 +1,12 @@
<template> <template>
<div id="profile-popup"> <div id="profile-popup">
<Avatar :user="props.user" id="avatar"/> <img v-if="props.user.avatar" id="avatar" :src="props.user.avatar" alt="profile avatar">
<Icon v-else id="avatar" name="lucide:user" />
<div id="cover-color"></div> <div id="cover-color"></div>
<div id="main-body"> <div id="main-body">
<p id="display-name"> <p id="display-name">
<strong>{{ getDisplayName(props.user) }}</strong> <strong>{{ props.user.display_name }}</strong>
</p> </p>
<p id="username-and-pronouns"> <p id="username-and-pronouns">
{{ props.user.username }} {{ props.user.username }}
@ -21,6 +22,8 @@
<script lang="ts" setup> <script lang="ts" setup>
import type { UserResponse } from '~/types/interfaces'; import type { UserResponse } from '~/types/interfaces';
const { fetchMembers } = useApi();
const props = defineProps<{ const props = defineProps<{
user: UserResponse user: UserResponse
}>(); }>();

View file

@ -1,61 +1,37 @@
import type { ChannelResponse, GuildMemberResponse, GuildResponse, MessageResponse, StatsResponse, UserResponse } from "~/types/interfaces"; import type { ChannelResponse, GuildMemberResponse, GuildResponse, MessageResponse } from "~/types/interfaces";
function ensureIsArray(list: any) {
if (Array.isArray(list)) {
return list
} else {
return []
}
}
export const useApi = () => { export const useApi = () => {
async function fetchGuilds(): Promise<GuildResponse[]> { async function fetchGuilds(): Promise<GuildResponse[] | undefined> {
return ensureIsArray(await fetchWithApi(`/guilds`)); return await fetchWithApi(`/guilds`);
} }
async function fetchGuild(guildId: string): Promise<GuildResponse | undefined> { async function fetchGuild(guildId: string): Promise<GuildResponse | undefined> {
return await fetchWithApi(`/guilds/${guildId}`); return await fetchWithApi(`/guilds/${guildId}`);
} }
async function fetchMyGuilds(): Promise<GuildResponse[]> { async function fetchChannels(guildId: string): Promise<ChannelResponse[] | undefined> {
return ensureIsArray(await fetchWithApi(`/me/guilds`)); return await fetchWithApi(`/guilds/${guildId}/channels`);
}
async function fetchChannels(guildId: string): Promise<ChannelResponse[]> {
return ensureIsArray(await fetchWithApi(`/guilds/${guildId}/channels`));
} }
async function fetchChannel(channelId: string): Promise<ChannelResponse | undefined> { async function fetchChannel(channelId: string): Promise<ChannelResponse | undefined> {
return await fetchWithApi(`/channels/${channelId}`) return await fetchWithApi(`/channels/${channelId}`)
} }
async function fetchMembers(guildId: string): Promise<GuildMemberResponse[]> { async function fetchMembers(guildId: string): Promise<GuildMemberResponse[] | undefined> {
return ensureIsArray(await fetchWithApi(`/guilds/${guildId}/members`)); return await fetchWithApi(`/guilds/${guildId}/members`);
} }
async function fetchMember(guildId: string, memberId: string): Promise<GuildMemberResponse | undefined> { async function fetchMember(guildId: string, memberId: string): Promise<GuildMemberResponse | undefined> {
return await fetchWithApi(`/guilds/${guildId}/members/${memberId}`); return await fetchWithApi(`/guilds/${guildId}/members/${memberId}`);
} }
async function fetchUsers() { async function fetchUsers() {
return await fetchWithApi(`/users`); return await fetchWithApi(`/users`);
} }
async function fetchUser(userId: string) { async function fetchUser(userId: string) {
return await fetchWithApi(`/users/${userId}`); return await fetchWithApi(`/users/${userId}`);
} }
async function fetchFriends(): Promise<UserResponse[]> {
return ensureIsArray(await fetchWithApi('/me/friends'));
}
async function addFriend(username: string): Promise<void> {
return await fetchWithApi('/me/friends', { method: "POST", body: { username } });
}
async function removeFriend(userId: string): Promise<void> {
return await fetchWithApi(`/me/friends/${userId}`, { method: "DELETE" });
}
async function fetchMessages(channelId: string, options?: { amount?: number, offset?: number }): Promise<MessageResponse[] | undefined> { async function fetchMessages(channelId: string, options?: { amount?: number, offset?: number }): Promise<MessageResponse[] | undefined> {
return await fetchWithApi(`/channels/${channelId}/messages`, { query: { amount: options?.amount ?? 100, offset: options?.offset ?? 0 } }); return await fetchWithApi(`/channels/${channelId}/messages`, { query: { amount: options?.amount ?? 100, offset: options?.offset ?? 0 } });
@ -65,61 +41,16 @@ export const useApi = () => {
return await fetchWithApi(`/channels/${channelId}/messages/${messageId}`); return await fetchWithApi(`/channels/${channelId}/messages/${messageId}`);
} }
async function createGuild(name: string): Promise<GuildResponse | undefined> {
return await fetchWithApi(`/guilds`, { method: "POST", body: { name } });
}
async function joinGuild(invite: string): Promise<GuildResponse> {
return await fetchWithApi(`/invites/${invite}`, { method: "POST" }) as GuildResponse;
}
async function createChannel(guildId: string, name: string, description?: string): Promise<void> {
return await fetchWithApi(`/guilds/${guildId}/channels`, { method: "POST", body: { name, description } });
}
async function fetchInstanceStats(apiBase: string): Promise<StatsResponse> {
return await $fetch(`${apiBase}/stats`, { method: "GET" });
}
async function sendVerificationEmail(): Promise<void> {
const email = useAuth().user.value?.email;
await fetchWithApi("/auth/verify-email", { method: "POST", body: { email } });
}
async function sendPasswordResetEmail(identifier: string): Promise<void> {
await fetchWithApi("/auth/reset-password", { method: "GET", query: { identifier } });
}
async function resetPassword(password: string, token: string) {
await fetchWithApi("/auth/reset-password", { method: "POST", body: { password, token } });
}
async function fetchInvite(id: string): Promise<GuildResponse | undefined> {
return await fetchWithApi(`/invites/${id}`);
}
return { return {
fetchGuilds, fetchGuilds,
fetchGuild, fetchGuild,
fetchMyGuilds,
fetchChannels, fetchChannels,
fetchChannel, fetchChannel,
fetchMembers, fetchMembers,
fetchMember, fetchMember,
fetchUsers, fetchUsers,
fetchUser, fetchUser,
fetchFriends,
addFriend,
removeFriend,
fetchMessages, fetchMessages,
fetchMessage, fetchMessage
createGuild,
joinGuild,
createChannel,
fetchInstanceStats,
sendVerificationEmail,
sendPasswordResetEmail,
resetPassword,
fetchInvite
} }
} }

View file

@ -7,7 +7,6 @@ export const useAuth = () => {
async function clearAuth() { async function clearAuth() {
accessToken.value = null; accessToken.value = null;
user.value = null; user.value = null;
await navigateTo("/login");
} }
async function register(username: string, email: string, password: string) { async function register(username: string, email: string, password: string) {
@ -41,10 +40,10 @@ export const useAuth = () => {
async function logout() { async function logout() {
console.log("access:", accessToken.value); console.log("access:", accessToken.value);
await fetchWithApi("/auth/logout", { method: "DELETE", credentials: "include" }); await fetchWithApi("/auth/logout", { method: "GET", credentials: "include" });
clearAuth(); clearAuth();
return await navigateTo("/login"); return await navigateTo("/login");
} }
async function revoke(password: string) { async function revoke(password: string) {
@ -106,7 +105,7 @@ export const useAuth = () => {
} }
return { return {
clearAuth, accessToken,
register, register,
login, login,
logout, logout,

View file

@ -18,10 +18,32 @@
</div> </div>
<div v-else id="auth-form-container"> <div v-else id="auth-form-container">
<slot /> <slot />
<div v-if="!['/recover', '/reset-password'].includes(route.path)">Forgot password? Recover <NuxtLink href="/recover">here</NuxtLink>!</div>
</div> </div>
<div v-if="instanceUrl"> <div v-if="instanceUrl">
Instance URL is set to <span style="color: var(--primary-color);">{{ instanceUrl }}</span> Instance URL is set to {{ instanceUrl }}
</div>
<div v-if="auth.accessToken.value">
You're logged in!
<form @submit="logout">
<div>
<label for="logout-password">Password</label>
<br>
<input type="password" name="logout-password" id="logout-password" v-model="form.password"
required>
</div>
<div>
<button type="submit">Log out</button>
</div>
</form>
<div>
<button @click="refresh">Refresh</button>
</div>
<div>
<button @click="showUser">Show user</button>
</div>
<div>
<button @click="getUser">Get me</button>
</div>
</div> </div>
</div> </div>
</div> </div>
@ -29,6 +51,7 @@
<script lang="ts" setup> <script lang="ts" setup>
import { FetchError } from 'ofetch'; import { FetchError } from 'ofetch';
import type { StatsResponse } from '~/types/interfaces';
const instanceUrl = ref<string | null | undefined>(null); const instanceUrl = ref<string | null | undefined>(null);
const instanceUrlInput = ref<string>(); const instanceUrlInput = ref<string>();
@ -37,14 +60,12 @@ const apiVersion = useRuntimeConfig().public.apiVersion;
const apiBase = useCookie("api_base"); const apiBase = useCookie("api_base");
const registrationEnabled = useState("registrationEnabled", () => true); const registrationEnabled = useState("registrationEnabled", () => true);
const route = useRoute(); const auth = useAuth();
const query = route.query as Record<string, string>;
const searchParams = new URLSearchParams(query);
searchParams.delete("token");
onMounted(async () => { onMounted(async () => {
instanceUrl.value = useCookie("instance_url").value; const cookie = useCookie("instance_url").value;
instanceUrl.value = cookie;
console.log(cookie);
console.log("set instance url to:", instanceUrl.value); console.log("set instance url to:", instanceUrl.value);
}); });
@ -52,8 +73,8 @@ async function selectInstance(e: Event) {
e.preventDefault(); e.preventDefault();
console.log("trying input instance"); console.log("trying input instance");
if (instanceUrlInput.value) { if (instanceUrlInput.value) {
const gorbTxtUrl = new URL(`/.well-known/gorb.txt`, instanceUrlInput.value);
console.log("input has value"); console.log("input has value");
const gorbTxtUrl = new URL(`/.well-known/gorb.txt`, instanceUrlInput.value);
try { try {
console.log("trying to get gorb.txt:", gorbTxtUrl); console.log("trying to get gorb.txt:", gorbTxtUrl);
const res = await $fetch.raw(gorbTxtUrl.href, { responseType: "text" }); const res = await $fetch.raw(gorbTxtUrl.href, { responseType: "text" });
@ -66,10 +87,10 @@ async function selectInstance(e: Event) {
instanceUrl.value = origin; instanceUrl.value = origin;
useCookie("instance_url").value = origin; useCookie("instance_url").value = origin;
console.log("set instance url to:", origin); console.log("set instance url to:", origin);
const stats = await useApi().fetchInstanceStats(apiBase.value); const { status, data, error } = await useFetch<StatsResponse>(`${apiBase.value}/stats`);
if (stats) { if (status.value == "success" && data.value) {
registrationEnabled.value = stats.registration_enabled; registrationEnabled.value = data.value.registration_enabled;
console.log("set registration enabled value to:", stats.registration_enabled); console.log("set registration enabled value to:", data.value.registration_enabled);
} }
return; return;
} }
@ -93,6 +114,30 @@ async function selectInstance(e: Event) {
const form = reactive({ const form = reactive({
password: "" password: ""
}); });
async function logout(e: Event) {
e.preventDefault();
await auth.logout(form.password);
console.log("logout");
}
async function refresh(e: Event) {
e.preventDefault();
await auth.refresh();
console.log("refreshed");
}
async function getUser(e: Event) {
e.preventDefault();
await auth.getUser();
console.log("user:", auth.user.value);
}
async function showUser(e: Event) {
e.preventDefault();
console.log("user:", auth.user.value);
}
</script> </script>
<style> <style>
@ -103,23 +148,18 @@ const form = reactive({
align-items: center; align-items: center;
} }
#auth-form-container { #auth-form-container,
#auth-form-container form {
display: flex; display: flex;
width: 20dvw; width: 50dvw;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
text-align: center;
gap: 1em; gap: 1em;
margin-bottom: 2dvh;
} }
#auth-form-container form { #auth-form-container form {
display: flex;
flex-direction: column;
align-items: center;
text-align: left; text-align: left;
margin-top: 10dvh; margin-top: 10dvh;
gap: 1em;
} }
#instance-error-container { #instance-error-container {

View file

@ -3,182 +3,42 @@
<div :class="{ hidden: loading, visible: !loading }" id="client-root"> <div :class="{ hidden: loading, visible: !loading }" id="client-root">
<div id="homebar"> <div id="homebar">
<div class="homebar-item"> <div class="homebar-item">
<marquee> main bar
gorb!!!!!
</marquee>
</div> </div>
</div> </div>
<div id="page-content"> <div id="left-column">
<div id="left-column"> <NuxtLink id="home-button" href="/">
<div class="left-column-segment"> <img class="sidebar-icon" src="/public/icon.svg"/>
<NuxtLink id="home-button" href="/me"> </NuxtLink>
<img class="sidebar-icon" src="/public/icon.svg"/> <div id="servers-list">
</NuxtLink> <NuxtLink v-for="guild of guilds" :href="`/servers/${guild.uuid}`">
</div> <img v-if="guild.icon" class="sidebar-icon" :src="guild.icon" :alt="guild.name"/>
<VerticalSpacer /> <Icon v-else name="lucide:server" class="sidebar-icon white" :alt="guild.name" />
<div class="left-column-segment" id="left-column-middle"> </NuxtLink>
<NuxtLink v-for="guild of guilds" :href="`/servers/${guild.uuid}`">
<NuxtImg v-if="guild.icon"
class="sidebar-icon guild-icon"
:alt="guild.name"
:src="guild.icon" />
<NuxtImg v-else-if="!blockedCanvas"
class="sidebar-icon guild-icon"
:alt="guild.name"
:src="generateDefaultIcon(guild.name, guild.uuid)" />
<Icon v-else name="lucide:server"
:style="`color: ${generateIrcColor(guild.uuid, 50)}`"
class="sidebar-icon guild-icon"
:alt="guild.name" />
</NuxtLink>
</div>
<VerticalSpacer />
<div class="left-column-segment">
<div ref="createButtonContainer">
<button id="create-button" class="sidebar-bottom-buttons" @click.prevent="createDropdown">
<Icon id="create-icon" name="lucide:square-plus" alt="Create or join guild"/>
</button>
</div>
<NuxtLink id="settings-menu" class="sidebar-bottom-buttons" href="/settings">
<Icon name="lucide:settings" alt="Settings menu" />
</NuxtLink>
</div>
</div> </div>
<slot /> <NuxtLink id="settings-menu" href="/settings">
<Icon name="lucide:settings" class="sidebar-icon white" alt="Settings menu" />
</NuxtLink>
</div> </div>
<slot />
</div> </div>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { ModalBase } from '#components';
import { render } from 'vue';
import GuildDropdown from '~/components/Guild/GuildDropdown.vue';
import Button from '~/components/UserInterface/Button.vue';
import VerticalSpacer from '~/components/UserInterface/VerticalSpacer.vue';
import type { GuildResponse } from '~/types/interfaces'; import type { GuildResponse } from '~/types/interfaces';
const loading = useState("loading", () => false); const loading = useState("loading", () => false);
const createButtonContainer = ref<HTMLButtonElement>(); const guilds: GuildResponse[] | undefined = await fetchWithApi("/me/guilds");
const api = useApi();
const blockedCanvas = isCanvasBlocked()
const options = [
{ name: "Join", value: "join", callback: async () => {
console.log("join guild!");
const div = document.createElement("div");
const guildJoinModal = h(ModalBase, {
title: "Join Guild",
id: "guild-join-modal",
onClose: () => {
unrender(div);
},
onCancel: () => {
unrender(div);
},
style: "height: 20dvh; width: 15dvw"
},
[
h("input", {
id: "guild-invite-input",
type: "text",
placeholder: "oyqICZ",
}),
h(Button, {
text: "Join",
variant: "normal",
callback: async () => {
const input = document.getElementById("guild-invite-input") as HTMLInputElement;
const invite = input.value;
if (invite.length == 6) {
try {
const joinedGuild = await api.joinGuild(invite);
guilds.push(joinedGuild);
return await navigateTo(`/servers/${joinedGuild.uuid}`);
} catch (error) {
alert(`Couldn't use invite: ${error}`);
}
}
}
})
]);
document.body.appendChild(div);
render(guildJoinModal, div);
}
},
{ name: "Create", value: "create", callback: async () => {
console.log("create guild");
const user = await useAuth().getUser();
const div = document.createElement("div");
const guildCreateModal = h(ModalBase, {
title: "Create a Guild",
id: "guild-join-modal",
onClose: () => {
unrender(div);
},
onCancel: () => {
unrender(div);
},
style: "height: 20dvh; width: 15dvw;"
},
[
h("input", {
id: "guild-name-input",
type: "text",
placeholder: `${getDisplayName(user!)}'s Awesome Bouncy Castle'`,
style: "width: 100%"
}),
h(Button, {
text: "Create!",
variant: "normal",
callback: async () => {
const input = document.getElementById("guild-name-input") as HTMLInputElement;
const name = input.value;
try {
const guild = (await api.createGuild(name)) as GuildResponse;
await api.createChannel(guild.uuid, "general");
} catch (error) {
alert(`Couldn't create guild: ${error}`);
}
}
})
]);
document.body.appendChild(div);
render(guildCreateModal, div);
}
}
];
const guilds = await api.fetchMyGuilds();
function createDropdown() {
const dropdown = h(GuildDropdown, { options });
const div = document.createElement("div");
div.classList.add("dropdown", "destroy-on-click");
if (createButtonContainer.value) {
createButtonContainer.value.appendChild(div);
} else {
document.body.appendChild(div);
}
render(dropdown, div);
div.addEventListener("keyup", (e) => {
if (e.key == "Escape") {
unrender(div);
}
});
div.focus();
}
</script> </script>
<style> <style>
#client-root { #client-root {
/* border: 1px solid white; */
height: 100dvh; height: 100dvh;
width: 100dvw; display: grid;
display: flex; grid-template-columns: 1fr 4fr 18fr 4fr;
flex-direction: column; grid-template-rows: 4dvh auto;
text-align: center; text-align: center;
} }
@ -188,88 +48,81 @@ function createDropdown() {
.visible { .visible {
opacity: 100%; opacity: 100%;
transition: opacity 500ms; transition-duration: 500ms;
} }
#homebar { #homebar {
min-height: 4dvh; grid-row: 1;
grid-column: 1 / -1;
display: flex; display: flex;
justify-content: space-evenly; justify-content: space-evenly;
align-items: center; align-items: center;
background: var(--optional-topbar-background); background: var(--optional-topbar-background);
background-color: var(--topbar-background-color); background-color: var(--topbar-background-color);
border-bottom: 1px solid var(--padding-color);
padding-left: 5dvw; padding-left: 5dvw;
padding-right: 5dvw; padding-right: 5dvw;
} }
.homebar-item { #client-root>div:nth-child(-n+4) {
width: 100dvw; border-bottom: 1px solid var(--padding-color);
} }
#page-content { #__nuxt {
display: flex; display: flex;
flex-direction: row; flex-flow: column;
flex-grow: 1; }
overflow: auto;
.grid-column {
padding-top: 1dvh;
}
#home {
padding-left: .5dvw;
padding-right: .5dvw;
}
.sidebar-icon {
width: 3rem;
height: 3rem;
}
#current-info {
grid-column: 2;
grid-row: 1;
} }
#left-column { #left-column {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 2dvh;
padding-left: var(--sidebar-margin); padding-left: .5dvw;
padding-right: var(--sidebar-margin); padding-right: .5dvw;
padding-top: .5em; border-right: 1px solid var(--padding-color);
background: var(--optional-sidebar-background); background: var(--optional-sidebar-background);
background-color: var(--sidebar-background-color); background-color: var(--sidebar-background-color);
padding-top: 1.5dvh;
}
#middle-left-column {
padding-left: 1dvw;
padding-right: 1dvw;
border-right: 1px solid var(--padding-color); border-right: 1px solid var(--padding-color);
} }
.left-column-segment { #home-button {
border-bottom: 1px solid var(--padding-color);
padding-bottom: 1dvh;
}
#settings-menu {
position: absolute;
bottom: .25dvh
}
#servers-list {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 1dvh;
scrollbar-width: none;
} }
.left-column-segment::-webkit-scrollbar { </style>
display: none;
}
#left-column-middle {
overflow-y: scroll;
flex-grow: 1;
gap: var(--sidebar-icon-gap);
}
#home-button {
height: var(--sidebar-icon-width);
}
.guild-icon {
border-radius: var(--guild-icon-radius);
}
.sidebar-icon {
width: var(--sidebar-icon-width);
height: var(--sidebar-icon-width);
}
.sidebar-bottom-buttons {
color: var(--primary-color);
background-color: transparent;
border: none;
cursor: pointer;
font-size: 2.4rem;
padding: 0;
display: inline-block;
}
.sidebar-bottom-buttons:hover {
color: var(--primary-highlighted-color);
}
</style>

View file

@ -2,21 +2,7 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
console.log("to.fullPath:", to.fullPath); console.log("to.fullPath:", to.fullPath);
const loading = useState("loading"); const loading = useState("loading");
const accessToken = useCookie("access_token").value; const accessToken = useCookie("access_token").value;
const apiBase = useCookie("api_base").value; if (["/login", "/register"].includes(to.path)) {
const { fetchInstanceStats } = useApi();
console.log("[AUTH] instance url:", apiBase);
if (apiBase && !Object.keys(to.query).includes("special") && to.path != "/verify-email") {
const user = await useAuth().getUser();
const stats = await fetchInstanceStats(apiBase);
console.log("[AUTH] stats:", stats);
console.log("[AUTH] email verification check:", user?.email && !user.email_verified && stats.email_verification_required);
if (user?.email && !user.email_verified && stats.email_verification_required) {
return await navigateTo("/register?special=verify_email");
}
}
if (["/login", "/register", "/recover", "/reset-password"].includes(to.path) && !Object.keys(to.query).includes("special")) {
console.log("path is login or register"); console.log("path is login or register");
const apiBase = useCookie("api_base"); const apiBase = useCookie("api_base");
console.log("apiBase gotten:", apiBase.value); console.log("apiBase gotten:", apiBase.value);
@ -33,14 +19,6 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
if (parsed.ApiBaseUrl) { if (parsed.ApiBaseUrl) {
apiBase.value = `${parsed.ApiBaseUrl}/v${apiVersion}`; apiBase.value = `${parsed.ApiBaseUrl}/v${apiVersion}`;
console.log("set apiBase to:", parsed.ApiBaseUrl); console.log("set apiBase to:", parsed.ApiBaseUrl);
console.log("hHEYOO");
const instanceUrl = useCookie("instance_url");
console.log("hHEYOO 2");
console.log("instance url:", instanceUrl.value);
if (!instanceUrl.value) {
instanceUrl.value = `${requestUrl.protocol}//${requestUrl.host}`;
console.log("set instance url to:", instanceUrl.value);
}
} }
} }
} }

View file

@ -5,10 +5,10 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
const guildId = to.params.serverId as string; const guildId = to.params.serverId as string;
const channels: ChannelResponse[] = await fetchChannels(guildId); const channels: ChannelResponse[] | undefined = await fetchChannels(guildId);
console.log("channels:", channels); console.log("channels:", channels);
if (channels.length > 0) { if (channels && channels.length > 0) {
console.log("wah"); console.log("wah");
return await navigateTo(`/servers/${guildId}/channels/${channels[0].uuid}`, { replace: true }); return await navigateTo(`/servers/${guildId}/channels/${channels[0].uuid}`, { replace: true });
} }

View file

@ -22,8 +22,7 @@
"pinia-plugin-persistedstate": "^4.2.0", "pinia-plugin-persistedstate": "^4.2.0",
"typescript": "^5.8.3", "typescript": "^5.8.3",
"vue": "^3.5.13", "vue": "^3.5.13",
"vue-router": "^4.5.1", "vue-router": "^4.5.1"
"xxhash-wasm": "^1.1.0"
}, },
"packageManager": "pnpm@10.11.0", "packageManager": "pnpm@10.11.0",
"license": "MIT", "license": "MIT",

View file

@ -5,7 +5,6 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
await navigateTo("/me/", { replace: true })
definePageMeta({ definePageMeta({
layout: "client" layout: "client"

View file

@ -1,180 +0,0 @@
<template>
<div id="invite-root">
<div id="invite-container">
<div id="guild-container" v-if="guild">
<h1>You have been invited to {{ guild.name }}!</h1>
<div id="guild-card">
<div id="card-grid">
<div id="guild-details">
<div id="guild-name" title="Server name">
<span>{{ guild.name }}</span>
</div>
<div id="guild-member-count" :title="`${guild.member_count} members`">
<Icon name="lucide:users" />
<span>{{ guild.member_count }}</span>
</div>
</div>
<VerticalSpacer id="space" />
<div id="guild-description">
<span>{{ guild.description }}</span>
</div>
<div id="guild-icon">
<NuxtImg v-if="guild.icon" id="guild-icon-img" :src="guild.icon" :alt="`${guild.name} server icon`" />
</div>
</div>
<Button :text="isMember ? 'Joined' : 'Join'" variant="normal" :callback="acceptInvite" />
</div>
</div>
<div v-else-if="errorMessage">
<h1>{{ errorMessage }}</h1>
</div>
</div>
</div>
</template>
<script lang="ts" setup>
import Button from '~/components/UserInterface/Button.vue';
import VerticalSpacer from '~/components/UserInterface/VerticalSpacer.vue';
import type { GuildResponse } from '~/types/interfaces';
const route = useRoute();
const { fetchInvite, joinGuild, fetchMembers } = useApi();
const { getUser } = useAuth();
const inviteId = route.params.inviteId as string;
const guild = ref<GuildResponse>();
const errorMessage = ref<string>();
const isMember = ref(false);
const accessToken = useCookie("access_token");
if (inviteId) {
try {
guild.value = await fetchInvite(inviteId);
console.log("invite guild:", guild.value);
if (accessToken.value && guild.value) {
const members = await fetchMembers(guild.value.uuid);
const me = await getUser();
if (me && members.find(member => member.user.uuid == me.uuid)) {
isMember.value = true;
}
}
} catch (error: any) {
if (error.response) {
if (error.status == 404) {
errorMessage.value = "That invite doesn't exist or has expired.";
}
}
console.error(error);
}
}
async function acceptInvite() {
if (accessToken.value && guild.value) {
await joinGuild(inviteId);
return await navigateTo(`/servers/${guild.value.uuid}`);
}
return await navigateTo(`/login?redirect_to=${route.fullPath}`);
}
</script>
<style>
#invite-root {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100dvh;
}
#invite-container {
border: .5rem solid var(--chat-highlighted-background-color);
border-radius: var(--standard-radius);
height: 50%;
width: 50%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 50%;
height: 60%;
}
#guild-container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 50%;
height: 60%;
}
#guild-card {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100%;
width: 100%;
background-color: var(--sidebar-highlighted-background-color);
border: .5rem solid black;
border-radius: var(--standard-radius);
padding: .5rem;
}
#card-grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 5rem auto 1fr;
height: 100%;
width: 100%;
}
#guild-details {
grid-row: 1;
grid-column: span 2;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
#guild-name {
font-size: 2rem;
flex-direction: column;
}
#guild-member-count {
gap: .3rem;
}
#space {
grid-row: 2;
grid-column: span 3;
}
#guild-description {
grid-row: 3;
grid-column: span 3;
word-break: break-all;
padding: .3rem;
}
#guild-name, #guild-member-count {
display: flex;
justify-content: center;
align-items: center;
}
#guild-icon-img {
height: 100%;
width: 100%;
object-fit: scale-down;
}
</style>

View file

@ -22,6 +22,8 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import type { StatsResponse } from '~/types/interfaces';
definePageMeta({ definePageMeta({
layout: "auth" layout: "auth"
@ -36,20 +38,20 @@ const form = reactive({
const query = useRoute().query as Record<string, string>; const query = useRoute().query as Record<string, string>;
const searchParams = new URLSearchParams(query); const searchParams = new URLSearchParams(query);
searchParams.delete("token");
const registrationEnabled = ref<boolean>(true); const registrationEnabled = ref<boolean>(true);
const apiBase = useCookie("api_base"); const apiBase = useCookie("api_base");
if (apiBase.value) { if (apiBase.value) {
console.log("apiBase:", apiBase.value); console.log("apiBase:", apiBase.value);
const stats = await useApi().fetchInstanceStats(apiBase.value); const statsUrl = new URL("/stats", apiBase.value).href;
if (stats) { const { status, data } = await useFetch<StatsResponse>(statsUrl);
registrationEnabled.value = stats.registration_enabled; if (status.value == "success" && data.value) {
registrationEnabled.value = data.value.registration_enabled;
} }
} }
const registerUrl = `/register?${searchParams}`; const registerUrl = `/register?${searchParams}`
const { login } = useAuth(); const { login } = useAuth();

View file

@ -1,15 +0,0 @@
<template>
<NuxtLayout name="client">
<DirectMessagesSidebar />
<MessageArea channel-url="channels/01970e8c-a09c-76a0-9c98-80a43364bea7"/> <!-- currently just links to the default channel -->
</NuxtLayout>
</template>
<script lang="ts" setup>
import DirectMessagesSidebar from '~/components/Me/DirectMessagesSidebar.vue';
</script>
<style>
</style>

View file

@ -1,56 +0,0 @@
<template>
<NuxtLayout name="client">
<DirectMessagesSidebar />
<div :id="$style['page-content']">
<div :id="$style['navigation-bar']">
<Button :text="`All Friends ${friends?.length}`" variant="neutral" :callback="() => updateFilter('all')" />
<Button :text="`Online ${0}`" variant="neutral" :callback="() => updateFilter('online')" />
<Button :text="`Pending ${0}`" variant="neutral" :callback="() => updateFilter('pending')" />
<Button text="Add Friend" variant="normal" :callback="() => updateFilter('add')" />
</div>
<div>
<AddFriend v-if="filter == 'add'"></AddFriend>
<FriendsList v-else :variant="filter"></FriendsList>
</div>
</div>
</NuxtLayout>
</template>
<script lang="ts" setup>
import DirectMessagesSidebar from '~/components/Me/DirectMessagesSidebar.vue';
import Button from '~/components/UserInterface/Button.vue';
import AddFriend from '~/components/Me/AddFriend.vue';
import FriendsList from '~/components/Me/FriendsList.vue';
const { fetchFriends } = useApi();
let filter = ref("all");
const friends = await fetchFriends()
function updateFilter(newFilter: string) {
filter.value = newFilter;
}
</script>
<style module>
#page-content {
display: flex;
flex-direction: column;
flex-grow: 1;
margin: .75em;
}
#navigation-bar {
display: flex;
align-items: left;
text-align: left;
flex-direction: row;
gap: .5em;
}
</style>

View file

@ -1,89 +0,0 @@
<template>
<NuxtLayout name="auth">
<div v-if="errorValue">{{ errorValue }}</div>
<form v-if="!emailFormSent" @submit.prevent="sendEmail">
<div>
<label for="identifier">Email or username</label>
<br>
<input type="text" name="identifier" id="identifier" v-model="emailForm.identifier">
</div>
<div>
<Button type="submit" text="Send email" variant="normal" />
</div>
</form>
<div v-else>
If an account with that username or email exists, an email will be sent to it shortly.
</div>
<div v-if="registrationEnabled">
Don't have an account? <NuxtLink :href="registerUrl">Register</NuxtLink> one!
</div>
<div>
Already have an account? <NuxtLink :href="loginUrl">Log in</NuxtLink>!
</div>
</NuxtLayout>
</template>
<script lang="ts" setup>
import Button from '~/components/UserInterface/Button.vue';
const emailForm = reactive({
identifier: ""
});
const emailFormSent = ref(false);
const passwordForm = reactive({
password: ""
});
const errorValue = ref<string>();
const registrationEnabled = ref<boolean>(true);
const apiBase = useCookie("api_base");
const query = useRoute().query as Record<string, string>;
const searchParams = new URLSearchParams(query);
const token = ref(searchParams.get("token"))
searchParams.delete("token");
const { resetPassword } = useApi();
const registerUrl = `/register?${searchParams}`;
const loginUrl = `/login?${searchParams}`;
if (apiBase.value) {
console.log("apiBase:", apiBase.value);
const stats = await useApi().fetchInstanceStats(apiBase.value);
if (stats) {
registrationEnabled.value = stats.registration_enabled;
}
}
const { sendPasswordResetEmail } = useApi();
async function sendEmail() {
try {
await sendPasswordResetEmail(emailForm.identifier);
emailFormSent.value = true;
} catch (error) {
errorValue.value = (error as any).toString();
}
}
async function sendPassword() {
try {
console.log("pass:", passwordForm.password);
const hashedPass = await hashPassword(passwordForm.password)
console.log("hashed pass:", hashedPass);
await resetPassword(hashedPass, token.value!);
return await navigateTo(`/login?${searchParams}`);
} catch (error) {
errorValue.value = (error as any).toString();
}
}
</script>
<style>
</style>

View file

@ -1,6 +1,6 @@
<template> <template>
<NuxtLayout> <NuxtLayout>
<form v-if="registrationEnabled && !registrationSubmitted && !showEmailVerificationScreen" @submit="register"> <form v-if="registrationEnabled" @submit="register">
<div> <div>
<!-- <!--
<span class="form-error" v-if="errors.username.length > 0"> <span class="form-error" v-if="errors.username.length > 0">
@ -32,88 +32,32 @@
<button type="submit">Register</button> <button type="submit">Register</button>
</div> </div>
</form> </form>
<div v-else-if="registrationEnabled && (registrationSubmitted || showEmailVerificationScreen) && !emailSent">
<p v-if="emailVerificationRequired">
This instance requires email verification to use it.
<br><br>
<span v-if="registrationSubmitted">
Please open the link sent to your email.
</span>
<span v-else-if="showEmailVerificationScreen">
Please click on the link you've already received, or click on the button below to receive a new email.
</span>
</p>
<p v-else>
Would you like to verify your email?
<!--
<br>
This is required for resetting your password and making other important changes.
-->
</p>
<Button v-if="(!emailVerificationRequired || showEmailVerificationScreen) && !emailSent" text="Send email" variant="neutral" :callback="sendEmail"></Button>
</div>
<div v-else-if="emailSent">
<p>
An email has been sent and should arrive soon.
<br>
If you don't see it in your inbox, try checking the spam folder.
</p>
</div>
<div v-else> <div v-else>
<h3>This instance has disabled registration.</h3> <h3>This instance has disabled registration.</h3>
</div> </div>
<div v-if="loggedIn"> <div>
<Button text="Log out" variant="scary" :callback="() => {}"></Button> Already have an account? <NuxtLink :href="loginUrl">Log in</NuxtLink>!
</div>
<div v-else>
Already have an account? <NuxtLink :href="loginUrl">Log in</NuxtLink>!
</div> </div>
</NuxtLayout> </NuxtLayout>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import type { StatsResponse } from '~/types/interfaces';
definePageMeta({ definePageMeta({
layout: "auth" layout: "auth"
}); })
const registrationEnabled = useState("registrationEnabled", () => true); const registrationEnabled = useState("registrationEnabled", () => true);
const emailVerificationRequired = useState("emailVerificationRequired", () => false);
const registrationSubmitted = ref(false);
const emailSent = ref(false);
const auth = useAuth();
const loggedIn = ref(await auth.getUser());
const query = new URLSearchParams(useRoute().query as Record<string, string>);
query.delete("token");
const user = await useAuth().getUser();
if (user?.email_verified) {
if (query.get("redirect_to")) {
await navigateTo(query.get("redirect_to"));
} else {
await navigateTo("/");
}
}
const showEmailVerificationScreen = query.get("special") == "verify_email";
console.log("show email verification screen?", showEmailVerificationScreen);
const { fetchInstanceStats, sendVerificationEmail } = useApi();
console.log("wah"); console.log("wah");
console.log("weoooo") console.log("weoooo")
const apiBase = useCookie("api_base"); const apiBase = useCookie("api_base");
console.log("apiBase:", apiBase.value); console.log("apiBase:", apiBase.value);
if (apiBase.value) { if (apiBase.value) {
const stats = await fetchInstanceStats(apiBase.value); const { status, data, error } = await useFetch<StatsResponse>(`${apiBase.value}/stats`);
if (stats) { if (status.value == "success" && data.value) {
registrationEnabled.value = stats.registration_enabled; registrationEnabled.value = data.value.registration_enabled;
console.log("set registration enabled value to:", stats.registration_enabled); console.log("set registration enabled value to:", data.value.registration_enabled);
emailVerificationRequired.value = stats.email_verification_required;
console.log("set email verification required value to:", stats.email_verification_required);
} }
} }
@ -146,6 +90,8 @@ const errorMessages = reactive({
*/ */
//const authStore = useAuthStore(); //const authStore = useAuthStore();
const auth = useAuth();
const query = useRoute().query as Record<string, string>;
const searchParams = new URLSearchParams(query); const searchParams = new URLSearchParams(query);
const loginUrl = `/login?${searchParams}` const loginUrl = `/login?${searchParams}`
@ -187,22 +133,13 @@ async function register(e: Event) {
console.log("Sending registration data"); console.log("Sending registration data");
try { try {
await auth.register(form.username, form.email, form.password); await auth.register(form.username, form.email, form.password);
if (!emailVerificationRequired.value) { return await navigateTo(query.redirect_to);
return await navigateTo(query.get("redirect_to"));
}
await sendVerificationEmail();
registrationSubmitted.value = true;
} catch (error) { } catch (error) {
console.error("Error registering:", error); console.error("Error registering:", error);
} }
//return navigateTo(redirectTo ? redirectTo as string : useAppConfig().baseURL as string); //return navigateTo(redirectTo ? redirectTo as string : useAppConfig().baseURL as string);
} }
async function sendEmail() {
await sendVerificationEmail();
emailSent.value = true;
}
</script> </script>
<style></style> <style></style>

View file

@ -1,56 +0,0 @@
<template>
<NuxtLayout name="auth">
<div v-if="errorValue">{{ errorValue }}</div>
<form @submit.prevent="sendPassword">
<div>
<label for="password">Password</label>
<br>
<input type="password" name="password" id="password" v-model="passwordForm.password">
</div>
<div>
<Button type="submit" text="Submit" variant="normal" />
</div>
</form>
<div>
Already have an account? <NuxtLink :href="loginUrl">Log in</NuxtLink>!
</div>
</NuxtLayout>
</template>
<script lang="ts" setup>
import Button from '~/components/UserInterface/Button.vue';
const query = useRoute().query as Record<string, string>;
const searchParams = new URLSearchParams(query);
const loginUrl = `/login?${searchParams}`;
const token = ref(searchParams.get("token"))
if (!token.value) await navigateTo("/login");
const passwordForm = reactive({
password: ""
});
const errorValue = ref<string>();
const { resetPassword } = useApi();
async function sendPassword() {
try {
console.log("pass:", passwordForm.password);
const hashedPass = await hashPassword(passwordForm.password)
console.log("hashed pass:", hashedPass);
await resetPassword(hashedPass, token.value!);
return await navigateTo("/login?");
} catch (error) {
errorValue.value = (error as any).toString();
}
}
</script>
<style>
</style>

View file

@ -1,42 +1,38 @@
<template> <template>
<NuxtLayout name="client"> <NuxtLayout name="client">
<ResizableSidebar <div id="middle-left-column" class="main-grid-row">
width="14rem" min-width="8rem" max-width="30rem" <div id="server-title">
border-sides="right" local-storage-name="middleLeftColumn"> <h3>
<div id="middle-left-column" class="main-grid-row"> {{ server?.name }}
<div id="server-name-container"> <span>
<span id="server-name" :title="server?.name">{{ server?.name }}</span> <button @click="showGuildSettings">
<button id="server-settings-button" @click="toggleGuildSettings"> <Icon name="lucide:settings" />
<Icon id="server-settings-icon" name="lucide:chevron-down" /> </button>
</button> </span>
<GuildOptionsMenu v-if="showGuildSettings" /> <span>
</div> <button @click="toggleInvitePopup">
<div id="channels-list"> <Icon name="lucide:share-2" />
<ChannelEntry v-for="channel of channels" :name="channel.name" </button>
:uuid="channel.uuid" :current-uuid="(route.params.channelId as string)" </span>
:href="`/servers/${route.params.serverId}/channels/${channel.uuid}`" /> <InvitePopup v-if="showInvitePopup" />
</div> </h3>
</div> </div>
</ResizableSidebar> <div id="channels-list">
<Channel v-for="channel of channels" :name="channel.name"
:uuid="channel.uuid" :current-uuid="(route.params.channelId as string)"
:href="`/servers/${route.params.serverId}/channels/${channel.uuid}`" />
</div>
</div>
<MessageArea :channel-url="channelUrlPath" /> <MessageArea :channel-url="channelUrlPath" />
<ResizableSidebar <div id="members-container">
width="14rem" min-width="5.5rem" max-width="30rem" <div id="members-list">
border-sides="left" local-storage-name="membersListWidth"> <MemberEntry v-for="member of members" :member="member" tabindex="0"/>
<div id="members-container">
<div id="members-list">
<MemberEntry v-for="member of members" :member="member" tabindex="0"/>
</div>
</div> </div>
</ResizableSidebar> </div>
</NuxtLayout> </NuxtLayout>
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import ChannelEntry from "~/components/Guild/ChannelEntry.vue";
import GuildOptionsMenu from "~/components/Guild/GuildOptionsMenu.vue";
import MemberEntry from "~/components/Guild/MemberEntry.vue";
import ResizableSidebar from "~/components/UserInterface/ResizableSidebar.vue";
import type { ChannelResponse, GuildMemberResponse, GuildResponse } from "~/types/interfaces";
const route = useRoute(); const route = useRoute();
@ -48,47 +44,32 @@ const server = ref<GuildResponse | undefined>();
const channels = ref<ChannelResponse[] | undefined>(); const channels = ref<ChannelResponse[] | undefined>();
const channel = ref<ChannelResponse | undefined>(); const channel = ref<ChannelResponse | undefined>();
const members = ref<GuildMemberResponse[]>();
const showInvitePopup = ref(false); const showInvitePopup = ref(false);
const showGuildSettings = ref(false);
import UserPopup from "~/components/UserPopup.vue";
import type { ChannelResponse, GuildMemberResponse, GuildResponse, MessageResponse } from "~/types/interfaces";
//const servers = await fetchWithApi("/servers") as { uuid: string, name: string, description: string }[]; //const servers = await fetchWithApi("/servers") as { uuid: string, name: string, description: string }[];
//console.log("channelid: servers:", servers); //console.log("channelid: servers:", servers);
const { fetchMembers } = useApi(); const { fetchMembers } = useApi();
const members = await fetchMembers(route.params.serverId as string);
onMounted(async () => { onMounted(async () => {
console.log("mounting"); console.log("channelid: set loading to true");
const guildUrl = `guilds/${route.params.serverId}`; const guildUrl = `guilds/${route.params.serverId}`;
server.value = await fetchWithApi(guildUrl); server.value = await fetchWithApi(guildUrl);
console.log("fetched guild");
await setArrayVariables();
console.log("set array variables");
});
onActivated(async () => {
console.log("activating");
const guildUrl = `guilds/${route.params.serverId}`;
server.value = await fetchWithApi(guildUrl);
console.log("fetched guild");
await setArrayVariables();
console.log("set array variables");
});
async function setArrayVariables() {
members.value = sortMembers(await fetchMembers(route.params.serverId as string))
const guildUrl = `guilds/${route.params.serverId}`;
channels.value = await fetchWithApi(`${guildUrl}/channels`); channels.value = await fetchWithApi(`${guildUrl}/channels`);
console.log("channels:", channels.value); console.log("channels:", channels.value);
channel.value = await fetchWithApi(`/channels/${route.params.channelId}`); channel.value = await fetchWithApi(`/channels/${route.params.channelId}`);
console.log("channel:", channel.value); console.log("channel:", channel.value);
}
function toggleGuildSettings(e: Event) { console.log("channelid: channel:", channel);
e.preventDefault(); console.log("channelid: set loading to false");
showGuildSettings.value = !showGuildSettings.value; });
}
function showGuildSettings() { }
function toggleInvitePopup(e: Event) { function toggleInvitePopup(e: Event) {
e.preventDefault(); e.preventDefault();
@ -100,27 +81,39 @@ function handleMemberClick(member: GuildMemberResponse) {
</script> </script>
<style> <style>
#middle-left-column {
padding-left: 1dvw;
padding-right: 1dvw;
border-right: 1px solid var(--padding-color);
background: var(--optional-channel-list-background);
background-color: var(--sidebar-background-color);
}
#members-container { #members-container {
padding-top: 1dvh;
padding-left: 1dvw;
padding-right: 1dvw;
border-left: 1px solid var(--padding-color);
background: var(--optional-member-list-background); background: var(--optional-member-list-background);
} }
#members-list { #members-list {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
overflow-x: hidden;
overflow-y: scroll; overflow-y: scroll;
padding-left: 1.25em; max-height: 92dvh;
padding-right: 1.25em; padding-left: 1dvw;
padding-top: 0.75em; padding-right: 1dvw;
padding-bottom: 0.75em; margin-top: 1dvh;
max-height: calc(100% - 0.75em * 2); /* 100% - top and bottom */
} }
.member-item { .member-item {
display: flex; display: grid;
grid-template-columns: 2dvw 1fr;
margin-top: .5em; margin-top: .5em;
margin-bottom: .5em; margin-bottom: .5em;
gap: .5em; gap: 1em;
align-items: center; align-items: center;
text-align: left; text-align: left;
cursor: pointer; cursor: pointer;
@ -129,15 +122,13 @@ function handleMemberClick(member: GuildMemberResponse) {
#channels-list { #channels-list {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: .5em; gap: 1dvh;
text-overflow: ellipsis;
} }
.member-avatar { .member-avatar {
min-width: 2.3em; height: 2.3em;
max-width: 2.3em; width: 2.3em;
min-width: 2.3em; border-radius: 50%;
max-height: 2.3em;
} }
.member-display-name { .member-display-name {
@ -145,25 +136,4 @@ function handleMemberClick(member: GuildMemberResponse) {
text-overflow: ellipsis; text-overflow: ellipsis;
} }
#server-name-container {
padding-top: 3dvh;
padding-bottom: 3dvh;
display: flex;
justify-content: center;
position: relative;
}
#server-name {
font-size: 1.5em;
overflow: hidden;
text-overflow: ellipsis;
}
#server-settings-button {
background-color: transparent;
font-size: 1em;
color: white;
border: none;
padding: 0%;
}
</style> </style>

View file

@ -8,7 +8,7 @@
<Icon class="back-button" size="2em" name="lucide:circle-arrow-left" alt="Back"></Icon> <Icon class="back-button" size="2em" name="lucide:circle-arrow-left" alt="Back"></Icon>
</span> </span>
</p> </p>
<VerticalSpacer /> <span class="spacer"></span>
<!-- categories and dynamic settings pages --> <!-- categories and dynamic settings pages -->
<div v-for="category in categories" :key="category.displayName"> <div v-for="category in categories" :key="category.displayName">
@ -17,13 +17,13 @@
:class="{ 'sidebar-focus': selectedPage === page.displayName }"> :class="{ 'sidebar-focus': selectedPage === page.displayName }">
{{ page.displayName }} {{ page.displayName }}
</li> </li>
<VerticalSpacer /> <span class="spacer"></span>
</div> </div>
<p> <p>
<Button text="Log Out" :callback=logout variant="scary"></Button> <Button text="Log Out" :callback=logout variant="scary"></Button>
</p> </p>
<VerticalSpacer /> <span class="spacer"></span>
<p id="links-and-socials"> <p id="links-and-socials">
<NuxtLink href="https://git.gorb.app/gorb/frontend" title="Source"><Icon name="lucide:git-branch-plus" /></NuxtLink> <NuxtLink href="https://git.gorb.app/gorb/frontend" title="Source"><Icon name="lucide:git-branch-plus" /></NuxtLink>
@ -46,13 +46,6 @@
<script lang="ts" setup> <script lang="ts" setup>
import { Profile, Account, Privacy, Devices, Connections } from '~/components/Settings/UserSettings';
import { Appearance, Notifications, Keybinds, Language } from '~/components/Settings/AppSettings';
import VerticalSpacer from '~/components/UserInterface/VerticalSpacer.vue';
import Button from '~/components/UserInterface/Button.vue';
const { logout } = useAuth() const { logout } = useAuth()
const appConfig = useRuntimeConfig() const appConfig = useRuntimeConfig()
@ -66,6 +59,17 @@ interface Category {
pages: Page[]; pages: Page[];
} }
import Profile from '~/components/Settings/UserSettings/Profile.vue';
import Account from '~/components/Settings/UserSettings/Account.vue';
import Privacy from '~/components/Settings/UserSettings/Privacy.vue';
import Devices from '~/components/Settings/UserSettings/Devices.vue';
import Connections from '~/components/Settings/UserSettings/Connections.vue';
import Appearance from '~/components/Settings/AppSettings/Appearance.vue';
import Notifications from '~/components/Settings/AppSettings/Notifications.vue';
import Keybinds from '~/components/Settings/AppSettings/Keybinds.vue';
import Language from '~/components/Settings/AppSettings/Language.vue';
const settingsCategories = { const settingsCategories = {
userSettings: { userSettings: {
displayName: "User Settings", displayName: "User Settings",
@ -192,6 +196,13 @@ onMounted(() => {
margin-right: 0.2em; margin-right: 0.2em;
} }
.spacer {
height: 0.2dvh;
display: block;
margin: 0.8dvh 1dvw;
background-color: var(--padding-color);
}
/* applies to child pages too */ /* applies to child pages too */
:deep(.subtitle) { :deep(.subtitle) {
display: block; display: block;

View file

@ -15,12 +15,6 @@ const token = useRoute().query.token;
try { try {
const res = await fetchWithApi("/auth/verify-email", { query: { token } }); const res = await fetchWithApi("/auth/verify-email", { query: { token } });
console.log("hi"); console.log("hi");
const query = useRoute().query;
if (query.redirect_to) {
await navigateTo(`/?redirect_to=${query.redirect_to}`);
} else {
await navigateTo("/");
}
} catch (error) { } catch (error) {
console.error("Error verifying email:", error); console.error("Error verifying email:", error);
errorMessage.value = error; errorMessage.value = error;

8
pnpm-lock.yaml generated
View file

@ -47,9 +47,6 @@ importers:
vue-router: vue-router:
specifier: ^4.5.1 specifier: ^4.5.1
version: 4.5.1(vue@3.5.13(typescript@5.8.3)) version: 4.5.1(vue@3.5.13(typescript@5.8.3))
xxhash-wasm:
specifier: ^1.1.0
version: 1.1.0
devDependencies: devDependencies:
'@iconify-json/lucide': '@iconify-json/lucide':
specifier: ^1.2.44 specifier: ^1.2.44
@ -4747,9 +4744,6 @@ packages:
engines: {node: '>= 0.10.0'} engines: {node: '>= 0.10.0'}
hasBin: true hasBin: true
xxhash-wasm@1.1.0:
resolution: {integrity: sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA==}
y18n@5.0.8: y18n@5.0.8:
resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}
engines: {node: '>=10'} engines: {node: '>=10'}
@ -10152,8 +10146,6 @@ snapshots:
cssfilter: 0.0.10 cssfilter: 0.0.10
optional: true optional: true
xxhash-wasm@1.1.0: {}
y18n@5.0.8: {} y18n@5.0.8: {}
yallist@3.1.1: {} yallist@3.1.1: {}

View file

@ -1,7 +1,6 @@
:root { :root {
--text-color: #f0e5e0; --text-color: #f0e5e0;
--secondary-text-color: #e8e0db; --secondary-text-color: #e8e0db;
--reply-text-color: #969696;
--chat-background-color: #2f2e2d; --chat-background-color: #2f2e2d;
--chat-highlighted-background-color: #3f3b38; --chat-highlighted-background-color: #3f3b38;
@ -11,18 +10,11 @@
--chatbox-background-color: #3a3733; --chatbox-background-color: #3a3733;
--padding-color: #e0e0e0; --padding-color: #e0e0e0;
--primary-color: #f07028; --primary-color: #f07028;
--primary-highlighted-color: #f28f4b; --primary-highlighted-color: #f28f4b;
--secondary-color: #683820; --secondary-color: #683820;
--secondary-highlighted-color: #885830; --secondary-highlighted-color: #885830;
--accent-color: #a04b24; --accent-color: #a04b24;
--accent-highlighted-color: #b86038; --accent-highlighted-color: #b86038;
--sidebar-width: 2.5em;
--standard-radius: .5em;
--button-radius: .6em;
--guild-icon-radius: 20%;
--pfp-radius: 50%;
--preferred-font: Arial;
} }

View file

@ -1,14 +1,13 @@
:root { :root {
--text-color: #f7eee8; --text-color: #f7eee8;
--secondary-text-color: #f0e8e4; --secondary-text-color: #f0e8e4;
--reply-text-color: #969696;
--chat-background-color: #1f1e1d; --chat-background-color: #1f1e1d;
--chat-highlighted-background-color: #2f2b28; --chat-highlighted-background-color: #2f2b28;
--sidebar-background-color: #2e2a27; --sidebar-background-color: #2e2a27;
--sidebar-highlighted-background-color: #36322b; --sidebar-highlighted-background-color: #36322b;
--topbar-background-color: #2a2723; --topbar-background-color: #2a2723;
--chatbox-background-color: #1a1713; --chatbox-background-color: #2a2723;
--padding-color: #484848; --padding-color: #484848;
@ -18,14 +17,4 @@
--secondary-highlighted-color: #8f5b2c; --secondary-highlighted-color: #8f5b2c;
--accent-color: #b35719; --accent-color: #b35719;
--accent-highlighted-color: #c76a2e; --accent-highlighted-color: #c76a2e;
--sidebar-icon-width: 2.5em;
--sidebar-icon-gap: .25em;
--sidebar-margin: .5em;
--standard-radius: .5em;
--button-radius: .6em;
--guild-icon-radius: 15%;
--pfp-radius: 50%;
--preferred-font: Arial;
} }

View file

@ -2,7 +2,6 @@
:root { :root {
--text-color: #161518; --text-color: #161518;
--secondary-text-color: #2b2930; --secondary-text-color: #2b2930;
--reply-text-color: #969696;
--chat-background-color: #80808000; --chat-background-color: #80808000;
--chat-highlighted-background-color: #ffffff20; --chat-highlighted-background-color: #ffffff20;
@ -20,12 +19,6 @@
--accent-color: #ff218c80; --accent-color: #ff218c80;
--accent-highlighted-color: #df1b6f80; --accent-highlighted-color: #df1b6f80;
--sidebar-width: 2.5em;
--standard-radius: .5em;
--button-radius: .6em;
--pfp-radius: 50%;
--preferred-font: Arial;
--optional-body-background: ; /* background element for the body */ --optional-body-background: ; /* background element for the body */
--optional-chat-background: ; /* background element for the chat box */ --optional-chat-background: ; /* background element for the chat box */
--optional-topbar-background: ; /* background element for the topbar */ --optional-topbar-background: ; /* background element for the topbar */

View file

@ -1,7 +1,6 @@
:root { :root {
--text-color: #170f08; --text-color: #170f08;
--secondary-text-color: #2f2b28; --secondary-text-color: #2f2b28;
--reply-text-color: #969696;
--chat-background-color: #f0ebe8; --chat-background-color: #f0ebe8;
--chat-highlighted-background-color: #e8e4e0; --chat-highlighted-background-color: #e8e4e0;
@ -18,10 +17,4 @@
--secondary-highlighted-color: #f8b68a; --secondary-highlighted-color: #f8b68a;
--accent-color: #e68b4e; --accent-color: #e68b4e;
--accent-highlighted-color: #f69254; --accent-highlighted-color: #f69254;
--sidebar-width: 2.5em;
--standard-radius: .5em;
--button-radius: .6em;
--pfp-radius: 50%;
--preferred-font: Arial;
} }

View file

@ -1,7 +1,6 @@
:root { :root {
--text-color: #161518; --text-color: #161518;
--secondary-text-color: #2b2930; --secondary-text-color: #2b2930;
--reply-text-color: #969696;
--chat-background-color: #80808000; --chat-background-color: #80808000;
--chat-highlighted-background-color: #ffffff20; --chat-highlighted-background-color: #ffffff20;
@ -19,12 +18,6 @@
--accent-color: #ff218c80; --accent-color: #ff218c80;
--accent-highlighted-color: #df1b6f80; --accent-highlighted-color: #df1b6f80;
--sidebar-width: 2.5em;
--standard-radius: .5em;
--button-radius: .6em;
--pfp-radius: 50%;
--preferred-font: Arial;
/* --optional-body-background: background */ /* --optional-body-background: background */
--optional-body-background: linear-gradient(45deg, #ed222480, #ed222480, #ed222480, #ed222480, #ed222480, #ed222480, #f35b2280, #f9962180, #f5c11e80, #f1eb1b80, #f1eb1b80, #f1eb1b80, #63c72080, #0c9b4980, #21878d80, #3954a580, #61379b80, #93288e80); --optional-body-background: linear-gradient(45deg, #ed222480, #ed222480, #ed222480, #ed222480, #ed222480, #ed222480, #f35b2280, #f9962180, #f5c11e80, #f1eb1b80, #f1eb1b80, #f1eb1b80, #63c72080, #0c9b4980, #21878d80, #3954a580, #61379b80, #93288e80);
--optional-topbar-background: linear-gradient(-12.5deg, cyan, pink, white, pink, cyan); --optional-topbar-background: linear-gradient(-12.5deg, cyan, pink, white, pink, cyan);

View file

@ -1,5 +0,0 @@
declare module "nuxt/schema" {
interface RuntimeNuxtHooks {
"app:message:right-clicked": (payload: { messageId: string }) => void
}
}

View file

@ -44,8 +44,7 @@ export interface MessageResponse {
channel_uuid: string, channel_uuid: string,
user_uuid: string, user_uuid: string,
message: string, message: string,
reply_to: string | null, user: UserResponse
user: UserResponse,
} }
export interface InviteResponse { export interface InviteResponse {
@ -62,8 +61,7 @@ export interface UserResponse {
pronouns: string | null, pronouns: string | null,
about: string | null, about: string | null,
email?: string, email?: string,
email_verified?: boolean, email_verified?: boolean
friends_since: string | null,
} }
export interface StatsResponse { export interface StatsResponse {
@ -85,21 +83,3 @@ export interface ScrollPosition {
offsetTop: number, offsetTop: number,
offsetLeft: number offsetLeft: number
} }
export interface DropdownOption {
name: string,
value: string | number,
callback: () => void
}
export interface ModalProps {
title?: string,
obscure?: boolean,
onClose?: () => void,
onCancel?: () => void
}
export interface ContextMenuItem {
name: string,
callback: (...args: any[]) => any;
}

View file

@ -1,21 +0,0 @@
import type { MessageResponse, UserResponse } from "./interfaces";
export interface MessageProps {
class?: string,
img?: string | null,
author: UserResponse
text: string,
timestamp: number,
format: "12" | "24",
type: "normal" | "grouped",
marginBottom: boolean,
authorColor: string,
last: boolean,
messageId: string,
replyingTo?: boolean,
editing?: boolean,
me: UserResponse
message: MessageResponse,
replyMessage?: MessageResponse
isMentioned?: boolean,
}

View file

@ -1,9 +0,0 @@
export interface ClientSettings {
selectedThemeId?: string, // the ID of the theme, not the URL, for example "dark"
timeFormat?: TimeFormat
}
export interface TimeFormat {
index: number,
format: "auto" | "12" | "24"
}

View file

@ -1,21 +0,0 @@
import { render } from "vue";
import ContextMenu from "~/components/UserInterface/ContextMenu.vue";
import type { ContextMenuItem } from "~/types/interfaces";
export default (e: PointerEvent | MouseEvent, menuItems: ContextMenuItem[]) => {
console.log("Rendering new context menu");
const menuContainer = document.createElement("div");
console.log("hello");
menuContainer.id = "context-menu";
document.body.appendChild(menuContainer);
console.log("pointer x:", e.clientX);
console.log("pointer y:", e.clientY);
console.log("menu items:", menuItems);
const contextMenu = h(ContextMenu, {
menuItems,
pointerX: e.clientX,
pointerY: e.clientY
});
render(contextMenu, menuContainer);
console.log("Rendered");
}

View file

@ -1,24 +0,0 @@
import type { MessageProps } from "~/types/props";
export default async (element: HTMLDivElement, props: MessageProps) => {
console.log("message:", element);
const me = await fetchWithApi("/me") as any;
if (props.author?.uuid == me.uuid) {
const text = element.getElementsByClassName("message-text")[0] as HTMLDivElement;
text.contentEditable = "true";
text.focus();
const range = document.createRange();
range.selectNodeContents(text);
range.collapse(false);
const selection = window.getSelection();
selection?.removeAllRanges();
selection?.addRange(range);
element.addEventListener("keyup", (e) => {
console.log("key released:", e.key);
if (e.key == "Escape") {
text.contentEditable = "false";
}
text.blur();
}, { once: true });
}
}

View file

@ -1,4 +1,4 @@
import type { NitroFetchOptions } from "nitropack"; import type { NitroFetchRequest, NitroFetchOptions } from "nitropack";
export default async <T>(path: string, options: NitroFetchOptions<string> = {}) => { export default async <T>(path: string, options: NitroFetchOptions<string> = {}) => {
console.log("path received:", path); console.log("path received:", path);
@ -18,7 +18,7 @@ export default async <T>(path: string, options: NitroFetchOptions<string> = {})
return; return;
} }
console.log("path:", path) console.log("path:", path)
const { clearAuth, refresh } = useAuth(); const { revoke, refresh } = useAuth();
let headers: HeadersInit = {}; let headers: HeadersInit = {};
@ -61,7 +61,8 @@ export default async <T>(path: string, options: NitroFetchOptions<string> = {})
if (error?.response?.status === 401) { if (error?.response?.status === 401) {
console.log("Refresh returned 401"); console.log("Refresh returned 401");
reauthFailed = true; reauthFailed = true;
await clearAuth() console.log("Revoking");
await revoke();
console.log("Redirecting to login"); console.log("Redirecting to login");
await navigateTo("/login"); await navigateTo("/login");
console.log("redirected"); console.log("redirected");

View file

@ -1,38 +0,0 @@
export default (name: string, seed: string): string => {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
if (canvas && ctx) {
canvas.width = 256;
canvas.height = 256;
// get the first char from every word in the guild name
let previewName = "";
if (name.length > 3) {
let guildName: string[] = name.split(' ')
for (let i = 0; i < 3; i ++) {
if (guildName.length > i) {
previewName += guildName[i].charAt(0)
} else {
break
}
}
} else {
previewName = name
}
// fill background using seeded colour
ctx.fillStyle = generateIrcColor(seed, 50)
ctx.fillRect(0, 0, 256, 256)
ctx.fillStyle = 'white'
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.font = `bold 96px Arial, Helvetica, sans-serif`
// 136 isn't actually centered, but it *looks* centered
ctx.fillText(previewName, 128, 136)
return canvas.toDataURL("image/png");
}
return "https://tenor.com/view/dame-da-ne-guy-kiryukazuma-kiryu-yakuza-yakuza-0-gif-14355451116903905918"
}

View file

@ -1,13 +0,0 @@
import xxhash from "xxhash-wasm"
let h64: CallableFunction;
(async () => {
h64 = (await xxhash()).h64;
})();
export default (seed: string, saturation: number = 100, lightness: number = 50): string => {
const idHash = useState(`h64Hash-${seed}`, () => h64(seed))
const hashValue: bigint = idHash.value
return `hsl(${hashValue % 360n}, ${saturation}%, ${lightness}%)`
}

View file

@ -1,7 +0,0 @@
import type { GuildMemberResponse, UserResponse } from "~/types/interfaces";
export default (user: UserResponse, member?: GuildMemberResponse): string => {
if (member?.nickname) return member.nickname
if (user.display_name) return user.display_name
return user.username
}

View file

@ -1,11 +0,0 @@
export default (): "12" | "24" => {
const format = settingsLoad().timeFormat?.format ?? "auto"
if (format == "12") {
return "12"
} else if (format == "24") {
return "24"
}
return "24"
}

View file

@ -1,4 +1,4 @@
export default async (password: string) => { export async function hashPassword(password: string) {
const encodedPass = new TextEncoder().encode(password); const encodedPass = new TextEncoder().encode(password);
const hashBuffer = await crypto.subtle.digest("SHA-384", encodedPass); const hashBuffer = await crypto.subtle.digest("SHA-384", encodedPass);
const hashArray = Array.from(new Uint8Array(hashBuffer)); const hashArray = Array.from(new Uint8Array(hashBuffer));

View file

@ -1,50 +0,0 @@
//
// Canvas Blocker &
// Firefox privacy.resistFingerprinting Detector.
// (c) 2018 // JOHN OZBAY // CRYPT.EE
// MIT License
//
export default () => {
// create a 1px image data
var blocked = false;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
// some blockers just return an undefined ctx. So let's check that first.
if (ctx) {
var imageData = ctx.createImageData(1,1);
var originalImageData = imageData.data;
// set pixels to RGB 128
originalImageData[0]=128;
originalImageData[1]=128;
originalImageData[2]=128;
originalImageData[3]=255;
// set this to canvas
ctx.putImageData(imageData,1,1);
try {
// now get the data back from canvas.
var checkData = ctx.getImageData(1, 1, 1, 1).data;
// If this is firefox, and privacy.resistFingerprinting is enabled,
// OR a browser extension blocking the canvas,
// This will return RGB all white (255,255,255) instead of the (128,128,128) we put.
// so let's check the R and G to see if they're 255 or 128 (matching what we've initially set)
if (originalImageData[0] !== checkData[0] && originalImageData[1] !== checkData[1]) {
blocked = true;
console.log("Canvas is blocked. Will display warning.");
}
} catch (error) {
// some extensions will return getImageData null. this is to account for that.
blocked = true;
console.log("Canvas is blocked. Will display warning.");
}
} else {
blocked = true;
console.log("Canvas is blocked. Will display warning.");
}
return blocked;
}

View file

@ -1,28 +0,0 @@
let themeLinkElement: HTMLLinkElement | null;
export default function loadPreferredTheme() {
const currentTheme = settingsLoad().selectedThemeId ?? "dark"
if (themeLinkElement) {
themeLinkElement.href = getThemeUrl(currentTheme);
} else {
// create the theme link if one doesn't already exist
useHead({
link: [{
id: "main-theme",
rel: "stylesheet",
href: getThemeUrl(currentTheme)
}]
})
themeLinkElement = document.getElementById('main-theme') as HTMLLinkElement;
}
}
function getThemeUrl(id: string): string {
const runtimeConfig = useRuntimeConfig()
const baseURL = runtimeConfig.app.baseURL;
// this should preferrably use version hash, but that's not implemented yet
return `${baseURL}themes/${id}.css?v=${runtimeConfig.public.buildTimeString}`
}

View file

@ -1,6 +0,0 @@
export default () => {
const contextMenu = document.getElementById("context-menu");
if (contextMenu) {
contextMenu.remove();
}
}

View file

@ -1,14 +0,0 @@
import { render } from "vue";
import MessageReply from "~/components/UserInterface/MessageReply.vue";
import type { MessageProps } from "~/types/props";
export default (element: HTMLDivElement, props: MessageProps) => {
console.log("element:", element);
const messageBox = document.getElementById("message-box") as HTMLDivElement;
if (messageBox) {
const div = document.createElement("div");
const messageReply = h(MessageReply, { author: getDisplayName(props.author), text: props.text || "", id: props.message.uuid, replyId: props.replyMessage?.uuid || element.dataset.messageId!, maxWidth: "full" });
messageBox.prepend(div);
render(messageReply, div);
}
}

View file

@ -1,21 +0,0 @@
export default (key: string, value: any): void => {
let clientSettingsItem: string | null = localStorage.getItem("clientSettings")
if (typeof clientSettingsItem != "string") {
clientSettingsItem = "{}"
}
let clientSettings: { [key: string]: any } = {}
try {
clientSettings = JSON.parse(clientSettingsItem)
} catch {
clientSettings = {}
}
if (typeof clientSettings !== "object") {
clientSettings = {}
}
clientSettings[key] = value
localStorage.setItem("clientSettings", JSON.stringify(clientSettings))
}

View file

@ -1,21 +0,0 @@
import type { ClientSettings } from "~/types/settings"
export default (): ClientSettings => {
let clientSettingsItem: string | null = localStorage.getItem("clientSettings")
if (typeof clientSettingsItem != "string") {
clientSettingsItem = "{}"
}
let clientSettings: ClientSettings = {}
try {
clientSettings = JSON.parse(clientSettingsItem)
} catch {
clientSettings = {}
}
if (typeof clientSettings !== "object") {
clientSettings = {}
}
return clientSettings
}

View file

@ -1,7 +0,0 @@
import type { GuildMemberResponse } from "~/types/interfaces";
export default (members: GuildMemberResponse[]): GuildMemberResponse[] => {
return members.sort((a, b) => {
return getDisplayName(a.user, a).localeCompare(getDisplayName(b.user, b))
})
}

View file

@ -1,7 +0,0 @@
import type { UserResponse } from "~/types/interfaces";
export default (users: UserResponse[]): UserResponse[] => {
return users.sort((a, b) => {
return getDisplayName(a).localeCompare(getDisplayName(b))
})
}

View file

@ -1,6 +0,0 @@
import { render } from "vue";
export default (div: Element) => {
render(null, div);
div.remove();
}

View file

@ -1,3 +0,0 @@
export default (username: string) => {
return /^[\w.-]+$/.test(username);
}

3
utils/validation.ts Normal file
View file

@ -0,0 +1,3 @@
export function validateUsername(username: string) {
return /^[\w.-]+$/.test(username);
}