Add keyword and URL filtering for posts (#711)

* feat: Add keyword and URL filtering for posts

* impr: add minimizing filters, improve UI, fix some reactivity problems
This commit is contained in:
Kehet authored and GitHub committed 2026-01-29 02:28:50 +00:00
1 parent 21a0baacf9
commit 5630ac3bf8
8 files changed
+232 -42

No files matched your search

+8
View File
@@ -903,6 +903,14 @@
"deleted": "Deleted by user",
"removed": "Removed by moderator"
},
"contentFilter": {
"title": "Content filters",
"description": "Hide or minimize posts matching given strings. Supports regular expressions.",
"hide": "Hide",
"minimize": "Minimize",
"minimized": "Content hidden by your filters",
"disabled": "Off"
},
"nsfwBlur": {
"title": "NSFW blur",
"description": "Blurs images and remove post bodies of NSFW posts."
+6
View File
@@ -47,6 +47,12 @@
}
}
export function rerender() {
requestAnimationFrame(() => {
updateVisibleItems()
})
}
onDestroy(() => {
restore = {
itemHeights: itemHeights,
+6 -2
View File
@@ -1,8 +1,11 @@
import { browser } from '$app/environment'
import { env } from '$env/dynamic/public'
import type { CommentSortType, ListingType, SortType } from '$lib/api/types'
import type { Filter } from '$lib/feature/post/filters'
import { locale } from './i18n'
// TODO extract settings into submodules
export type View = 'cozy' | 'compact'
export const SSR_ENABLED = env.PUBLIC_SSR_ENABLED?.toLowerCase() == 'true'
@@ -89,6 +92,7 @@ interface Settings {
reverseActions: boolean
titleOpensUrl: boolean
}
filters: Filter[]
forms: {
autosubmitAutofill: boolean
}
@@ -97,7 +101,6 @@ interface Settings {
useRtl: boolean
parseTags: boolean
logoColorMonth: number | null
absoluteDates: boolean
messages: {
fullMarkdown: boolean
@@ -106,7 +109,7 @@ interface Settings {
}
export const defaultSettings: Settings = {
settingsVer: 7,
settingsVer: 8,
expandableImages: toBool(env.PUBLIC_EXPANDABLE_IMAGES) ?? true,
markReadPosts: toBool(env.PUBLIC_MARK_READ_POSTS) ?? true,
showInstances: {
@@ -172,6 +175,7 @@ export const defaultSettings: Settings = {
reverseActions: toBool(env.PUBLIC_REVERSE_ACTIONS) ?? false,
titleOpensUrl: toBool(env.PUBLIC_TITLE_OPENS_URL) ?? false,
},
filters: [],
forms: {
autosubmitAutofill: false,
},
+47 -17
View File
@@ -4,8 +4,10 @@
import Placeholder from '$lib/ui/info/Placeholder.svelte'
import { Button } from 'mono-svelte'
import type { Snippet } from 'svelte'
import { ArchiveBox, Plus } from 'svelte-hero-icons/dist'
import { ArchiveBox, ArrowsPointingOut, Plus } from 'svelte-hero-icons/dist'
import { Post } from '..'
import { filterPost, type FilteredItem } from '../filters'
import { t } from '$lib/app/i18n'
interface Props {
posts: PostView[]
@@ -14,12 +16,25 @@
}
let { posts = $bindable(), community = false, children }: Props = $props()
let filteredPosts: FilteredItem[] = $derived(
posts.map((post) => ({
id: post.post.id,
action: filterPost(post, settings.filters),
})),
)
const removePost = (postId: number) => {
const index = posts.findIndex((post) => post.post.id === postId)
if (index === -1) return
posts = posts.toSpliced(index, 1)
}
</script>
<ul
class="flex flex-col list-none divide-y divide-slate-200 dark:divide-zinc-800"
>
{#if posts?.length == 0}
{#if posts.length === 0}
<div class="h-full grid place-items-center">
<Placeholder
icon={ArchiveBox}
@@ -32,21 +47,36 @@
</Placeholder>
</div>
{:else}
{#each posts as post, index (post.post.id)}
<li class="relative post-container">
<Post
hideCommunity={community}
view={(post.post.featured_community || post.post.featured_local) &&
settings.posts.compactFeatured
? 'compact'
: settings.view}
{post}
class="transition-all duration-250"
onhide={() => {
posts = posts.toSpliced(index, 1)
}}
/>
</li>
{#each posts as post, row (post.post.id)}
{@const filter = filteredPosts[row]}
{#if filter.action != 'hide'}
<li class="relative post-container">
{#if filter.action == 'none'}
<Post
hideCommunity={community}
view={(post.post.featured_community ||
post.post.featured_local) &&
settings.posts.compactFeatured
? 'compact'
: settings.view}
{post}
class="transition-all duration-250"
onhide={() => removePost(post.post.id)}
/>
{:else if filteredPosts[row].action == 'minimize'}
<Button
onclick={() => (filteredPosts[row].action = 'none')}
color="tertiary"
rounding="none"
icon={ArrowsPointingOut}
class="text-slate-400 dark:text-zinc-600 w-full"
size="xs"
>
{$t('settings.lemmy.contentFilter.minimized')}
</Button>
{/if}
</li>
{/if}
{/each}
{/if}
{@render children?.()}
+59 -22
View File
@@ -12,6 +12,7 @@
import { onDestroy, onMount, untrack } from 'svelte'
import {
ArchiveBox,
ArrowsPointingOut,
ArrowTopRightOnSquare,
ChevronDoubleUp,
ExclamationTriangle,
@@ -22,6 +23,8 @@
import { SvelteSet } from 'svelte/reactivity'
import { fly } from 'svelte/transition'
import { Post } from '..'
import { filterPost, type FilteredItem } from '../filters'
import { ReactiveState } from '$lib/app/util.svelte'
interface Props {
posts: PostView[]
@@ -41,9 +44,17 @@
children,
}: Props = $props()
let filteredPosts: FilteredItem[] = $derived(
posts.map((post) => ({
id: post.post.id,
action: filterPost(post, settings.filters),
})),
)
let listEl = $state<HTMLUListElement>()
let listComp = $state<{
scrollToIndex: (index: number, window?: boolean) => void
rerender: () => void
}>()
let error = $state()
@@ -53,6 +64,12 @@
const abortLoad = new AbortController()
let seenIds = new SvelteSet<number>(posts.map((post) => post.post.id))
const removePost = (postId: number) => {
const index = posts.findIndex((post) => post.post.id === postId)
if (index === -1) return
posts = posts.toSpliced(index, 1)
}
async function loadMore() {
if (!hasMore || loading) return
@@ -157,7 +174,7 @@
<ul class="flex flex-col list-none" bind:this={listEl}>
{#key posts}
{#if posts?.length == 0}
{#if posts.length == 0}
<div class="h-full grid place-items-center my-8">
<Placeholder
icon={ArchiveBox}
@@ -186,27 +203,47 @@
bind:this={listComp}
>
{#snippet item(row)}
<li
in:fly={row < 7
? { duration: 800, easing: expoOut, y: 24, delay: row * 50 }
: { opacity: 1, duration: 0 }}
data-index={row}
class={['relative post-container', row < 7 && '']}
>
<Post
bind:post={posts[row]}
hideCommunity={community}
view={(posts[row]?.post.featured_community ||
posts[row]?.post.featured_local) &&
settings.posts.compactFeatured
? 'compact'
: settings.view}
onhide={() => {
posts = posts.toSpliced(row, 1)
}}
class="px-3 sm:px-6 hover:bg-slate-100/30 hover:dark:bg-zinc-900/30 transition-colors"
></Post>
</li>
<!--god svelte is gonna make me lose it-->
{@const filter = new ReactiveState(filteredPosts[row])}
{#if posts[row] && filter.value.action != 'hide'}
<li
in:fly={row < 7
? { duration: 800, easing: expoOut, y: 24, delay: row * 50 }
: { opacity: 1, duration: 0 }}
data-index={row}
class={['relative post-container', row < 7 && '']}
>
<!--TODO make my component isolation not abysmal-->
{#if filter.value.action == 'none'}
<Post
bind:post={posts[row]}
hideCommunity={community}
view={(posts[row].post.featured_community ||
posts[row].post.featured_local) &&
settings.posts.compactFeatured
? 'compact'
: settings.view}
onhide={() => removePost(posts[row].post.id)}
class="px-3 sm:px-6 hover:bg-slate-100/30 hover:dark:bg-zinc-900/30 transition-colors"
></Post>
{:else if filter.value.action == 'minimize'}
<Button
onclick={() => {
filteredPosts[row].action = 'none'
filter.value.action = 'none'
listComp?.rerender()
}}
color="tertiary"
rounding="none"
icon={ArrowsPointingOut}
class="text-slate-400 dark:text-zinc-600 w-full"
size="xs"
>
{$t('settings.lemmy.contentFilter.minimized')}
</Button>
{/if}
</li>
{/if}
{/snippet}
</VirtualList>
{/if}
+30
View File
@@ -0,0 +1,30 @@
import type { PostView } from '$lib/api/types'
type FilterAction = 'none' | 'minimize' | 'hide'
type FilterType = 'keyword'
// since we can test regexes on URLs, why not unify them?
export interface Filter {
match: string
action: FilterAction
type: FilterType
}
export type FilteredItem = { id: number; action: FilterAction }
export function filterPost(post: PostView, filters: Filter[]): FilterAction {
for (const filter of filters) {
try {
const regex = new RegExp(filter.match, 'i')
if (
regex.test(post.post.url ?? '') ||
regex.test(post.post.name) ||
regex.test(post.post.body ?? '')
)
return filter.action
} catch {
/* */
}
}
return 'none'
}
+30 -1
View File
@@ -7,7 +7,7 @@
import Link from '$lib/ui/form/Link.svelte'
import Switch from '$lib/ui/form/Switch.svelte'
import { CommonList } from '$lib/ui/layout'
import { Button, Option, Select } from 'mono-svelte'
import { Button, Option, Select, TextArea } from 'mono-svelte'
import {
ArrowsPointingOut,
ArrowsRightLeft,
@@ -22,12 +22,14 @@
Clock,
CubeTransparent,
DocumentText,
EyeSlash,
Fire,
GlobeAmericas,
Heart,
Icon,
Language,
Photo,
Plus,
Star,
TableCells,
Tag,
@@ -36,6 +38,7 @@
} from 'svelte-hero-icons/dist'
import Setting from '../Setting.svelte'
import ToggleSetting from '../ToggleSetting.svelte'
import Filter from './Filter.svelte'
let localeMap: Map<
string,
@@ -191,6 +194,32 @@
title={$t('settings.app.infiniteScroll.title')}
description={$t('settings.app.infiniteScroll.description')}
/>
<Setting icon={EyeSlash} adaptive={false} mainClass="rounded-b-none!">
{#snippet title()}
<span>{$t('settings.lemmy.contentFilter.title')}</span>
{/snippet}
{#snippet description()}
<span>{$t('settings.lemmy.contentFilter.description')}</span>
{/snippet}
</Setting>
{#each settings.filters as filter, index}
<Filter onremove={() => settings.filters.splice(index, 1)} bind:filter />
{/each}
<li class="rounded-t-none! -mt-1! border-t-0!">
<Button
color="none"
class="w-full p-2"
icon={Plus}
onclick={() =>
settings.filters.push({
match: 'New filter.',
action: 'none',
type: 'keyword',
})}
>
{$t('common.add')}
</Button>
</li>
<Setting icon={Photo}>
{#snippet title()}
<span>{$t('settings.app.thumbnailSide.title')}</span>
+46
View File
@@ -0,0 +1,46 @@
<script lang="ts">
import { t } from '$lib/app/i18n'
import type { Filter } from '$lib/feature/post/filters'
import Switch from '$lib/ui/form/Switch.svelte'
import { Button, TextInput } from 'mono-svelte'
import { Trash } from 'svelte-hero-icons/dist'
interface Props {
filter: Filter
onremove?: () => void
}
let { filter = $bindable(), onremove }: Props = $props()
</script>
<li
class="adaptive px-3 py-1 flex flex-col md:flex-row md:items-center xs gap-4"
>
<TextInput bind:value={filter.match} label="" class="flex-1"></TextInput>
<Switch
options={['hide', 'minimize', 'none']}
optionNames={[
$t('settings.lemmy.contentFilter.hide'),
$t('settings.lemmy.contentFilter.minimize'),
$t('settings.lemmy.contentFilter.disabled'),
]}
bind:selected={filter.action}
/>
<Button
icon={Trash}
size="square-md"
onclick={onremove}
aria-label={$t('common.remove')}
/>
</li>
<style>
li {
border-top-left-radius: 0 !important;
border-top-right-radius: 0 !important;
border-bottom-left-radius: 0 !important;
border-bottom-right-radius: 0 !important;
margin-top: calc(var(--spacing) * -1);
border-top: none !important;
}
</style>