feat: Rework OIDC flow, add emoji autosuggestions

This commit is contained in:
Jesse Wierzbinski 2024-05-16 20:25:59 -10:00
parent 7253a01921
commit a03392bbc3
No known key found for this signature in database
22 changed files with 358 additions and 78 deletions

30
app.vue
View file

@ -7,6 +7,7 @@
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
<NotificationsRenderer />
</template>
<script setup lang="ts">
@ -19,10 +20,8 @@ const code = useRequestURL().searchParams.get("code");
const appData = useAppData();
const tokenData = useTokenData();
const client = useMegalodon(tokenData);
const instance = useInstance(client);
const instance = useInstance();
const description = useExtendedDescription(client);
const me = useMe();
const customEmojis = useCustomEmojis(client);
useSeoMeta({
titleTemplate: (titleChunk) => {
@ -70,30 +69,7 @@ if (code) {
}
}
watch(
tokenData,
async () => {
if (tokenData.value && !me.value) {
const response = await client.value?.verifyAccountCredentials();
if (response?.data) {
me.value = response.data;
}
}
},
{ immediate: true },
);
// Refresh custom emojis and instance data and me on every reload
if (tokenData.value) {
await client.value?.verifyAccountCredentials().then((res) => {
me.value = res.data;
});
}
client.value?.getInstanceCustomEmojis().then((res) => {
customEmojis.value = res.data;
});
useCacheRefresh(client);
</script>
<style>

BIN
bun.lockb

Binary file not shown.

View file

@ -22,6 +22,8 @@
:class="['absolute bottom-0 right-0 p-2 text-gray-400 font-semibold text-xs', remainingCharacters < 0 && 'text-red-500']">
{{ remainingCharacters }}
</div>
<ComposerEmojiSuggestbox :currently-typing-emoji="currentlyBeingTypedEmoji"
@autocomplete="autocompleteEmoji" />
</div>
<!-- Content warning textbox -->
<div v-if="cw" class="mb-4">
@ -56,6 +58,7 @@
</template>
<script lang="ts" setup>
import { char, createRegExp, exactly } from "magic-regexp";
import type { Instance } from "~/types/mastodon/instance";
import type { Status } from "~/types/mastodon/status";
import { OverlayScrollbarsComponent } from "#imports";
@ -74,10 +77,25 @@ const markdown = ref(true);
const splashes = useConfig().COMPOSER_SPLASHES;
const chosenSplash = ref(splashes[Math.floor(Math.random() * splashes.length)]);
const currentlyBeingTypedEmoji = computed(() => {
const match = content.value?.match(partiallyTypedEmojiValidator);
return match ? match.at(-1)?.replace(":", "") ?? "" : null;
});
const autocompleteEmoji = (emoji: string) => {
// Replace the end of the string with the emoji
content.value = content.value?.replace(
createRegExp(
exactly(":"),
exactly(currentlyBeingTypedEmoji.value ?? "").notBefore(char),
),
`:${emoji}:`,
);
};
watch(Control_Alt, () => {
chosenSplash.value = splashes[Math.floor(Math.random() * splashes.length)];
});
onMounted(() => {
useListen("composer:reply", (note: Status) => {
respondingTo.value = note;

View file

@ -0,0 +1,87 @@
<template>
<ComposerSuggestbox class="max-h-40 overflow-auto !w-auto !flex-row">
<div v-for="(emoji, index) in topEmojis" :key="emoji.shortcode" @click="emit('autocomplete', emoji.shortcode)"
:ref="el => { if (el) emojiRefs[index] = el as Element }" :title="emoji.shortcode"
:class="['flex', 'justify-center', 'shrink-0', 'items-center', 'p-2', 'hover:bg-dark-900/70', { 'bg-pink-500': index === selectedEmojiIndex }]">
<img :src="emoji.url" class="w-8 h-8" :alt="`Emoji with shortcode ${emoji.shortcode}`" />
</div>
</ComposerSuggestbox>
</template>
<script lang="ts" setup>
import { distance } from "fastest-levenshtein";
import type { UnwrapRef } from "vue";
const props = defineProps<{
currentlyTypingEmoji: string | null;
}>();
const emojiRefs = ref<Element[]>([]);
const customEmojis = useCustomEmojis();
const { Tab, ArrowRight, ArrowLeft, Enter } = useMagicKeys({
passive: false,
onEventFired(e) {
if (
["Tab", "Enter", "ArrowRight", "ArrowLeft"].includes(e.key) &&
topEmojis.value !== null
)
e.preventDefault();
},
});
const topEmojis = ref<UnwrapRef<typeof customEmojis> | null>(null);
const selectedEmojiIndex = ref<number | null>(null);
watchEffect(() => {
if (props.currentlyTypingEmoji !== null)
topEmojis.value = customEmojis.value
.map((emoji) => ({
...emoji,
distance: distance(
props.currentlyTypingEmoji as string,
emoji.shortcode,
),
}))
.sort((a, b) => a.distance - b.distance)
.slice(0, 20);
else topEmojis.value = null;
if (ArrowRight.value && topEmojis.value !== null) {
selectedEmojiIndex.value = (selectedEmojiIndex.value ?? -1) + 1;
if (selectedEmojiIndex.value >= topEmojis.value.length) {
selectedEmojiIndex.value = 0;
}
emojiRefs.value[selectedEmojiIndex.value]?.scrollIntoView({
behavior: "smooth",
block: "nearest",
});
}
if (ArrowLeft.value && topEmojis.value !== null) {
selectedEmojiIndex.value =
(selectedEmojiIndex.value ?? topEmojis.value.length) - 1;
if (selectedEmojiIndex.value < 0) {
selectedEmojiIndex.value = topEmojis.value.length - 1;
}
emojiRefs.value[selectedEmojiIndex.value]?.scrollIntoView({
behavior: "smooth",
block: "nearest",
});
}
if ((Tab.value || Enter.value) && topEmojis.value !== null) {
const emoji = topEmojis.value[selectedEmojiIndex.value ?? 0];
if (emoji) emit("autocomplete", emoji.shortcode);
}
});
// When currentlyTypingEmoji changes, reset the selected emoji index
watch(
() => props.currentlyTypingEmoji,
() => {
selectedEmojiIndex.value = null;
},
);
const emit = defineEmits<{
autocomplete: [emoji: string];
}>();
</script>

View file

@ -14,7 +14,7 @@
leave-from="opacity-100 translate-y-0 sm:scale-100"
leave-to="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95">
<HeadlessDialogPanel
class="relative transform overflow-hidden rounded-lg bg-dark-700 ring-1 ring-dark-800 text-left shadow-xl transition-all sm:my-8 w-full max-w-xl">
class="relative transform rounded-lg bg-dark-700 ring-1 ring-dark-800 text-left shadow-xl transition-all sm:my-8 w-full max-w-xl">
<Composer v-if="instance" :instance="instance" />
</HeadlessDialogPanel>
</HeadlessTransitionChild>
@ -44,5 +44,5 @@ useListen("composer:close", () => {
});
const client = useMegalodon();
const tokenData = useTokenData();
const instance = useInstance(client);
const instance = useInstance();
</script>

View file

@ -0,0 +1,8 @@
<template>
<div class="w-full max-w-full rounded ring-1 ring-dark-300 bg-dark-800 absolute z-20 flex flex-col">
<slot />
</div>
</template>
<script lang="ts" setup>
</script>

View file

@ -10,6 +10,15 @@
<script lang="ts" setup>
const loading = ref(true);
const oidcError = useRequestURL().searchParams.get(
"oidc_account_linking_error",
);
const oidcErrorDesc = useRequestURL().searchParams.get(
"oidc_account_linking_error_message",
);
const oidcAccountLinked = useRequestURL().searchParams.get(
"oidc_account_linked",
);
const estimatedProgress = (duration: number, elapsed: number) =>
(2 / Math.PI) * 100 * Math.atan(((elapsed / duration) * 100) / 50);
@ -29,5 +38,42 @@ app.hook("page:finish", async () => {
// Wait until page has loaded for at least 1 second
await new Promise((resolve) => setTimeout(resolve, 1000));
loading.value = false;
if (oidcError) {
useEvent("notification:new", {
type: "error",
title: oidcError,
message: oidcErrorDesc ?? undefined,
persistent: true,
onDismiss: () => {
// Remove data from URL
window.history.replaceState(
{},
document.title,
window.location.pathname,
);
},
});
// Remove the error from the URL
}
if (oidcAccountLinked) {
useEvent("notification:new", {
type: "info",
title: "Account linked",
message:
"Your account has been successfully linked to your OpenID Connect provider.",
persistent: true,
onDismiss: () => {
// Remove data from URL
window.history.replaceState(
{},
document.title,
window.location.pathname,
);
},
});
}
});
</script>

View file

@ -0,0 +1,65 @@
<template>
<div aria-live="assertive" class="pointer-events-none fixed inset-0 flex items-end px-4 py-6 sm:items-start sm:p-6">
<div class="flex w-full flex-col items-center space-y-4 sm:items-end">
<!-- Notification panel, dynamically insert this into the live region when it needs to be displayed -->
<TransitionGroup enter-active-class="transform ease-out duration-300 transition"
enter-from-class="translate-y-2 opacity-0 sm:translate-y-0 sm:translate-x-2"
enter-to-class="translate-y-0 opacity-100 sm:translate-x-0"
leave-active-class="transition transform ease-in duration-100"
leave-from-class="translate-y-0 opacity-100 sm:translate-x-0"
leave-to-class="translate-y-2 opacity-0 sm:translate-y-0 sm:translate-x-2">
<div v-for="notification in notifications" :key="notification.id"
class="pointer-events-auto w-full max-w-sm overflow-hidden rounded-lg bg-dark-500 shadow-lg ring-1 ring-white/10">
<div class="p-4">
<div class="flex items-start">
<div class="shrink-0 h-6 w-6">
<iconify-icon v-if="notification.type === 'info'" icon="tabler:check" height="none"
class="h-6 w-6 text-green-400" aria-hidden="true" />
<iconify-icon v-else-if="notification.type === 'error'" icon="tabler:alert-triangle"
height="none" class="h-6 w-6 text-red-400" aria-hidden="true" />
</div>
<div class="ml-3 w-0 flex-1 pt-0.5">
<p class="text-sm font-semibold text-gray-50">{{ notification.title }}</p>
<p class="mt-1 text-sm text-gray-400" v-if="notification.message">{{
notification.message }}</p>
</div>
<div class="ml-4 flex flex-shrink-0">
<button type="button" title="Close this notification"
@click="notifications.splice(notifications.indexOf(notification), 1); notification.onDismiss?.()"
class="inline-flex rounded-md text-gray-400 hover:text-gray-300 duration-200">
<iconify-icon icon="tabler:x" class="h-5 w-5" aria-hidden="true" />
</button>
</div>
</div>
</div>
</div>
</TransitionGroup>
</div>
</div>
</template>
<script lang="ts" setup>
const notifications = ref<
(NotificationEvent & {
id: string;
})[]
>([]);
useListen("notification:new", (n) => {
const newNotification = {
...n,
id: Math.random().toString(36).substring(7),
};
notifications.value.push(newNotification);
!newNotification.persistent &&
setTimeout(() => {
notifications.value.splice(
notifications.value.indexOf(newNotification),
1,
);
newNotification.onDismiss?.();
}, 5000);
});
</script>

View file

@ -2,8 +2,8 @@
<div class="flex flex-col p-10 gap-4 h-full">
<div
class="aspect-video shrink-0 w-full rounded ring-white/5 bg-dark-800 shadow overflow-hidden ring-1 hover:ring-2 duration-100">
<img class="object-cover w-full h-full duration-150 hover:scale-[102%] ease-in-out"
v-if="instance?.banner" alt="Instance banner" :src="instance.banner" />
<img class="object-cover w-full h-full duration-150 hover:scale-[102%] ease-in-out" v-if="instance?.banner"
alt="Instance banner" :src="instance.banner" />
</div>
<div class="prose prose-invert prose-sm">
@ -20,6 +20,6 @@
<script lang="ts" setup>
const client = useMegalodon();
const instance = useInstance(client);
const instance = useInstance();
const description = useExtendedDescription(client);
</script>

View file

@ -0,0 +1,32 @@
import type { Mastodon } from "megalodon";
import type { InstanceWithExtra } from "./Instance";
export const useCacheRefresh = (client: MaybeRef<Mastodon | null>) => {
const tokenData = useTokenData();
const me = useMe();
const instance = useInstance();
const customEmojis = useCustomEmojis();
// Refresh custom emojis and instance data and me on every reload
watchEffect(async () => {
if (tokenData.value) {
await toValue(client)
?.verifyAccountCredentials()
.then((res) => {
me.value = res.data;
});
}
toValue(client)
?.getInstanceCustomEmojis()
.then((res) => {
customEmojis.value = res.data;
});
toValue(client)
?.getInstance()
.then((res) => {
instance.value = res.data as InstanceWithExtra;
});
});
};

View file

@ -1,7 +1,6 @@
import type { Mastodon } from "megalodon";
import type { Emoji } from "~/types/mastodon/emoji";
export const useCustomEmojis = (client: MaybeRef<Mastodon | null>) => {
export const useCustomEmojis = () => {
// Cache in localStorage
return useLocalStorage<Emoji[]>("lysand:custom_emojis", []);
};

View file

@ -1,6 +1,14 @@
import mitt from "mitt";
import type { Status } from "~/types/mastodon/status";
export type NotificationEvent = {
type: "error" | "info";
title: string;
message?: string;
persistent?: boolean;
onDismiss?: () => void;
};
type ApplicationEvents = {
"note:reply": Status;
"note:delete": Status;
@ -15,6 +23,7 @@ type ApplicationEvents = {
"composer:quote": Status;
"composer:send": Status;
"composer:close": undefined;
"notification:new": NotificationEvent;
};
const emitter = mitt<ApplicationEvents>();

View file

@ -1,23 +1,26 @@
import { StorageSerializers } from "@vueuse/core";
import type { Mastodon } from "megalodon";
import type { Instance } from "~/types/mastodon/instance";
type InstanceWithExtra = Instance & {
banner?: string;
lysand_version?: string;
export type InstanceWithExtra = Instance & {
banner: string | null;
lysand_version: string;
sso: {
forced: boolean;
providers: {
id: string;
name: string;
icon?: string;
}[];
};
};
export const useInstance = (client: MaybeRef<Mastodon | null>) => {
if (!ref(client).value) {
return ref(null as InstanceWithExtra | null);
export const useInstance = () => {
if (process.server) {
return ref(null);
}
const output = ref(null as InstanceWithExtra | null);
ref(client)
.value?.getInstance()
.then((res) => {
output.value = res.data;
});
return output;
return useLocalStorage<InstanceWithExtra | null>("lysand:instance", null, {
serializer: StorageSerializers.object,
});
};

View file

@ -1,13 +0,0 @@
export const useOAuthProviders = async () => {
if (process.server) return ref([]);
const providers = await fetch(
new URL("/oauth/providers", useBaseUrl().value),
).then((d) => d.json());
return ref(
providers as {
name: string;
icon: string;
id: string;
}[],
);
};

7
composables/SSOConfig.ts Normal file
View file

@ -0,0 +1,7 @@
import type { InstanceWithExtra } from "./Instance";
export const useSSOConfig = (): Ref<InstanceWithExtra["sso"] | null> => {
const instance = useInstance();
return computed(() => instance.value?.sso || null);
};

View file

@ -44,10 +44,10 @@
import { OverlayScrollbarsComponent } from "#imports";
const { width } = useWindowSize();
const { n, o_i_d_c } = useMagicKeys();
const { n, o_i_d_c, t_e_s_t } = useMagicKeys();
const tokenData = useTokenData();
const client = useMegalodon(tokenData);
const providers = await useOAuthProviders();
const providers = useSSOConfig();
watchEffect(async () => {
if (n.value) {
@ -56,20 +56,36 @@ watchEffect(async () => {
useEvent("composer:open");
}
if (o_i_d_c.value) {
const issuer = providers.value?.providers[0];
if (!issuer) {
console.error("No SSO provider found");
return;
}
const response = await fetch(
new URL(
`/oauth/link?issuer=${providers.value[0].id}`,
client.value?.baseUrl,
),
new URL("/api/v1/sso", client.value?.baseUrl),
{
method: "POST",
headers: {
Authorization: `Bearer ${tokenData.value?.access_token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
issuer: issuer.id,
}),
},
);
const json = await response.json();
window.location.href = json.link;
}
if (t_e_s_t.value) {
useEvent("notification:new", {
type: "info",
title: "Test Notification",
message: "This is a test notification",
});
}
});
</script>

View file

@ -24,7 +24,8 @@
"dev": "nuxt dev --https --https.cert config/lysand-fe.localhost.pem --https.key config/lysand-fe.localhost-key.pem --host lysand-fe.localhost",
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare"
"postinstall": "nuxt prepare",
"lint": "bunx @biomejs/biome check ."
},
"dependencies": {
"@nuxt/fonts": "^0.7.0",
@ -33,8 +34,10 @@
"@vee-validate/zod": "^4.12.6",
"@vite-pwa/nuxt": "^0.7.0",
"c12": "^1.10.0",
"fastest-levenshtein": "^1.0.16",
"html-to-text": "^9.0.5",
"iconify-icon": "^2.1.0",
"magic-regexp": "^0.8.0",
"megalodon": "^10.0.0",
"mitt": "^3.0.1",
"nuxt": "^3.11.2",

View file

@ -11,7 +11,6 @@
</div>
<VeeForm class="space-y-6" method="POST" :validation-schema="schema"
:action="`/api/auth/login?redirect_uri=${redirect_uri}&response_type=${response_type}&client_id=${client_id}&scope=${scope}`">
<h1 class="font-bold text-2xl text-gray-50 text-center tracking-tight">Login to your account</h1>
<VeeField name="identifier" as="div" v-slot="{ errors, field }" validate-on-change>
@ -31,11 +30,11 @@
</VeeErrorMessage>
</VeeField>
<div v-if="oauthProviders && oauthProviders.length > 0" class="w-full flex flex-col gap-3">
<div v-if="ssoConfig && ssoConfig.providers.length > 0" class="w-full flex flex-col gap-3">
<h2 class="text-sm text-gray-200">Or sign in with</h2>
<div class="grid grid-cols-1 gap-4 w-full">
<a v-for="provider of oauthProviders" :key="provider.id"
:href="`/oauth/authorize-external?issuer=${provider.id}&redirect_uri=${redirect_uri}&response_type=${response_type}&clientId=${client_id}&scope=${scope}`">
<a v-for="provider of ssoConfig.providers" :key="provider.id"
:href="`/oauth/sso?issuer=${provider.id}&redirect_uri=${redirect_uri}&response_type=${response_type}&client_id=${client_id}&scope=${scope}`">
<ButtonsSecondary class="flex flex-row w-full items-center justify-center gap-3">
<img crossorigin="anonymous" :src="provider.icon" :alt="`${provider.name}'s logo'`"
class="w-6 h-6" />
@ -110,5 +109,5 @@ const error_description = query.get("error_description");
const validUrlParameters = redirect_uri && response_type && client_id && scope;
const oauthProviders = await useOAuthProviders();
const ssoConfig = useSSOConfig();
</script>

View file

@ -69,7 +69,7 @@
</VeeField>
<ButtonsPrimary type="submit" class="w-full" :disabled="isLoading">{{ isLoading ? "Registering..." :
"Register" }}</ButtonsPrimary>
"Register" }}</ButtonsPrimary>
</VeeForm>
</div>
<div v-else>
@ -115,7 +115,7 @@ const schema = toTypedSchema(
);
const client = useMegalodon();
const instance = useInstance(client);
const instance = useInstance();
const errors = ref<{
[key: string]: {

View file

@ -10,7 +10,7 @@ import type { Reaction } from "./reaction";
export type Status = {
id: string;
uri: string;
url: string;
url?: string;
account: Account;
in_reply_to_id: string | null;
in_reply_to_account_id: string | null;

25
utils/validators.ts Normal file
View file

@ -0,0 +1,25 @@
import {
caseInsensitive,
char,
createRegExp,
digit,
exactly,
global,
letter,
multiline,
oneOrMore,
} from "magic-regexp";
export const emojiValidator = createRegExp(
// A-Z a-z 0-9 _ -
oneOrMore(letter.or(digit).or(exactly("_")).or(exactly("-"))),
[caseInsensitive, global],
);
export const partiallyTypedEmojiValidator = createRegExp(
exactly(":"),
oneOrMore(letter.or(digit).or(exactly("_")).or(exactly("-"))).notBefore(
char,
),
[caseInsensitive, multiline],
);