restructure for sveltekit

This commit is contained in:
ari melody 2024-06-29 10:46:27 +01:00
parent 7deea47857
commit 9ef27fd2a2
Signed by: ari
GPG key ID: CF99829C92678188
73 changed files with 469 additions and 28 deletions

221
src/lib/App.svelte Normal file
View file

@ -0,0 +1,221 @@
<script>
import Navigation from './ui/Navigation.svelte';
import Widgets from './ui/Widgets.svelte';
import Feed from './ui/Feed.svelte';
import { Client } from './client/client.js';
import Button from './ui/Button.svelte';
import { get } from 'svelte/store';
let client = get(Client.get());
let ready = client.app && client.app.token;
let instance_url_error = false;
let logging_in = false;
let auth_code = new URLSearchParams(location.search).get("code");
if (auth_code) {
client.getToken(auth_code).then(() => {
client.save();
location = location.origin;
});
}
if (client.app && client.app.token) {
// this triggers the client actually getting the authenticated user's data.
client.verifyCredentials().then(res => {
if (res) {
console.log(`Logged in as @${client.user.username}@${client.user.host}`);
}
});
}
function log_in(event) {
logging_in = true;
event.preventDefault();
const host = event.target.host.value;
client.init(host).then(res => {
logging_in = false;
if (!res) return;
if (res.constructor === String) {
instance_url_error = res;
return;
};
let oauth_url = client.getOAuthUrl();
location = oauth_url;
});
}
</script>
<div id="spacesocial-app">
<header>
<Navigation />
</header>
<main>
{#if ready}
<Feed />
{:else}
<div>
<form on:submit={log_in} id="login">
<h1>Space Social</h1>
<p>Welcome, fediverse user!</p>
<p>Please enter your instance domain to log in.</p>
<div class="input-wrapper">
<input type="text" id="host" aria-label="instance domain" class={logging_in ? "throb" : ""}>
{#if instance_url_error}
<p class="error">{instance_url_error}</p>
{/if}
</div>
<br>
<button type="submit" id="login" class={logging_in ? "disabled" : ""}>Log in</button>
<p><small>
Please note this is
<strong><em>extremely experimental software</em></strong>;
things are likely to break!
<br>
If that's all cool with you, welcome aboard!
</small></p>
<p class="form-footer">made with ❤️ by <a href="https://arimelody.me">ari melody</a>, 2024</p>
</form>
</div>
{/if}
</main>
<div id="widgets">
<Widgets />
</div>
</div>
<style>
#spacesocial-app {
margin: auto 0;
padding: 0 16px;
display: flex;
flex-direction: row;
justify-content: center;
gap: 16px;
}
header, #widgets {
width: 300px;
}
main {
width: 732px;
}
div.pane {
margin-top: 16px;
padding: 20px 32px;
border: 1px solid #8884;
border-radius: 16px;
background-color: var(--bg1);
}
form#login {
margin: 25vh 0 32px 0;
text-align: center;
}
a {
color: var(--accent);
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.input-wrapper {
width: 360px;
margin: 0 auto;
display: flex;
flex-direction: column;
align-items: center;
}
input[type=text] {
width: 100%;
padding: 12px;
display: block;
border-radius: 8px;
border: 1px solid var(--accent);
background-color: var(--bg-800);
font-family: inherit;
font-weight: bold;
font-size: inherit;
color: var(--text);
transition: box-shadow .2s;
}
input[type=text]::placeholder {
opacity: .8;
}
input[type=text]:focus {
outline: none;
box-shadow: 0 0 16px color-mix(in srgb, transparent, var(--accent) 25%);
}
.error {
margin: 6px;
font-style: italic;
font-size: .9em;
color: red;
opacity: .7;
}
button#login {
margin: -8px auto 0 auto;
padding: 12px 24px;
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
font-family: inherit;
font-size: 1rem;
font-weight: 600;
text-align: left;
border-radius: 8px;
border-width: 2px;
border-style: solid;
background-color: var(--bg-700);
color: var(--text);
border-color: transparent;
transition-property: border-color, background-color, color;
transition-timing-function: ease-out;
transition-duration: .1s;
cursor: pointer;
text-align: center;
justify-content: center;
}
button#login:hover {
background-color: color-mix(in srgb, var(--bg-700), var(--accent) 10%);
border-color: color-mix(in srgb, var(--bg-700), var(--accent) 20%);
}
button#login:active {
background-color: color-mix(in srgb, var(--bg-700), var(--bg-800) 50%);
border-color: color-mix(in srgb, var(--bg-700), var(--bg-800) 10%);
}
button#login.disabled {
opacity: .5;
cursor: initial;
}
.form-footer {
opacity: .7;
}
</style>

54
src/lib/app.css Normal file
View file

@ -0,0 +1,54 @@
@import url("/font/inter/inter.css");
:root {
--bg-1000: #fff6de;
--bg-900: #f9f1db;
--bg-800: #f1e8cf;
--bg-700: #d2c9b1;
--bg-600: #f0f6c2;
--accent: #8d9936;
--text: #322e1f;
}
@media (prefers-color-scheme: dark) {
:root {
--bg-1000: #141016;
--bg-900: #1B141E;
--bg-800: #2A202F;
--bg-700: #443749;
--bg-600: #513D60;
--accent: #CDA1EC;
--text: #E2DFE3;
}
}
@supports (font-variation-settings: normal) {
body { font-family: InterVariable, sans-serif; }
}
body {
width: 100vw;
margin: 0;
padding: 0;
color: var(--text);
background-color: var(--bg-1000);
font-family: "Inter", sans-serif;
font-feature-settings: 'liga' 1, 'calt' 1; /* fix for Chrome */
box-sizing: border-box;
}
.throb {
animation: .25s throb alternate infinite ease-in;
}
@keyframes throb {
from {
opacity: .5;
}
to {
opacity: 1;
}
}

353
src/lib/client/api.js Normal file
View file

@ -0,0 +1,353 @@
import { Client } from '../client/client.js';
import { capabilities } from '../client/instance.js';
import Post from '../post.js';
import User from '../user/user.js';
import Emoji from '../emoji.js';
import { get } from 'svelte/store';
export async function createApp(host) {
let form = new FormData();
form.append("client_name", "space social");
form.append("redirect_uris", `${location.origin}/callback`);
form.append("scopes", "read write push");
form.append("website", "https://spacesocial.arimelody.me");
const res = await fetch(`https://${host}/api/v1/apps`, {
method: "POST",
body: form,
})
.then(res => res.json())
.catch(error => {
console.error(error);
return false;
});
if (!res || !res.client_id) return false;
return {
id: res.client_id,
secret: res.client_secret,
};
}
export function getOAuthUrl() {
let client = get(Client.get());
return `https://${client.instance.host}/oauth/authorize` +
`?client_id=${client.app.id}` +
"&scope=read+write+push" +
`&redirect_uri=${location.origin}/callback` +
"&response_type=code";
}
export async function getToken(code) {
let client = get(Client.get());
let form = new FormData();
form.append("client_id", client.app.id);
form.append("client_secret", client.app.secret);
form.append("redirect_uri", `${location.origin}/callback`);
form.append("grant_type", "authorization_code");
form.append("code", code);
form.append("scope", "read write push");
const res = await fetch(`https://${client.instance.host}/oauth/token`, {
method: "POST",
body: form,
})
.then(res => res.json())
.catch(error => {
console.error(error);
return false;
});
if (!res || !res.access_token) return false;
return res.access_token;
}
export async function revokeToken() {
let client = get(Client.get());
let form = new FormData();
form.append("client_id", client.app.id);
form.append("client_secret", client.app.secret);
form.append("token", client.app.token);
const res = await fetch(`https://${client.instance.host}/oauth/revoke`, {
method: "POST",
body: form,
})
.catch(error => {
console.error(error);
return false;
});
if (!res.ok) return false;
return true;
}
export async function verifyCredentials() {
let client = get(Client.get());
let url = `https://${client.instance.host}/api/v1/accounts/verify_credentials`;
const data = await fetch(url, {
method: 'GET',
headers: { "Authorization": "Bearer " + client.app.token }
}).then(res => res.json());
return data;
}
export async function getTimeline(last_post_id) {
let client = get(Client.get());
let url = `https://${client.instance.host}/api/v1/timelines/home`;
if (last_post_id) url += "?max_id=" + last_post_id;
const data = await fetch(url, {
method: 'GET',
headers: { "Authorization": "Bearer " + client.app.token }
}).then(res => res.json());
return data;
}
export async function getPost(post_id, parent_replies) {
let client = get(Client.get());
let url = `https://${client.instance.host}/api/v1/statuses/${post_id}`;
const data = await fetch(url, {
method: 'GET',
headers: { "Authorization": "Bearer " + client.app.token }
}).then(res => { return res.ok ? res.json() : false });
if (data === false) return false;
return data;
}
export async function getPostContext(post_id) {
let client = get(Client.get());
let url = `https://${client.instance.host}/api/v1/statuses/${post_id}/context`;
const data = await fetch(url, {
method: 'GET',
headers: { "Authorization": "Bearer " + client.app.token }
}).then(res => { return res.ok ? res.json() : false });
if (data === false) return false;
return data;
}
export async function boostPost(post_id) {
let client = get(Client.get());
let url = `https://${client.instance.host}/api/v1/statuses/${post_id}/reblog`;
const data = await fetch(url, {
method: 'POST',
headers: { "Authorization": "Bearer " + client.app.token }
}).then(res => { return res.ok ? res.json() : false });
if (data === false) return false;
return data;
}
export async function unboostPost(post_id) {
let client = get(Client.get());
let url = `https://${client.instance.host}/api/v1/statuses/${post_id}/unreblog`;
const data = await fetch(url, {
method: 'POST',
headers: { "Authorization": "Bearer " + client.app.token }
}).then(res => { return res.ok ? res.json() : false });
if (data === false) return false;
return data;
}
export async function favouritePost(post_id) {
let client = get(Client.get());
let url = `https://${client.instance.host}/api/v1/statuses/${post_id}/favourite`;
const data = await fetch(url, {
method: 'POST',
headers: { "Authorization": "Bearer " + client.app.token }
}).then(res => { return res.ok ? res.json() : false });
if (data === false) return false;
return data;
}
export async function unfavouritePost(post_id) {
let client = get(Client.get());
let url = `https://${client.instance.host}/api/v1/statuses/${post_id}/unfavourite`;
const data = await fetch(url, {
method: 'POST',
headers: { "Authorization": "Bearer " + client.app.token }
}).then(res => { return res.ok ? res.json() : false });
if (data === false) return false;
return data;
}
export async function reactPost(post_id, shortcode) {
// for whatever reason (at least in my testing on iceshrimp)
// using shortcodes for external emoji results in a fallback
// to the default like emote.
// identical api calls on chuckya instances do not display
// this behaviour.
let client = get(Client.get());
let url = `https://${client.instance.host}/api/v1/statuses/${post_id}/react/${encodeURIComponent(shortcode)}`;
const data = await fetch(url, {
method: 'POST',
headers: { "Authorization": "Bearer " + client.app.token }
}).then(res => { return res.ok ? res.json() : false });
if (data === false) return false;
return data;
}
export async function unreactPost(post_id, shortcode) {
let client = get(Client.get());
let url = `https://${client.instance.host}/api/v1/statuses/${post_id}/unreact/${encodeURIComponent(shortcode)}`;
const data = await fetch(url, {
method: 'POST',
headers: { "Authorization": "Bearer " + client.app.token }
}).then(res => { return res.ok ? res.json() : false });
if (data === false) return false;
return data;
}
export async function parsePost(data, parent_replies, child_replies) {
let client = get(Client.get());
let post = new Post();
// if (client.instance.capabilities.includes(capabilities.MARKDOWN_CONTENT))
// post.text = data.text;
// else
post.text = data.content;
post.reply = null;
if ((data.in_reply_to_id || data.reply) && parent_replies !== 0) {
const reply_data = data.reply || await getPost(data.in_reply_to_id, parent_replies - 1);
post.reply = await parsePost(reply_data, parent_replies - 1, false);
// if the post returns false, we probably don't have permission to read it.
// we'll respect the thread's privacy, and leave it alone :)
if (post.reply === false) return false;
}
post.boost = data.reblog ? await parsePost(data.reblog, 1, false) : null;
post.replies = [];
if (child_replies) {
const replies_data = await getPostContext(data.id);
if (replies_data && replies_data.descendants) {
for (let i in replies_data.descendants) {
post.replies.push(await parsePost(replies_data.descendants[i], 0, false));
}
}
}
post.id = data.id;
post.created_at = new Date(data.created_at);
post.user = await parseUser(data.account);
post.warning = data.spoiler_text;
post.boost_count = data.reblogs_count;
post.reply_count = data.replies_count;
post.favourite_count = data.favourites_count;
post.favourited = data.favourited;
post.boosted = data.boosted;
post.mentions = data.mentions;
post.files = data.media_attachments;
post.url = data.url;
post.visibility = data.visibility;
post.emojis = [];
if (data.emojis) {
data.emojis.forEach(emoji_data => {
let name = emoji_data.shortcode.split('@')[0];
post.emojis.push(parseEmoji({
id: name + '@' + post.user.host,
name: name,
host: post.user.host,
url: emoji_data.url,
}));
});
}
if (data.reactions && client.instance.capabilities.includes(capabilities.REACTIONS)) {
post.reactions = parseReactions(data.reactions);
}
return post;
}
export async function parseUser(data) {
if (!data) {
console.error("Attempted to parse user data but no data was provided");
return null;
}
let client = get(Client.get());
let user = await client.getCacheUser(data.id);
if (user) return user;
// cache miss!
user = new User();
user.id = data.id;
user.nickname = data.display_name;
user.username = data.username;
user.avatar_url = data.avatar;
user.url = data.url;
if (data.acct.includes('@'))
user.host = data.acct.split('@')[1];
else
user.host = get(Client.get()).instance.host;
user.emojis = [];
data.emojis.forEach(emoji_data => {
emoji_data.id = emoji_data.shortcode + '@' + user.host;
emoji_data.name = emoji_data.shortcode;
emoji_data.host = user.host;
user.emojis.push(parseEmoji(emoji_data));
});
get(Client.get()).putCacheUser(user);
return user;
}
export function parseReactions(data) {
let client = get(Client.get());
let reactions = [];
data.forEach(reaction_data => {
let reaction = {
count: reaction_data.count,
name: reaction_data.name,
me: reaction_data.me,
};
if (reaction_data.url) reaction.url = reaction_data.url;
reactions.push(reaction);
});
return reactions;
}
export function parseEmoji(data) {
let emoji = new Emoji(
data.id,
data.name,
data.host,
data.url,
);
get(Client.get()).putCacheEmoji(emoji);
return emoji;
}
export async function getUser(user_id) {
let client = get(Client.get());
let url = `https://${client.instance.host}/api/v1/accounts/${user_id}`;
const data = await fetch(url, {
method: 'GET',
headers: { "Authorization": "Bearer " + client.app.token }
}).then(res => res.json());
const user = await parseUser(data);
if (user === null || user === undefined) {
if (data.id) {
console.warn("Failed to parse user data #" + data.id);
} else {
console.warn("Failed to parse user data:");
console.warn(data);
}
return false;
}
return user;
}

195
src/lib/client/client.js Normal file
View file

@ -0,0 +1,195 @@
import { Instance, server_types } from './instance.js';
import * as api from './api.js';
import { get, writable } from 'svelte/store';
let client = writable(false);
const save_name = "spacesocial";
export class Client {
instance;
app;
user;
#cache;
constructor() {
this.instance = null;
this.app = null;
this.cache = {
users: {},
emojis: {},
};
}
static get() {
if (get(client)) return client;
let new_client = new Client();
if (typeof window !== typeof undefined)
window.peekie = new_client;
new_client.load();
client.set(new_client);
return client;
}
async init(host) {
if (host.startsWith("https://")) host = host.substring(8);
const url = `https://${host}/api/v1/instance`;
const data = await fetch(url).then(res => res.json()).catch(error => { console.error(error) });
if (!data) {
console.error(`Failed to connect to ${host}`);
return `Failed to connect to ${host}!`;
}
this.instance = new Instance(host, data.version);
if (this.instance.type == server_types.UNSUPPORTED) {
console.warn(`Server ${host} is unsupported - ${data.version}`);
if (!confirm(
`This app does not officially support ${host}. ` +
`Things may break, or otherwise not work as epxected! ` +
`Are you sure you wish to continue?`
)) return false;
} else {
console.log(`Server is "${this.instance.type}" (or compatible) with capabilities: [${this.instance.capabilities}].`);
}
this.app = await api.createApp(host);
if (!this.app || !this.instance) {
console.error("Failed to create app. Check the network logs for details.");
return false;
}
this.save();
client.set(this);
return true;
}
getOAuthUrl() {
return api.getOAuthUrl(this.app.secret);
}
async getToken(code) {
const token = await api.getToken(code);
if (!token) {
console.error("Failed to obtain access token");
return false;
}
this.app.token = token;
client.set(this);
}
async revokeToken() {
return await api.revokeToken();
}
async verifyCredentials() {
const data = await api.verifyCredentials();
if (!data) return false;
this.user = await api.parseUser(data);
client.set(this);
return data;
}
async getTimeline(last_post_id) {
return await api.getTimeline(last_post_id);
}
async getPost(post_id, parent_replies, child_replies) {
return await api.getPost(post_id, parent_replies, child_replies);
}
async boostPost(post_id) {
return await api.boostPost(post_id);
}
async unboostPost(post_id) {
return await api.unboostPost(post_id);
}
async favouritePost(post_id) {
return await api.favouritePost(post_id);
}
async unfavouritePost(post_id) {
return await api.unfavouritePost(post_id);
}
async reactPost(post_id, shortcode) {
return await api.reactPost(post_id, shortcode);
}
async unreactPost(post_id, shortcode) {
return await api.unreactPost(post_id, shortcode);
}
putCacheUser(user) {
this.cache.users[user.id] = user;
client.set(this);
}
async getCacheUser(user_id) {
let user = this.cache.users[user_id];
if (user) return user;
return false;
}
async getUserByMention(mention) {
let users = Object.values(this.cache.users);
for (let i in users) {
const user = users[i];
if (user.mention == mention) return user;
}
return false;
}
putCacheEmoji(emoji) {
this.cache.emojis[emoji.id] = emoji;
client.set(this);
}
getEmoji(emoji_id) {
let emoji = this.cache.emojis[emoji_id];
if (!emoji) return false;
return emoji;
}
save() {
if (typeof localStorage === typeof undefined) return;
localStorage.setItem(save_name, JSON.stringify({
version: APP_VERSION,
instance: {
host: this.instance.host,
version: this.instance.version,
},
app: this.app,
}));
}
load() {
if (typeof localStorage === typeof undefined) return;
let json = localStorage.getItem(save_name);
if (!json) return false;
let saved = JSON.parse(json);
if (!saved.version || saved.version !== APP_VERSION) {
localStorage.removeItem(save_name);
return false;
}
this.instance = new Instance(saved.instance.host, saved.instance.version);
this.app = saved.app;
client.set(this);
return true;
}
async logout() {
if (!this.instance || !this.app) return;
if (!await this.revokeToken()) {
console.warn("Failed to log out correctly; ditching the old tokens anyways.");
}
localStorage.removeItem(save_name);
client.set(false);
console.log("Logged out successfully.");
}
}

View file

@ -0,0 +1,70 @@
export const server_types = {
UNSUPPORTED: "unsupported",
MASTODON: "mastodon",
GLITCHSOC: "glitchsoc",
CHUCKYA: "chuckya",
FIREFISH: "firefish",
ICESHRIMP: "iceshrimp",
SHARKEY: "sharkey",
};
export const capabilities = {
MARKDOWN_CONTENT: "mdcontent",
REACTIONS: "reactions",
};
export class Instance {
host;
version;
capabilities;
type = server_types.UNSUPPORTED;
constructor(host, version) {
this.host = host;
this.version = version;
this.#setType(version);
this.capabilities = this.#getCapabilities(this.type);
}
#setType(version) {
this.type = server_types.UNSUPPORTED;
if (version.constructor !== String) return;
let version_lower = version.toLowerCase();
for (let i = 1; i < Object.keys(server_types).length; i++) {
const check_type = Object.values(server_types)[i];
if (version_lower.includes(check_type)) {
this.type = check_type;
return;
}
}
}
#getCapabilities(type) {
let c = [];
switch (type) {
case server_types.MASTODON:
break;
case server_types.GLITCHSOC:
c.push(capabilities.REACTIONS);
break;
case server_types.CHUCKYA:
c.push(capabilities.REACTIONS);
break;
case server_types.FIREFISH:
c.push(capabilities.REACTIONS);
break;
case server_types.ICESHRIMP:
// more trouble than it's worth atm
// the server already hands this to us ;p
//c.push(capabilities.MARKDOWN_CONTENT);
c.push(capabilities.REACTIONS);
break;
case server_types.SHARKEY:
c.push(capabilities.REACTIONS);
break;
default:
break;
}
return c;
}
}

52
src/lib/emoji.js Normal file
View file

@ -0,0 +1,52 @@
import { Client } from './client/client.js';
import { get } from 'svelte/store';
export const EMOJI_REGEX = /:[\w\-.]{0,32}@[\w\-.]{0,32}:/g;
export const EMOJI_NAME_REGEX = /:[\w\-.]{0,32}:/g;
export default class Emoji {
name;
url;
constructor(id, name, host, url) {
this.id = id;
this.name = name;
this.host = host;
this.url = url;
}
get html() {
if (this.url)
return `<img src="${this.url}" class="emoji" height="20" title="${this.name}" alt="${this.name}">`;
else
return `${this.name}`;
}
}
export function parseText(text, host) {
if (!text) return text;
let index = text.search(EMOJI_NAME_REGEX);
if (index === -1) return text;
// find the emoji name
let length = text.substring(index + 1).search(':');
if (length <= 0) return text;
let emoji_name = text.substring(index + 1, index + length + 1);
let emoji = get(Client.get()).getEmoji(emoji_name + '@' + host);
if (emoji) {
return text.substring(0, index) + emoji.html +
parseText(text.substring(index + length + 2), host);
}
return text.substring(0, index + length + 1) +
parseText(text.substring(index + length + 1), host);
}
export function parseOne(emoji_id) {
if (emoji_id == '❤') return '❤️'; // stupid heart unicode
if (EMOJI_REGEX.exec(':' + emoji_id + ':')) return emoji_id;
let cached_emoji = get(Client.get()).getEmoji(emoji_id);
if (!cached_emoji) return emoji_id;
return cached_emoji.html;
}

8
src/lib/main.js Normal file
View file

@ -0,0 +1,8 @@
import './app.css';
import App from './App.svelte';
const app = new App({
target: document.getElementById('app')
});
export default app;

176
src/lib/post.js Normal file
View file

@ -0,0 +1,176 @@
import { parseText as parseEmoji } from './emoji.js';
export default class Post {
id;
created_at;
user;
text;
warning;
boost_count;
reply_count;
favourite_count;
favourited;
boosted;
mentions;
reactions;
emojis;
files;
url;
reply;
replies;
boost;
visibility;
async rich_text() {
return parseEmoji(this.text, this.user.host);
}
/*
async rich_text() {
let text = this.text;
if (!text) return text;
let client = Client.get();
const markdown_tokens = [
{ tag: "pre", token: "```" },
{ tag: "code", token: "`" },
{ tag: "strong", token: "**" },
{ tag: "strong", token: "__" },
{ tag: "em", token: "*" },
{ tag: "em", token: "_" },
];
let response = "";
let md_layer;
let index = 0;
while (index < text.length) {
let sample = text.substring(index);
let md_nostack = !(md_layer && md_layer.nostack);
// handle newlines
if (md_nostack && sample.startsWith('\n')) {
response += "<br>";
index++;
continue;
}
// handle mentions
if (client.instance.capabilities.includes(capabilities.MARKDOWN_CONTENT)
&& md_nostack
&& sample.match(/^@[\w\-.]+@[\w\-.]+/g)
) {
// find end of the mention
let length = 1;
while (index + length < text.length && /[a-z0-9-_.]/.test(text[index + length])) length++;
length++; // skim the middle @
while (index + length < text.length && /[a-z0-9-_.]/.test(text[index + length])) length++;
let mention = text.substring(index, index + length);
// attempt to resolve mention to a user
let user = await client.getUserByMention(mention);
if (user) {
const out = `<a href="/${user.mention}" class="mention">` +
`<img src="${user.avatar_url}" class="mention-avatar" width="20" height="20">` +
'@' + user.username + '@' + user.host + "</a>";
if (md_layer) md_layer.text += out;
else response += out;
} else {
response += mention;
}
index += mention.length;
continue;
}
// handle links
if (client.instance.capabilities.includes(capabilities.MARKDOWN_CONTENT)
&& md_nostack
&& sample.match(/^[a-z]{3,6}:\/\/[^\s]+/g)
) {
// get length of link
let length = text.substring(index).search(/\s|$/g);
let url = text.substring(index, index + length);
let out = `<a href="${url}">${url}</a>`;
if (md_layer) md_layer.text += out;
else response += out;
index += length;
continue;
}
// handle emojis
if (md_nostack && sample.match(/^:[\w\-.]{0,32}:/g)) {
// find the emoji name
let length = text.substring(index + 1).search(':');
if (length <= 0) return text;
let emoji_name = text.substring(index + 1, index + length + 1);
let emoji = client.getEmoji(emoji_name + '@' + this.user.host);
index += length + 2;
if (!emoji) {
let out = ':' + emoji_name + ':';
if (md_layer) md_layer.text += out;
else response += out;
continue;
}
let out = emoji.html;
if (md_layer) md_layer.text += out;
else response += out;
continue;
}
// handle markdown
// TODO: handle misskey-flavoured markdown(?)
if (md_layer) {
// try to pop layer
if (sample.startsWith(md_layer.token)) {
index += md_layer.token.length;
let out = `<${md_layer.tag}>${md_layer.text}</${md_layer.tag}>`;
if (md_layer.token === '```')
out = `<code><pre>${md_layer.text}</pre></code>`;
if (md_layer.parent) md_layer.parent.text += out;
else response += out;
md_layer = md_layer.parent;
} else {
md_layer.text += sample[0];
index++;
}
} else if (md_nostack) {
// should we add a layer?
let pushed = false;
for (let i = 0; i < markdown_tokens.length; i++) {
let item = markdown_tokens[i];
if (sample.startsWith(item.token)) {
let new_md_layer = {
token: item.token,
tag: item.tag,
text: "",
parent: md_layer,
};
if (item.token === '```' || item.token === '`') new_md_layer.nostack = true;
md_layer = new_md_layer;
pushed = true;
index += md_layer.token.length;
break;
}
}
if (!pushed) {
response += sample[0];
index++;
}
}
}
// destroy the remaining stack
while (md_layer) {
let out = md_layer.token + md_layer.text;
if (md_layer.parent) md_layer.parent.text += out;
else response += out;
md_layer = md_layer.parent;
}
return response;
}
*/
}

23
src/lib/sound.js Normal file
View file

@ -0,0 +1,23 @@
let sounds;
if (typeof Audio !== typeof undefined) {
sounds = {
"default": new Audio("/sound/log.ogg"),
"post": new Audio("/sound/success.ogg"),
"boost": new Audio("/sound/hello.ogg"),
};
}
export function play_sound(name) {
if (name === false) return;
if (!name) name = "default";
const sound = sounds[name];
if (!sound) {
console.warn(`Attempted to play sound "${name}", which does not exist!`);
return;
}
sound.pause();
sound.volume = 0.25;
sound.currentTime = 0;
sound.play();
}

23
src/lib/time.js Normal file
View file

@ -0,0 +1,23 @@
const denoms = [
{ unit: 's', min: 0 },
{ unit: 'm', min: 60 },
{ unit: 'h', min: 60 },
{ unit: 'd', min: 24 },
{ unit: 'w', min: 7 },
{ unit: 'y', min: 52 },
];
export function shorthand(date) {
let value = (new Date() - date) / 1000;
let unit = 's';
let index = 0;
while (index < denoms.length - 1) {
if (value < denoms[index + 1].min) break;
index++
value /= denoms[index].min;
unit = denoms[index].unit;
}
if (value > 0)
return Math.floor(value) + unit + " ago";
return "in " + Math.floor(value) + unit;
}

134
src/lib/ui/Button.svelte Normal file
View file

@ -0,0 +1,134 @@
<script>
import { play_sound } from '../sound.js';
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
export let active = false;
export let filled = false;
export let disabled = false;
export let centered = false;
export let label = undefined;
export let sound = "default";
export let href = false;
let classes = [];
if (active) classes = ["active"];
if (filled) classes = ["filled"];
if (disabled) classes = ["disabled"];
if (centered) classes.push("centered");
function click() {
if (href) {
location = href;
return;
}
if (disabled) return;
play_sound(sound);
dispatch('click');
}
</script>
<button
type="button"
class={classes.join(' ')}
title={label}
aria-label={label}
on:click={() => click()}>
<slot/>
</button>
<style>
button {
/* min-width: 64px; */
width: 100%;
height: 54px;
padding: 16px;
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
font-family: inherit;
font-size: 1rem;
font-weight: 600;
text-align: left;
border-radius: 8px;
border-width: 2px;
border-style: solid;
background-color: var(--bg-700);
color: var(--text);
border-color: transparent;
transition-property: border-color, background-color, color;
transition-timing-function: ease-out;
transition-duration: .1s;
cursor: pointer;
}
button.centered {
text-align: center;
justify-content: center;
}
button:hover {
background-color: color-mix(in srgb, var(--bg-700), var(--accent) 10%);
border-color: color-mix(in srgb, var(--bg-700), var(--accent) 20%);
}
button:active {
background-color: color-mix(in srgb, var(--bg-700), var(--bg-800) 50%);
border-color: color-mix(in srgb, var(--bg-700), var(--bg-800) 10%);
}
button.active {
background-color: var(--bg-600);
color: var(--accent);
border-color: var(--accent);
text-shadow: 0px 2px 32px var(--accent);
}
button.active:hover {
color: color-mix(in srgb, var(--accent), var(--bg-1000) 20%);
border-color: color-mix(in srgb, var(--accent), var(--bg-1000) 20%);
background-color: color-mix(in srgb, var(--bg-600), var(--accent) 10%);
}
button.active:active {
color: color-mix(in srgb, var(--accent), var(--bg-800) 10%);
border-color: color-mix(in srgb, var(--accent), var(--bg-800) 10%);
background-color: color-mix(in srgb, var(--bg-600), var(--bg-800) 10%);
}
button.filled {
background-color: var(--accent);
color: var(--bg-800);
border-color: transparent;
}
button.filled:hover {
color: color-mix(in srgb, var(--bg-800), white 10%);
background-color: color-mix(in srgb, var(--accent), white 20%);
}
button.filled:active {
color: color-mix(in srgb, var(--bg-800), black 10%);
background-color: color-mix(in srgb, var(--accent), black 20%);
}
button.disabled {
background-color: var(--bg-700);
color: var(--text);
opacity: .5;
border-color: transparent;
cursor: initial;
}
button.disabled:hover {
}
button.disabled:active {
}
</style>

24
src/lib/ui/Error.svelte Normal file
View file

@ -0,0 +1,24 @@
<script>
export let msg = "";
export let trace = "";
</script>
<div class="error">
{#if msg}
<p class="msg">{@html msg}</p>
{/if}
{#if trace}
<pre class="trace">{trace}</pre>
{/if}
<slot></slot>
</div>
<style>
.error {
margin-top: 16px;
padding: 20px 32px;
border: 1px solid #8884;
border-radius: 16px;
background-color: var(--bg1);
}
</style>

132
src/lib/ui/Feed.svelte Normal file
View file

@ -0,0 +1,132 @@
<script>
import Button from './Button.svelte';
import Post from './post/Post.svelte';
import Error from './Error.svelte';
import { Client } from '../client/client.js';
import { parsePost } from '../client/api.js';
import { get } from 'svelte/store';
let params = new URLSearchParams(location.search);
let client = get(Client.get());
let posts = [];
let loading = false;
let focus_post_id = location.pathname.startsWith("/post/") ? location.pathname.substring(6) : false;
let error;
async function getTimeline() {
if (loading) return; // no spamming!!
loading = true;
let timeline_data;
if (posts.length === 0) timeline_data = await client.getTimeline()
else timeline_data = await client.getTimeline(posts[posts.length - 1].id);
if (!timeline_data) {
console.error(`Failed to retrieve timeline.`);
loading = false;
return;
}
for (let i in timeline_data) {
const post_data = timeline_data[i];
const post = await parsePost(post_data, 1, false);
if (!post) {
if (post === null || post === undefined) {
if (post_data.id) {
console.warn("Failed to parse post #" + post_data.id);
} else {
console.warn("Failed to parse post:");
console.warn(post_data);
}
}
continue;
}
posts = [...posts, post];
}
loading = false;
}
async function getPost(post_id) {
loading = true;
const post_data = await client.getPost(post_id);
if (!post_data) {
console.error(`Failed to retrieve post ${post_id}.`);
loading = false;
return;
}
const post = await parsePost(post_data, 10, true);
posts = [post];
for (let i in post.replies) {
posts = [...posts, post.replies[i]];
}
loading = false;
}
if (focus_post_id) {
getPost(focus_post_id);
} else {
getTimeline();
document.addEventListener("scroll", event => {
if (!loading && window.innerHeight + window.scrollY >= document.body.offsetHeight - 2048) {
getTimeline();
}
});
}
</script>
<header>
<h1>Home</h1>
<nav>
<Button centered active>Home</Button>
<Button centered disabled>Local</Button>
<Button centered disabled>Federated</Button>
</nav>
</header>
<div id="feed">
{#if posts.length <= 0}
<div class="throb">
<span>just a moment...</span>
</div>
{/if}
{#each posts as post}
<Post post_data={post} focused={post.id === focus_post_id} />
{/each}
</div>
<style>
header {
margin: 16px 0 8px 0;
display: flex;
flex-direction: row;
}
header h1 {
font-size: 1.5em;
}
nav {
margin-left: auto;
display: flex;
flex-direction: row;
gap: 8px;
}
#feed {
margin-bottom: 20vh;
}
.throb {
width: 100%;
height: 80vh;
display: flex;
justify-content: center;
align-items: center;
font-size: 2em;
font-weight: bold;
}
</style>

View file

@ -0,0 +1,280 @@
<script>
import Logo from '../../img/spacesocial-logo.svg';
import Button from './Button.svelte';
import Feed from './Feed.svelte';
import { Client } from '../client/client.js';
import { play_sound } from '../sound.js';
let client = false;
Client.get().subscribe(c => {
client = c;
});
let notification_count = 0;
if (notification_count > 99) notification_count = "99+";
function goTimeline() {
location = "/";
}
function log_out() {
if (!confirm("This will log you out. Are you sure?")) return;
client.logout().then(() => {
location = "/";
});
}
</script>
<div id="navigation">
<header id="instance-header"> <!-- style={`background-image: url(${banner_url})`}> -->
<!-- <img src={icon_url} class="instance-icon" height="92px" aria-hidden="true"> -->
<div class="instance-icon instance-icon-mask" style={`mask-image: url(${Logo})`} height="92px" aria-hidden="true">
<!-- <img src={Logo} class="instance-icon" height="92px" aria-hidden="true"> -->
</header>
<div id="nav-items">
<Button label="Timeline" on:click={() => goTimeline()} active>🖼️ Timeline</Button>
<Button label="Notifications" disabled>
🔔 Notifications
{#if notification_count}
<span class="notification-count">{notification_count}</span>
{/if}
</Button>
<Button label="Explore" disabled>🌍 Explore</Button>
<Button label="Lists" disabled>🗒️ Lists</Button>
<div class="flex-row">
<Button centered label="Favourites" disabled></Button>
<Button centered label="Bookmarks" disabled>🔖</Button>
<Button centered label="Hashtags" disabled>#</Button>
</div>
<Button filled label="Post" disabled>✏️ Post</Button>
</div>
{#if (client.user)}
<div id="account-items">
<div class="flex-row">
<Button centered label="Profile information" disabled></Button>
<Button centered label="Settings" disabled>⚙️</Button>
<Button centered label="Log out" on:click={() => log_out()}>🚪</Button>
</div>
<div id="account-button">
<img src={client.user.avatar_url} class="account-avatar" height="64px" aria-hidden="true" on:click={() => play_sound()}>
<div class="account-name" aria-hidden="true">
<span class="nickname" title={client.user.nickname}>{client.user.nickname}</span>
<span class="username" title={`@${client.user.username}@${client.user.host}`}>
{`@${client.user.username}@${client.user.host}`}
</span>
</div>
<!-- <button class="settings" aria-label={`Account: ${client.user.username}@${client.user.host}`} on:click={() => play_sound()}>🔧</button> -->
</div>
</div>
{/if}
<span class="version">
space social v{APP_VERSION}
<br>
<ul>
<li><a href="https://git.arimelody.me/ari/spacesocial-client">source</a></li>
</ul>
</span>
</div>
<style>
#navigation {
display: flex;
flex-direction: column;
position: fixed;
top: 16px;
width: 300px;
height: calc(100vh - 32px);
border-radius: 8px;
background-color: var(--bg-800);
}
#instance-header {
width: 100%;
height: 172px;
display: flex;
justify-content: center;
align-items: center;
border-radius: 8px;
background-position: center;
background-size: cover;
background-color: var(--bg-600);
background-image: linear-gradient(to top, var(--bg-800), var(--bg-600));
}
.instance-icon {
height: 92px;
border-radius: 8px;
}
.instance-icon-mask {
width: 80%;
margin: auto;
background-color: var(--text);
mask-repeat: no-repeat;
-webkit-mask-repeat: no-repeat;
mask-origin: border-box;
-webkit-mask-origin: border-box;
}
#nav-items {
margin-bottom: auto;
padding: 16px;
display: flex;
flex-direction: column;
gap: 8px;
}
.notification-count {
position: relative;
transform: translate(22px, -16px);
min-width: 12px;
height: 28px;
padding: 0 8px;
display: flex;
justify-content: center;
align-items: center;
text-align: right;
border-radius: 8px;
font-weight: 700;
color: var(--bg-1000);
background-color: var(--accent);
box-shadow: 0 0 32px color-mix(in srgb, transparent, var(--accent) 100%);
}
#account-items {
padding: 16px;
display: flex;
flex-direction: column;
gap: 8px;
}
.version {
margin-bottom: 16px;
font-style: italic;
font-size: .9em;
opacity: .6;
text-align: center;
}
.version ul {
margin: 0;
padding: 0;
display: flex;
gap: 8px;
justify-content: center;
list-style: none;
}
.version ul li {
margin: 0;
}
.version ul li:not(:first-child):before {
content: '•';
margin-right: 8px;
color: inherit;
opacity: .7;
}
.version a {
color: inherit;
text-decoration: none;
opacity: .7;
}
.version a:hover {
text-decoration: underline;
}
#account-button {
width: calc(100% - 16px);
height: 48px;
padding: 8px;
display: flex;
flex-direction: row;
align-items: center;
gap: 8px;
font-family: inherit;
font-size: 1rem;
font-weight: 600;
border-radius: 8px;
background-color: var(--bg-700);
color: var(--text);
border-color: transparent;
transition-property: border-color, background-color, color;
transition-timing-function: ease-out;
transition-duration: .1s;
cursor: pointer;
}
.account-avatar {
width: 48px;
height: 48px;
border-radius: 8px;
transition: transform .1s ease-out, box-shadow .2s;
}
.account-avatar:hover {
transform: scale(1.05);
box-shadow: 0 0 16px color-mix(in srgb, transparent, var(--accent) 25%);
}
.account-avatar:active {
transform: scale(.95);
box-shadow: 0 0 16px var(--bg-1000);
}
.account-name {
/* width: 152px; */
display: flex;
flex-direction: column;
gap: 2px;
}
.username, .nickname {
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
font-size: .8em;
}
.username {
opacity: .8;
font-size: .65em;
}
.settings {
width: 32px;
height: 32px;
padding: none;
border: none;
font-size: inherit;
font-family: inherit;
background: none;
border-radius: 8px;
transition: background-color .1s;
}
.settings:hover {
background-color: color-mix(in srgb, var(--bg-700), var(--text) 15%);
}
.settings:active {
background-color: color-mix(in srgb, var(--bg-700), var(--bg-1000) 30%);
}
.flex-row {
display: flex;
flex-direction: row;
gap: 8px;
}
</style>

39
src/lib/ui/Widgets.svelte Normal file
View file

@ -0,0 +1,39 @@
<div id="widgets">
<input type="text" id="search" placeholder="🔍 Search">
</div>
<style>
#widgets {
position: fixed;
top: 16px;
width: 300px;
height: calc(100vh - 32px);
display: flex;
flex-direction: column;
gap: 8px;
}
#search {
padding: 16px;
border-radius: 8px;
border: 1px solid color-mix(in srgb, transparent, var(--accent) 25%);
background-color: var(--bg-800);
font-family: inherit;
font-weight: 600;
font-size: inherit;
color: var(--text);
transition: box-shadow .2s;
}
#search::placeholder {
opacity: .8;
}
#search:focus {
outline: none;
box-shadow: 0 0 16px color-mix(in srgb, transparent, var(--accent) 25%);
}
</style>

View file

@ -0,0 +1,91 @@
<script>
import { play_sound } from '../../sound.js';
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
export let type = "action";
export let label = "Action";
export let title = label;
export let count = 0;
export let active = false;
export let disabled = false;
export let sound = "default";
function click() {
if (disabled) return;
play_sound(sound);
dispatch('click');
}
</script>
<button
type="button"
class={[
type,
active ? "active" : "",
disabled ? "disabled" : "",
].join(' ')}
aria-label="{label}"
title="{title}"
on:click={click}>
<span class="icon">
<slot/>
</span>
{#if count}
<span class="count">{count}</span>
{/if}
</button>
<style>
button {
height: 32px;
padding: 6px 8px;
display: flex;
flex-direction: row;
gap: 4px;
font-family: inherit;
font-size: 1em;
background: none;
color: inherit;
border: none;
border-radius: 8px;
transition: background-color .1s, color .1s;
cursor: pointer;
}
button.active {
background-color: color-mix(in srgb, transparent, var(--accent) 50%);
color: var(--bg-1000);
}
button:not(.disabled):hover {
background-color: var(--bg-600);
color: var(--text);
}
button:not(.disabled):active {
background-color: var(--bg-1000);
color: var(--text);
}
button.disabled {
opacity: .5;
cursor: initial;
}
.icon {
width: 20px;
height: 20px;
display: flex;
justify-content: center;
align-items: center;
}
.count {
opacity: .5;
}
button:hover .count {
opacity: 1;
}
</style>

230
src/lib/ui/post/Body.svelte Normal file
View file

@ -0,0 +1,230 @@
<script>
export let post;
let rich_text;
post.rich_text().then(res => {rich_text = res});
let open_warned = false;
</script>
<div class="post-body">
{#if post.warning}
<button class="post-warning" on:click|stopPropagation={() => { open_warned = !open_warned }}>
<strong>
{post.warning}
<span class="warning-instructions">
{#if !open_warned}
(click to reveal)
{:else}
(click to hide)
{/if}
</span>
</strong>
</button>
{/if}
{#if !post.warning || open_warned}
{#if post.text}
<span class="post-text">{@html rich_text}</span>
{/if}
<div class="post-media-container" data-count={post.files.length}>
{#each post.files as file}
<div class="post-media {file.type}" on:click|stopPropagation={null}>
{#if file.type === "image"}
<a href={file.url} target="_blank">
<img src={file.url} alt={file.description} title={file.description} height="200" loading="lazy" decoding="async">
</a>
{:else if file.type === "video"}
<video controls height="200">
<source src={file.url} alt={file.description} title={file.description} type={file.url.endsWith('.mp4') ? 'video/mp4' : 'video/webm'}>
<p>{file.description} &ensp; <a href={file.url}>[link]</a></p>
<!-- <media src={file.url} alt={file.description} loading="lazy" decoding="async"> -->
</video>
{/if}
</div>
{/each}
</div>
{#if post.boost && post.text}
<p class="post-warning"><strong>this is quoting a post! quotes are not supported yet.</strong></p>
<!-- TODO: quotes support -->
{/if}
{/if}
</div>
<style>
.post-body {
margin-top: 10px;
}
.post-warning {
width: 100%;
margin-bottom: 10px;
padding: 4px 8px;
--warn-bg: color-mix(in srgb, var(--bg-700), var(--accent) 1%);
background: repeating-linear-gradient(-45deg, transparent, transparent 10px, var(--warn-bg) 10px, var(--warn-bg) 20px);
font-family: inherit;
font-size: inherit;
color: inherit;
text-align: left;
border: none;
border-radius: 8px;
cursor: pointer;
outline-color: var(--warn-bg);
transition: outline .05s, box-shadow .05s;
}
.post-warning:hover {
outline: 1px solid var(--warn-bg);
box-shadow: 0 0 8px var(--warn-bg);
}
.post-warning .warning-instructions {
font-weight: normal;
opacity: .5;
}
.post-text {
line-height: 1.2em;
word-wrap: break-word;
}
.post-text :global(.emoji) {
position: relative;
top: 6px;
margin-top: -10px;
height: 24px!important;
}
.post-text :global(blockquote) {
margin: .4em 0;
padding: .1em 0 .1em 1em;
border-left: 4px solid #8888;
}
.post-text :global(blockquote span) {
opacity: .5;
}
.post-text :global(code) {
font-size: 1.2em;
}
.post-text :global(pre:has(code)) {
margin: 8px 0;
padding: 8px;
display: block;
overflow-x: scroll;
border-radius: 8px;
background-color: #080808;
color: var(--accent);
}
.post-text :global(pre code) {
margin: 0;
}
.post-text :global(a) {
color: var(--accent);
}
.post-text :global(a.mention) {
color: inherit;
font-weight: 600;
padding: 3px 6px;
background: var(--bg-700);
border-radius: 6px;
text-decoration: none;
}
.post-text :global(a.mention:hover) {
text-decoration: underline;
}
.post-text :global(a.hashtag) {
background-color: transparent;
padding: 0;
font-style: italic;
}
.post-text :global(.mention-avatar) {
position: relative;
top: 4px;
height: 20px;
margin-right: 4px;
border-radius: 4px;
}
.post-media-container {
max-height: 540px;
margin: 16px 0 4px 0;
display: grid;
grid-gap: 8px;
}
.post-media-container[data-count="1"] {
grid-template-rows: 1fr;
}
.post-media-container[data-count="2"] {
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr;
}
.post-media-container[data-count="3"] {
grid-template-columns: 1fr .5fr;
grid-template-rows: 1fr 1fr;
}
.post-media-container[data-count="4"] {
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
}
.post-media {
border-radius: 12px;
background-color: #000;
overflow: hidden;
}
.post-media a {
width: 100%;
height: 100%;
display: block;
cursor: zoom-in;
}
.post-media img,
.post-media video {
width: 100%;
height: 100%;
display: block;
object-fit: contain;
}
.post-media-container > :nth-child(1) {
grid-column: 1/2;
grid-row: 1/2;
}
.post-media-container[data-count="3"] > :nth-child(1) {
grid-row: 1/3;
}
.post-media-container > :nth-child(2) {
grid-column: 2/2;
grid-row: 1/2;
}
.post-media-container > :nth-child(3) {
grid-column: 1/2;
grid-row: 2/2;
}
.post-media-container[data-count="3"] > :nth-child(3) {
grid-column: 2/2;
grid-row: 2/2;
}
.post-media-container > :nth-child(4) {
grid-column: 2/2;
grid-row: 2/2;
}
</style>

View file

@ -0,0 +1,52 @@
<script>
import { parseText as parseEmojis } from '../../emoji.js';
import { shorthand as short_time } from '../../time.js';
export let post;
let time_string = post.created_at.toLocaleString();
</script>
<div class="post-context">
<span class="post-context-icon">🔁</span>
<span class="post-context-action">
<a href={post.user.url} target="_blank">{@html parseEmojis(post.user.rich_name)}</a> boosted this post.
</span>
<span class="post-context-time">
<time title="{time_string}">{short_time(post.created_at)}</time>
{#if post.visibility !== "public"}
<span class="post-visibility">({post.visibility})</span>
{/if}
</span>
</div>
<style>
.post-context {
margin-bottom: 8px;
padding-left: 58px;
display: flex;
flex-direction: row;
align-items: center;
font-weight: 600;
color: var(--text);
opacity: .8;
transition: opacity .1s;
}
.post-context-icon {
margin-right: 4px;
}
.post-context a,
.post-context a:visited {
color: inherit;
text-decoration: none;
}
.post-context a:hover {
text-decoration: underline;
}
.post-context-time {
margin-left: auto;
}
</style>

182
src/lib/ui/post/Post.svelte Normal file
View file

@ -0,0 +1,182 @@
<script>
import BoostContext from './BoostContext.svelte';
import ReplyContext from './ReplyContext.svelte';
import PostHeader from './PostHeader.svelte';
import Body from './Body.svelte';
import ReactionButton from './ReactionButton.svelte';
import ActionButton from './ActionButton.svelte';
import { parseOne as parseEmoji } from '../../emoji.js';
import { play_sound } from '../../sound.js';
import { onMount } from 'svelte';
import { get } from 'svelte/store';
import { Client } from '../../client/client.js';
import * as api from '../../client/api.js';
export let post_data;
export let focused = false;
let post_context = undefined;
let post = post_data;
let is_boost = false;
if (post_data.boost) {
is_boost = true;
post_context = post_data;
post = post_data.boost;
}
function gotoPost() {
location = `/post/${post.id}`;
}
async function toggleBoost() {
let client = get(Client.get());
let data;
if (post.boosted)
data = await client.unboostPost(post.id);
else
data = await client.boostPost(post.id);
if (!data) {
console.error(`Failed to boost post ${post.id}`);
return;
}
post.boosted = data.boosted;
post.boost_count = data.reblogs_count;
}
async function toggleFavourite() {
let client = get(Client.get());
let data;
if (post.favourited)
data = await client.unfavouritePost(post.id);
else
data = await client.favouritePost(post.id);
if (!data) {
console.error(`Failed to favourite post ${post.id}`);
return;
}
post.favourited = data.favourited;
post.favourite_count = data.favourites_count;
if (data.reactions) post.reactions = api.parseReactions(data.reactions);
}
async function toggleReaction(reaction) {
if (reaction.name.includes('@')) return;
let client = get(Client.get());
let data;
if (reaction.me)
data = await client.unreactPost(post.id, reaction.name);
else
data = await client.reactPost(post.id, reaction.name);
if (!data) {
console.error(`Failed to favourite post ${post.id}`);
return;
}
post.favourited = data.favourited;
post.favourite_count = data.favourites_count;
if (data.reactions) post.reactions = api.parseReactions(data.reactions);
}
let el;
onMount(() => {
if (focused) {
window.scrollTo(0, el.scrollHeight - 700);
}
});
let aria_label = post.user.username + '; ' + post.text + '; ' + post.created_at;
</script>
<div class="post-container" aria-label={aria_label} bind:this={el}>
{#if post.reply}
<ReplyContext post={post.reply} />
{/if}
{#if is_boost && !post_context.text}
<BoostContext post={post_context} />
{/if}
<article class={"post" + (focused ? " focused" : "")} on:click={!focused ? gotoPost() : null}>
<PostHeader post={post} />
<Body post={post} />
<footer class="post-footer">
<div class="post-reactions" on:click|stopPropagation>
{#each post.reactions as reaction}
<ReactionButton
type="reaction"
on:click={() => toggleReaction(reaction)}
bind:active={reaction.me}
bind:count={reaction.count}
disabled={reaction.name.includes('@')}
title={reaction.name}
label="">
{#if reaction.url}
<img src={reaction.url} class="emoji" height="20" title={reaction.name} alt={reaction.name}>
{:else}
{reaction.name}
{/if}
</ReactionButton>
{/each}
</div>
<div class="post-actions" on:click|stopPropagation>
<ActionButton type="reply" label="Reply" bind:count={post.reply_count} sound="post" disabled>🗨️</ActionButton>
<ActionButton type="boost" label="Boost" on:click={() => toggleBoost()} bind:active={post.boosted} bind:count={post.boost_count} sound="boost">🔁</ActionButton>
<ActionButton type="favourite" label="Favourite" on:click={() => toggleFavourite()} bind:active={post.favourited} bind:count={post.favourite_count}>⭐</ActionButton>
<ActionButton type="react" label="React" disabled>😃</ActionButton>
<ActionButton type="quote" label="Quote" disabled>🗣️</ActionButton>
<ActionButton type="more" label="More" disabled>🛠️</ActionButton>
</div>
</footer>
</article>
</div>
<style>
.post-container {
width: 700px;
max-width: 700px;
margin-bottom: 8px;
padding: 16px;
display: flex;
flex-direction: column;
border-radius: 8px;
background-color: var(--bg-800);
transition: background-color .1s;
}
.post-container:hover {
background-color: color-mix(in srgb, var(--bg-800), black 5%);
}
.post-container:hover :global(.post-context) {
opacity: 1;
}
.post:not(.focused) {
cursor: pointer;
}
.post.focused {
padding: 16px;
margin: -16px;
border-radius: 8px;
border: 1px solid color-mix(in srgb, transparent, var(--accent) 20%);
box-shadow: 0 0 16px color-mix(in srgb, transparent, var(--accent) 20%);
}
:global(.post-reactions) {
width: fit-content;
display: flex;
flex-direction: row;
gap: 4px;
}
:global(.post-actions) {
width: fit-content;
margin-top: 8px;
display: flex;
flex-direction: row;
gap: 2px;
}
.post-container :global(.emoji) {
height: 20px;
}
</style>

View file

@ -0,0 +1,107 @@
<script>
import { parseText as parseEmojis } from '../../emoji.js';
import { shorthand as short_time } from '../../time.js';
export let post;
export let reply = undefined;
let time_string = post.created_at.toLocaleString();
</script>
<div class={"post-header-container" + (reply ? " reply" : "")}>
<a href={post.user.url} target="_blank" class="post-avatar-container">
<img src={post.user.avatar_url} type={post.user.avatar_type} alt="" width="48" height="48" class="post-avatar" loading="lazy" decoding="async">
</a>
<header class="post-header">
<div class="post-user-info">
<a href={post.user.url} target="_blank" class="name">{@html post.user.rich_name}</a>
<span class="username">{post.user.mention}</span>
</div>
<div class="post-info">
<a href={post.url} target="_blank" class="created-at">
<time title={time_string}>{short_time(post.created_at)}</time>
{#if post.visibility !== "public"}
<br>
<span class="post-visibility">{post.visibility}</span>
{/if}
</a>
</div>
</header>
</div>
<style>
.post-header-container {
width: 100%;
display: flex;
flex-direction: row;
}
.post-header-container.reply {
width: calc(100% + 60px);
margin-left: -60px;
}
.post-header-container a,
.post-header-container a:visited {
color: inherit;
text-decoration: none;
}
.post-header-container a:hover {
text-decoration: underline;
}
.post-avatar-container {
margin-right: 12px;
display: flex;
}
.post-avatar {
border-radius: 8px;
}
.post-header {
display: flex;
flex-grow: 1;
flex-direction: row;
}
.post-info {
margin-left: auto;
}
.post-user-info {
margin-top: -2px;
display: flex;
flex-direction: column;
justify-content: center;
}
.post-user-info a {
display: block;
}
.post-user-info .name :global(.emoji) {
position: relative;
top: 4px;
height: 20px;
}
.post-user-info .username {
opacity: .8;
font-size: .9em;
}
.post-info .created-at {
height: 100%;
display: flex;
flex-direction: column;
align-items: end;
justify-content: center;
font-size: .8em;
}
.post-visibility {
font-size: .9em;
opacity: .8;
}
</style>

View file

@ -0,0 +1,88 @@
<script>
import { play_sound } from '../../sound.js';
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
export let type = "react";
export let label = "React";
export let title = label;
export let count = 0;
export let active = false;
export let disabled = false;
export let sound = "default";
function click() {
play_sound(sound);
dispatch('click');
}
</script>
<button
type="button"
class={[
type,
active ? "active" : "",
disabled ? "disabled" : "",
].join(' ')}
aria-label="{label}"
title="{title}"
on:click={click}>
<span class="icon">
<slot/>
</span>
{#if count}
<span class="count">{count}</span>
{/if}
</button>
<style>
button {
height: 32px;
padding: 6px 8px;
display: flex;
flex-direction: row;
gap: 4px;
font-size: 1em;
background: none;
color: inherit;
border: none;
border-radius: 8px;
transition: background-color .1s, color .1s;
cursor: pointer;
}
button.active {
background-color: color-mix(in srgb, transparent, var(--accent) 50%);
color: var(--bg-1000);
}
button:not(.disabled):hover {
background-color: var(--bg-600);
color: var(--text);
}
button:not(.disabled):active {
background-color: var(--bg-1000);
color: var(--text);
}
button.disabled {
cursor: initial;
}
.icon {
width: 20px;
height: 20px;
display: flex;
justify-content: center;
align-items: center;
}
.count {
opacity: .5;
}
button:hover .count {
opacity: 1;
}
</style>

View file

@ -0,0 +1,146 @@
<script>
import PostHeader from './PostHeader.svelte';
import Body from './Body.svelte';
import ReactionButton from './ReactionButton.svelte';
import ActionButton from './ActionButton.svelte';
import Post from './Post.svelte';
import { parseText as parseEmojis, parseOne as parseEmoji } from '../../emoji.js';
import { shorthand as short_time } from '../../time.js';
import { get } from 'svelte/store';
import { Client } from '../../client/client.js';
import * as api from '../../client/api.js';
export let post;
let time_string = post.created_at.toLocaleString();
function gotoPost() {
location = `/post/${post.id}`;
}
async function toggleBoost() {
let client = get(Client.get());
let data;
if (post.boosted)
data = await client.unboostPost(post.id);
else
data = await client.boostPost(post.id);
if (!data) {
console.error(`Failed to boost post ${post.id}`);
return;
}
post.boosted = data.boosted;
post.boost_count = data.reblogs_count;
}
async function toggleFavourite() {
let client = get(Client.get());
let data;
if (post.favourited)
data = await client.unfavouritePost(post.id);
else
data = await client.favouritePost(post.id);
if (!data) {
console.error(`Failed to favourite post ${post.id}`);
return;
}
post.favourited = data.favourited;
post.favourite_count = data.favourites_count;
if (data.reactions) post.reactions = api.parseReactions(data.reactions);
}
async function toggleReaction(reaction) {
if (reaction.name.includes('@')) return;
let client = get(Client.get());
let data;
if (reaction.me)
data = await client.unreactPost(post.id, reaction.name);
else
data = await client.reactPost(post.id, reaction.name);
if (!data) {
console.error(`Failed to favourite post ${post.id}`);
return;
}
post.favourited = data.favourited;
post.favourite_count = data.favourites_count;
if (data.reactions) post.reactions = api.parseReactions(data.reactions);
}
</script>
{#if post.reply}
<svelte:self post={post.reply} />
{/if}
<article class="post-reply" on:click={() => gotoPost()}>
<div class="line"></div>
<div class="post-reply-main">
<PostHeader post={post} reply />
<Body post={post} />
<footer class="post-footer">
<div class="post-reactions" on:click|stopPropagation>
{#each post.reactions as reaction}
<ReactionButton
type="reaction"
on:click={() => toggleReaction(reaction)}
bind:active={reaction.me}
bind:count={reaction.count}
disabled={reaction.name.includes('@')}
title={reaction.name}
label="">
{#if reaction.url}
<img src={reaction.url} class="emoji" height="20" title={reaction.name} alt={reaction.name}>
{:else}
{reaction.name}
{/if}
</ReactionButton>
{/each}
</div>
<div class="post-actions" on:click|stopPropagation>
<ActionButton type="reply" label="Reply" bind:count={post.reply_count} sound="post" disabled>🗨️</ActionButton>
<ActionButton type="boost" label="Boost" on:click={() => toggleBoost()} bind:active={post.boosted} bind:count={post.boost_count} sound="boost">🔁</ActionButton>
<ActionButton type="favourite" label="Favourite" on:click={() => toggleFavourite()} bind:active={post.favourited} bind:count={post.favourite_count}>⭐</ActionButton>
<ActionButton type="react" label="React" disabled>😃</ActionButton>
<ActionButton type="quote" label="Quote" disabled>🗣️</ActionButton>
<ActionButton type="more" label="More" disabled>🛠️</ActionButton>
</div>
</footer>
</div>
</article>
<style>
.post-reply {
padding-bottom: 24px;
display: flex;
flex-direction: row;
color: var(--text);
align-items: stretch;
}
.post-avatar-container {
display: flex;
}
.line {
position: relative;
top: 24px;
left: 25px;
border-right: 2px solid var(--bg-700);
}
.post-reply-main {
width: 100%;
padding-left: 60px;
z-index: 1;
}
:global(.post-body) {
margin-top: 0;
}
:global(.post-body p) {
margin: 0;
}
</style>

29
src/lib/user/user.js Normal file
View file

@ -0,0 +1,29 @@
import { Client } from '../client/client.js';
import { parseText as parseEmojis } from '../emoji.js';
import { get } from 'svelte/store';
export default class User {
id;
nickname;
username;
host;
avatar_url;
emojis;
url;
get name() {
return this.nickname || this.username;
}
get mention() {
let res = "@" + this.username;
if (this.host != get(Client.get()).instance.host)
res += "@" + this.host;
return res;
}
get rich_name() {
if (!this.nickname) return this.username;
return parseEmojis(this.nickname, this.host);
}
}