refactor(dashboard): re-organize dashboard files

This commit is contained in:
Jake Fulmine
2022-11-26 13:23:59 +01:00
parent e0cde35b3d
commit 1b3f188997
41 changed files with 165 additions and 166 deletions

View File

@@ -0,0 +1,64 @@
<script lang="ts">
import { tick } from 'svelte';
import { Modal, CardTitle} from 'sveltestrap';
import default_avatar from '../../assets/default_avatar.png';
import resizeMedia from '../../api/resize-media';
import { toHTML } from 'discord-markdown';
import twemoji from 'twemoji';
export let item: any;
export let searchBy: string = null;
export let sortBy: string = null;
let htmlName: string;
let nameElement: any;
let settings = JSON.parse(localStorage.getItem("pk-settings"));
$: if (item.name) {
if ((searchBy === "display name" || sortBy === "display name") && item.display_name) htmlName = toHTML(item.display_name);
else htmlName = toHTML(item.name);
} else htmlName = "";
$: if (settings && settings.appearance.twemoji) {
if (nameElement) twemoji.parse(nameElement);
}
$: icon_url = item.avatar_url ? item.avatar_url : item.icon ? item.icon : default_avatar;
$: icon_url_resized = resizeMedia(icon_url)
let avatarOpen = false;
const toggleAvatarModal = () => (avatarOpen = !avatarOpen);
// this is the easiest way we can check what type of item the header has
// unsure if there's a better way
let altText = "icon";
if (item.icon) altText = item.name ? `group ${item.name} icon (full size)` : "group icon (full size)";
else if (item.proxy_tags) altText = item.name ? `member ${item.name} avatar (full size)` : "member avatar (full size)";
else if (item.tag) altText = item.name ? `system ${item.name} avatar (full size)` : "system avatar (full size)";
async function focus(el) {
await tick();
el.focus();
}
</script>
<CardTitle style="margin-top: 0px; margin-bottom: 0px; outline: none; align-items: center;" class="d-flex justify-content-between align-middle w-100">
<div>
<div class="icon d-inline-block">
<slot name="icon" />
</div>
<span bind:this={nameElement} style="vertical-align: middle;">{@html htmlName} ({item.id})</span>
</div>
<div style="margin-left: auto;">
{#if item && (item.avatar_url || item.icon)}
<img tabindex={0} on:keydown|stopPropagation={(event) => {if (event.key === "Enter") {avatarOpen = true}}} on:click|stopPropagation={toggleAvatarModal} class="rounded-circle avatar" src={icon_url_resized} alt={altText} />
{:else}
<img class="rounded-circle avatar" src={default_avatar} alt="icon (default)" tabindex={0} />
{/if}
</div>
<Modal isOpen={avatarOpen} toggle={toggleAvatarModal}>
<div slot="external" on:click={toggleAvatarModal} style="height: 100%; max-width: 640px; width: 100%; margin-left: auto; margin-right: auto; display: flex;">
<img class="d-block m-auto img-thumbnail" src={icon_url} alt={altText} tabindex={0} use:focus/>
</div>
</Modal>
</CardTitle>

View File

@@ -0,0 +1,73 @@
<script lang="ts">
import { Pagination, PaginationItem, PaginationLink } from "sveltestrap";
export let currentPage: number;
export let pageAmount: number;
export let smallPages: boolean = false;
</script>
{#if pageAmount > 1}
<Pagination size={smallPages ? "sm" : ""} class="mx-auto" arialabel="member list page navigation">
{#if currentPage !== 1}
<PaginationItem>
<PaginationLink href="#" previous on:click={(e) => {e.preventDefault(); currentPage -= 1}}></PaginationLink>
</PaginationItem>
{:else}
<PaginationItem disabled>
<PaginationLink previous></PaginationLink>
</PaginationItem>
{/if}
{#if currentPage > 2}
<PaginationItem>
<PaginationLink href="#" on:click={(e) => {e.preventDefault(); currentPage = 1}}>1</PaginationLink>
</PaginationItem>
{/if}
{#if currentPage === 4}
<PaginationItem>
<PaginationLink href="#" on:click={(e) => {e.preventDefault(); currentPage = 2}}>2</PaginationLink>
</PaginationItem>
{/if}
{#if currentPage > 4}
<PaginationItem disabled>
<PaginationLink>...</PaginationLink>
</PaginationItem>
{/if}
{#if currentPage > 1}
<PaginationItem>
<PaginationLink href="#" on:click={(e) => {e.preventDefault(); currentPage -= 1}}>{currentPage - 1}</PaginationLink>
</PaginationItem>
{/if}
<PaginationItem active>
<PaginationLink href="#">{currentPage}</PaginationLink>
</PaginationItem>
{#if currentPage < pageAmount}
<PaginationItem>
<PaginationLink href="#" on:click={(e) => {e.preventDefault(); currentPage += 1}}>{currentPage + 1}</PaginationLink>
</PaginationItem>
{/if}
{#if currentPage < pageAmount - 3}
<PaginationItem disabled>
<PaginationLink>...</PaginationLink>
</PaginationItem>
{/if}
{#if currentPage === pageAmount - 3}
<PaginationItem>
<PaginationLink href="#" on:click={(e) => {e.preventDefault(); currentPage = pageAmount - 1}}>{pageAmount - 1}</PaginationLink>
</PaginationItem>
{/if}
{#if currentPage < pageAmount - 1}
<PaginationItem>
<PaginationLink href="#" on:click={(e) => { e.preventDefault(); currentPage = pageAmount}}>{pageAmount}</PaginationLink>
</PaginationItem>
{/if}
{#if currentPage !== pageAmount}
<PaginationItem>
<PaginationLink href="#" next on:click={(e) => {e.preventDefault(); currentPage += 1}}></PaginationLink>
</PaginationItem>
{:else}
<PaginationItem disabled>
<PaginationLink next></PaginationLink>
</PaginationItem>
{/if}
</Pagination>
{/if}

View File

@@ -0,0 +1,66 @@
<script lang="ts">
import {Navbar, NavbarBrand, Nav, NavItem, NavLink, Collapse, NavbarToggler, Dropdown, DropdownItem, DropdownMenu, DropdownToggle, Button} from 'sveltestrap';
import { loggedIn } from '../../stores';
import { Link, navigate } from 'svelte-navigator';
export let style: string;
let isOpen = false;
const toggle = () => (isOpen = !isOpen);
let loggedIn_value: boolean;
loggedIn.subscribe(value => {
loggedIn_value = value;
});
function logout() {
localStorage.removeItem("pk-token");
localStorage.removeItem("pk-user");
loggedIn.update(() => false);
navigate("/");
}
</script>
<Navbar color="light" light expand="lg" class="mb-4">
<Link to="/" class="navbar-brand"><NavbarBrand tabindex={-1} class="m-0">PluralKit</NavbarBrand></Link>
<NavbarToggler on:click={toggle}></NavbarToggler>
<Collapse {isOpen} navbar expand="lg">
<Nav class="ms-auto" navbar>
<Dropdown nav inNavbar>
<DropdownToggle color="transparent" class="nav-link"><span class="select-text">Styles</span></DropdownToggle>
<DropdownMenu end>
<DropdownItem on:click={() => style = "light"}>Light</DropdownItem>
<DropdownItem on:click={() => style = "dark"}>Dark</DropdownItem>
</DropdownMenu>
</Dropdown>
{#if loggedIn_value || localStorage.getItem("pk-token")}
<Dropdown nav inNavbar>
<DropdownToggle color="transparent" class="nav-link"><span class="select-text">Dash</span></DropdownToggle>
<DropdownMenu end>
<Link style="text-decoration: none;" to="/dash?tab=system"><DropdownItem tabindex={-1}>System</DropdownItem></Link>
<Link style="text-decoration: none;" to="/dash?tab=members"><DropdownItem tabindex={-1}>Members</DropdownItem></Link>
<Link style="text-decoration: none;" to="/dash?tab=groups"><DropdownItem tabindex={-1}>Groups</DropdownItem></Link>
<DropdownItem divider />
<DropdownItem on:click={logout}>Log out</DropdownItem>
</DropdownMenu>
</Dropdown>
{/if}
<NavItem>
<Link to="/settings" class="nav-link">Settings</Link>
</NavItem>
<NavItem>
<Link to="/profile" class="nav-link">Public</Link>
</NavItem>
<NavItem>
<Link to="/status" class="nav-link">Bot status</Link>
</NavItem>
</Nav>
</Collapse>
</Navbar>
<style>
.select-text {
user-select: text;
}
</style>

View File

@@ -0,0 +1,169 @@
<script lang="ts">
import { tick } from 'svelte';
import { Row, Col, Modal, Image, Button, CardBody, ModalHeader, ModalBody, ModalFooter, Spinner } from 'sveltestrap';
import moment from 'moment';
import { toHTML } from 'discord-markdown';
import parseTimestamps from '../../api/parse-timestamps';
import resizeMedia from '../../api/resize-media';
import Edit from './Edit.svelte';
import twemoji from 'twemoji';
import Privacy from './Privacy.svelte';
import MemberEdit from './MemberEdit.svelte';
import { Link, useLocation } from 'svelte-navigator';
import { Member, Group } from '../../api/types';
export let group: Group;
let editMode: boolean = false;
let memberMode: boolean = false;
export let isPublic: boolean;
export let members: Member[] = [];
export let isMainDash = true;
export let isPage = false;
let htmlDescription: string;
$: if (group.description) {
htmlDescription = toHTML(parseTimestamps(group.description), {embed: true});
} else {
htmlDescription = "(no description)";
}
let htmlDisplayName: string;
$: if (group.display_name) htmlDisplayName = toHTML(group.display_name)
let settings = JSON.parse(localStorage.getItem("pk-settings"));
let descriptionElement: any;
let displayNameElement: any;
$: if (settings && settings.appearance.twemoji) {
if (descriptionElement) twemoji.parse(descriptionElement);
if (displayNameElement) twemoji.parse(displayNameElement);
};
let created = moment(group.created).format("MMM D, YYYY");
let bannerOpen = false;
const toggleBannerModal = () => (bannerOpen = !bannerOpen);
let privacyOpen = false;
const togglePrivacyModal = () => (privacyOpen = !privacyOpen);
async function focus(el) {
await tick();
el.focus();
}
let location = useLocation()
let pathName = $location.pathname;
function getGroupPageUrl(randomizer?: boolean) {
let str: string;
if (pathName.startsWith("/dash")) str = "/dash";
else str = "/profile";
str += `/g/${group.id}`;
if (randomizer) str += "/random";
return str;
}
</script>
<CardBody style="border-left: 4px solid #{settings && settings.appearance.color_background ? isPage ? "" : group.color : group.color }; margin: -1rem">
{#if !editMode && !memberMode}
<Row>
{#if group.id}
<Col xs={12} lg={4} class="mb-2">
<b>ID:</b> {group.id}
</Col>
{/if}
{#if group.name}
<Col xs={12} lg={4} class="mb-2">
<b>Name:</b> {group.name}
</Col>
{/if}
{#if group.display_name}
<Col xs={12} lg={4} class="mb-2">
<b>Display Name:</b> <span bind:this={displayNameElement}>{@html htmlDisplayName}</span>
</Col>
{/if}
{#if group.created && !isPublic}
<Col xs={12} lg={4} class="mb-2">
<b>Created:</b> {created}
</Col>
{/if}
{#if group.color}
<Col xs={12} lg={4} class="mb-2">
<b>Color:</b> {group.color}
</Col>
{/if}
{#if group.banner}
<Col xs={12} lg={3} class="mb-2">
<b>Banner:</b> <Button size="sm" color="secondary" on:click={toggleBannerModal} aria-label="view group banner">View</Button>
<Modal isOpen={bannerOpen} toggle={toggleBannerModal}>
<div slot="external" on:click={toggleBannerModal} style="height: 100%; width: max-content; max-width: 100%; margin-left: auto; margin-right: auto; display: flex;">
<img class="img-thumbnail d-block m-auto" src={group.banner} tabindex={0} alt={`Group ${group.name} banner (full size)`} use:focus/>
</div>
</Modal>
</Col>
{/if}
{#if group.privacy}
<Col xs={12} lg={4} class="mb-2">
<b>Privacy:</b> <Button size="sm" color="secondary" on:click={togglePrivacyModal} aria-label="edit group privacy">Edit</Button>
<Modal size="lg" isOpen={privacyOpen} toggle={togglePrivacyModal}>
<ModalHeader toggle={togglePrivacyModal}>
Edit privacy
</ModalHeader>
<ModalBody>
<Privacy on:update bind:group bind:privacyOpen={privacyOpen}/>
</ModalBody>
</Modal>
</Col>
{/if}
</Row>
<div class="mt-2 mb-3 description" bind:this={descriptionElement}>
<b>Description:</b><br />
{@html htmlDescription && htmlDescription}
</div>
{#if (group.banner && ((settings && settings.appearance.banner_bottom) || !settings))}
<img on:click={toggleBannerModal} src={resizeMedia(group.banner, [1200, 480])} alt="group banner" class="w-100 mb-3 rounded" style="max-height: 13em; object-fit: cover; cursor: pointer"/>
{/if}
{#if !isPublic}
<Button style="flex: 0" class="link-button" color="primary" on:click={() => editMode = true} aria-label="edit group information">Edit</Button>
{#if isMainDash}
<Button class="link-button" style="flex: 0" color="secondary" on:click={() => memberMode = true} aria-label="edit group members">Members</Button>
{/if}
{/if}
{#if !isPage}
<Link to={getGroupPageUrl()}><button class="link-button button-right btn btn-primary" tabindex={-1} aria-label="view group page">View page</button></Link>
{:else if !isPublic}
<Link to="/dash?tab=groups"><button class="link-button button-right btn btn-primary" tabindex={-1} aria-label="view group system">View system</button></Link>
{/if}
<Link to={getGroupPageUrl(true)}><button class="link-button button-right btn btn-secondary" style={isPublic ? "float: none !important; margin-left: 0;" : ""} tabindex={-1} aria-label="randomize group members">Randomize group</button></Link>
{:else if editMode}
<Edit on:update on:deletion bind:group bind:editMode />
{:else if memberMode}
<MemberEdit on:updateGroupMembers bind:group bind:memberMode bind:members />
{/if}
</CardBody>
<style>
.link-button {
width: 100%;
margin-bottom: 0.2em;
}
@media (min-width: 992px) {
.link-button {
width: max-content;
margin-bottom: 0;
}
.button-right {
float: right;
margin-left: 0.25em;
}
}
</style>

View File

@@ -0,0 +1,230 @@
<script lang="ts">
import { createEventDispatcher } from 'svelte';
import { Card, CardHeader, CardTitle, Modal, Button, ListGroup, ListGroupItem, Label, Input, Alert, Tooltip, Row, Col } from 'sveltestrap';
import { toHTML } from 'discord-markdown';
import twemoji from 'twemoji';
import { Link } from 'svelte-navigator';
import { autoresize } from 'svelte-textarea-autoresize';
import FaEdit from 'svelte-icons/fa/FaEdit.svelte'
import FaInfoCircle from 'svelte-icons/fa/FaInfoCircle.svelte'
import FaUserAlt from 'svelte-icons/fa/FaUserAlt.svelte'
import FaTimes from 'svelte-icons/fa/FaTimes.svelte'
import FaCheck from 'svelte-icons/fa/FaCheck.svelte'
import type { Group, Member} from '../../api/types';
import api from '../../api';
import default_avatar from '../../assets/default_avatar.png';
import resizeMedia from '../../api/resize-media';
export let group: Group;
export let searchBy: string;
export let sortBy: string;
export let members: Member[];
export let isPublic = false;
export let isDash = false;
let input: Group = JSON.parse(JSON.stringify(group));
let view = "card";
let err: string[] = [];
let loading = false;
let success = false;
let settings = JSON.parse(localStorage.getItem("pk-settings"));
let htmlName: string;
$: htmlDesc = group.description && toHTML(group.description, { embed: true}) || "(no description)";
$: htmlDisplayName = group.display_name && toHTML(group.display_name);
let nameElement: any;
let descElement: any;
let dnElement: any;
$: if (group.name) {
if ((searchBy === "display name" || sortBy === "display name") && group.display_name) htmlName = toHTML(group.display_name);
else htmlName = toHTML(group.name);
}
if (settings && settings.appearance.twemoji) {
if (nameElement) twemoji.parse(nameElement);
if (descElement) twemoji.parse(descElement);
if (dnElement) twemoji.parse(dnElement);
}
let avatarOpen = false;
const toggleAvatarModal = () => (avatarOpen = !avatarOpen);
$: icon_url = group.icon ? group.icon : default_avatar;
$: icon_url_resized = resizeMedia(icon_url);
let altText = `member ${group.name} avatar`;
$: memberList = members && members.filter(m => group.members && group.members.includes(m.uuid) && true).sort((a, b) => a.name.localeCompare(b.name)) || [];
let listGroupElements = [];
let pageLink = isPublic ? `/profile/g/${group.id}` : `/dash/g/${group.id}`;
const dispatch = createEventDispatcher();
function update(group: Group) {
dispatch('update', group);
}
async function submit() {
let data = input;
err = [];
success = false;
if (data.color && !/^#?[A-Fa-f0-9]{6}$/.test(input.color)) {
err.push(`"${data.color}" is not a valid color, the color must be a 6-digit hex code. (example: #ff0000)`);
} else if (data.color) {
if (data.color.startsWith("#")) {
data.color = input.color.slice(1, input.color.length);
}
}
// trim all string fields
Object.keys(data).forEach(k => data[k] = typeof data[k] == "string" ? data[k].trim() : data[k]);
err = err;
if (err.length > 0) return;
loading = true;
try {
let res = await api().groups(group.id).patch({data});
update({...group, ...res});
group = {...group, ...res};
err = [];
success = true;
loading = false;
} catch (error) {
console.log(error);
err.push(error.message);
err = err;
loading = false;
}
}
</script>
<Card class="mb-4 pb-3" style={`height: 27.5rem; ${group.color && `border-bottom: 4px solid #${group.color}`}`}>
<CardHeader>
<CardTitle class="d-flex justify-content-center align-middle w-100 mb-0">
<div class="icon d-inline-block">
<slot name="icon" />
</div>
<span bind:this={nameElement} style="vertical-align: middle; margin-bottom: 0;">{@html htmlName} ({group.id})</span>
</CardTitle>
</CardHeader>
<div class="card-body d-block hide-scrollbar" style="flex: 1; overflow: auto;">
{#if view === "card"}
<img style="cursor: pointer;" tabindex={0} on:keydown={(event) => {if (event.key === "Enter") {avatarOpen = true}}} on:click={toggleAvatarModal} class="rounded avatar mx-auto w-100 h-auto mb-2" src={icon_url_resized} alt={altText}/>
<Modal isOpen={avatarOpen} toggle={toggleAvatarModal}>
<div slot="external" on:click={toggleAvatarModal} style="height: 100%; max-width: 640px; width: 100%; margin-left: auto; margin-right: auto; display: flex;">
<img class="d-block m-auto img-thumbnail" src={icon_url} alt="Member avatar" tabindex={0}/>
</div>
</Modal>
{#if group.display_name}
<div class="text-center" bind:this={dnElement}><b>{@html htmlDisplayName}</b></div>
{/if}
<hr style="min-height: 1px;"/>
<div bind:this={descElement}>
{@html htmlDesc}
</div>
<hr style="min-height: 1px;"/>
<Row>
<Col xs={4} class="align-items-center justify-content-center">
{#if !isPublic}<Button color="link" class="mt-2" on:click={() => {view = "edit"}} id={`group-${group.uuid}-edit-button-card`}><FaEdit/></Button>{/if}
</Col>
<Col xs={4} class="align-items-center justify-content-center">
{#if !isPublic && isDash}<Button color="link" class="mt-2 text-reset" on:click={() => {view = "groups"}} id={`group-${group.uuid}-groups-button-card`}><FaUserAlt/></Button>{/if}
</Col>
<Col xs={4} class="align-items-center justify-content-center">
<Link tabindex={-1} to={pageLink} class="text-reset"><Button color="link" class="mt-2 w-100 text-reset" id={`group-${group.uuid}-view-button-card`}><FaInfoCircle/></Button></Link>
</Col>
{#if !isPublic}<Tooltip target={`group-${group.uuid}-edit-button-card`} placement="bottom">Edit group</Tooltip>{/if}
{#if !isPublic && isDash}<Tooltip target={`group-${group.uuid}-groups-button-card`} placement="bottom">View members</Tooltip>{/if}
<Tooltip target={`group-${group.uuid}-view-button-card`} placement="bottom">View page</Tooltip>
</Row>
{:else if view === "groups"}
{#if memberList.length > 0}
<b class="d-block text-center w-100">Members</b>
<hr style="min-height: 1px"/>
<ListGroup>
{#each memberList as member, index (member.id)}
<ListGroupItem class="d-flex"><span bind:this={listGroupElements[index]}><span><b>{@html toHTML(member.name)}</b> (<code>{member.id}</code>)</span></ListGroupItem>
{/each}
</ListGroup>
{:else}
<b class="d-block text-center w-100">This group has no members.</b>
{/if}
<hr style="min-height: 1px"/>
<Row>
<Col xs={4} class="align-items-center justify-content-center">
<Button color="link" class="mt-2" on:click={() => {view = "edit"}} id={`group-${group.uuid}-edit-button-groups`}><FaEdit/></Button>
</Col>
<Col xs={4} class="align-items-center justify-content-center">
<Button color="link" class="mt-2 text-reset" on:click={() => {view = "card"}} id={`group-${group.uuid}-back-button-groups`}><FaTimes/></Button>
</Col>
<Col xs={4} class="align-items-center justify-content-center">
<Link tabindex={-1} to={`./m/${group.id}`} class="text-reset"><Button color="link" class="mt-2 w-100 text-reset" id={`group-${group.uuid}-view-button-groups`}><FaInfoCircle/></Button></Link>
</Col>
<Tooltip target={`group-${group.uuid}-edit-button-groups`} placement="bottom">Edit group</Tooltip>
<Tooltip target={`group-${group.uuid}-back-button-groups`} placement="bottom">Back to info</Tooltip>
<Tooltip target={`group-${group.uuid}-view-button-groups`} placement="bottom">View page</Tooltip>
</Row>
{:else if view === "edit"}
<Label>Name:</Label>
<Input class="mb-2" bind:value={input.name} maxlength={100} type="text" placeholder={group.name} aria-label="group name"/>
<Label>Icon url:</Label>
<Input bind:value={input.icon} maxlength={256} type="url" placeholder={group.icon} aria-label="group avatar url"/>
<hr style="min-height: 1px" />
<Label>Display name:</Label>
<textarea class="form-control mb-2" style="resize: none; height: 1em" bind:value={input.display_name} maxlength={100} type="text" placeholder={group.display_name} aria-label="group display name" />
<hr style="min-height: 1px" />
<Label>Description:</Label>
<textarea class="form-control" style="resize: none; overflow: hidden;" bind:value={input.description} maxlength={1000} use:autoresize placeholder={group.description} aria-label="group description"/>
<hr style="min-height: 1px" />
<Label>Color:</Label>
<Row>
<Col xs={9}>
<Input type="text" bind:value={input.color} aria-label="group color value"/>
</Col>
<Col class="p-0">
<Input class="p-0" on:change={(e) => input.color = e.target.value.slice(1, 7)} type="color" aria-label="color picker" />
</Col>
</Row>
<hr style="min-height: 1px" />
{#if success}
<Alert class="m-0 mb-2" color="success">group edited!</Alert>
{/if}
{#if err}
{#each err as errorMessage}
<Alert class="m-0 mb-2" color="danger">{@html errorMessage}</Alert>
{/each}
{/if}
<Row>
<Col xs={4} class="align-items-center justify-content-center">
<Button disabled={loading} color="link" class="mt-2 text-danger" style="height: 3rem;" on:click={() => {view = "card"}} id={`group-${group.uuid}-back-button-edit`}><FaTimes/></Button>
</Col>
<Col xs={4}>
</Col>
<Col xs={4} class="align-items-center justify-content-center">
<Button disabled={loading} color="link" class="mt-2 text-success" on:click={submit} id={`group-${group.uuid}-submit-button-edit`}><FaCheck/></Button>
</Col>
<Tooltip target={`group-${group.uuid}-back-button-edit`} placement="bottom">Go back</Tooltip>
<Tooltip target={`group-${group.uuid}-submit-button-edit`} placement="bottom">Submit edit</Tooltip>
</Row>
{/if}
</div>
</Card>
<style>
.hide-scrollbar::-webkit-scrollbar {
display: none;
}
.hide-scrollbar {
scrollbar-width: none;
}
</style>

View File

@@ -0,0 +1,156 @@
<script lang="ts">
import { Row, Col, Input, Button, Label, Alert, Spinner, Modal, ModalHeader, ModalBody } from 'sveltestrap';
import { createEventDispatcher, tick } from 'svelte';
import { Group } from '../../api/types';
import api from '../../api';
import { autoresize } from 'svelte-textarea-autoresize';
const descriptions: string[] = JSON.parse(localStorage.getItem("pk-config"))?.description_templates;
let loading: boolean = false;
let success = false;
export let group: Group;
export let editMode: boolean;
let err: string[] = [];
let input: Group = group;
const dispatch = createEventDispatcher();
function deletion() {
dispatch('deletion', group.id);
}
function update(group: Group) {
dispatch('update', group);
}
async function submit() {
let data = input;
err = [];
success = false;
if (data.color && !/^#?[A-Fa-f0-9]{6}$/.test(input.color)) {
err.push(`"${data.color}" is not a valid color, the color must be a 6-digit hex code. (example: #ff0000)`);
} else if (data.color) {
if (data.color.startsWith("#")) {
data.color = input.color.slice(1, input.color.length);
}
}
// trim all string fields
Object.keys(data).forEach(k => data[k] = typeof data[k] == "string" ? data[k].trim() : data[k]);
err = err;
if (err.length > 0) return;
loading = true;
try {
let res = await api().groups(group.id).patch({data});
update({...group, ...res});
err = [];
success = true;
loading = false;
} catch (error) {
console.log(error);
err.push(error.message);
err = err;
loading = false;
}
}
let deleteOpen: boolean = false;
const toggleDeleteModal = () => deleteOpen = !deleteOpen;
let deleteInput: string;
let deleteErr: string;
async function submitDelete() {
deleteErr = null;
if (!deleteInput) {
deleteErr = "Please type out the group ID.";
return;
}
if (deleteInput.trim().toLowerCase() !== group.id) {
deleteErr = "This group's ID does not match the provided ID.";
return;
}
loading = true;
try {
await api().groups(group.id).delete();
deleteErr = null;
toggleDeleteModal();
loading = false;
deletion();
} catch (error) {
loading = false;
}
}
async function focus(el) {
await tick();
el.focus();
}
</script>
{#each err as error}
<Alert fade={false} color="danger">{@html error}</Alert>
{/each}
{#if success}
<Alert fade={false} color="success">Group information updated!</Alert>
{/if}
<Row>
<Col xs={12} lg={4} class="mb-2">
<Label>Name:</Label>
<Input bind:value={input.name} maxlength={100} type="text" placeholder={group.name} aria-label="group name" />
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Display name:</Label>
<textarea class="form-control" style="resize: none; height: 1em" bind:value={input.display_name} maxlength={100} type="text" placeholder={group.display_name} aria-label="group display name"/>
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Color:</Label>
<Input bind:value={input.color} type="text" placeholder={group.color} aria-label="group color"/>
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Icon url:</Label>
<Input bind:value={input.icon} maxlength={256} type="url" placeholder={group.icon} aria-label="group icon url"/>
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Banner url:</Label>
<Input bind:value={input.banner} maxlength={256} type="url" placeholder={group.banner} aria-label="group banner url"/>
</Col>
</Row>
<div class="my-2">
<b>Description:</b><br />
{#if descriptions.length > 0 && descriptions[0].trim() != ""}
<Button size="sm" color="primary" on:click={() => input.description = descriptions[0]} aria-label="use template 1">Template 1</Button>
{/if}
{#if descriptions.length > 1 && descriptions[1].trim() != ""}
<Button size="sm" color="primary" on:click={() => input.description = descriptions[1]} aria-label="use template 2">Template 2</Button>
{/if}
{#if descriptions.length > 2 && descriptions[2].trim() != ""}
<Button size="sm" color="primary" on:click={() => input.description = descriptions[2]} aria-label="use template 3">Template 3</Button>
{/if}
<br>
<textarea class="form-control" bind:value={input.description} maxlength={1000} use:autoresize placeholder={group.description} aria-label="group description"/>
</div>
{#if !loading}<Button style="flex: 0" color="primary" on:click={submit} aria-label="submit edits">Submit</Button> <Button style="flex: 0" color="secondary" on:click={() => editMode = false} aria-label="cancel edits">Back</Button><Button style="flex: 0; float: right;" color="danger" on:click={toggleDeleteModal} aria-label="delete group">Delete</Button>
{:else}<Button style="flex: 0" color="primary" disabled aria-label="submit edits"><Spinner size="sm"/></Button> <Button style="flex: 0" color="secondary" disabled aria-label="cancel edits">Back</Button><Button style="flex: 0; float: right;" color="danger" disabled aria-label="delete group">Delete</Button>{/if}
<Modal size="lg" isOpen={deleteOpen} toggle={toggleDeleteModal}>
<ModalHeader toggle={toggleDeleteModal}>
Delete member
</ModalHeader>
<ModalBody>
{#if deleteErr}<Alert color="danger">{deleteErr}</Alert>{/if}
<Label>If you're sure you want to delete this group, type out the group ID (<code>{group.id}</code>) below.</Label>
<input class="mb-3 form-control" bind:value={deleteInput} maxlength={7} placeholder={group.id} aria-label={`type out the group id ${group.id} to confirm deletion`} use:focus>
{#if !loading}<Button style="flex 0" color="danger" on:click={submitDelete} aria-label="confirm delete">Delete</Button> <Button style="flex: 0" color="secondary" on:click={toggleDeleteModal} aria-label="cancel delete">Back</Button>
{:else}<Button style="flex 0" color="danger" disabled aria-label="confirm delete"><Spinner size="sm"/></Button> <Button style="flex: 0" color="secondary" disabled aria-label="cancel delete">Back</Button>
{/if}
</ModalBody>
</Modal>

View File

@@ -0,0 +1,145 @@
<script lang="ts">
import { Row, Col, Button, Alert, ListGroup, ListGroupItem, Spinner } from 'sveltestrap';
import ListPagination from "../common/ListPagination.svelte";
import twemoji from "twemoji";
import FaUserPlus from 'svelte-icons/fa/FaUserPlus.svelte'
import FaUserFriends from 'svelte-icons/fa/FaUserFriends.svelte'
import FaUserMinus from 'svelte-icons/fa/FaUserMinus.svelte'
import Svelecte, { addFormatter } from 'svelecte';
import { Group, Member } from '../../api/types';
import api from '../../api';
let loading: boolean = false;
let err: string;
export let group: Group;
export let memberMode: boolean = true;
export let members: Member[];
let membersInGroup: Member[];
let membersNotInGroup: Member[];
let membersInGroupSelection: any[];
let membersNotInGroupSelection: any[];
let membersToBeAdded: any[];
let membersToBeRemoved: any[];
let currentPage: number = 1;
let smallPages = true;
updateMemberList();
function updateMemberList() {
membersInGroup = members.filter(member => group.members.includes(member.uuid));
membersInGroup = membersInGroup.sort((a, b) => a.name.localeCompare(b.name));
membersNotInGroup = members.filter(member => !group.members.includes(member.uuid));
membersNotInGroup = membersNotInGroup.sort((a, b) => a.name.localeCompare(b.name));
membersInGroupSelection = membersInGroup.map(function(member) { return {name: member.name, shortid: member.id, id: member.uuid, display_name: member.display_name}; }).sort((a, b) => a.name.localeCompare(b.name));
membersNotInGroupSelection = membersNotInGroup.map(function(member) { return {name: member.name, shortid: member.id, id: member.uuid, display_name: member.display_name}; }).sort((a, b) => a.name.localeCompare(b.name));
}
$: indexOfLastItem = currentPage * 10;
$: indexOfFirstItem = indexOfLastItem - 10;
$: pageAmount = Math.ceil(membersInGroup && membersInGroup.length / 10);
$: finalMemberList = membersInGroup && membersInGroup.slice(indexOfFirstItem, indexOfLastItem);
let settings = JSON.parse(localStorage.getItem('pk-settings'));
let listGroupElements: any[] = [];
$: if (settings && settings.appearance.twemoji) {
if (listGroupElements && listGroupElements.length > 0) {
listGroupElements.forEach(element => element && twemoji.parse(element));
};
}
function memberListRenderer(item: any) {
return `${item.name} (<code>${item.shortid}</code>)`;
}
addFormatter({
'member-list': memberListRenderer
});
async function submitAdd() {
let data = membersToBeAdded;
try {
loading = true;
await api().groups(group.id).members.add.post({data});
data.forEach(member => group.members.push(member));
updateMemberList();
err = null;
membersToBeAdded = [];
loading = false;
} catch (error) {
console.log(error);
err = error.message;
loading = false;
}
}
async function submitRemove() {
let data = membersToBeRemoved;
try {
loading = true;
await api().groups(group.id).members.remove.post({data});
group.members = group.members.filter(m => !data.includes(m));
updateMemberList();
err = null;
membersToBeRemoved = [];
loading = false;
} catch (error) {
console.log(error);
err = error.message;
loading = false;
}
}
</script>
{#if err}
<Alert color="danger">{err}</Alert>
{/if}
<Row>
<Col xs={12} lg={6} class="text-center mb-3">
<h5><div class="icon d-inline-block">
<FaUserFriends />
</div>Current Members
{#if finalMemberList && finalMemberList.length > 0}
({membersInGroup.length} total)
{/if}
</h5>
<ListPagination bind:currentPage bind:pageAmount bind:smallPages/>
{#if finalMemberList && finalMemberList.length > 0}
<ListGroup>
{#each finalMemberList as member, index (member.id)}
<ListGroupItem class="d-flex"><span bind:this={listGroupElements[index]} class="d-flex justify-content-between flex-grow-1"><span><b>{member.name}</b> (<code>{member.id}</code>)</span> <span>{member.display_name ? `${member.display_name}` : ""}</span></span></ListGroupItem>
{/each}
</ListGroup>
{:else}
<p>There are no members in this group yet.</p>
<p>You can add some in this menu!</p>
{/if}
</Col>
<Col xs={12} lg={6} class="text-center mb-3">
<h5><div class="icon d-inline-block">
<FaUserPlus />
</div>Add Members</h5>
<Svelecte renderer="member-list" disableHighlight bind:value={membersToBeAdded} options={membersNotInGroupSelection} multiple/>
{#if !loading && membersToBeAdded && membersToBeAdded.length > 0}
<Button class="w-100 mt-2" color="primary" on:click={submitAdd} aria-label="add members">Add</Button>{:else}
<Button class="w-100 mt-2" color="primary" disabled aria-label="add members">{#if loading}<Spinner size="sm" />{:else}Add{/if}</Button>
{/if}
<hr/>
<h5><div class="icon d-inline-block">
<FaUserMinus />
</div>Remove Members</h5>
<Svelecte renderer="member-list" disableHighlight bind:value={membersToBeRemoved} options={membersInGroupSelection} multiple/>
{#if !loading && membersToBeRemoved && membersToBeRemoved.length > 0}
<Button class="w-100 mt-2" color="primary" on:click={submitRemove} aria-label="remove members">Remove</Button>{:else}
<Button class="w-100 mt-2" color="primary" disabled aria-label="remove members">{#if loading}<Spinner size="sm" />{:else}Remove{/if}</Button>
{/if}
</Col>
</Row>
<Button style="flex: 0" color="secondary" on:click={() => memberMode = false} aria-label="back to group card">Back</Button>

View File

@@ -0,0 +1,179 @@
<script lang="ts">
import { Row, Col, Input, Button, Label, Alert, Spinner, Accordion, AccordionItem, CardTitle } from 'sveltestrap';
import { Group } from '../../api/types';
import api from '../../api';
import { autoresize } from 'svelte-textarea-autoresize';
import { createEventDispatcher } from 'svelte';
import FaPlus from 'svelte-icons/fa/FaPlus.svelte';
const descriptions: string[] = JSON.parse(localStorage.getItem("pk-config"))?.description_templates;
let loading: boolean = false;
let err: string[] = [];
let message: string;
let privacyMode = false;
let defaultGroup: Group = {
privacy: {
description_privacy: "public",
metadata_privacy: "public",
list_privacy: "public",
icon_privacy: "public",
name_privacy: "public",
visibility: "public"
}
}
const dispatch = createEventDispatcher();
function create(data: Group) {
dispatch('create', data);
}
let input: Group = JSON.parse(JSON.stringify(defaultGroup));
async function submit() {
let data = input;
message = "";
err = [];
if (data.color && !/^#?[A-Fa-f0-9]{6}$/.test(input.color)) {
err.push(`"${data.color}" is not a valid color, the color must be a 6-digit hex code. (example: #ff0000)`);
} else if (data.color) {
if (data.color.startsWith("#")) {
data.color = input.color.slice(1, input.color.length);
}
}
// trim all string fields
Object.keys(data).forEach(k => data[k] = typeof data[k] == "string" ? data[k].trim() : data[k]);
err = err;
if (err.length > 0) return;
loading = true;
try {
let res: Group = await api().groups().post({data});
res.members = [];
create(res);
input = JSON.parse(JSON.stringify(defaultGroup));
message = `Group ${data.name} successfully created!`
err = [];
loading = false;
} catch (error) {
console.log(error);
err.push(error.message);
err = err;
loading = false;
}
}
</script>
<Accordion class="mb-3">
<AccordionItem>
<CardTitle slot="header" style="margin-top: 0px; margin-bottom: 0px; outline: none; align-items: center;" class="d-flex align-middle w-100 p-2">
<div class="icon d-inline-block">
<FaPlus/>
</div>
<span style="vertical-align: middle;">Add new Group</span>
</CardTitle>
{#if message}
<Alert color="success">{@html message}</Alert>
{/if}
{#each err as error}
<Alert color="danger">{@html error}</Alert>
{/each}
<Row>
<Col xs={12} lg={4} class="mb-2">
<Label>Name:</Label>
<Input bind:value={input.name} maxlength={100} type="text" />
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Display name:</Label>
<textarea class="form-control" style="resize: none; height: 1em" bind:value={input.display_name} maxlength={100} type="text"/>
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Color:</Label>
<Input bind:value={input.color} type="text"/>
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Icon url:</Label>
<Input bind:value={input.icon} maxlength={256} type="url"/>
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Banner url:</Label>
<Input bind:value={input.banner} maxlength={256} type="url"/>
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Privacy:</Label>
<Button class="w-100" color="secondary" on:click={() => privacyMode = !privacyMode}>Toggle privacy</Button>
</Col>
</Row>
{#if privacyMode}
<hr />
<Row>
<Col xs={12} lg={4} class="mb-3">
<Label>Description:</Label>
<Input type="select" bind:value={input.privacy.description_privacy}>
<option>public</option>
<option>private</option>
</Input>
</Col>
<Col xs={12} lg={4} class="mb-3">
<Label>Name:</Label>
<Input type="select" bind:value={input.privacy.name_privacy}>
<option>public</option>
<option>private</option>
</Input>
</Col>
<Col xs={12} lg={4} class="mb-3">
<Label>Member list:</Label>
<Input type="select" bind:value={input.privacy.list_privacy}>
<option>public</option>
<option>private</option>
</Input>
</Col>
<Col xs={12} lg={4} class="mb-3">
<Label>Icon:</Label>
<Input type="select" bind:value={input.privacy.icon_privacy}>
<option>public</option>
<option>private</option>
</Input>
</Col>
<Col xs={12} lg={4} class="mb-3">
<Label>Visibility:</Label>
<Input type="select" bind:value={input.privacy.visibility}>
<option>public</option>
<option>private</option>
</Input>
</Col>
<Col xs={12} lg={4} class="mb-3">
<Label>Metadata:</Label>
<Input type="select" bind:value={input.privacy.metadata_privacy}>
<option>public</option>
<option>private</option>
</Input>
</Col>
</Row>
<hr />
{/if}
<div class="my-2">
<b>Description:</b><br />
{#if descriptions.length > 0 && descriptions[0].trim() != ""}
<Button size="sm" color="primary" on:click={() => input.description = descriptions[0]}>Template 1</Button>
{/if}
{#if descriptions.length > 1 && descriptions[1].trim() != ""}
<Button size="sm" color="primary" on:click={() => input.description = descriptions[1]}>Template 2</Button>
{/if}
{#if descriptions.length > 2 && descriptions[2].trim() != ""}
<Button size="sm" color="primary" on:click={() => input.description = descriptions[2]}>Template 3</Button>
{/if}
<br>
<textarea class="form-control" bind:value={input.description} maxlength={1000} use:autoresize />
</div>
{#if !loading && input.name}<Button style="flex: 0" color="primary" on:click={submit}>Submit</Button>
{:else if !input.name }<Button style="flex: 0" color="primary" disabled>Submit</Button>
{:else}<Button style="flex: 0" color="primary" disabled><Spinner size="sm"/></Button>{/if}
</AccordionItem>
</Accordion>

View File

@@ -0,0 +1,88 @@
<script lang="ts">
import { tick, createEventDispatcher } from "svelte";
import { ModalBody, ModalHeader, Col, Row, Input, Label, ModalFooter, Button, Spinner, Alert } from "sveltestrap";
import { Group, GroupPrivacy } from '../../api/types';
import api from '../../api';
export let privacyOpen: boolean;
export let group: Group;
const togglePrivacyModal = () => (privacyOpen = !privacyOpen);
let err: string;
let loading = false;
let success = false;
function changeAll(e: Event) {
const target = e.target as HTMLInputElement;
Object.keys(privacy).forEach(x => privacy[x] = target.value);
}
const dispatch = createEventDispatcher();
function update(group) {
dispatch('update', group);
}
// I can't use the hacked together Required<T> type from the bulk privacy here
// that breaks updating the displayed privacy after submitting
// but there's not really any way for any privacy fields here to be missing
let privacy = group.privacy;
const privacyNames: { [P in keyof GroupPrivacy]-?: string; } = {
name_privacy: "Name",
description_privacy: "Description",
icon_privacy: "Icon",
list_privacy: "Member list",
metadata_privacy: "Metadata",
visibility: "Visbility",
};
async function submit() {
loading = true;
const data: Group = {privacy: privacy};
try {
let res = await api().groups(group.id).patch({data});
group = {...group, ...res};
success = true;
} catch (error) {
console.log(error);
err = error.message;
}
loading = false;
}
async function focus(el) {
await tick();
el.focus();
}
</script>
{#if err}
<Alert color="danger">{err}</Alert>
{/if}
{#if success}
<Alert color="success">Group privacy updated!</Alert>
{/if}
<Label><b>Set all to:</b></Label>
<select class="form-control" on:change={(e) => changeAll(e)} aria-label="set all to" use:focus>
<option>public</option>
<option>private</option>
</select>
<hr/>
<Row>
{#each Object.keys(privacy) as x}
<Col xs={12} lg={6} class="mb-3">
<Label>{privacyNames[x]}:</Label>
<Input type="select" bind:value={privacy[x]} aria-label={`group ${privacyNames[x]} privacy`}>
<option default={privacy[x] === "public"}>public</option>
<option default={privacy[x] === "private"}>private</option>
</Input>
</Col>
{/each}
</Row>
{#if !loading}<Button style="flex: 0" color="primary" on:click={submit} aria-label="submit privacy edits">Submit</Button> <Button style="flex: 0" color="secondary" on:click={togglePrivacyModal} aria-label="cancel privacy edits">Back</Button>
{:else}<Button style="flex: 0" color="primary" disabled aria-label="submit privacy edits"><Spinner size="sm"/></Button> <Button style="flex: 0" color="secondary" disabled aria-label="cancel privacy edits">Back</Button>
{/if}

View File

@@ -0,0 +1,96 @@
<script lang="ts">
import { Row, Tooltip } from 'sveltestrap';
import FaLock from 'svelte-icons/fa/FaLock.svelte';
import FaUserCircle from 'svelte-icons/fa/FaUserCircle.svelte';
import FaUsers from 'svelte-icons/fa/FaUsers.svelte'
import { Member, Group } from '../../api/types';
import MemberCard from '../member/CardView.svelte';
import GroupCard from '../group/CardView.svelte';
export let list: Member[]|Group[];
export let groups: Group[] = [];
export let members: Group[] = [];
export let itemType: string;
export let searchBy = "name";
export let sortBy = "name";
export let isPublic = false;
export let isDash = false;
let copiedItems = {};
function getShortLink(id: string) {
let url = "https://pk.mt"
if (itemType === "member") url += "/m/"
else if (itemType === "group") url += "/g/"
url += id;
return url;
}
async function copyShortLink(index: string, id: string, event?) {
if (event) {
if (event.key !== "Tab") event.preventDefault();
event.stopPropagation();
let ctrlDown = event.ctrlKey||event.metaKey; // mac support
if (!(ctrlDown && event.key === "c") && event.key !== "Enter") return;
}
try {
await navigator.clipboard.writeText(getShortLink(id));
copiedItems[index] = copiedItems[index] || false;
copiedItems[index] = true;
await new Promise(resolve => setTimeout(resolve, 2000));
copiedItems[index] = false;
} catch (error) {
console.log(error);
}
}
</script>
<Row>
{#if itemType === "member"}
{#each list as item (item.uuid)}
<div class="col-12 col-sm-6 col-md-4 col-lg-3 mx-auto mx-sm-0 dont-squish">
<MemberCard on:update member={item} {searchBy} {sortBy} {groups} {isPublic} {isDash}>
<div slot="icon" style="width: auto; height: 1em; cursor: pointer;" id={`${itemType}-copy-${item.uuid}`} on:click|stopPropagation={() => copyShortLink(item.uuid, item.id)} on:keydown={(e) => copyShortLink(item.uuid, item.id, e)} tabindex={0} >
{#if item.privacy && item.privacy.visibility === "private"}
<FaLock />
{:else}
<FaUserCircle />
{/if}
</div>
</MemberCard>
<Tooltip placement="top" target={`${itemType}-copy-${item.uuid}`}>{copiedItems[item.uuid] ? "Copied!" : "Copy public link"}</Tooltip>
</div>
{/each}
{:else if itemType === "group"}
{#each list as item (item.uuid)}
<div class="col-12 col-sm-6 col-md-4 col-lg-3 mx-auto mx-sm-0 dont-squish">
<GroupCard group={item} {searchBy} {sortBy} {members} {isPublic} {isDash}>
<div slot="icon" style="width: auto; height: 1em; cursor: pointer;" id={`${itemType}-copy-${item.uuid}`} on:click|stopPropagation={() => copyShortLink(item.uuid, item.id)} on:keydown={(e) => copyShortLink(item.uuid, item.id, e)} tabindex={0} >
{#if item.privacy && item.privacy.visibility === "private"}
<FaLock />
{:else}
<FaUsers />
{/if}
</div>
</GroupCard>
<Tooltip placement="top" target={`${itemType}-copy-${item.uuid}`}>{copiedItems[item.uuid] ? "Copied!" : "Copy public link"}</Tooltip>
</div>
{/each}
{/if}
</Row>
<style>
@media (max-width: 576px) {
.dont-squish {
max-width: 24rem;
}
}
</style>

View File

@@ -0,0 +1,168 @@
<script lang="ts">
import { Alert, Row, Col, Spinner, Button } from 'sveltestrap';
import { onMount } from 'svelte';
import { useParams } from 'svelte-navigator';
import NewMember from '../member/NewMember.svelte';
import NewGroup from '../group/NewGroup.svelte';
import ListPagination from '../common/ListPagination.svelte';
import ListControl from './ListControl.svelte';
import ListSearch from './ListSearch.svelte';
import ListView from './ListView.svelte';
import CardView from './CardView.svelte';
import { Member, Group } from '../../api/types';
import api from '../../api';
export let members: Member[] = [];
export let groups: Group[] = [];
export let view: string = "list";
export let isDash = false;
let list: Member[] | Group[] = [];
let processedList: Member[] | Group[] = [];
$: groupList = groups && groups.map(function(group) { return {name: group.name, shortid: group.id, id: group.uuid, members: group.members, display_name: group.display_name}; }).sort((a, b) => a.name.localeCompare(b.name));
$: memberList = members && members.map(function(member) { return {name: member.name, shortid: member.id, id: member.uuid, display_name: member.display_name}; }).sort((a, b) => a.name.localeCompare(b.name));
let token = localStorage.getItem("pk-token");
let listLoading = true;
let err: string;
let settings = JSON.parse(localStorage.getItem("pk-settings"));
let pageAmount: number;
let currentPage: number = 1;
let itemsPerPageValue;
$: {
if (view === "card") itemsPerPageValue = "24";
else if (settings && settings.accessibility && settings.accessibility.expandedcards) itemsPerPageValue = "10";
else itemsPerPageValue = "25";
}
$: itemsPerPage = parseInt(itemsPerPageValue);
$: indexOfLastItem = currentPage * itemsPerPage;
$: indexOfFirstItem = indexOfLastItem - itemsPerPage;
$: pageAmount = Math.ceil(processedList.length / itemsPerPage);
$: slicedList = processedList.slice(indexOfFirstItem, indexOfLastItem);
export let isPublic: boolean;
export let itemType: string;
let searchValue: string = "";
let searchBy: string = "name";
let sortBy: string = "name";
let params = useParams();
$: id = $params.id;
onMount(() => {
if (token || isPublic) fetchList();
});
async function fetchList() {
err = "";
listLoading = true;
try {
if (itemType === "member") {
const res: Member[] = await api().systems(isPublic ? id : "@me").members.get({ auth: !isPublic });
members = res;
list = res;
}
else if (itemType === "group") {
const res: Group[] = await api().systems(isPublic ? id : "@me").groups.get({ auth: !isPublic, query: { with_members: !isPublic } });
groups = res;
list = res;
}
else throw new Error(`Unknown list type ${itemType}`);
} catch (error) {
console.log(error);
err = error.message;
}
listLoading = false;
}
function addItemToList(event: any) {
if (itemType === "member") {
members.push(event.detail);
list = members;
} else if (itemType === "group") {
groups.push(event.detail);
list = groups;
}
}
function updateDelete(event: any) {
if (itemType === "member") {
members = members.filter(m => m.id !== event.detail);
list = members;
} else if (itemType === "group") {
groups = groups.filter(g => g.id !== event.detail);
list = groups;
}
}
function update(event: any) {
if (itemType === "member") {
members = members.map(m => m.id === event.detail.id ? m = event.detail : m);
list = members;
} else if (itemType === "group") {
groups = groups.map(g => g.id === event.detail.id ? g = event.detail : g);
list = groups;
}
}
</script>
<ListControl on:viewChange {itemType} {isPublic} {memberList} {groups} {groupList} {list} bind:finalList={processedList} bind:searchValue bind:searchBy bind:sortBy bind:itemsPerPageValue bind:currentPage bind:view />
{#if listLoading && !err}
<div class="mx-auto text-center">
<Spinner class="d-inline-block" />
</div>
{:else if err}
<Row>
<Col xs={12} lg={10}>
<Alert color="danger">{err}</Alert>
</Col>
<Col xs={12} lg={2}>
<Button class="w-100 mb-3" color="primary" on:click={fetchList} aria-label="refresh member list">Refresh</Button>
</Col>
</Row>
{:else}
<span class="itemcounter">{processedList.length} {itemType}s ({slicedList.length} shown)</span>
<ListSearch bind:searchBy bind:searchValue on:refresh={fetchList} />
<ListPagination bind:currentPage {pageAmount} />
{#if !err && !isPublic}
{#if itemType === "member"}
<NewMember on:create={addItemToList} />
{:else if itemType === "group"}
<NewGroup on:create={addItemToList} />
{/if}
{/if}
{#if view === "card"}
<CardView on:update={update} list={slicedList} {groups} {members} {itemType} {sortBy} {searchBy} {isPublic} {isDash} />
{:else if view === "tiny"}
tiny!
{:else}
<ListView on:update={update} on:deletion={updateDelete} list={slicedList} {groups} {members} {isPublic} {itemType} {itemsPerPage} {currentPage} {sortBy} {searchBy} fullLength={list.length} />
{/if}
<ListPagination bind:currentPage {pageAmount} />
{/if}
<style>
.itemcounter {
width: 100%;
text-align: center;
display: inline-block;
margin-bottom: 0.5rem;
}
</style>

View File

@@ -0,0 +1,365 @@
<script lang="ts">
import { createEventDispatcher } from 'svelte';
import { Card, CardHeader, CardBody, CardTitle, Alert, Accordion, AccordionItem, InputGroupText, InputGroup, Input, Row, Col, Spinner, Button, Tooltip, Label } from 'sveltestrap';
import FaSearch from 'svelte-icons/fa/FaSearch.svelte'
import Svelecte, { addFormatter } from 'svelecte';
import { Member, Group } from '../../api/types';
import { Link, useParams } from 'svelte-navigator';
import moment from 'moment';
export let list: Member[] | Group[] = [];
export let itemType: string;
export let memberList: any = [];
export let groups: Group[] = [];
export let groupList: any = [];
export let searchBy = "name";
export let searchValue: string;
export let itemsPerPageValue: string;
export let view = "list";
let itemsPerPageSelection = {
small: "10",
default: "25",
large: "50"
}
$: { if (view === "card") itemsPerPageSelection = {
small: "12",
default: "24",
large: "60"
}
else {
itemsPerPageSelection = {
small: "10",
default: "25",
large: "50"
}
}
}
const dispatch = createEventDispatcher();
function onViewChange(e: any) {
dispatch("viewChange", e.target.value);
}
export let sortBy = "name";
let sortOrder = "ascending";
let privacyFilter = "all";
let groupSearchMode = "include";
let selectedGroups = [];
export let currentPage: number;
export let isPublic: boolean;
let params = useParams();
$: systemId = $params.id;
$: {searchValue; privacyFilter; currentPage = 1};
// converting list to any[] avoids a "this expression is not calleable" error
$: searchedList = (list as any[]).filter((item: Member | Group) => {
if (!searchValue && searchBy !== "description" && searchBy !== "display name") return true;
switch (searchBy) {
case "name": if (item.name.toLowerCase().includes(searchValue.toLowerCase())) return true;
break;
case "display name": if (!searchValue) {
if (!item.display_name) return true;
else return false;
}
if (item.display_name && item.display_name.toLowerCase().includes(searchValue.toLowerCase())) return true;
break;
case "description": if (!searchValue) {
if (!item.description) return true;
else return false;
}
else if (item.description && item.description.toLowerCase().includes(searchValue.toLowerCase())) return true;
break;
case "ID": if (item.id.toLowerCase().includes(searchValue.toLowerCase())) return true;
break;
default: if (item.name.toLowerCase().includes(searchValue.toLowerCase())) return true;
break;
}
return false;
})
$: filteredList = searchedList.filter((item) => {
if (privacyFilter === "all") return true;
if (privacyFilter === "public" && item.privacy.visibility === "public") return true;
if (privacyFilter === "private" && item.privacy.visibility === "private") return true;
return false;
});
let sortedList = [];
$: if (filteredList) {
let alphabeticalList = filteredList.sort((a, b) => a.name.localeCompare(b.name));
switch (sortBy) {
case "name": sortedList = alphabeticalList;
break;
case "display name": sortedList = filteredList.sort((a, b) => {
if (a.display_name && b.display_name) return a.display_name.localeCompare(b.display_name);
else if (a.display_name && !b.display_name) return a.display_name.localeCompare(b.name);
else if (!a.display_name && b.display_name) return a.name.localeCompare(b.display_name);
else return a.name.localeCompare(b.name);
});
break;
case "creation date": sortedList = filteredList.sort((a, b) => {
if (a.created && b.created) return a.created.localeCompare(b.created);
});
break;
case "ID": sortedList = filteredList.sort((a, b) => a.id.localeCompare(b.id));
break;
case "avatar": sortedList = alphabeticalList.sort((a, b) => {
if (a.icon === null || a.avatar_url === null) {
return 1;
};
if (b.icon === null || b.avatar_url === null) {
return -1;
};
if (a.icon === b.icon || a.avatar_url === b.avatar_url) {
return 0;
}
});
break;
case "color": sortedList = alphabeticalList.sort((a, b) => {
if (a.color === null) {
return 1;
};
if (b.color === null) {
return -1;
};
if (a.color === b.color) {
return 0;
}
});
break;
case "birthday": sortedList = alphabeticalList.sort((a, b) => {
if (a.birthday === null) {
return 1;
}
if (b.birthday === null) {
return -1;
}
let aBirthday = moment(a.birthday.slice(5, a.birthday.length), "MM-DD", true);
let bBirthday = moment(b.birthday.slice(5, b.birthday.length), "MM-DD", true);
if (aBirthday.isBefore(bBirthday)) {
return -1;
}
if (aBirthday.isAfter(bBirthday)) {
return 1;
}
if (aBirthday === bBirthday) {
return 0;
}
});
break;
case "pronouns": sortedList = alphabeticalList.sort((a, b) => {
if (a.pronouns === null) {
return 1;
};
if (b.pronouns === null) {
return -1;
};
return 0;
})
break;
default: sortedList = filteredList.sort((a, b) => a.name.localeCompare(b.name));
break;
}
}
let memberFilteredList = [];
$: memberFilteredList = sortedList.filter((item: Member | Group): boolean => {
if (itemType === "member") {
if (groupSearchMode === "none") {
if (groups.some(group => group.members && group.members.includes(item.uuid))) return false;
}
if (selectedGroups.length < 1) return true;
switch (groupSearchMode) {
case "include": if (selectedGroups.some(group => group.members && group.members.includes(item.uuid))) return true;
break;
case "exclude": if (selectedGroups.every(group => group.members && !group.members.includes(item.uuid))) return true;
break;
case "match": if (selectedGroups.every(group => group.members && group.members.includes(item.uuid))) return true;
break;
default: return true;
}
} else if (itemType === "group") {
let group = (item as Group);
if (groupSearchMode === "none") {
if (group.members && group.members.length > 0) return false;
}
if (selectedGroups.length < 1) return true;
switch (groupSearchMode) {
case "include": if (group.members && selectedGroups.some(member => group.members.includes(member.id))) return true;
break;
case "exclude": if (group.members && selectedGroups.every(member => !group.members.includes(member.id))) return true;
break;
case "match": if (group.members && selectedGroups.every(member => group.members.includes(member.id))) return true;
break;
default: return true;
}
}
return false;
})
export let finalList = [];
$:{sortOrder; if (sortOrder === "descending") finalList = memberFilteredList.reverse(); else finalList = memberFilteredList;}
function groupListRenderer(item: any) {
return `${item.name} (<code>${item.shortid}</code>)`;
}
addFormatter({
'group-list': groupListRenderer
});
function memberListRenderer(item: any) {
return `${item.name} (<code>${item.shortid}</code>)`;
}
addFormatter({
'member-list': memberListRenderer
});
function getRandomizerUrl(): string {
let str: string;
if (isPublic) str = `/profile/s/${systemId}/random`
else str = "/dash/random";
if (itemType === "group") str += "/g";
return str;
}
function capitalizeFirstLetter(string: string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
</script>
<Card class="mb-3">
<CardHeader>
<CardTitle>
<CardTitle style="margin-top: 8px; outline: none;">
<div class="icon d-inline-block">
<FaSearch />
</div> Search {itemType === "member" ? "members" : "groups"}
</CardTitle>
</CardTitle>
</CardHeader>
<CardBody>
<Row>
<Col xs={12} lg={3} class="mb-2">
<InputGroup>
<InputGroupText>Page length</InputGroupText>
<Input bind:value={itemsPerPageValue} type="select" aria-label="page length">
<option>{itemsPerPageSelection.small}</option>
<option>{itemsPerPageSelection.default}</option>
<option>{itemsPerPageSelection.large}</option>
</Input>
</InputGroup>
</Col>
<Col xs={12} lg={3} class="mb-2">
<InputGroup>
<InputGroupText>Search by</InputGroupText>
<Input bind:value={searchBy} type="select" aria-label="search by">
<option>name</option>
<option>display name</option>
<option>description</option>
<option>ID</option>
</Input>
</InputGroup>
</Col>
<Col xs={12} lg={3} class="mb-2">
<InputGroup>
<InputGroupText>Sort by</InputGroupText>
<Input bind:value={sortBy} type="select" aria-label="sort by">
<option>name</option>
<option>display name</option>
{#if !isPublic}<option>creation date</option>{/if}
<option>ID</option>
<option>avatar</option>
<option>color</option>
{#if itemType === "member"}<option>birthday</option>{/if}
{#if itemType === "member"}<option>pronouns</option>{/if}
</Input>
</InputGroup>
</Col>
<Col xs={12} lg={3} class="mb-2">
<InputGroup>
<InputGroupText>Sort order</InputGroupText>
<Input bind:value={sortOrder} type="select" aria-label="sort order">
<option>ascending</option>
<option>descending</option>
</Input>
</InputGroup>
</Col>
{#if !isPublic}
<Col xs={12} lg={3} class="mb-2">
<InputGroup>
<InputGroupText>Only show</InputGroupText>
<Input bind:value={privacyFilter} type="select" aria-label="only show">
<option>all</option>
<option>public</option>
<option>private</option>
</Input>
</InputGroup>
</Col>
{/if}
<Col xs={12} lg={3} class="mb-2">
<InputGroup>
<InputGroupText>View mode</InputGroupText>
<Input bind:value={view} type="select" aria-label="view mode" on:change={(e) => onViewChange(e)} >
<option>list</option>
<option value="card">cards</option>
</Input>
</InputGroup>
</Col>
<Col xs={12} lg={3} class="mb-2">
<Link to={getRandomizerUrl()}><Button class="w-100" color="secondary" tabindex={-1} aria-label={`randomize ${itemType}s`}>Random {capitalizeFirstLetter(itemType)}</Button></Link>
</Col>
</Row>
{#if !isPublic}
<hr/>
<Label>Filter {itemType === "member" ? "member" : "group"} by {itemType === "member" ? "group" : "member"}</Label>
{#if itemType === "member"}
<Svelecte disableHighlight renderer="group-list" valueAsObject bind:value={selectedGroups} options={groupList} multiple style="margin-bottom: 0.5rem" />
{:else if itemType === "group"}
<Svelecte disableHighlight renderer="member-list" valueAsObject bind:value={selectedGroups} options={memberList} multiple style="margin-bottom: 0.5rem" />
{/if}
<div class="filter-mode-group">
<span class="filter-mode-label" id="m-include" on:click={() => groupSearchMode = "include"} on:keyup={e => e.key === "Enter" ? groupSearchMode = "include" : ""} tabindex={0}>{@html groupSearchMode === "include" ? "<b>include</b>" : "include"}</span>
| <span class="filter-mode-label" id="m-exclude" on:click={() => groupSearchMode = "exclude"} on:keyup={e => e.key === "Enter" ? groupSearchMode = "exclude" : ""} tabindex={0}>{@html groupSearchMode === "exclude" ? "<b>exclude</b>" : "exclude"}</span>
| <span class="filter-mode-label" id="m-match" on:click={() => groupSearchMode = "match"} on:keyup={e => e.key === "Enter" ? groupSearchMode = "match" : ""} tabindex={0}>{@html groupSearchMode === "match" ? "<b>exact match</b>" : "exact match"}</span>
| <span class="filter-mode-label" id="m-none" on:click={() => groupSearchMode = "none"} on:keyup={e => e.key === "Enter" ? groupSearchMode = "none" : ""} tabindex={0}>{@html groupSearchMode === "none" ? "<b>none</b>" : "none"}</span>
</div>
<Tooltip placement="bottom" target="m-include">Includes every member who's a part of any of the groups.</Tooltip>
<Tooltip placement="bottom" target="m-exclude">Excludes every member who's a part of any of the groups, the opposite of include.</Tooltip>
<Tooltip placement="bottom" target="m-match">Only includes members who are a part of every group.</Tooltip>
<Tooltip placement="bottom" target="m-none">Only includes members that are in no groups.</Tooltip>
{/if}
</CardBody>
</Card>
<style>
.filter-mode-label {
cursor: pointer;
}
.filter-mode-group {
line-height: 1.5em;
padding:0.375rem 0;
display: inline-block;
margin-bottom: 0.25em;
}
</style>

View File

@@ -0,0 +1,23 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import { Button, Col, Input, Row } from "sveltestrap";
export let searchValue: string;
export let searchBy: string;
const dispatch = createEventDispatcher();
function update() {
dispatch("refresh");
}
</script>
<Row>
<Col xs={12} lg={10}>
<Input class="mb-3" bind:value={searchValue} placeholder="search by {searchBy}..."/>
</Col>
<Col xs={12} lg={2} class="mb-3 mb-lg-0">
<Button class="w-100 mb-3" color="primary" on:click={() => update()} aria-label="refresh member list">Refresh</Button>
</Col>
</Row>

View File

@@ -0,0 +1,198 @@
<script lang="ts">
import { Card, CardHeader, CardBody, Collapse, Tooltip } from 'sveltestrap';
import { Member, Group } from '../../api/types';
import { link } from 'svelte-navigator';
import FaLock from 'svelte-icons/fa/FaLock.svelte';
import FaUserCircle from 'svelte-icons/fa/FaUserCircle.svelte';
import FaUsers from 'svelte-icons/fa/FaUsers.svelte'
import MemberBody from '../member/Body.svelte';
import GroupBody from '../group/Body.svelte';
import CardsHeader from '../common/CardsHeader.svelte';
let settings = JSON.parse(localStorage.getItem("pk-settings"));
export let list: Member[]|Group[];
export let members: Member[] = [];
export let groups: Group[] = [];
export let isPublic: boolean;
export let itemType: string;
export let itemsPerPage: number;
export let currentPage: number;
export let fullLength: number;
export let openByDefault = false;
export let searchBy = "name";
export let sortBy = "name";
$: indexStart = itemsPerPage * (currentPage - 1);
function getItemLink(item: Member | Group): string {
let url: string;
if (!isPublic) url = "/dash/";
else url = "/profile/";
if (itemType === "member") url += "m/";
else if (itemType === "group") url += "g/";
url += item.id;
return url;
}
function skipToNextItem(event, index: number) {
let el;
if (event.key === "ArrowDown") {
if (index + 1 < indexStart + itemsPerPage && index + 1 < fullLength) el = document.getElementById(`${itemType}-card-${index + 1}`);
else el = document.getElementById(`${itemType}-card-${indexStart}`);
}
if (event.key === "ArrowUp") {
if (index - 1 >= indexStart) el = document.getElementById(`${itemType}-card-${index - 1}`);
else if (fullLength <= indexStart + itemsPerPage) el = document.getElementById(`${itemType}-card-${fullLength - 1}`);
else el = document.getElementById(`${itemType}-card-${indexStart + itemsPerPage - 1}`);
}
if (el) {
event.preventDefault();
el.focus();
}
}
let isOpen = {};
function toggleCard(index: string) {
isOpen[index] = isOpen[index] || {};
if (isOpen[index] === true) {
isOpen[index] = false;
} else {
isOpen[index] = true;
}
}
function getShortLink(id: string) {
let url = "https://pk.mt"
if (itemType === "member") url += "/m/"
else if (itemType === "group") url += "/g/"
url += id;
return url;
}
let copiedArray = [];
async function copyShortLink(index: number, id: string, event?) {
if (event) {
if (event.key !== "Tab") event.preventDefault();
event.stopPropagation();
let ctrlDown = event.ctrlKey||event.metaKey; // mac support
if (!(ctrlDown && event.key === "c") && event.key !== "Enter") return;
}
try {
await navigator.clipboard.writeText(getShortLink(id));
copiedArray[index] = true;
await new Promise(resolve => setTimeout(resolve, 2000));
copiedArray[index] = false;
} catch (error) {
console.log(error);
}
}
</script>
{#if !openByDefault && (settings && settings.accessibility ? (!settings.accessibility.expandedcards && !settings.accessibility.pagelinks) : true)}
<div class="mb-3">
{#each list as item, index (item.uuid)}
<Card>
<h2 class="accordion-header">
<button class="w-100 accordion-button collapsed card-header" id={`${itemType}-card-${indexStart + index}`} on:click={() => toggleCard(item.uuid)} on:keydown={(e) => skipToNextItem(e, indexStart + index)}>
<CardsHeader {item} {sortBy} {searchBy}>
<div slot="icon" style="cursor: pointer;" id={`${itemType}-copy-${item.id}-${indexStart + index}`} on:click|stopPropagation={() => copyShortLink(indexStart + index, item.id)} on:keydown={(e) => copyShortLink(indexStart + index, item.id, e)} tabindex={0} >
{#if isPublic || item.privacy.visibility === "public"}
{#if itemType === "member"}
<FaUserCircle />
{:else if itemType === "group"}
<FaUsers />
{/if}
{:else}
<FaLock />
{/if}
</div>
</CardsHeader>
<Tooltip placement="top" target={`${itemType}-copy-${item.id}-${indexStart + index}`}>{copiedArray[indexStart + index] ? "Copied!" : "Copy public link"}</Tooltip>
</button>
</h2>
<Collapse isOpen={isOpen[item.uuid]}>
<CardBody>
{#if itemType === "member"}
<MemberBody on:update on:deletion bind:isPublic groups={groups} member={item} />
{:else if itemType === "group"}
<GroupBody on:update on:deletion bind:isPublic {members} group={item} />
{/if}
</CardBody>
</Collapse>
</Card>
{/each}
</div>
{:else if openByDefault || settings.accessibility.expandedcards}
{#each list as item, index (item.id + index)}
<Card class="mb-3">
<div class="accordion-button collapsed p-0" id={`${itemType}-card-${indexStart + index}`} on:keydown={(e) => skipToNextItem(e, indexStart + index)} tabindex={0}>
<CardHeader class="w-100">
<CardsHeader {item} {sortBy} {searchBy}>
<div slot="icon" style="cursor: pointer;" id={`${itemType}-copy-${item.id}-${indexStart + index}`} on:click|stopPropagation={() => copyShortLink(indexStart + index, item.id)} on:keydown|stopPropagation={(e) => copyShortLink(indexStart + index, item.id, e)} tabindex={0} >
{#if isPublic || item.privacy.visibility === "public"}
{#if itemType === "member"}
<FaUserCircle />
{:else if itemType === "group"}
<FaUsers />
{/if}
{:else}
<FaLock />
{/if}
</div>
</CardsHeader>
<Tooltip placement="top" target={`${itemType}-copy-${item.id}-${indexStart + index}`}>{copiedArray[indexStart + index] ? "Copied!" : "Copy public link"}</Tooltip>
</CardHeader>
</div>
<CardBody>
{#if itemType === "member"}
<MemberBody on:update on:deletion bind:isPublic groups={groups} member={item} />
{:else if itemType === "group"}
<GroupBody on:update on:deletion bind:isPublic {members} group={item} />
{/if}
</CardBody>
</Card>
{/each}
{:else}
<div class="my-3">
{#each list as item, index (item.id + index)}
<Card>
<a class="accordion-button collapsed" style="text-decoration: none;" href={getItemLink(item)} id={`${itemType}-card-${indexStart + index}`} on:keydown={(e) => skipToNextItem(e, indexStart + index)} use:link >
<CardsHeader {item}>
<div slot="icon" style="cursor: pointer;" id={`${itemType}-copy-${item.id}-${indexStart + index}`} on:click|stopPropagation={() => copyShortLink(indexStart + index, item.id)} on:keydown|stopPropagation={(e) => copyShortLink(indexStart + index, item.id, e)} tabindex={0} >
{#if isPublic || item.privacy.visibility === "public"}
{#if itemType === "member"}
<FaUserCircle />
{:else if itemType === "group"}
<FaUsers />
{/if}
{:else}
<FaLock />
{/if}
</div>
</CardsHeader>
<Tooltip placement="top" target={`${itemType}-copy-${item.id}-${indexStart + index}`}>{copiedArray[indexStart + index] ? "Copied!" : "Copy public link"}</Tooltip>
</a>
</Card>
{/each}
</div>
{/if}

View File

@@ -0,0 +1,194 @@
<script lang="ts">
import { tick } from 'svelte';
import { Row, Col, Modal, Image, Button, CardBody, ModalHeader, ModalBody } from 'sveltestrap';
import moment from 'moment';
import { toHTML } from 'discord-markdown';
import parseTimestamps from '../../api/parse-timestamps';
import resizeMedia from '../../api/resize-media';
import twemoji from 'twemoji';
import GroupEdit from './GroupEdit.svelte';
import Edit from './Edit.svelte';
import Privacy from './Privacy.svelte';
import ProxyTags from './ProxyTags.svelte';
import { Member, Group } from '../../api/types';
import { Link, useLocation } from 'svelte-navigator';
export let groups: Group[] = [];
export let member: Member;
export let isPublic: boolean = false;
export let isPage: boolean = false;
export let isMainDash = true;
let editMode: boolean = false;
let groupMode: boolean = false;
let htmlDescription: string;
$: if (member.description) {
htmlDescription = toHTML(parseTimestamps(member.description), {embed: true});
} else {
htmlDescription = "(no description)";
}
let htmlPronouns: string;
$: if (member.pronouns) {
htmlPronouns = toHTML(parseTimestamps(member.pronouns), {embed: true});
}
let settings = JSON.parse(localStorage.getItem("pk-settings"));
let descriptionElement: any;
let displayNameElement: any;
let pronounElement: any;
$: if (settings && settings.appearance.twemoji) {
if (descriptionElement) twemoji.parse(descriptionElement);
if (displayNameElement) twemoji.parse(displayNameElement);
if (pronounElement) twemoji.parse(pronounElement);
};
let bannerOpen = false;
const toggleBannerModal = () => (bannerOpen = !bannerOpen);
let privacyOpen = false;
const togglePrivacyModal = () => (privacyOpen = !privacyOpen);
let proxyOpen = false;
const toggleProxyModal = () => (proxyOpen = !proxyOpen);
let created = moment(member.created).format("MMM D, YYYY");
let birthday: string;
$: {member.birthday;
if (member.birthday) birthday = moment(member.birthday, "YYYY-MM-DD").format("MMM D, YYYY");
}
$: trimmedBirthday = birthday && birthday.endsWith(', 0004') ? trimmedBirthday = birthday.replace(', 0004', '') : birthday;
async function focus(el) {
await tick();
el.focus();
}
let location = useLocation()
let pathName = $location.pathname;
function getMemberPageUrl() {
let str: string;
if (pathName.startsWith("/dash")) str = "/dash";
else str = "/profile";
str += `/m/${member.id}`;
return str;
}
function getSystemPageUrl() {
let str: string;
if (pathName.startsWith("/dash")) str = "/dash";
else {
str = "/profile";
str += `/s/${member.system}`;
}
str += "?tab=members";
return str;
}
</script>
<CardBody style="border-left: 4px solid #{settings && settings.appearance.color_background ? isPage ? "" : member.color : member.color }; margin: -1rem">
{#if !editMode && !groupMode}
<Row>
{#if member.id}
<Col xs={12} lg={4} class="mb-2">
<b>ID:</b> {member.id}
</Col>
{/if}
{#if member.name}
<Col xs={12} lg={4} class="mb-2">
<b>Name:</b> {member.name}
</Col>
{/if}
{#if member.display_name}
<Col xs={12} lg={4} class="mb-2">
<b>Display Name:</b> <span bind:this={displayNameElement}>{member.display_name}</span>
</Col>
{/if}
{#if member.pronouns}
<Col xs={12} lg={4} class="mb-2">
<b>Pronouns:</b> <span bind:this={pronounElement}>{@html htmlPronouns}</span>
</Col>
{/if}
{#if member.birthday}
<Col xs={12} lg={4} class="mb-2">
<b>Birthday:</b> {trimmedBirthday}
</Col>
{/if}
{#if member.created}
<Col xs={12} lg={4} class="mb-2">
<b>Created:</b> {created}
</Col>
{/if}
{#if member.color}
<Col xs={12} lg={4} class="mb-2">
<b>Color:</b> {member.color}
</Col>
{/if}
{#if member.banner}
<Col xs={12} lg={4} class="mb-2">
<b>Banner:</b> <Button size="sm" color="secondary" on:click={toggleBannerModal} aria-label="view member banner">View</Button>
<Modal isOpen={bannerOpen} toggle={toggleBannerModal}>
<div slot="external" on:click={toggleBannerModal} style="height: 100%; width: max-content; max-width: 100%; margin-left: auto; margin-right: auto; display: flex;">
<img class="img-thumbnail d-block m-auto" src={member.banner} tabindex={0} alt={`Member ${member.name} banner (full size)`} use:focus/>
</div>
</Modal>
</Col>
{/if}
{#if member.privacy && !isPublic}
<Col xs={12} lg={4} class="mb-2">
<b>Privacy:</b> <Button size="sm" color="secondary" on:click={togglePrivacyModal} aria-label="edit member privacy">Edit</Button>
<Modal size="lg" isOpen={privacyOpen} toggle={togglePrivacyModal}>
<ModalHeader toggle={togglePrivacyModal}>
Edit privacy
</ModalHeader>
<ModalBody>
<Privacy on:update bind:member bind:privacyOpen/>
</ModalBody>
</Modal>
</Col>
{/if}
{#if member.proxy_tags && !isPublic}
<Col xs={12} lg={4} class="mb-2">
<b>Proxy Tags:</b> <Button size="sm" color="secondary" on:click={toggleProxyModal} aria-label="edit member proxy tags">Edit</Button>
<Modal size="lg" isOpen={proxyOpen} toggle={toggleProxyModal}>
<ModalHeader toggle={toggleProxyModal}>
Edit proxy tags
</ModalHeader>
<ModalBody>
<ProxyTags bind:member bind:proxyOpen/>
</ModalBody>
</Modal>
</Col>
{/if}
</Row>
<div class="my-2 mb-3 description" bind:this={descriptionElement}>
<b>Description:</b><br />
{@html htmlDescription && htmlDescription}
</div>
{#if (member.banner && ((settings && settings.appearance.banner_bottom) || !settings))}
<img on:click={toggleBannerModal} src={resizeMedia(member.banner, [1200, 480])} alt="member banner" class="w-100 mb-3 rounded" style="max-height: 13em; object-fit: cover; cursor: pointer"/>
{/if}
{#if !isPublic}
<Button style="flex: 0" color="primary" on:click={() => editMode = true} aria-label="edit member information">Edit</Button>
{#if isMainDash}<Button style="flex: 0" color="secondary" on:click={() => groupMode = true} aria-label="edit member groups">Groups</Button>{/if}
{/if}
{#if !isPage}
<Link to={getMemberPageUrl()}><Button style="flex: 0; {!isPublic && "float: right;"}" color="primary" tabindex={-1} aria-label="view member page">View page</Button></Link>
{:else}
<Link to={getSystemPageUrl()}><Button style="flex: 0; {!isPublic && "float: right;"}" color="primary" tabindex={-1} aria-label="view member's system">View system</Button></Link>
{/if}
{:else if editMode}
<Edit on:update on:deletion bind:member bind:editMode />
{:else if groupMode}
<GroupEdit on:updateMemberGroups bind:member bind:groups bind:groupMode />
{/if}
</CardBody>

View File

@@ -0,0 +1,240 @@
<script lang="ts">
import { createEventDispatcher } from 'svelte';
import { Card, CardHeader, CardTitle, Modal, Button, ListGroup, ListGroupItem, Input, Alert, Label, Spinner, Row, Col, Tooltip } from 'sveltestrap';
import { toHTML } from 'discord-markdown';
import twemoji from 'twemoji';
import { Link } from 'svelte-navigator';
import { autoresize } from 'svelte-textarea-autoresize';
import FaEdit from 'svelte-icons/fa/FaEdit.svelte'
import FaInfoCircle from 'svelte-icons/fa/FaInfoCircle.svelte'
import FaUsers from 'svelte-icons/fa/FaUsers.svelte'
import FaTimes from 'svelte-icons/fa/FaTimes.svelte'
import FaCheck from 'svelte-icons/fa/FaCheck.svelte'
import type { Group, Member} from '../../api/types';
import api from '../../api';
import default_avatar from '../../assets/default_avatar.png';
import resizeMedia from '../../api/resize-media';
export let member: Member;
export let searchBy: string;
export let sortBy: string;
export let groups: Group[];
export let isPublic = false;
export let isDash = false;
let input: Member = JSON.parse(JSON.stringify(member));
let view = "card";
let err: string[] = [];
let loading = false;
let success = false;
let settings = JSON.parse(localStorage.getItem("pk-settings"));
let htmlName: string;
$: htmlDesc = member.description && toHTML(member.description, { embed: true}) || "(no description)";
$: htmlDisplayName = member.display_name && toHTML(member.display_name);
$: htmlPronouns = member.pronouns && toHTML(member.pronouns, {embed: true});
let nameElement: any;
let descElement: any;
let dnElement: any;
let prnsElement: any;
$: if (member.name) {
if ((searchBy === "display name" || sortBy === "display name") && member.display_name) htmlName = toHTML(member.display_name);
else htmlName = toHTML(member.name);
}
if (settings && settings.appearance.twemoji) {
if (nameElement) twemoji.parse(nameElement);
if (descElement) twemoji.parse(descElement);
if (dnElement) twemoji.parse(dnElement);
if (prnsElement) twemoji.parse(prnsElement);
}
let avatarOpen = false;
const toggleAvatarModal = () => (avatarOpen = !avatarOpen);
$: icon_url = member.avatar_url ? member.avatar_url : default_avatar;
$: icon_url_resized = resizeMedia(icon_url);
let altText = `member ${member.name} avatar`;
let pageLink = isPublic ? `/profile/m/${member.id}` : `/dash/m/${member.id}`;
const dispatch = createEventDispatcher();
function update(member: Member) {
dispatch('update', member);
}
async function submit() {
let data = input;
err = [];
if (data.color && !/^#?[A-Fa-f0-9]{6}$/.test(input.color)) {
err.push(`"${data.color}" is not a valid color, the color must be a 6-digit hex code. (example: #ff0000)`);
} else if (data.color) {
if (data.color.startsWith("#")) {
data.color = input.color.slice(1, input.color.length);
}
}
// trim all string fields
Object.keys(data).forEach(k => data[k] = typeof data[k] == "string" ? data[k].trim() : data[k]);
err = err;
if (err.length > 0) return;
loading = true;
try {
let res = await api().members(member.id).patch({data});
update({...member, ...res});
success = true;
} catch (error) {
console.log(error);
err.push(error.message);
err = err;
}
loading = false;
}
$: groupList = groups && groups.filter(g => g.members && g.members.includes(member.uuid)).sort((a, b) => a.name.localeCompare(b.name)) || [];
let listGroupElements = [];
$: if (view !== "edit") {
err = [];
success = false;
}
</script>
<Card class="mb-4 pb-3" style={`height: 27.5rem; ${member.color && `border-bottom: 4px solid #${member.color}`}`}>
<CardHeader>
<CardTitle class="d-flex justify-content-center align-middle w-100 mb-0">
<div class="icon d-inline-block">
<slot name="icon" />
</div>
<span bind:this={nameElement} style="vertical-align: middle; margin-bottom: 0;">{@html htmlName} ({member.id})</span>
</CardTitle>
</CardHeader>
<div class="card-body d-block hide-scrollbar" style="flex: 1; overflow: auto;">
{#if view === "card"}
<img style="cursor: pointer;" tabindex={0} on:keydown={(event) => {if (event.key === "Enter") {avatarOpen = true}}} on:click={toggleAvatarModal} class="rounded avatar mx-auto w-100 h-auto mb-2" src={icon_url_resized} alt={altText}/>
<Modal isOpen={avatarOpen} toggle={toggleAvatarModal}>
<div slot="external" on:click={toggleAvatarModal} style="height: 100%; max-width: 640px; width: 100%; margin-left: auto; margin-right: auto; display: flex;">
<img class="d-block m-auto img-thumbnail" src={icon_url} alt="Member avatar" tabindex={0}/>
</div>
</Modal>
{#if member.display_name}
<div class="text-center" bind:this={dnElement}><b>{@html htmlDisplayName}</b></div>
{/if}
{#if member.pronouns}
<div class="text-center" bind:this={prnsElement}>{@html htmlPronouns}</div>
{/if}
<hr style="min-height: 1px;"/>
<div bind:this={descElement}>
{@html htmlDesc}
</div>
<hr style="min-height: 1px;"/>
<Row>
<Col xs={4} class="align-items-center justify-content-center">
{#if !isPublic}<Button color="link" class="mt-2" on:click={() => {view = "edit"}} id={`member-${member.uuid}-edit-button-card`}><FaEdit/></Button>{/if}
</Col>
<Col xs={4} class="align-items-center justify-content-center">
{#if !isPublic && isDash}<Button color="link" class="mt-2 text-reset" on:click={() => {view = "groups"}} id={`member-${member.uuid}-groups-button-card`}><FaUsers/></Button>{/if}
</Col>
<Col xs={4} class="align-items-center justify-content-center">
<Link tabindex={-1} to={pageLink} class="text-reset"><Button color="link" class="mt-2 w-100 text-reset" id={`member-${member.uuid}-view-button-card`}><FaInfoCircle/></Button></Link>
</Col>
{#if !isPublic}<Tooltip target={`member-${member.uuid}-edit-button-card`} placement="bottom">Edit member</Tooltip>{/if}
{#if !isPublic && isDash}<Tooltip target={`member-${member.uuid}-groups-button-card`} placement="bottom">View groups</Tooltip>{/if}
<Tooltip target={`member-${member.uuid}-view-button-card`} placement="bottom">View page</Tooltip>
</Row>
{:else if view === "groups"}
{#if groupList.length > 0}
<b class="d-block text-center w-100">Groups</b>
<hr style="min-height: 1px"/>
<ListGroup>
{#each groupList as group, index (group.id)}
<ListGroupItem class="d-flex"><span bind:this={listGroupElements[index]}><span><b>{@html toHTML(group.name)}</b> (<code>{group.id}</code>)</span></ListGroupItem>
{/each}
</ListGroup>
{:else}
<b class="d-block text-center w-100">This member is in no groups.</b>
{/if}
<hr style="min-height: 1px"/>
<Row>
<Col xs={4} class="align-items-center justify-content-center">
<Button color="link" class="mt-2" on:click={() => {view = "edit"}} id={`member-${member.uuid}-edit-button-groups`}><FaEdit/></Button>
</Col>
<Col xs={4} class="align-items-center justify-content-center">
<Button color="link" class="mt-2 text-reset" on:click={() => {view = "card"}} id={`member-${member.uuid}-back-button-groups`}><FaTimes/></Button>
</Col>
<Col xs={4} class="align-items-center justify-content-center">
<Link tabindex={-1} to={`./m/${member.id}`} class="text-reset"><Button color="link" class="mt-2 w-100 text-reset" id={`member-${member.uuid}-view-button-groups`}><FaInfoCircle/></Button></Link>
</Col>
<Tooltip target={`member-${member.uuid}-edit-button-groups`} placement="bottom">Edit member</Tooltip>
<Tooltip target={`member-${member.uuid}-back-button-groups`} placement="bottom">Back to info</Tooltip>
<Tooltip target={`member-${member.uuid}-view-button-groups`} placement="bottom">View page</Tooltip>
</Row>
{:else if view === "edit"}
<Label>Name:</Label>
<Input class="mb-2" bind:value={input.name} maxlength={100} type="text" placeholder={member.name} aria-label="member name"/>
<Label>Avatar url:</Label>
<Input bind:value={input.avatar_url} maxlength={256} type="url" placeholder={member.avatar_url} aria-label="member avatar url"/>
<hr style="min-height: 1px" />
<Label>Display name:</Label>
<textarea class="form-control mb-2" style="resize: none; height: 1em" bind:value={input.display_name} maxlength={100} type="text" placeholder={member.display_name} aria-label="member display name" />
<Label>Pronouns:</Label>
<textarea class="form-control" style="resize: none; height: 1em" bind:value={input.pronouns} maxlength={100} type="text" placeholder={member.pronouns} aria-label="member pronouns" />
<hr style="min-height: 1px" />
<Label>Description:</Label>
<textarea class="form-control" style="resize: none; overflow: hidden;" bind:value={input.description} maxlength={1000} use:autoresize placeholder={member.description} aria-label="member description"/>
<hr style="min-height: 1px" />
<Label>Color:</Label>
<Row>
<Col xs={9}>
<Input type="text" bind:value={input.color} aria-label="member color value"/>
</Col>
<Col class="p-0">
<Input class="p-0" on:change={(e) => input.color = e.target.value.slice(1, 7)} type="color" aria-label="color picker" />
</Col>
</Row>
<hr style="min-height: 1px" />
{#if success}
<Alert class="m-0 mb-2" color="success">Member edited!</Alert>
{/if}
{#if err}
{#each err as errorMessage}
<Alert class="m-0 mb-2" color="danger">{@html errorMessage}</Alert>
{/each}
{/if}
<Row>
<Col xs={4} class="align-items-center justify-content-center">
<Button disabled={loading} color="link" class="mt-2 text-danger" style="height: 3rem;" on:click={() => {view = "card"}} id={`member-${member.uuid}-back-button-edit`}><FaTimes/></Button>
</Col>
<Col xs={4}>
</Col>
<Col xs={4} class="align-items-center justify-content-center">
<Button disabled={loading} color="link" class="mt-2 text-success" on:click={submit} id={`member-${member.uuid}-submit-button-edit`}><FaCheck/></Button>
</Col>
<Tooltip target={`member-${member.uuid}-back-button-edit`} placement="bottom">Go back</Tooltip>
<Tooltip target={`member-${member.uuid}-submit-button-edit`} placement="bottom">Submit edit</Tooltip>
</Row>
{/if}
</div>
</Card>
<style>
.hide-scrollbar::-webkit-scrollbar {
display: none;
}
.hide-scrollbar {
scrollbar-width: none;
}
</style>

View File

@@ -0,0 +1,188 @@
<script lang="ts">
import { Row, Col, Input, Button, Label, Alert, Spinner, Modal, ModalHeader, ModalBody } from 'sveltestrap';
import { createEventDispatcher, tick } from 'svelte';
import { autoresize } from 'svelte-textarea-autoresize';
import moment from 'moment';
import { Member } from '../../api/types'
import api from '../../api';
const descriptions: string[] = JSON.parse(localStorage.getItem("pk-config"))?.description_templates;
let loading: boolean = false;
export let member: Member;
export let editMode: boolean;
let err: string[] = [];
let success = false;
let input: Member = JSON.parse(JSON.stringify(member));
const dispatch = createEventDispatcher();
function deletion() {
dispatch('deletion', member.id);
}
function update(member: Member) {
dispatch('update', member);
}
async function submit() {
let data = input;
err = [];
if (data.color && !/^#?[A-Fa-f0-9]{6}$/.test(input.color)) {
err.push(`"${data.color}" is not a valid color, the color must be a 6-digit hex code. (example: #ff0000)`);
} else if (data.color) {
if (data.color.startsWith("#")) {
data.color = input.color.slice(1, input.color.length);
}
}
if (data.birthday) {
let allowedFormats = ['YYYY-MM-DD','YYYY-M-D', 'YYYY-MM-D', 'YYYY-M-DD'];
// replace all brackets with dashes
if (data.birthday.includes('/')) {
data.birthday = data.birthday.replaceAll('/', '-');
}
// add a generic year if there's no year included
// NOTE: for some reason moment parses a date with only a month and day as a YEAR and a month
// so I'm just checking by the amount of dashes in the string
if (data.birthday.split('-').length - 1 === 1) {
data.birthday = '0004-' + data.birthday;
}
// try matching the birthday to the YYYY-MM-DD format
if (moment(data.birthday, allowedFormats, true).isValid()) {
// convert the format to have months and days as double digits.
data.birthday = moment(data.birthday, 'YYYY-MM-DD').format('YYYY-MM-DD');
} else {
err.push(`${data.birthday} is not a valid date, please use the following format: YYYY-MM-DD. (example: 2019-07-21)`);
}
}
// trim all string fields
Object.keys(data).forEach(k => data[k] = typeof data[k] == "string" ? data[k].trim() : data[k]);
err = err;
if (err.length > 0) return;
loading = true;
try {
let res = await api().members(member.id).patch({data});
update({...member, ...res});
success = true;
} catch (error) {
console.log(error);
err.push(error.message);
err = err;
}
loading = false;
}
let deleteOpen: boolean = false;
const toggleDeleteModal = () => deleteOpen = !deleteOpen;
let deleteInput: string;
let deleteErr: string;
async function submitDelete() {
deleteErr = null;
if (!deleteInput) {
deleteErr = "Please type out the member ID.";
return;
}
if (deleteInput.trim().toLowerCase() !== member.id) {
deleteErr = "This member's ID does not match the provided ID.";
return;
}
loading = true;
try {
await api().members(member.id).delete();
deleteErr = null;
toggleDeleteModal();
loading = false;
deletion();
} catch (error) {
console.log(error);
deleteErr = error.message;
loading = false;
}
}
async function focus(el) {
await tick();
el.focus();
}
</script>
{#each err as error}
<Alert fade={false} color="danger">{@html error}</Alert>
{/each}
{#if success}
<Alert fade={false} color="success">Member information updated!</Alert>
{/if}
<Row>
<Col xs={12} lg={4} class="mb-2">
<Label>Name:</Label>
<Input bind:value={input.name} maxlength={100} type="text" placeholder={member.name} aria-label="member name"/>
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Display name:</Label>
<textarea class="form-control" style="resize: none; height: 1em" bind:value={input.display_name} maxlength={100} type="text" placeholder={member.display_name} aria-label="member display name" />
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Pronouns:</Label>
<textarea class="form-control" style="resize: none; height: 1em" bind:value={input.pronouns} maxlength={100} type="text" placeholder={member.pronouns} aria-label="member pronouns" />
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Birthday:</Label>
<Input bind:value={input.birthday} maxlength={100} type="text" placeholder={member.birthday} aria-label="member birthday" />
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Color:</Label>
<Input bind:value={input.color} type="text" placeholder={member.color} aria-label="member color" />
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Avatar url:</Label>
<Input bind:value={input.avatar_url} maxlength={256} type="url" placeholder={member.avatar_url} aria-label="member avatar url"/>
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Banner url:</Label>
<Input bind:value={input.banner} maxlength={256} type="url" placeholder={member.banner} aria-label="member banner url"/>
</Col>
</Row>
<div class="my-2">
<b>Description:</b><br />
{#if descriptions.length > 0 && descriptions[0].trim() != ""}
<Button size="sm" color="primary" on:click={() => input.description = descriptions[0]} aria-label="use template 1">Template 1</Button>
{/if}
{#if descriptions.length > 1 && descriptions[1].trim() != ""}
<Button size="sm" color="primary" on:click={() => input.description = descriptions[1]} aria-label="use template 2">Template 2</Button>
{/if}
{#if descriptions.length > 2 && descriptions[2].trim() != ""}
<Button size="sm" color="primary" on:click={() => input.description = descriptions[2]} aria-label="use template 3">Template 3</Button>
{/if}
<br>
<textarea class="form-control" bind:value={input.description} maxlength={1000} use:autoresize placeholder={member.description} aria-label="member description"/>
</div>
{#if !loading}<Button style="flex: 0" color="primary" on:click={submit} aria-label="submit edits" >Submit</Button> <Button style="flex: 0" color="secondary" on:click={() => editMode = false} aria-label="cancel edits">Back</Button><Button style="flex: 0; float: right;" color="danger" on:click={toggleDeleteModal} aria-label="delete member">Delete</Button>
{:else}<Button style="flex: 0" color="primary" disabled aria-label="submit edits"><Spinner size="sm"/></Button> <Button style="flex: 0" color="secondary" disabled aria-label="cancel edits">Back</Button><Button style="flex: 0; float: right;" color="danger" disabled aria-label="delete member">Delete</Button>{/if}
<Modal size="lg" isOpen={deleteOpen} toggle={toggleDeleteModal}>
<ModalHeader toggle={toggleDeleteModal}>
Delete member
</ModalHeader>
<ModalBody>
{#if deleteErr}<Alert color="danger">{deleteErr}</Alert>{/if}
<Label>If you're sure you want to delete this member, type out the member ID (<code>{member.id}</code>) below.</Label>
<input class="mb-3 form-control" bind:value={deleteInput} maxlength={7} placeholder={member.id} aria-label={`type out the member id ${member.id} to confirm deletion`} use:focus>
{#if !loading}<Button style="flex 0" color="danger" on:click={submitDelete} aria-label="confirm delete">Delete</Button> <Button style="flex: 0" color="secondary" on:click={toggleDeleteModal} aria-label="cancel deletion">Back</Button>
{:else}<Button style="flex 0" color="danger" disabled><Spinner size="sm"/></Button> <Button style="flex: 0" color="secondary" disabled aria-label="cancel deletion">Back</Button>
{/if}
</ModalBody>
</Modal>

View File

@@ -0,0 +1,146 @@
<script lang="ts">
import { Row, Col, Button, Alert, ListGroup, ListGroupItem, Spinner } from 'sveltestrap';
import ListPagination from "../common/ListPagination.svelte";
import twemoji from "twemoji";
import Svelecte, { addFormatter } from 'svelecte';
import { toHTML } from 'discord-markdown';
import FaFolderOpen from 'svelte-icons/fa/FaFolderOpen.svelte'
import FaFolderPlus from 'svelte-icons/fa/FaFolderPlus.svelte'
import FaFolderMinus from 'svelte-icons/fa/FaFolderMinus.svelte'
import { Member, Group } from '../../api/types';
import api from '../../api';
export let member: Member;
export let groups: Group[] = [];
let loading: boolean = false;
let err: string;
export let groupMode: boolean = true;
let groupsWithMember: Group[];
let groupsWithoutMember: Group[];
let groupsWithMemberSelection: any[];
let groupsWithoutMemberSelection: any[];
let groupsToBeAdded: any[];
let groupsToBeRemoved: any[];
let currentPage = 1;
let smallPages = true;
updateGroupLists();
function updateGroupLists() {
groupsWithMember = groups.filter(group => group.members && group.members.includes(member.uuid));
groupsWithMember.sort((a, b) => a.name.localeCompare(b.name));
groupsWithoutMember = groups.filter(group => group.members && !group.members.includes(member.uuid));
groupsWithoutMember.sort((a, b) => a.name.localeCompare(b.name));
groupsWithMemberSelection = groupsWithMember.map(function(group) { return {name: group.name, shortid: group.id, id: group.uuid, members: group.members, display_name: group.display_name}; }).sort((a, b) => a.name.localeCompare(b.name));
groupsWithoutMemberSelection = groupsWithoutMember.map(function(group) { return {name: group.name, shortid: group.id, id: group.uuid, members: group.members, display_name: group.display_name}; }).sort((a, b) => a.name.localeCompare(b.name));
}
$: indexOfLastItem = currentPage * 10;
$: indexOfFirstItem = indexOfLastItem - 10;
$: pageAmount = Math.ceil(groupsWithMember && groupsWithMember.length / 10);
$: finalGroupsList = groupsWithMember && groupsWithMember.slice(indexOfFirstItem, indexOfLastItem);
let settings = JSON.parse(localStorage.getItem('pk-settings'));
let listGroupElements: any[] = [];
$: if (settings && settings.appearance.twemoji) {
if (listGroupElements && listGroupElements.length > 0) {
listGroupElements.forEach(element => element && twemoji.parse(element));
};
}
function groupListRenderer(item: any) {
return `${item.name} (<code>${item.shortid}</code>)`;
}
addFormatter({
'member-list': groupListRenderer
});
async function submitAdd() {
let data = groupsToBeAdded;
try {
loading = true;
await api().members(member.id).groups.add.post({data});
groups.forEach(group => data.includes(group.uuid) && group.members.push(member.uuid));
updateGroupLists();
err = null;
groupsToBeAdded = [];
loading = false;
} catch (error) {
console.log(error);
err = error.message;
loading = false;
}
}
async function submitRemove() {
let data = groupsToBeRemoved;
try {
loading = true;
await api().members(member.id).groups.remove.post({data});
groups.forEach(group => {if (data.includes(group.uuid)) group.members = group.members.filter(m => m !== member.uuid)});
updateGroupLists();
err = null;
groupsToBeRemoved = [];
loading = false;
} catch (error) {
console.log(error);
err = error.message;
loading = false;
}
}
</script>
{#if err}
<Alert color="danger">{err}</Alert>
{/if}
<Row>
<Col xs={12} lg={6} class="text-center mb-3">
<h5><div class="icon d-inline-block">
<FaFolderOpen />
</div>Current Groups
{#if finalGroupsList && finalGroupsList.length > 0}
({groupsWithMember.length} total)
{/if}
</h5>
<ListPagination bind:currentPage bind:pageAmount bind:smallPages/>
{#if finalGroupsList && finalGroupsList.length > 0}
<ListGroup>
{#each finalGroupsList as group, index (group.id)}
<ListGroupItem class="d-flex"><span bind:this={listGroupElements[index]} class="d-flex justify-content-between flex-grow-1"><span><b>{group.name}</b> (<code>{group.id}</code>)</span> <span>{@html group.display_name ? `${toHTML(group.display_name)}` : ""}</span></span></ListGroupItem>
{/each}
</ListGroup>
{:else}
<p>This member is inside no groups.</p>
<p>You can add groups in this menu!</p>
{/if}
</Col>
<Col xs={12} lg={6} class="text-center mb-3">
<h5><div class="icon d-inline-block">
<FaFolderPlus />
</div>Add to Groups</h5>
<Svelecte renderer="member-list" disableHighlight bind:value={groupsToBeAdded} options={groupsWithoutMemberSelection} multiple />
{#if !loading && groupsToBeAdded && groupsToBeAdded.length > 0}
<Button class="w-100 mt-2" color="primary" on:click={submitAdd} aria-label="add groups to member">Add</Button>{:else}
<Button class="w-100 mt-2" color="primary" disabled aria-label="add groups to member">{#if loading}<Spinner size="sm" />{:else}Add{/if}</Button>
{/if}
<hr/>
<h5><div class="icon d-inline-block">
<FaFolderMinus />
</div>Remove from Groups</h5>
<Svelecte renderer="member-list" disableHighlight bind:value={groupsToBeRemoved} options={groupsWithMemberSelection} multiple />
{#if !loading && groupsToBeRemoved && groupsToBeRemoved.length > 0}
<Button class="w-100 mt-2" color="primary" on:click={submitRemove} aria-label="remove groups from member">Remove</Button>{:else}
<Button class="w-100 mt-2" color="primary" disabled aria-label="remove groups from member">{#if loading}<Spinner size="sm" />{:else}Remove{/if}</Button>
{/if}
</Col>
</Row>
<Button style="flex: 0" color="secondary" on:click={() => groupMode = false} aria-label="back to member card">Back</Button>

View File

@@ -0,0 +1,254 @@
<script lang="ts">
import { Accordion, AccordionItem, Row, Col, Input, Button, Label, Alert, Spinner, CardTitle, InputGroup } from 'sveltestrap';
import { createEventDispatcher } from 'svelte';
import { autoresize } from 'svelte-textarea-autoresize';
import moment from 'moment';
import FaPlus from 'svelte-icons/fa/FaPlus.svelte';
import { Member } from '../../api/types';
import api from '../../api';
const descriptions: string[] = JSON.parse(localStorage.getItem("pk-config"))?.description_templates;
let err: string[] = [];
let message: string;
let loading: boolean = false;
let privacyMode: boolean = false;
let proxyTagMode: boolean = false;
let defaultMember = {
privacy: {
visibility: "public",
metadata_privacy: "public",
description_privacy: "public",
pronoun_privacy: "public",
birthday_privacy: "public",
name_privacy: "public",
avatar_privacy: "public"
},
proxy_tags: [
{
prefix: "",
suffix: ""
}
]
};
// creating a deep copy here so that defaultMember doesn't get updated too
let input: Member = JSON.parse(JSON.stringify(defaultMember));
const dispatch = createEventDispatcher();
function create(data: Member) {
dispatch('create', data);
}
async function submit() {
let data = input;
message = "";
err = [];
if (input.proxy_tags.some(tag => tag.prefix && tag.suffix && tag.prefix.length + tag.suffix.length + 4 > 100)) {
err.push("One of your proxy tags is too long (prefix + 'text' + suffix must be shorter than 100 characters). Please shorten this tag, or remove it.");
}
if (data.color && !/^#?[A-Fa-f0-9]{6}$/.test(input.color)) {
err.push(`"${data.color}" is not a valid color, the color must be a 6-digit hex code. (example: #ff0000)`);
} else if (data.color) {
if (data.color.startsWith("#")) {
data.color = input.color.slice(1, input.color.length);
}
}
if (data.birthday) {
let allowedFormats = ['YYYY-MM-DD','YYYY-M-D', 'YYYY-MM-D', 'YYYY-M-DD'];
// replace all brackets with dashes
if (data.birthday.includes('/')) {
data.birthday = data.birthday.replaceAll('/', '-');
}
// add a generic year if there's no year included
// NOTE: for some reason moment parses a date with only a month and day as a YEAR and a month
// so I'm just checking by the amount of dashes in the string
if (data.birthday.split('-').length - 1 === 1) {
data.birthday = '0004-' + data.birthday;
}
// try matching the birthday to the YYYY-MM-DD format
if (moment(data.birthday, allowedFormats, true).isValid()) {
// convert the format to have months and days as double digits.
data.birthday = moment(data.birthday, 'YYYY-MM-DD').format('YYYY-MM-DD');
} else {
err.push(`${data.birthday} is not a valid date, please use the following format: YYYY-MM-DD. (example: 2019-07-21)`);
}
}
// trim all string fields
Object.keys(data).forEach(k => data[k] = typeof data[k] == "string" ? data[k].trim() : data[k]);
err = err;
if (err.length > 0) return;
loading = true;
try {
let res = await api().members().post({data});
create(res);
input = JSON.parse(JSON.stringify(defaultMember));
message = `Member ${data.name} successfully created!`
err = [];
loading = false;
} catch (error) {
console.log(error);
err.push(error.message);
err = err;
loading = false;
}
}
</script>
<Accordion class="mb-3">
<AccordionItem>
<CardTitle slot="header" style="margin-top: 0px; margin-bottom: 0px; outline: none; align-items: center;" class="d-flex align-middle w-100 p-2">
<div class="icon d-inline-block">
<FaPlus/>
</div>
<span style="vertical-align: middle;">Add new Member</span>
</CardTitle>
{#if message}
<Alert color="success">{@html message}</Alert>
{/if}
{#each err as error}
<Alert color="danger">{@html error}</Alert>
{/each}
<Row>
<Col xs={12} lg={4} class="mb-2">
<Label>Name:</Label>
<Input bind:value={input.name} maxlength={100} type="text" placeholder={input.name} />
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Display name:</Label>
<textarea class="form-control" style="resize: none; height: 1em" bind:value={input.display_name} maxlength={100} type="text" placeholder={input.display_name} />
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Pronouns:</Label>
<textarea class="form-control" style="resize: none; height: 1em" bind:value={input.pronouns} maxlength={100} type="text" placeholder={input.pronouns} />
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Birthday:</Label>
<Input bind:value={input.birthday} maxlength={100} type="text" placeholder={input.birthday} />
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Color:</Label>
<Input bind:value={input.color} type="text" placeholder={input.color}/>
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Avatar url:</Label>
<Input bind:value={input.avatar_url} maxlength={256} type="url" placeholder={input.avatar_url}/>
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Banner url:</Label>
<Input bind:value={input.banner} maxlength={256} type="url" placeholder={input.banner}/>
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Privacy:</Label>
<Button class="w-100" color="secondary" on:click={() => privacyMode = !privacyMode}>Toggle privacy</Button>
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Proxy tags:</Label>
<Button class="w-100" color="secondary" on:click={() => proxyTagMode = !proxyTagMode}>Toggle proxy tags</Button>
</Col>
</Row>
{#if privacyMode}
<hr/>
<b>Privacy:</b>
<Row>
<Col xs={12} lg={4} class="mb-3">
<Label>Description:</Label>
<Input type="select" bind:value={input.privacy.description_privacy}>
<option default>public</option>
<option>private</option>
</Input>
</Col>
<Col xs={12} lg={4} class="mb-3">
<Label>Name:</Label>
<Input type="select" bind:value={input.privacy.name_privacy}>
<option default>public</option>
<option>private</option>
</Input>
</Col>
<Col xs={12} lg={4} class="mb-3">
<Label>Avatar:</Label>
<Input type="select" bind:value={input.privacy.avatar_privacy}>
<option default>public</option>
<option>private</option>
</Input>
</Col>
<Col xs={12} lg={4} class="mb-3">
<Label>Birthday:</Label>
<Input type="select" bind:value={input.privacy.birthday_privacy}>
<option default>public</option>
<option>private</option>
</Input>
</Col>
<Col xs={12} lg={4} class="mb-3">
<Label>Pronouns:</Label>
<Input type="select" bind:value={input.privacy.pronoun_privacy}>
<option default>public</option>
<option>private</option>
</Input>
</Col>
<Col xs={12} lg={4} class="mb-3">
<Label>Visibility:</Label>
<Input type="select" bind:value={input.privacy.visibility}>
<option default>public</option>
<option>private</option>
</Input>
</Col>
<Col xs={12} lg={4} class="mb-3">
<Label>Metadata:</Label>
<Input type="select" bind:value={input.privacy.metadata_privacy}>
<option default>public</option>
<option>private</option>
</Input>
</Col>
</Row>
{/if}
{#if proxyTagMode}
<hr/>
<b>Proxy tags:</b>
<Row class="mb-2">
{#each input.proxy_tags as proxyTag, index (index)}
<Col xs={12} lg={4} class="mb-2">
<InputGroup>
<Input style="resize: none; height: 1em" type="textarea" bind:value={proxyTag.prefix} />
<Input disabled value="text"/>
<Input style="resize: none; height: 1em" type="textarea" bind:value={proxyTag.suffix}/>
</InputGroup>
</Col>
{/each}
<Col xs={12} lg={4} class="mb-2">
<Button class="w-100" color="secondary" on:click={() => {input.proxy_tags.push({prefix: "", suffix: ""}); input.proxy_tags = input.proxy_tags;}}>New</Button>
</Col>
</Row>
{/if}
<hr/>
<div class="my-2">
<b>Description:</b><br />
{#if descriptions.length > 0 && descriptions[0].trim() != ""}
<Button size="sm" color="primary" on:click={() => input.description = descriptions[0]}>Template 1</Button>
{/if}
{#if descriptions.length > 1 && descriptions[1].trim() != ""}
<Button size="sm" color="primary" on:click={() => input.description = descriptions[1]}>Template 2</Button>
{/if}
{#if descriptions.length > 2 && descriptions[2].trim() != ""}
<Button size="sm" color="primary" on:click={() => input.description = descriptions[2]}>Template 3</Button>
{/if}
<br>
<textarea class="form-control" bind:value={input.description} maxlength={1000} use:autoresize placeholder={input.description}/>
</div>
{#if !loading && input.name}<Button style="flex: 0" color="primary" on:click={submit}>Submit</Button>
{:else if !input.name }<Button style="flex: 0" color="primary" disabled>Submit</Button>
{:else}<Button style="flex: 0" color="primary" disabled><Spinner size="sm"/></Button>{/if}
</AccordionItem>
</Accordion>

View File

@@ -0,0 +1,89 @@
<script lang="ts">
import { tick, createEventDispatcher } from "svelte";
import { Col, Row, Input, Label, Button, Alert, Spinner } from "sveltestrap";
import { Member, MemberPrivacy } from '../../api/types';
import api from '../../api';
export let privacyOpen: boolean;
export let member: Member;
const togglePrivacyModal = () => (privacyOpen = !privacyOpen);
let err: string;
let loading = false;
let success = false;
function changeAll(e: Event) {
const target = e.target as HTMLInputElement;
Object.keys(privacy).forEach(x => privacy[x] = target.value);
}
const dispatch = createEventDispatcher();
function update(member) {
dispatch('update', member);
}
// I can't use the hacked together Required<T> type from the bulk privacy here
// that breaks updating the displayed privacy after submitting
// but there's not really any way for any privacy fields here to be missing
let privacy = member.privacy;
const privacyNames: { [P in keyof MemberPrivacy]-?: string; } = {
avatar_privacy: "Avatar",
birthday_privacy: "Birthday",
description_privacy: "Description",
metadata_privacy: "Metadata",
name_privacy: "Name",
pronoun_privacy: "Pronouns",
visibility: "Visibility",
};
async function submit() {
loading = true;
const data: Member = {privacy: privacy};
try {
let res = await api().members(member.id).patch({data});
update({...member, ...res});
success = true;
} catch (error) {
console.log(error);
err = error.message;
}
loading = false;
}
async function focus(el) {
await tick();
el.focus();
}
</script>
{#if err}
<Alert color="danger">{err}</Alert>
{/if}
{#if success}
<Alert color="success">Member privacy updated!</Alert>
{/if}
<Label><b>Set all to:</b></Label>
<select class="form-control" on:change={(e) => changeAll(e)} aria-label="set all to" use:focus>
<option>public</option>
<option>private</option>
</select>
<hr/>
<Row>
{#each Object.keys(privacy) as x}
<Col xs={12} lg={6} class="mb-3">
<Label>{privacyNames[x]}:</Label>
<Input type="select" bind:value={privacy[x]} aria-label={`group ${privacyNames[x]} privacy`}>
<option default={privacy[x] === "public"}>public</option>
<option default={privacy[x] === "private"}>private</option>
</Input>
</Col>
{/each}
</Row>
{#if !loading}<Button style="flex: 0" color="primary" on:click={submit} aria-label="submit privacy edits">Submit</Button> <Button style="flex: 0" color="secondary" on:click={togglePrivacyModal} aria-label="cancel privacy edits">Back</Button>
{:else}<Button style="flex: 0" color="primary" disabled aria-label="submit privacy edits"><Spinner size="sm"/></Button> <Button style="flex: 0" color="secondary" disabled aria-label="cancel privacy edits">Back</Button>
{/if}

View File

@@ -0,0 +1,67 @@
<script lang="ts">
import {tick } from "svelte";
import { Col, Row, Input, Label, Button, Alert, Spinner, InputGroup } from "sveltestrap";
import { Member } from '../../api/types';
import api from '../../api';
let loading: boolean;
export let proxyOpen: boolean;
export let member: Member;
const toggleProxyModal = () => (proxyOpen = !proxyOpen);
let err: string;
let input = member.proxy_tags;
async function submit() {
err = null;
if (input.some(tag => tag.prefix && tag.suffix && tag.prefix.length + tag.suffix.length + 4 > 100)) {
err = "One of your proxy tags is too long (prefix + 'text' + suffix must be shorter than 100 characters). Please shorten this tag, or remove it."
return;
}
let data: Member = {proxy_tags: input};
loading = true;
try {
let res = await api().members(member.id).patch({data});
member = res;
err = null;
loading = false;
toggleProxyModal();
} catch (error) {
console.log(error);
err = error.message;
loading = false;
}
}
async function focus(el, first) {
if (first) {
await tick();
el.focus();
}
}
</script>
{#if err}
<Alert color="danger">{err}</Alert>
{/if}
<Row class="mb-2">
{#each input as proxyTag, index (index)}
<Col xs={12} lg={6} class="mb-2">
<InputGroup>
<textarea class="form-control" style="resize: none; height: 1em" bind:value={proxyTag.prefix} use:focus={index === 0 ? true : false} aria-label="proxy tag prefix"/>
<Input disabled value="text"/>
<Input style="resize: none; height: 1em" type="textarea" bind:value={proxyTag.suffix} aria-label="proxy tag suffix"/>
</InputGroup>
</Col>
{/each}
<Col xs={12} lg={6} class="mb-2">
<button class="w-100 btn btn-secondary" use:focus={member.proxy_tags.length > 0 ? false : true} on:click={() => {input.push({prefix: "", suffix: ""}); input = input;}}>New</button>
</Col>
</Row>
{#if !loading}<Button style="flex 0" color="primary" on:click={submit} aria-label="submit proxy tags">Submit</Button> <Button style="flex: 0" color="secondary" on:click={toggleProxyModal} aria-label="go back">Back</Button>
{:else}<Button style="flex 0" color="primary" disabled aria-label="submit proxy tags"><Spinner size="sm"/></Button> <Button style="flex: 0" color="secondary" disabled aria-label="go back">Back</Button>
{/if}

View File

@@ -0,0 +1,76 @@
<script lang="ts">
import { Tooltip } from 'sveltestrap';
export let shard = {
id: 1,
status: "",
ping:0,
disconnection_count:0,
last_connection:0,
last_heartbeat:0,
heartbeat_minutes_ago:0
};
let color = "background-color: #fff";
// shard is down
if (shard.status != "up" || shard.heartbeat_minutes_ago > 5) color = "background-color: #000;";
// shard latency is < 250ms: OK!
else if (shard.ping < 300) color = "background-color: #00cc00;";
// shard latency is 250ms < ping < 600ms: slow, but OK
else if (shard.ping < 600) color = "background-color: #da9317;";
// shard latency is >600ms, this might be problematic
else color = "background-color: #cc0000;"
</script>
<div class="wrapper">
<div
class="shard" id={`shard-${shard.id.toString()}`}
style={color}
>{ shard.id }</div>
<Tooltip target={`shard-${shard.id.toString()}`} placement="bottom">
<br>
<h3>Shard { shard.id }</h3>
<br>
<span>Status: <b>{ shard.status }</b></span><br>
<span>Latency: { shard.ping }ms</span><br>
<span>Disconnection count: { shard.disconnection_count }</span><br>
<span>Last connection: { shard.last_connection } UTC</span><br>
<span>Last heartbeat: { shard.last_heartbeat } UTC</span>
{#if shard.heartbeat_minutes_ago > 5}
<span>(over {Math.floor(shard.heartbeat_minutes_ago)} minutes ago)</span>
{/if}
<br><br>
</Tooltip>
</div>
<style>
.wrapper {
position: relative;
display: inline-block;
}
.shard:hover {
cursor: pointer;
}
.shard {
color: #fff;
display: block;
float: left;
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
justify-content: center;
z-index: 1;
height: 3em;
width: 3em;
border-radius: 2px;
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Safari */
-khtml-user-select: none; /* Konqueror HTML */
-moz-user-select: none; /* Old versions of Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently
supported by Chrome, Edge, Opera and Firefox */
}
</style>

View File

@@ -0,0 +1,109 @@
<script lang="ts">
import { Row, Col, Modal, Image, Button } from 'sveltestrap';
import moment from 'moment';
import { toHTML } from 'discord-markdown';
import parseTimestamps from '../../api/parse-timestamps';
import resizeMedia from '../../api/resize-media';
import twemoji from 'twemoji';
import { System } from '../../api/types';
export let user: System;
export let editMode: boolean;
export let isPublic: boolean;
let htmlDescription: string;
let htmlName: string;
let htmlPronouns: string;
if (user.description) {
htmlDescription = toHTML(parseTimestamps(user.description), {embed: true});
} else {
htmlDescription = "(no description)";
}
if (user.name) {
htmlName = toHTML(user.name);
}
if (user.pronouns) {
htmlPronouns = toHTML(user.pronouns);
}
let created = moment(user.created).format("MMM D, YYYY");
let bannerOpen = false;
const toggleBannerModal = () => (bannerOpen = !bannerOpen);
let settings = JSON.parse(localStorage.getItem("pk-settings"));
let descriptionElement: any;
let nameElement: any;
let tagElement: any;
let pronounElement: any;
$: if (settings && settings.appearance.twemoji) {
if (descriptionElement) twemoji.parse(descriptionElement);
if (nameElement) twemoji.parse(nameElement);
if (tagElement) twemoji.parse(tagElement);
if (pronounElement) twemoji.parse(pronounElement);
}
</script>
<Row>
{#if user.id}
<Col xs={12} lg={4} class="mb-2">
<b>ID:</b> {user.id}
</Col>
{/if}
{#if user.name}
<Col xs={12} lg={4} class="mb-2">
<span bind:this={nameElement}><b>Name:</b> {@html htmlName}</span>
</Col>
{/if}
{#if user.tag}
<Col xs={12} lg={4} class="mb-2">
<span bind:this={tagElement}><b>Tag:</b> {user.tag}</span>
</Col>
{/if}
{#if user.pronouns}
<Col xs={12} lg={4} class="mb-2">
<span bind:this={pronounElement}><b>Pronouns:</b> {@html htmlPronouns}</span>
</Col>
{/if}
{#if user.created && !isPublic}
<Col xs={12} lg={4} class="mb-2">
<b>Created:</b> {created}
</Col>
{/if}
{#if user.timezone && !isPublic}
<Col xs={12} lg={4} class="mb-2">
<b>Timezone:</b> {user.timezone}
</Col>
{/if}
{#if user.color}
<Col xs={12} lg={4} class="mb-2">
<b>Color:</b> {user.color}
</Col>
{/if}
{#if user.banner}
<Col xs={12} lg={3} class="mb-2">
<b>Banner:</b> <Button size="sm" color="secondary" on:click={toggleBannerModal} aria-label="view system banner">View</Button>
<Modal isOpen={bannerOpen} toggle={toggleBannerModal}>
<div slot="external" on:click={toggleBannerModal} style="height: 100%; width: max-content; max-width: 100%; margin-left: auto; margin-right: auto; display: flex;">
<Image style="display: block; margin: auto;" src={user.banner} thumbnail alt="system banner" />
</div>
</Modal>
</Col>
{/if}
</Row>
<div class="my-2 description" bind:this={descriptionElement}>
<b>Description:</b><br />
{@html htmlDescription}
</div>
{#if (user.banner && ((settings && settings.appearance.banner_bottom) || !settings))}
<img on:click={toggleBannerModal} src={resizeMedia(user.banner, [1200, 480])} alt="system banner" class="w-100 mb-3 rounded" style="max-height: 13em; object-fit: cover; cursor: pointer;"/>
{/if}
{#if !isPublic}
<Button style="flex: 0" color="primary" on:click={() => editMode = true} aria-label="edit system information">Edit</Button>
{/if}

View File

@@ -0,0 +1,107 @@
<script lang="ts">
import { Row, Col, Input, Button, Label, Alert, Spinner } from 'sveltestrap';
import { autoresize } from 'svelte-textarea-autoresize';
// import moment from 'moment-timezone';
import { currentUser } from '../../stores';
const descriptions: string[] = JSON.parse(localStorage.getItem("pk-config"))?.description_templates;
import { System } from '../../api/types';
import api from '../../api';
export let editMode: boolean;
export let user: System;
let loading: boolean;
let success = false;
let err: string[] = [];
let input: System = {...user};
async function submit() {
let data = input;
err = [];
if (data.color && !/^#?[A-Fa-f0-9]{6}$/.test(input.color)) {
err.push(`"${data.color}" is not a valid color, the color must be a 6-digit hex code. (example: #ff0000)`);
} else if (data.color) {
if (data.color.startsWith("#")) {
data.color = input.color.slice(1, input.color.length);
}
}
/* if (data.timezone && !moment.tz.zone(data.timezone)) {
err.push(`"${data.timezone}" is not a valid timezone, check out <a target="_blank" style="color: var(--bs-body-color);" href="https://xske.github.io/tz/">this site</a> to see your current timezone!`);
} */
// trim all string fields
Object.keys(data).forEach(k => data[k] = typeof data[k] == "string" ? data[k].trim() : data[k]);
err = err;
if (err.length > 0) return;
loading = true;
try {
let res = await api().systems("@me").patch({data});
user = res;
currentUser.update(() => res);
err = [];
success = true;
loading = false;
} catch (error) {
console.log(error);
err.push(error.message);
err = err;
loading = false;
}
}
</script>
{#each err as error}
<Alert color="danger">{@html error}</Alert>
{/each}
{#if success}
<Alert fade={false} color="success">System information updated!</Alert>
{/if}
<Row>
<Col xs={12} lg={4} class="mb-2">
<Label>Name:</Label>
<Input bind:value={input.name} maxlength={100} type="text" placeholder={user.name} aria-label="system name" />
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Tag:</Label>
<Input bind:value={input.tag} maxlength={100} type="text" placeholder={user.tag} aria-label="system tag" />
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Pronouns:</Label>
<Input bind:value={input.pronouns} maxlength={100} style="resize: none; height: 1em" type="textarea" placeholder={user.pronouns} aria-label="system pronouns" />
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Color:</Label>
<Input bind:value={input.color} type="text" placeholder={user.color} aria-label="system color"/>
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Avatar url:</Label>
<Input bind:value={input.avatar_url} maxlength={256} type="url" placeholder={user.avatar_url} aria-label="system avatar url" />
</Col>
<Col xs={12} lg={4} class="mb-2">
<Label>Banner url:</Label>
<Input bind:value={input.banner} maxlength={256} type="url" placeholder={user.banner} aria-label="system banner url" />
</Col>
</Row>
<div class="my-2">
<b>Description:</b><br />
{#if descriptions.length > 0 && descriptions[0].trim() != ""}
<Button size="sm" color="primary" on:click={() => input.description = descriptions[0]} aria-label="use template 1">Template 1</Button>
{/if}
{#if descriptions.length > 1 && descriptions[1].trim() != ""}
<Button size="sm" color="primary" on:click={() => input.description = descriptions[1]} aria-label="use template 2">Template 2</Button>
{/if}
{#if descriptions.length > 2 && descriptions[2].trim() != ""}
<Button size="sm" color="primary" on:click={() => input.description = descriptions[2]} aria-label="use template 3">Template 3</Button>
{/if}
<br>
<textarea class="form-control" bind:value={input.description} maxlength={1000} use:autoresize placeholder={user.description} aria-label="system description"/>
</div>
{#if !loading}<Button style="flex: 0" color="primary" on:click={submit} aria-label="submit edits" >Submit</Button> <Button style="flex: 0" color="secondary" on:click={() => editMode = false} aria-label="cancel edits">Back</Button>
{:else}<Button style="flex: 0" color="primary" disabled aria-label="submit edits"><Spinner size="sm"/></Button> <Button style="flex: 0" color="secondary" disabled aria-label="cancel edits">Back</Button>{/if}

View File

@@ -0,0 +1,53 @@
<script lang="ts">
import { Card, CardBody, CardHeader, Tooltip } from 'sveltestrap';
import FaAddressCard from 'svelte-icons/fa/FaAddressCard.svelte'
import CardsHeader from '../common/CardsHeader.svelte';
import Body from './Body.svelte';
import Privacy from './Privacy.svelte';
import Edit from './Edit.svelte';
import { System } from '../../api/types';
export let user: System;
export let isPublic = true;
let editMode = false;
let copied = false;
async function copyShortLink(event?) {
if (event) {
let ctrlDown = event.ctrlKey||event.metaKey; // mac support
if (!(ctrlDown && event.key === "c") && event.key !== "Enter") return;
}
try {
await navigator.clipboard.writeText(`https://pk.mt/s/${user.id}`);
copied = true;
await new Promise(resolve => setTimeout(resolve, 2000));
copied = false;
} catch (error) {
console.log(error);
}
}
</script>
<Card class="mb-4">
<CardHeader>
<CardsHeader bind:item={user}>
<div slot="icon" style="cursor: pointer;" id={`copy-${user.id}`} on:click|stopPropagation={() => copyShortLink()} on:keydown|stopPropagation={(e) => copyShortLink(e)} tabindex={0} >
<FaAddressCard />
</div>
</CardsHeader>
<Tooltip placement="top" target={`copy-${user.id}`}>{copied ? "Copied!" : "Copy public link"}</Tooltip>
</CardHeader>
<CardBody style="border-left: 4px solid #{user.color}">
{#if !editMode}
<Body bind:user bind:editMode bind:isPublic/>
{:else}
<Edit bind:user bind:editMode />
{/if}
</CardBody>
</Card>
{#if !isPublic}
<Privacy bind:user />
{/if}

View File

@@ -0,0 +1,50 @@
<script lang="ts">
import { Card, CardHeader, CardBody, CardTitle, Row, Col, Button, Spinner } from 'sveltestrap';
import {Link} from 'svelte-navigator';
import FaUserLock from 'svelte-icons/fa/FaUserLock.svelte';
import PrivacyEdit from './PrivacyEdit.svelte';
import { System, SystemPrivacy } from '../../api/types';
export let user: System;
let editMode = false;
let loading: boolean;
const privacyNames: { [P in keyof SystemPrivacy]-?: string; } = {
description_privacy: "Description",
member_list_privacy: "Member list",
front_privacy: "Front",
front_history_privacy: "Front history",
group_list_privacy: "Group list",
pronoun_privacy: "Pronouns"
};
</script>
<Card class="mb-4">
<CardHeader>
<CardTitle style="margin-top: 8px; outline: none;">
<div class="icon d-inline-block">
<FaUserLock />
</div> System privacy
{#if loading}<div class="d-inline-block mr-5" style="float: right;"><Spinner color="primary" /></div>{/if}
</CardTitle>
</CardHeader>
<CardBody style="border-left: 4px solid #{user.color}">
{#if editMode}
<PrivacyEdit bind:user={user} bind:editMode/>
{:else}
<Row>
{#each Object.keys(user.privacy) as x}
<Col xs={12} lg={4} class="mb-3">
<b>{privacyNames[x]}:</b> {user.privacy[x]}
</Col>
{/each}
</Row>
<Button style="flex: 0" color="primary" on:click={() => editMode = true} aria-label="edit system privacy">Edit</Button>
<Link to="/dash/bulk-member-privacy"><Button style="flex: 0" color="secondary" tabindex={-1}>Bulk member privacy</Button></Link>
<Link to="/dash/bulk-group-privacy"><Button style="flex: 0" color="secondary" tabindex={-1}>Bulk group privacy</Button></Link>
{/if}
</CardBody>
</Card>

View File

@@ -0,0 +1,76 @@
<script lang="ts">
import { Input, Row, Col, Button, Label, Alert, Spinner } from 'sveltestrap';
import { currentUser } from '../../stores';
import { System, SystemPrivacy } from '../../api/types';
import api from '../../api';
export let user: System;
export let editMode: boolean;
let err: string;
let success = false;
let loading = false;
function changeAll(e: Event) {
const target = e.target as HTMLInputElement;
Object.keys(privacy).forEach(x => privacy[x] = target.value);
}
let privacy = user.privacy;
const privacyNames: { [P in keyof SystemPrivacy]-?: string; } = {
description_privacy: "Description",
member_list_privacy: "Member list",
front_privacy: "Front",
front_history_privacy: "Front history",
group_list_privacy: "Group list",
pronoun_privacy: "Pronouns"
};
async function submit() {
loading = true;
const data: System = {privacy: privacy};
try {
let res = await api().systems(user.id).patch({data});
user = res;
currentUser.update(() => res);
success = true;
} catch (error) {
console.log(error);
err = error.message;
}
loading = false;
}
</script>
{#if err}
<Alert color="danger">{err}</Alert>
{/if}
{#if success}
<Alert color="success">System privacy updated!</Alert>
{/if}
<Label><b>Set all to:</b></Label>
<select class="form-control" on:change={(e) => changeAll(e)} aria-label="set all to">
<option>public</option>
<option>private</option>
</select>
<hr/>
<Row>
{#each Object.keys(privacy) as x}
<Col xs={12} lg={6} class="mb-3">
<Label>{privacyNames[x]}:</Label>
<Input type="select" bind:value={privacy[x]} aria-label={`group ${privacyNames[x]} privacy`}>
<option default={privacy[x] === "public"}>public</option>
<option default={privacy[x] === "private"}>private</option>
</Input>
</Col>
{/each}
</Row>
{#if loading}
<Button style="flex: 0" color="primary" aria-label="submit privacy edit"><Spinner size="sm"/></Button> <Button style="flex: 0" color="secondary" aria-label="cancel privacy edit"><Spinner size="sm"/></Button>
{:else}
<Button style="flex: 0" color="primary" on:click={submit} aria-label="submit privacy edit">Submit</Button> <Button style="flex: 0" color="secondary" on:click={() => editMode = false} aria-label="cancel privacy edit">Back</Button>
{/if}