feat: Add post and comment editing (#12)

* feat: Add editing

* feat: Add comment badges

* fix: make loading more consistent

* misc: remove prop drilling

* feat: Add post editing

* misc: update version

* feat: Add comment deletion
This commit is contained in:
Xylight authored and GitHub committed 2023-07-25 11:12:15 -07:00
1 parent 0327ae4aed
commit 7b1ad247f9
16 files changed
+417 -192

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "photon-lemmy",
"version": "0.1.1",
"version": "0.2.1",
"private": true,
"scripts": {
"dev": "vite dev",
@@ -1,5 +1,13 @@
<script lang="ts">
import { Icon, Minus, Plus } from 'svelte-hero-icons'
import {
ArrowUp,
Bookmark,
Icon,
Minus,
Pencil,
Plus,
Trash,
} from 'svelte-hero-icons'
import type { CommentNodeI } from './comments'
import RelativeDate from '$lib/components/util/RelativeDate.svelte'
import CommentForm from './CommentForm.svelte'
@@ -7,6 +15,12 @@
import UserLink from '$lib/components/user/UserLink.svelte'
import Markdown from '$lib/components/markdown/Markdown.svelte'
import CommentActions from '$lib/components/lemmy/comment/CommentActions.svelte'
import { createEventDispatcher } from 'svelte'
import type { CommentView } from 'lemmy-js-client'
import Modal from '$lib/components/ui/modal/Modal.svelte'
import { authData, getClient } from '$lib/lemmy.js'
import { ToastType, toast } from '$lib/components/ui/toasts/toasts.js'
import TextArea from '$lib/components/input/TextArea.svelte'
export let node: CommentNodeI
export let postId: number
@@ -14,8 +28,48 @@
export let open = true
export let replying = false
let editing = false
let newComment = node.comment_view.comment.content
</script>
{#if editing}
<Modal
bind:open={editing}
action="Save"
on:action={async () => {
if (!$authData || newComment.length <= 0) return
try {
await getClient().editComment({
auth: $authData.token,
comment_id: node.comment_view.comment.id,
content: newComment,
})
node.comment_view.comment.content = newComment
editing = false
toast({
content:
'Successfully edited comment. You may need to refresh to see changes.',
type: ToastType.success,
})
} catch (err) {
toast({
// @ts-ignore i hate this
content: err,
type: ToastType.error,
})
}
}}
>
<span slot="title">Edit comment</span>
<TextArea bind:value={newComment} />
</Modal>
{/if}
<li
class="py-2 {node.depth == 0
? 'border-b border-slate-200 dark:border-zinc-800'
@@ -32,7 +86,15 @@
<span class="text-sky-500">OP</span>
{/if}
</span>
<span class="opacity-60 flex flex-row gap-1">
<span class="text-slate-600 dark:text-zinc-400 flex flex-row gap-1">
{#if !open}
<div
class="flex items-center gap-0.5 mr-1 text-slate-800 dark:text-zinc-200"
>
<Icon src={ArrowUp} mini size="14" />
{node.comment_view.counts.score}
</div>
{/if}
<RelativeDate date={new Date(node.comment_view.comment.published)} />
<span>•</span>
<span>
@@ -44,6 +106,17 @@
) || 0}%
</span>
</span>
<span class="text-slate-600 dark:text-zinc-400 flex flex-row gap-2 ml-1">
{#if node.comment_view.comment.updated}
<Icon src={Pencil} solid size="12" title="Edited" />
{/if}
{#if node.comment_view.comment.deleted || node.comment_view.comment.removed}
<Icon src={Trash} solid size="12" title="Deleted" />
{/if}
{#if node.comment_view.saved}
<Icon src={Bookmark} solid size="12" title="Saved" />
{/if}
</span>
<span
class="ml-auto translate-x-1 opacity-0
group-hover:translate-x-0 group-hover:opacity-100 text-xs transition-all
@@ -68,7 +141,11 @@
<Markdown source={node.comment_view.comment.content} />
</div>
<div class="flex flex-row gap-2 items-center h-[26px]">
<CommentActions comment={node.comment_view} bind:replying />
<CommentActions
comment={node.comment_view}
bind:replying
on:edit={() => (editing = true)}
/>
</div>
</div>
{#if replying}
@@ -9,12 +9,16 @@
ChatBubbleOvalLeft,
EllipsisHorizontal,
Icon,
PencilSquare,
Trash,
} from 'svelte-hero-icons'
import { authData, getClient } from '$lib/lemmy.js'
import { authData, getClient, user } from '$lib/lemmy.js'
import { ToastType, toast } from '$lib/components/ui/toasts/toasts.js'
import Menu from '$lib/components/ui/menu/Menu.svelte'
import MenuButton from '$lib/components/ui/menu/MenuButton.svelte'
import Button from '$lib/components/input/Button.svelte'
import { createEventDispatcher } from 'svelte'
import { isCommentMutable } from '$lib/components/lemmy/post/helpers.js'
export let comment: CommentView
export let replying: boolean = false
@@ -41,6 +45,8 @@
})
}
}
const dispatcher = createEventDispatcher<{ edit: CommentView }>()
</script>
<div class="flex flex-row gap-2 items-center mt-1 h-[26px] relative">
@@ -53,34 +59,59 @@
<Icon src={ChatBubbleOvalLeft} width={16} height={16} mini />
<span class="text-xs">Reply</span>
</Button>
<div class="h-full relative">
<Menu
let:toggleOpen
class="h-[26px] top-0"
absolute
alignment="bottom-center"
<Menu
let:toggleOpen
class="h-[26px] top-0 leading-3"
alignment="bottom-center"
>
<Button
slot="button"
color="elevatedLow"
on:click={toggleOpen}
size="sm"
class="!p-1"
>
<Button
slot="button"
color="elevatedLow"
on:click={toggleOpen}
size="sm"
class="!p-1"
>
<Icon
src={EllipsisHorizontal}
width={16}
height={16}
mini
slot="icon"
/>
</Button>
{#if $authData?.token}
<MenuButton on:click={save}>
<Icon src={comment.saved ? BookmarkSlash : Bookmark} mini size="16" />
<span>{comment.saved ? 'Unsave' : 'Save'}</span>
<Icon src={EllipsisHorizontal} width={16} height={16} mini slot="icon" />
</Button>
<span class="text-xs opacity-80 py-1 my-1 px-4">Comment actions</span>
{#if $authData?.token}
{#if comment.creator.id == $user?.person.id}
<MenuButton on:click={() => dispatcher('edit', comment)}>
<Icon src={PencilSquare} mini size="16" />
<span>Edit</span>
</MenuButton>
{/if}
</Menu>
</div>
<MenuButton on:click={save}>
<Icon src={comment.saved ? BookmarkSlash : Bookmark} mini size="16" />
<span>{comment.saved ? 'Unsave' : 'Save'}</span>
</MenuButton>
{#if $user && $authData && isCommentMutable(comment, $user)}
<MenuButton
color={Color.dangerSecondary}
on:click={async () => {
if (!$authData) return
try {
await getClient().deleteComment({
auth: $authData.token,
comment_id: comment.comment.id,
deleted: true,
})
toast({
content: 'The comment was deleted.',
type: ToastType.success,
})
} catch (error) {
toast({
content: 'Failed to delete comment',
type: ToastType.error,
})
}
}}
>
<Icon src={Trash} mini size="16" />
<span>Delete</span>
</MenuButton>
{/if}
{/if}
</Menu>
</div>
@@ -6,9 +6,11 @@
import Button from '$lib/components/input/Button.svelte'
import { ChevronDown, Icon } from 'svelte-hero-icons'
import { authData, getClient } from '$lib/lemmy.js'
import type { Post } from 'lemmy-js-client'
import type { CommentView, Post } from 'lemmy-js-client'
import { fly } from 'svelte/transition'
import { toast, ToastType } from '$lib/components/ui/toasts/toasts.js'
import Modal from '$lib/components/ui/modal/Modal.svelte'
import TextArea from '$lib/components/input/TextArea.svelte'
export let nodes: CommentNodeI[]
export let isParent: boolean
@@ -80,7 +82,7 @@
{/if}
{#if node.comment_view.counts.child_count > 0 && node.children.length == 0}
<div
class="my-2 min-w-[7rem] w-max h-8 border-l-2 border-slate-200 dark:border-zinc-900 ml-2.5 pl-1"
class="my-2 min-w-[7rem] w-max h-8 border-l-2 border-slate-200 dark:border-zinc-900 pl-2"
>
<Button
loading={node.loading}
+15 -1
View File
@@ -7,6 +7,9 @@
import { userSettings } from '$lib/settings.js'
import PostLink from '$lib/components/lemmy/post/PostLink.svelte'
import PostMeta from '$lib/components/lemmy/post/PostMeta.svelte'
import Modal from '$lib/components/ui/modal/Modal.svelte'
import PostForm from '$lib/components/lemmy/post/PostForm.svelte'
import { ToastType, toast } from '$lib/components/ui/toasts/toasts.js'
export let post: PostView
</script>
@@ -80,5 +83,16 @@
{post.post.body}
</p>
{/if}
<PostActions {post} />
<PostActions
{post}
on:edit={(e) => {
post.post.name = e.detail.post.name
post.post.body = e.detail.post.body
post.post.url = e.detail.post.url
toast({
content: 'The post was edited successfully.',
type: ToastType.success,
})
}}
/>
</Card>
@@ -11,6 +11,7 @@
EllipsisHorizontal,
Icon,
Newspaper,
PencilSquare,
Square2Stack,
Trash,
UserCircle,
@@ -22,6 +23,10 @@
import { page } from '$app/stores'
import { user, authData } from '$lib/lemmy.js'
import { ToastType, toast } from '$lib/components/ui/toasts/toasts.js'
import { isMutable } from '$lib/components/lemmy/post/helpers.js'
import { createEventDispatcher } from 'svelte'
import Modal from '$lib/components/ui/modal/Modal.svelte'
import PostForm from '$lib/components/lemmy/post/PostForm.svelte'
export let post: PostView
@@ -57,8 +62,25 @@
})
}
}
const dispatcher = createEventDispatcher<{ edit: PostView }>()
let editing = false
</script>
{#if editing}
<Modal bind:open={editing}>
<PostForm
edit
editingPost={post.post}
on:submit={(e) => {
editing = false
dispatcher('edit', e.detail)
}}
/>
</Modal>
{/if}
<div class="flex flex-row gap-2 items-center">
<PostVote post={post.post} vote={post.my_vote} score={post.counts.score} />
@@ -99,6 +121,12 @@
</MenuButton>
<hr class="w-[90%] mx-auto opacity-100 dark:opacity-10 my-2" />
<li class="mx-4 text-xs opacity-80 text-left my-1 py-1">Actions</li>
{#if $user && $user.person.id == post.creator.id}
<MenuButton on:click={() => (editing = true)}>
<Icon src={PencilSquare} width={16} mini />
Edit
</MenuButton>
{/if}
<MenuButton
on:click={() => {
navigator.clipboard.writeText(
@@ -115,7 +143,7 @@
{post.saved ? 'Unsave' : 'Save'}
</MenuButton>
{/if}
{#if $user?.person.id == post.post.creator_id}
{#if $user && isMutable(post, $user)}
<MenuButton on:click={deletePost} color={Color.dangerSecondary}>
<Icon src={Trash} width={16} mini />
Delete
@@ -0,0 +1,160 @@
<script lang="ts">
import { createEventDispatcher, onMount } from 'svelte'
import { getClient, authData, uploadImage } from '$lib/lemmy.js'
import type { Community, Post, PostView } from 'lemmy-js-client'
import TextInput from '$lib/components/input/TextInput.svelte'
import TextArea from '$lib/components/input/TextArea.svelte'
import SelectMenu from '$lib/components/input/SelectMenu.svelte'
import Dots from '$lib/components/ui/loader/Dots.svelte'
import FileInput from '$lib/components/input/FileInput.svelte'
import Button from '$lib/components/input/Button.svelte'
import { ToastType, toast } from '$lib/components/ui/toasts/toasts.js'
import { goto } from '$app/navigation'
export let edit = false
/**
* The post to edit
*/
export let editingPost: Post | undefined = undefined
let data: {
community: number | null
title: string
body: string
image: FileList | null
url: string | undefined
loading: boolean
} = {
community: null,
title: '',
body: '',
image: null,
url: undefined,
loading: false,
}
const placeholders = [
'Is starting nuclear warfare illegal?',
'A cool photo I took before the destruction of mankind!',
'AITA for ending all contention and causing world peace?',
'BREAKING NEWS: Police break into gun shop, find weapons',
'How do I make sure my pet rock stays alive?',
'My cat just invented a time machine, what do I do?',
'Unpopular opinion: world peace and global happiness would be beneficial to humanity',
'LPT: The smaller weights are easier to lift than the bigger weights in a gym',
'javascript bad',
'ELI5: What is 4 + 8?',
]
const placeholder =
placeholders[Math.floor(Math.random() * placeholders.length)]
const placeholder2 =
placeholders[Math.floor(Math.random() * placeholders.length)]
let communities: Community[] | undefined
const dispatcher = createEventDispatcher<{ submit: PostView }>()
onMount(async () => {
if (editingPost) {
data.url = editingPost.url ?? ''
data.body = editingPost.body ?? ''
data.title = editingPost.name
}
const list = await getClient().listCommunities({
auth: $authData?.token,
type_: 'Subscribed',
sort: 'New',
limit: 40,
})
communities = list.communities.map((c) => c.community)
})
async function submit() {
if (!(!data.community && edit) || !data.title || !$authData) return
data.loading = true
try {
if (edit) {
if (!editingPost) {
throw new Error('Post is being edited but editingPost is null')
}
const post = await getClient().editPost({
auth: $authData.token,
name: data.title,
body: data.body,
url: data.url || undefined,
post_id: editingPost.id,
})
if (!post) throw new Error('Failed to edit post')
console.log(`Edited post ${post?.post_view.post.id}`)
dispatcher('submit', post.post_view)
} else {
let image = data.image ? await uploadImage(data.image[0]) : undefined
data.url = image
const post = await getClient().createPost({
auth: $authData.token,
community_id: data.community!,
name: data.title,
body: data.body,
url: data.url,
})
if (!post) throw new Error('Failed to upload post')
console.log(`Uploaded post ${post?.post_view.post.id}`)
dispatcher('submit', post.post_view)
}
} catch (err) {
toast({ content: err as any, type: ToastType.error })
}
}
</script>
<form on:submit|preventDefault={submit} class="flex flex-col gap-4">
<h1 class="font-bold text-xl">{edit ? 'Edit' : 'Create'} Post</h1>
{#if !edit}
<div>
<span class="block my-1 font-bold text-sm">
Community <span class="text-red-500">*</span>
</span>
{#if communities}
<SelectMenu
bind:selected={data.community}
options={communities.map((c) => c.id)}
optionNames={new Map(communities.map((c) => [c.id, c.title]))}
/>
{:else}
<Dots />
{/if}
</div>
{/if}
<TextInput required label="Title" bind:value={data.title} {placeholder} />
<TextInput
label="URL"
bind:value={data.url}
placeholder="https://notascam.com"
/>
<TextArea label="Body" bind:value={data.body} placeholder={placeholder2} />
<div>
<span class="block my-1 font-bold text-sm">Image</span>
<FileInput
accept="image/jpeg,image/png,image/webp"
image
bind:files={data.image}
/>
</div>
<Button submit color="primary" loading={data.loading} size="lg">
Submit
</Button>
</form>
+8
View File
@@ -0,0 +1,8 @@
import type { CommentView, PersonView, PostView } from 'lemmy-js-client'
export const isMutable = (post: PostView, me: PersonView) =>
(me.person.admin && post.post.local) || me.person.id == post.creator.id
export const isCommentMutable = (comment: CommentView, me: PersonView) =>
(me.person.admin && comment.comment.local) ||
me.person.id == comment.creator.id
+1 -1
View File
@@ -17,7 +17,7 @@
<div
class="bg-white break-words
p-1 {getColor(cardColor)} rounded-md {clazz}"
{getColor(cardColor)} rounded-md {clazz}"
>
<slot />
</div>
+1 -1
View File
@@ -78,7 +78,7 @@
{itemsClass}"
>
{#if open}
<div on:click={toggleOpen}>
<div on:click={toggleOpen} class="flex flex-col gap-0">
<slot {toggleOpen} />
</div>
{/if}
+3 -3
View File
@@ -15,8 +15,8 @@
<!-- svelte-ignore a11y-click-events-have-key-events -->
<div
class="overflow-hidden fixed top-0 left-0 w-screen h-screen z-[100]
flex flex-col items-center justify-center bg-black/50 backdrop-blur-sm"
transition:fade|local={{ duration: 200 }}
flex flex-col items-center justify-center bg-black/50 backdrop-blur-sm rounded-xl"
transition:fade={{ duration: 200 }}
on:click={() => (open = false)}
>
<!-- svelte-ignore a11y-click-events-have-key-events -->
@@ -35,7 +35,7 @@ flex flex-col items-center justify-center bg-black/50 backdrop-blur-sm"
</div>
{#if action}
<div
class="border-t bg-slate-100 dark:bg-zinc-900 dark:border-zinc-800 p-3 flex justify-end"
class="border-t bg-slate-100 dark:bg-zinc-900 dark:border-zinc-800 p-3 py-2 flex justify-end rounded-b-xl"
>
<slot name="action">
<Button
@@ -5,7 +5,7 @@
</script>
<div
class="fixed right-0 bottom-0 flex flex-col items-end justify-end z-50 p-4
class="fixed right-0 bottom-0 flex flex-col items-end justify-end z-[200] p-4
group
overflow-hidden h-screen min-w-[24rem] pointer-events-none"
>
+32 -1
View File
@@ -4,7 +4,7 @@ import { ToastType, toast } from '$lib/components/ui/toasts/toasts.js'
import { userSettings } from '$lib/settings.js'
import { env } from '$env/dynamic/public'
export const DEFAULT_INSTANCE_URL = env.PUBLIC_INSTANCE_URL || 'lemmy.world'
export const DEFAULT_INSTANCE_URL = env.PUBLIC_INSTANCE_URL || 'lemmy.ml'
export let instance = writable(DEFAULT_INSTANCE_URL)
export let corsSupported = writable(true)
@@ -111,3 +111,34 @@ export async function validateInstance(instance: string): Promise<boolean> {
return false
}
}
export async function uploadImage(
image: File | null | undefined
): Promise<string | undefined> {
if (!image || !get(authData)) return
const formData = new FormData()
formData.append('images[]', image)
const response = await fetch(
`${
window.location.origin
}/cors/${getInstance()}/pictrs/image?${new URLSearchParams({
auth: get(authData)!.token,
})}`,
{
method: 'POST',
body: formData,
}
)
const json = await response.json()
if (json.msg == 'ok') {
return `https://${get(authData)?.instance}/pictrs/image/${
json.files?.[0]?.file
}`
}
throw new Error(`error uploading image: ${response.status}`)
}
+7
View File
@@ -1,7 +1,14 @@
<script>
import { goto } from '$app/navigation'
import { page } from '$app/stores'
import Button from '$lib/components/input/Button.svelte'
</script>
<div class="flex flex-col mx-auto gap-4 justify-center items-center">
<h1 class="font-black text-3xl">404</h1>
<p class="mx-4 md:mx-8">
It's likely that this community hasn't been federated (nobody on your
instance has subscribed to it yet.)
</p>
<Button on:click={() => goto($page.url)}>Retry</Button>
</div>
+2 -148
View File
@@ -1,124 +1,7 @@
<script lang="ts">
import { goto } from '$app/navigation'
import Button from '$lib/components/input/Button.svelte'
import FileInput from '$lib/components/input/FileInput.svelte'
import SelectMenu from '$lib/components/input/SelectMenu.svelte'
import TextArea from '$lib/components/input/TextArea.svelte'
import TextInput from '$lib/components/input/TextInput.svelte'
import PostForm from '$lib/components/lemmy/post/PostForm.svelte'
import Card from '$lib/components/ui/Card.svelte'
import Loading from '$lib/components/ui/loader/Dots.svelte'
import { ToastType, addToast } from '$lib/components/ui/toasts/toasts.js'
import { authData, buildBaseUrl, getClient, getInstance } from '$lib/lemmy.js'
import { Color } from '$lib/ui/colors.js'
import type { Community } from 'lemmy-js-client'
import { list } from 'postcss'
import { onMount } from 'svelte'
let data: {
community: number | null
title: string
body: string
image: FileList | null
loading: boolean
} = {
community: null,
title: '',
body: '',
image: null,
loading: false,
}
async function uploadImage(
image: File | null | undefined
): Promise<string | undefined> {
if (!image || !$authData) return
const formData = new FormData()
formData.append('images[]', image)
const response = await fetch(
`${window.location.origin}/cors/${getInstance()}/pictrs/image?${new URLSearchParams({
auth: $authData.token,
})}`,
{
method: 'POST',
body: formData,
}
)
const json = await response.json()
if (json.msg == 'ok') {
return `https://${$authData.instance}/pictrs/image/${json.files?.[0]?.file}`
}
throw new Error(`error uploading image: ${response.status}`)
}
async function submit() {
if (!data.community || !data.title || !$authData) return
data.loading = true
try {
let image = data.image ? await uploadImage(data.image[0]) : undefined
const post = await getClient().createPost({
auth: $authData.token,
community_id: data.community,
name: data.title,
body: data.body,
url: image,
})
if (!post) throw new Error('Failed to upload post')
console.log(`Uploading post ${post?.post_view.post.id}`)
goto(`/post/${post?.post_view.post.id}`)
} catch (err) {
addToast('Error', err as any, ToastType.error)
}
data.loading = false
}
const placeholders = [
'Is starting nuclear warfare illegal?',
'A cool photo I took before the destruction of mankind!',
'AITA for ending all contention and causing world peace?',
'BREAKING NEWS: Police break into gun shop, find weapons',
'How do I make sure my pet rock stays alive?',
'My cat just invented a time machine, what do I do?',
'Unpopular opinion: world peace and global happiness would be beneficial to humanity',
'LPT: The smaller weights are easier to lift than the bigger weights in a gym',
'javascript bad',
'ELI5: What is 4 + 8?',
]
const placeholder =
placeholders[Math.floor(Math.random() * placeholders.length)]
const placeholder2 =
placeholders[Math.floor(Math.random() * placeholders.length)]
let communities: Community[] | undefined
onMount(async () => {
if (!$authData) {
goto('/login')
return
}
const list = await getClient().listCommunities({
auth: $authData.token,
type_: 'Subscribed',
sort: 'New',
limit: 40,
})
communities = list.communities.map((c) => c.community)
})
</script>
<svelte:head>
@@ -126,34 +9,5 @@
</svelte:head>
<Card class="p-6 max-w-2xl mx-auto">
<form on:submit|preventDefault={submit} class="flex flex-col gap-4">
<h1 class="font-bold text-xl">Create Post</h1>
<div>
<span class="block my-1 font-bold text-sm">
Community <span class="text-red-500">*</span>
</span>
{#if communities}
<SelectMenu
bind:selected={data.community}
options={communities.map((c) => c.id)}
optionNames={new Map(communities.map((c) => [c.id, c.title]))}
/>
{:else}
<Loading />
{/if}
</div>
<TextInput required label="Title" bind:value={data.title} {placeholder} />
<TextArea label="Body" bind:value={data.body} placeholder={placeholder2} />
<div>
<span class="block my-1 font-bold text-sm">Image</span>
<FileInput
accept="image/jpeg,image/png,image/webp"
image
bind:files={data.image}
/>
</div>
<Button submit color="primary" loading={data.loading} size="lg">
Submit
</Button>
</form>
<PostForm on:submit={(e) => goto(`/post/${e.detail.post.id}`)} />
</Card>
+14 -1
View File
@@ -29,6 +29,7 @@
import Card from '$lib/components/ui/Card.svelte'
import PostLink from '$lib/components/lemmy/post/PostLink.svelte'
import PostMeta from '$lib/components/lemmy/post/PostMeta.svelte'
import { ToastType, toast } from '$lib/components/ui/toasts/toasts.js'
export let data
@@ -118,7 +119,19 @@
</p>
{/if}
<div class="w-full relative">
<PostActions post={data.post.post_view} />
<PostActions
post={data.post.post_view}
on:edit={(e) => {
post.name = e.detail.post.name
post.body = e.detail.post.body
post.url = e.detail.post.url
toast({
content: 'The post was edited successfully.',
type: ToastType.success,
})
}}
/>
</div>
</div>
<div class="mt-4 flex flex-col gap-2">