refactor: 🎨 Refactor notes, event system and timelines

This commit is contained in:
Jesse Wierzbinski 2024-04-27 19:02:27 -10:00
parent 7461478170
commit 0f214b6a17
No known key found for this signature in database
18 changed files with 266 additions and 188 deletions

BIN
bun.lockb

Binary file not shown.

View file

@ -32,10 +32,6 @@ const props = defineProps<{
instance: Instance;
}>();
const emits = defineEmits<{
send: [];
}>();
const submitting = ref(false);
const tokenData = useTokenData();
const client = useMegalodon(tokenData);
@ -43,29 +39,29 @@ const client = useMegalodon(tokenData);
const send = async () => {
submitting.value = true;
await fetch(
new URL("/api/v1/statuses", client.value?.baseUrl ?? "").toString(),
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${tokenData.value?.access_token}`,
},
body: JSON.stringify({
status: content.value,
content_type: "text/markdown",
}),
fetch(new URL("/api/v1/statuses", client.value?.baseUrl ?? "").toString(), {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${tokenData.value?.access_token}`,
},
).then((res) => {
if (!res.ok) {
throw new Error("Failed to send status");
}
body: JSON.stringify({
status: content.value,
content_type: "text/markdown",
}),
})
.then(async (res) => {
if (!res.ok) {
throw new Error("Failed to send status");
}
content.value = "";
submitting.value = false;
});
emits("send");
content.value = "";
submitting.value = false;
useEvent("composer:send", await res.json());
})
.finally(() => {
useEvent("composer:close");
});
};
const characterLimit = computed(

View file

@ -1,6 +1,6 @@
<template>
<HeadlessTransitionRoot as="template" :show="open">
<HeadlessDialog as="div" class="relative z-50" @close="emits('close')">
<HeadlessDialog as="div" class="relative z-50" @close="useEvent('composer:close')">
<HeadlessTransitionChild as="template" enter="ease-out duration-300" enter-from="opacity-0"
enter-to="opacity-100" leave="ease-in duration-200" leave-from="opacity-100" leave-to="opacity-0">
<div class="fixed inset-0 bg-black/70 transition-opacity" />
@ -15,7 +15,7 @@
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-white/10 text-left shadow-xl transition-all sm:my-8 w-full max-w-xl">
<Composer v-if="instance" :instance="instance" @send="emits('close')" />
<Composer v-if="instance" :instance="instance" />
</HeadlessDialogPanel>
</HeadlessTransitionChild>
</div>
@ -25,14 +25,13 @@
</template>
<script lang="ts" setup>
const props = defineProps<{
open: boolean;
}>();
const open = ref(false);
useListen("composer:open", () => {
open.value = true;
});
useListen("composer:close", () => {
open.value = false;
});
const client = useMegalodon();
const instance = useInstance(client);
const emits = defineEmits<{
close: [];
}>();
</script>

View file

@ -47,7 +47,6 @@
</ButtonsBase>
</div>
</aside>
<ComposerModal :open="composerOpen" @close="composerOpen = false" />
</template>
<script lang="ts" setup>
@ -64,7 +63,6 @@ const timelines = ref([
},
]);
const composerOpen = ref(false);
const loadingAuth = ref(false);
const appData = useAppData();
@ -72,7 +70,7 @@ const tokenData = useTokenData();
const client = useMegalodon();
const compose = () => {
composerOpen.value = true;
useEvent("composer:open");
};
const signIn = async () => {

View file

@ -1,27 +1,27 @@
<template>
<div
class="first:rounded-t last:rounded-b ring-1 ring-white/5 p-6 flex flex-col bg-dark-800 hover:bg-dark-700 duration-200">
<div v-if="props.note?.reblog" class="mb-4 flex flex-row gap-2 items-center text-pink-500">
<Skeleton :enabled="!props.note" shape="rect" class="!h-6" :min-width="40" :max-width="100" width-unit="%">
<div v-if="reblog" class="mb-4 flex flex-row gap-2 items-center text-pink-500">
<Skeleton :enabled="!loaded" shape="rect" class="!h-6" :min-width="40" :max-width="100" width-unit="%">
<Icon name="tabler:repeat" class="h-6 w-6" aria-hidden="true" />
<img v-if="props.note?.account.avatar" :src="props.note?.account.avatar"
:alt="`${props.note?.account.acct}'s avatar'`" class="h-6 w-6 rounded ring-1 ring-white/10" />
<span><strong v-html="eventualReblogAccountName"></strong> reblogged</span>
<img v-if="reblog.avatar" :src="reblog.avatar" :alt="`${reblog.acct}'s avatar'`"
class="h-6 w-6 rounded ring-1 ring-white/10" />
<span><strong v-html="reblogDisplayName"></strong> reblogged</span>
</Skeleton>
</div>
<SocialElementsNotesHeader :note="note" :small="small" />
<div v-if="!noteClosed">
<NuxtLink :href="noteUrl" class="mt-6 block relative">
<Skeleton :enabled="true" v-if="!note" :min-width="50" :max-width="100" width-unit="%" shape="rect"
<div v-if="!collapsed">
<NuxtLink :href="url" class="mt-6 block relative">
<Skeleton :enabled="!loaded" :min-width="50" :max-width="100" width-unit="%" shape="rect"
type="content">
<div v-if="content"
:class="['prose prose-invert duration-200 !max-w-full break-words prose-a:no-underline content']"
v-html="content">
</div>
</Skeleton>
<div v-else-if="content"
:class="['prose prose-invert duration-200 !max-w-full break-words prose-a:no-underline content']"
v-html="content">
</div>
</NuxtLink>
<div v-if="attachments.length > 0" class="[&:not(:first-child)]:mt-6">
<SocialElementsNotesAttachment v-for="attachment of attachments" :key="attachment.id"
<div v-if="note && note.media_attachments.length > 0" class="[&:not(:first-child)]:mt-6">
<SocialElementsNotesAttachment v-for="attachment of note.media_attachments" :key="attachment.id"
:attachment="attachment" />
</div>
</div>
@ -32,7 +32,7 @@
<!-- Spoiler text is it's specified -->
<span v-if="note?.spoiler_text" class="mt-2 break-all">{{ note.spoiler_text
}}</span>
<ButtonsSecondary @click="noteClosed = false" class="mt-4">Show content</ButtonsSecondary>
<ButtonsSecondary @click="collapsed = false" class="mt-4">Show content</ButtonsSecondary>
</div>
<Skeleton class="!h-10 w-full mt-6" :enabled="true" v-if="!note && !small"></Skeleton>
<div v-else-if="!small"
@ -70,12 +70,12 @@
</ButtonsDropdownElement>
</HeadlessMenuItem>
<HeadlessMenuItem>
<ButtonsDropdownElement @click="note && copy(note.uri)" icon="tabler:link" class="w-full">
<ButtonsDropdownElement @click="copy(url)" icon="tabler:link" class="w-full">
Copy Link
</ButtonsDropdownElement>
</HeadlessMenuItem>
<HeadlessMenuItem>
<ButtonsDropdownElement @click="note && deleteNote()" icon="tabler:backspace"
<ButtonsDropdownElement @click="remove" icon="tabler:backspace"
class="w-full border-r-2 border-red-500">
Delete
</ButtonsDropdownElement>
@ -95,55 +95,30 @@ const props = defineProps<{
small?: boolean;
}>();
const emits = defineEmits<{
delete: [];
}>();
// Handle reblogs
const note = computed(() => props.note?.reblog ?? props.note);
const noteClosed = ref(
note.value?.sensitive || !!note.value?.spoiler_text || false,
);
const { copy } = useClipboard();
const tokenData = useTokenData();
const client = useMegalodon(tokenData);
const mentions = await useResolveMentions(
note.value?.mentions ?? [],
client.value,
);
const eventualReblogAccountName = props.note?.reblog
? useParsedContent(
props.note?.account.display_name,
props.note?.account.emojis,
mentions.value,
).value
: null;
const content =
note.value && process.client
? useParsedContent(
note.value.content,
note.value.emojis,
mentions.value,
)
: "";
const {
loaded,
note,
remove,
content,
shouldHide,
url,
reblog,
reblogDisplayName,
} = useNoteData(ref(props.note), client);
console.log(props.note?.account.display_name ?? "");
const collapsed = ref(shouldHide.value);
const { copy } = useClipboard();
const numberFormat = (number = 0) =>
new Intl.NumberFormat(undefined, {
notation: "compact",
compactDisplay: "short",
maximumFractionDigits: 1,
}).format(number);
const attachments = note.value?.media_attachments ?? [];
const noteUrl = note.value && `/@${note.value.account.acct}/${note.value.id}`;
const deleteNote = async () => {
const result = await client.value?.deleteStatus(note.value?.id ?? "");
if (result?.data) {
console.log("Status deleted", result.data);
emits("delete");
}
};
</script>
<style>

View file

@ -6,7 +6,8 @@
<Icon :name="icon" class="h-6 w-6 text-gray-200" aria-hidden="true" />
<img v-if="notification?.account?.avatar" :src="notification?.account.avatar"
:alt="`${notification?.account.acct}'s avatar'`" class="h-6 w-6 rounded ring-1 ring-white/10" />
<span class="text-gray-200"><strong v-html="accountName"></strong> {{ text }}</span>
<span class="text-gray-200"><strong v-html="accountName"></strong> {{ text
}}</span>
</Skeleton>
</div>
<div>
@ -29,7 +30,6 @@ const props = defineProps<{
const accountName = useParsedContent(
props.notification?.account?.display_name ?? "",
props.notification?.account?.emojis ?? [],
[],
);
const text = computed(() => {
if (!props.notification) return "";

View file

@ -119,22 +119,15 @@ watch(
useParsedContent(
props.account?.note ?? "",
props.account?.emojis ?? [],
[],
).value ?? "";
parsedFields.value =
props.account?.fields.map((field) => ({
name:
useParsedContent(
field.name,
props.account?.emojis ?? [],
[],
).value ?? "",
useParsedContent(field.name, props.account?.emojis ?? [])
.value ?? "",
value:
useParsedContent(
field.value,
props.account?.emojis ?? [],
[],
).value ?? "",
useParsedContent(field.value, props.account?.emojis ?? [])
.value ?? "",
})) ?? [];
},
{

View file

@ -1,5 +1,5 @@
<template>
<TimelinesTimeline :timeline="timeline" :load-next="loadNext" :load-prev="loadPrev" @delete="noteDelete" />
<TimelinesTimeline :timeline="timeline" :load-next="loadNext" :load-prev="loadPrev" />
</template>
<script lang="ts" setup>
@ -15,7 +15,7 @@ const { timeline, loadNext, loadPrev } = useAccountTimeline(
timelineParameters,
);
const noteDelete = async (id: string) => {
useListen("note:delete", ({ id }) => {
timeline.value = timeline.value.filter((note) => note.id !== id);
};
});
</script>

View file

@ -1,5 +1,5 @@
<template>
<TimelinesTimeline :timeline="timeline" :load-next="loadNext" :load-prev="loadPrev" @delete="noteDelete" />
<TimelinesTimeline :timeline="timeline" :load-next="loadNext" :load-prev="loadPrev" />
</template>
<script lang="ts" setup>
@ -10,7 +10,7 @@ const { timeline, loadNext, loadPrev } = useLocalTimeline(
timelineParameters,
);
const noteDelete = async (id: string) => {
useListen("note:delete", ({ id }) => {
timeline.value = timeline.value.filter((note) => note.id !== id);
};
});
</script>

View file

@ -1,5 +1,5 @@
<template>
<TimelinesTimeline :timeline="timeline" :load-next="loadNext" :load-prev="loadPrev" @delete="noteDelete" />
<TimelinesTimeline :timeline="timeline" :load-next="loadNext" :load-prev="loadPrev" />
</template>
<script lang="ts" setup>
@ -10,7 +10,7 @@ const { timeline, loadNext, loadPrev } = usePublicTimeline(
timelineParameters,
);
const noteDelete = async (id: string) => {
useListen("note:delete", ({ id }) => {
timeline.value = timeline.value.filter((note) => note.id !== id);
};
});
</script>

View file

@ -2,8 +2,7 @@
<ClientOnly>
<TransitionGroup leave-active-class="ease-in duration-200" leave-from-class="scale-100 opacity-100"
leave-to-class="opacity-0 scale-90">
<SocialElementsNotesNote @delete="emits('delete', note.id)" v-for="note of timeline" :key="note.id"
:note="note" />
<SocialElementsNotesNote v-for="note of timeline" :key="note.id" :note="note" />
</TransitionGroup>
<span ref="skeleton"></span>
<SocialElementsNotesNote v-for="index of 5" v-if="!hasReachedEnd" :skeleton="true" />
@ -25,10 +24,6 @@ const props = defineProps<{
loadPrev: () => Promise<void>;
}>();
const emits = defineEmits<{
delete: [id: string];
}>();
const isLoading = ref(true);
const hasReachedEnd = ref(false);
@ -47,10 +42,14 @@ onMounted(() => {
});
});
useListen("composer:send", () => {
props.loadPrev();
});
// Every 5 seconds, load newer posts (prev)
useIntervalFn(() => {
props.loadPrev();
}, 5000);
}, 10000);
watch(
() => props.timeline,

16
composables/EventBus.ts Normal file
View file

@ -0,0 +1,16 @@
import mitt from "mitt";
import type { Status } from "~/types/mastodon/status";
type ApplicationEvents = {
"note:reply": Status;
"note:delete": Status;
"note:edit": Status;
"composer:open": undefined;
"composer:send": Status;
"composer:close": undefined;
};
const emitter = mitt<ApplicationEvents>();
export const useEvent = emitter.emit;
export const useListen = emitter.on;

66
composables/NoteData.ts Normal file
View file

@ -0,0 +1,66 @@
import type { Mastodon } from "megalodon";
import type { Status } from "~/types/mastodon/status";
export const useNoteData = (
noteProp: MaybeRef<Status | undefined>,
client: Ref<Mastodon | null>,
) => {
const renderedNote = computed(
() => toValue(noteProp)?.reblog ?? toValue(noteProp),
);
const isReblog = computed(() => !!toValue(noteProp)?.reblog);
const shouldHide = computed(
() =>
renderedNote.value?.sensitive ||
!!renderedNote.value?.spoiler_text ||
false,
);
const mentions = useResolveMentions(
renderedNote.value?.mentions ?? [],
client.value,
);
const content = useParsedContent(
renderedNote.value?.content ?? "",
renderedNote.value?.emojis ?? [],
mentions,
);
const loaded = computed(() => content.value !== null);
const reblogDisplayName = useParsedContent(
renderedNote.value?.account.display_name ?? "",
renderedNote.value?.account.emojis ?? [],
);
const reblog = computed(() =>
isReblog.value && renderedNote.value
? {
avatar: renderedNote.value.account.avatar,
acct: renderedNote.value.account.acct,
}
: null,
);
const url = computed(
() => `/@${renderedNote.value?.account.acct}/${renderedNote.value?.id}`,
);
const remove = async () => {
const result = await client.value?.deleteStatus(
renderedNote.value?.id ?? "",
);
if (result?.data) {
useEvent("note:delete", result.data);
}
};
return {
loaded,
note: renderedNote,
content,
reblog,
reblogDisplayName,
shouldHide,
url,
remove,
};
};

View file

@ -12,76 +12,84 @@ import MentionComponent from "../components/social-elements/notes/mention.vue";
export const useParsedContent = (
content: string,
emojis: Emoji[],
mentions: Account[],
mentions: MaybeRef<Account[]> = ref([]),
): Ref<string | null> => {
const result = ref(null as string | null);
(async () => {
const contentHtml = document.createElement("div");
contentHtml.innerHTML = content;
watch(
mentions,
async () => {
const contentHtml = document.createElement("div");
contentHtml.innerHTML = content;
// Replace emoji shortcodes with images
const paragraphs = contentHtml.querySelectorAll("p");
// Replace emoji shortcodes with images
const paragraphs = contentHtml.querySelectorAll("p");
for (const paragraph of paragraphs) {
paragraph.innerHTML = paragraph.innerHTML.replace(
/:([a-z0-9_-]+):/g,
(match, emoji) => {
const emojiData = emojis.find((e) => e.shortcode === emoji);
if (!emojiData) {
return match;
}
const image = document.createElement("img");
image.src = emojiData.url;
image.alt = `:${emoji}:`;
image.title = emojiData.shortcode;
image.className =
"h-6 align-text-bottom inline not-prose hover:scale-110 transition-transform duration-75 ease-in-out";
return image.outerHTML;
},
);
}
// Replace links containing mentions with interactive mentions
const links = contentHtml.querySelectorAll("a");
for (const link of links) {
const mention = mentions.find(
(m) => link.textContent === `@${m.acct}`,
);
if (!mention) {
continue;
for (const paragraph of paragraphs) {
paragraph.innerHTML = paragraph.innerHTML.replace(
/:([a-z0-9_-]+):/g,
(match, emoji) => {
const emojiData = emojis.find(
(e) => e.shortcode === emoji,
);
if (!emojiData) {
return match;
}
const image = document.createElement("img");
image.src = emojiData.url;
image.alt = `:${emoji}:`;
image.title = emojiData.shortcode;
image.className =
"h-6 align-text-bottom inline not-prose hover:scale-110 transition-transform duration-75 ease-in-out";
return image.outerHTML;
},
);
}
const renderedMention = h(MentionComponent);
renderedMention.props = {
account: mention,
};
// Replace links containing mentions with interactive mentions
const links = contentHtml.querySelectorAll("a");
link.outerHTML = await renderToString(renderedMention);
}
for (const link of links) {
const mention = toValue(mentions).find(
(m) => link.textContent === `@${m.acct}`,
);
if (!mention) {
continue;
}
// Highlight code blocks
const codeBlocks = contentHtml.querySelectorAll("pre code");
for (const codeBlock of codeBlocks) {
const code = codeBlock.textContent;
if (!code) {
continue;
const renderedMention = h(MentionComponent);
renderedMention.props = {
account: mention,
};
link.outerHTML = await renderToString(renderedMention);
}
const newCode = (await getShikiHighlighter()).highlight(code, {
lang: codeBlock.getAttribute("class")?.replace("language-", ""),
});
// Replace parent pre tag with highlighted code
const parent = codeBlock.parentElement;
if (!parent) {
continue;
// Highlight code blocks
const codeBlocks = contentHtml.querySelectorAll("pre code");
for (const codeBlock of codeBlocks) {
const code = codeBlock.textContent;
if (!code) {
continue;
}
const newCode = (await getShikiHighlighter()).highlight(code, {
lang: codeBlock
.getAttribute("class")
?.replace("language-", ""),
});
// Replace parent pre tag with highlighted code
const parent = codeBlock.parentElement;
if (!parent) {
continue;
}
parent.outerHTML = newCode;
}
parent.outerHTML = newCode;
}
result.value = contentHtml.innerHTML;
})();
result.value = contentHtml.innerHTML;
},
{ immediate: true },
);
return result;
};

View file

@ -2,19 +2,24 @@ import type { Mastodon } from "megalodon";
import type { Account } from "~/types/mastodon/account";
import type { Mention } from "~/types/mastodon/mention";
export const useResolveMentions = async (
export const useResolveMentions = (
mentions: Mention[],
client: Mastodon | null,
): Promise<Ref<Account[]>> => {
): Ref<Account[]> => {
if (!client) {
return ref([]);
}
return ref(
await Promise.all(
const output = ref<Account[]>([]);
(async () => {
output.value = await Promise.all(
mentions.map(async (mention) => {
const response = await client.getAccount(mention.id);
return response.data;
}),
),
);
);
})();
return output;
};

View file

@ -53,6 +53,7 @@
</aside>
</div>
</div>
<ComposerModal />
</template>
<script setup lang="ts">
@ -71,4 +72,12 @@ useServerSeoMeta({
colorScheme: "dark",
referrer: "no-referrer",
});
const { n } = useMagicKeys();
watchEffect(() => {
if (n.value) {
useEvent("composer:open");
}
});
</script>

View file

@ -10,6 +10,7 @@ export default defineNuxtConfig({
"@vee-validate/nuxt",
"nuxt-shiki",
],
app: {
head: {
link: [
@ -22,6 +23,7 @@ export default defineNuxtConfig({
htmlAttrs: { lang: "en-us" },
},
},
shiki: {
defaultTheme: "rose-pine",
bundledLangs: [
@ -40,6 +42,7 @@ export default defineNuxtConfig({
"yaml",
],
},
nitro: {
preset: "bun",
minify: true,
@ -51,12 +54,15 @@ export default defineNuxtConfig({
gzip: false,
},
},
schemaOrg: {
enabled: false,
},
ogImage: {
enabled: false,
},
vite: {
define: {
__VERSION__: JSON.stringify("0.4"),
@ -69,6 +75,7 @@ export default defineNuxtConfig({
},
},
},
veeValidate: {
autoImports: true,
componentNames: {
@ -78,6 +85,7 @@ export default defineNuxtConfig({
ErrorMessage: "VeeErrorMessage",
},
},
runtimeConfig: {
public: {
language: "en-US",
@ -87,7 +95,12 @@ export default defineNuxtConfig({
apiHost: "https://social.lysand.org",
},
},
site: {
url: "https://social.lysand.org",
},
devtools: {
enabled: true,
},
});

View file

@ -34,6 +34,7 @@
"c12": "^1.10.0",
"html-to-text": "^9.0.5",
"megalodon": "^10.0.0",
"mitt": "^3.0.1",
"nuxt": "^3.11.2",
"nuxt-headlessui": "^1.2.0",
"nuxt-icon": "^0.6.10",