impr: restructure src/lib

This commit is contained in:
Xylight committed 2025-09-24 17:12:19 -07:00
1 parent d85b889409
commit 75f907743e
376 files changed
+1000 -1033

No files matched your search

@@ -0,0 +1,61 @@
<script lang="ts">
import { t } from '$lib/app/i18n'
import { Button, Material, toast } from 'mono-svelte'
import { Icon, ClipboardDocument } from 'svelte-hero-icons'
interface Props {
raw: string
}
let { raw }: Props = $props()
function parseCodeblock(src: string): {
code: string
lang?: string
} {
const match = /^```(.*)/gi.exec(src)
if (match?.[1]) {
return {
code: src.replace(/^```(.*)/gi, '').replaceAll('```', ''),
lang: match?.[1],
}
} else {
return { code: src.replaceAll('```', '') }
}
}
let codeblock = $derived(parseCodeblock(raw))
</script>
<Material
padding="none"
rounding="2xl"
class="flex flex-col rounded-xl
divide-y divide-slate-200 dark:divide-zinc-800 overflow-hidden"
>
<div
class="w-full bg-slate-25 dark:bg-zinc-925 h-9 flex items-center justify-between p-2"
>
<pre class="code-baseline text-xs"> {codeblock.lang}</pre>
<Button
size="square-sm"
color="tertiary"
onclick={() => {
navigator?.clipboard?.writeText(codeblock.code)
toast({ content: $t('toast.copied') })
}}
>
<Icon
src={ClipboardDocument}
size="16"
micro
class="text-slate-600 dark:text-zinc-400"
/>
</Button>
</div>
<pre
class="code-baseline w-full overflow-x-auto text-xs bg-white dark:bg-zinc-950 px-4">
{codeblock.code}
</pre>
</Material>
@@ -0,0 +1,25 @@
<script lang="ts">
interface Props {
depth?: number
raw?: string | undefined
children?: import('svelte').Snippet
}
let { depth = 0, raw = undefined, children }: Props = $props()
</script>
{#if depth === 1}
<h1 class="font-bold text-4xl">{@render children?.()}</h1>
{:else if depth === 2}
<h2 class="font-bold text-3xl">{@render children?.()}</h2>
{:else if depth === 3}
<h3 class="font-bold text-2xl">{@render children?.()}</h3>
{:else if depth === 4}
<h4 class="font-semibold text-xl">{@render children?.()}</h4>
{:else if depth === 5}
<h5 class="font-semibold text-lg">{@render children?.()}</h5>
{:else if depth === 6}
<h6 class="font-semibold text-base">{@render children?.()}</h6>
{:else}
{raw}
{/if}
@@ -0,0 +1 @@
<hr class="border-slate-200 dark:border-zinc-800" />
@@ -0,0 +1,11 @@
<script lang="ts">
interface Props {
text: string
}
let { text }: Props = $props()
</script>
<p>
{text}
</p>
@@ -0,0 +1,72 @@
<script lang="ts">
import {
iframeType,
mediaType,
optimizeImageURL,
PostIframe,
} from '$comp/lemmy/post'
import { showImage } from '$lib/ui/generic/ExpandableImage.svelte'
import { t } from '$lib/app/i18n'
import { getContext } from 'svelte'
import { ArrowDownTray, Icon } from 'svelte-hero-icons'
let loaded: boolean = $state(
(getContext('options') as { autoloadImages: boolean })?.autoloadImages ??
true,
)
interface Props {
href: string
title?: string | undefined
text?: string
}
let { href, title = undefined, text = '' }: Props = $props()
let type = $derived(mediaType(href))
</script>
<div
class="w-auto h-auto max-h-96 rounded-xl border border-slate-200 dark:border-zinc-800 inline-block group"
>
{#if loaded}
{#if type == 'video' || type == 'embed' || type == 'iframe'}
<PostIframe
type={iframeType(href)}
url={href}
opened={true}
autoplay={false}
class="w-auto h-auto max-h-80 inline-block rounded-[inherit] cursor-pointer"
/>
{:else}
<button
class="inline cursor-pointer bg-slate-200 dark:bg-zinc-800 rounded-[inherit]"
onclick={() => showImage(optimizeImageURL(href, -1))}
>
<img
src={optimizeImageURL(href, 1024)}
{title}
alt={text}
width={300}
height={300}
class={[
'object-contain w-auto h-auto max-h-80 inline rounded-[inherit] group-hover:scale-98 group-active:scale-95',
'transition-transform ease-cubic',
]}
/>
</button>
{/if}
{:else}
<button
onclick={() => (loaded = true)}
class="w-40 h-40 flex flex-col justify-center items-center gap-4 p-2 group cursor-pointer"
title={$t('common.download')}
>
<Icon
src={ArrowDownTray}
size="24"
class="text-primary-900 dark:text-primary-100"
/>
</button>
{/if}
</div>
@@ -0,0 +1,29 @@
<script lang="ts">
import { photonify } from './plugins.js'
interface Props {
href?: string
title?: string
children?: import('svelte').Snippet
}
let { href = '', title = undefined, children }: Props = $props()
export const parseURL = (href: string) => {
try {
return new URL(href)
} catch {
return undefined
}
}
let photonified = $derived(photonify(href))
</script>
<a
href={photonified ?? href}
{title}
class="hover:underline text-blue-600 dark:text-blue-400"
>
{@render children?.()}
</a>
@@ -0,0 +1,19 @@
<script lang="ts">
interface Props {
ordered: boolean
start: number
children?: import('svelte').Snippet
}
let { ordered, start, children }: Props = $props()
</script>
{#if ordered}
<ol {start} class="pl-5 list-decimal">
{@render children?.()}
</ol>
{:else}
<ul class="list-disc pl-8 *:marker:content-['• ']!">
{@render children?.()}
</ul>
{/if}
@@ -0,0 +1,17 @@
<script>
let { children } = $props()
</script>
<li>
{@render children?.()}
</li>
<style>
@reference '../../../../app.css';
li::marker {
color: var(--color-slate-400);
@variant dark {
color: var(--color-zinc-600);
}
}
</style>
@@ -0,0 +1,17 @@
<script>
import { getContext } from 'svelte'
let { children } = $props()
const options = getContext('options')
</script>
<p class={[!options.noStyle && 'leading-[1.7] break-words max-w']}>
{@render children?.()}
</p>
<style>
.max-w {
max-width: 70ch;
}
</style>
@@ -0,0 +1,15 @@
<script>
/**
* @typedef {Object} Props
* @property {import('svelte').Snippet} [children]
*/
/** @type {Props} */
let { children } = $props()
</script>
<blockquote
class="flex flex-col gap-2 border-l-2 dark:border-zinc-700 border-slate-300 p-1 px-3"
>
{@render children?.()}
</blockquote>
@@ -0,0 +1,39 @@
<script lang="ts">
import Expandable from 'mono-svelte/disclosure/Expandable.svelte'
import type { Snippet } from 'svelte'
interface Props {
raw: string
children?: Snippet
}
let { raw, children }: Props = $props()
function extractTitle(text: string) {
const spoilerRegex = /^::: ?spoiler (.+)\n([\s\S]+?)\n:::/gm
const result = spoilerRegex.exec(text)
if (!result?.[1] || !result?.[2])
return {
title: 'parsing error',
content: 'parsing error',
}
return {
title: result[1],
content: result[2],
}
}
let data = $derived(extractTitle(raw))
</script>
<Expandable class="border-y border-slate-200 dark:border-zinc-800 py-2">
{#snippet title()}
<div class="text-left">
{data.title}
</div>
{/snippet}
{@render children?.()}
</Expandable>
@@ -0,0 +1,9 @@
<script lang="ts">
interface Props {
text: string
}
let { text }: Props = $props()
</script>
<sub>{text}</sub>
@@ -0,0 +1,9 @@
<script lang="ts">
interface Props {
text: string
}
let { text }: Props = $props()
</script>
<sup>{text}</sup>
@@ -0,0 +1,11 @@
<script>
/**
* @typedef {Object} Props
* @property {import('svelte').Snippet} [children]
*/
/** @type {Props} */
let { children } = $props()
</script>
{@render children?.()}
+173
View File
@@ -0,0 +1,173 @@
import { marked } from 'marked'
import markedLinkifyIt from 'marked-linkify-it'
export const spoilerPlugin = {
name: 'spoiler',
level: 'block',
start(src) {
return src.match(/:::/)?.index
},
// eslint-disable-next-line
tokenizer(src, tokens) {
const rule = /::: ?spoiler(?: ?(.*))\n([\s\S]*?)\n:::/
const match = rule.exec(src)
if (match) {
return {
type: 'spoiler',
raw: match[0],
title: match[1].trim(),
text: match[2].trim(),
}
}
},
renderer(token) {
return `
<details>
<summary>${marked.parseInline(token.title)}</summary>
${marked.parse(token.text)}
</details>
`
},
}
export const linkify = markedLinkifyIt(
{
'!': {
validate: function (text, pos, self) {
var tail = text.slice(pos)
if (!self.re.community) {
self.re.community = new RegExp(
/^([a-z0-9_.-]+)@([\da-z.-]+)\.([a-z]{2,63})/i,
)
}
if (self.re.community.test(tail)) {
// Linkifier allows punctuation chars before prefix,
// but we additionally disable `@` ("@@mention" is invalid)
if (pos >= 2 && tail[pos - 2] === '!') {
return false
}
return tail.match(self.re.community)[0].length
}
return 0
},
normalize: function (match) {
let prefix = match.url
prefix = prefix.startsWith('c/') ? prefix.slice(2) : prefix.slice(1)
match.url = `/c/${prefix}`
},
},
'@': {
validate: function (text, pos, self) {
var tail = text.slice(pos)
if (!self.re.user) {
self.re.user = new RegExp(
/^([a-z0-9_.-]+)@([\da-z.-]+)\.([a-z]{2,63})/i,
)
}
if (self.re.user.test(tail)) {
// Linkifier allows punctuation chars before prefix,
// but we additionally disable `@` ("@@mention" is invalid)
if (pos >= 2 && tail[pos - 2] === '!') {
return false
}
return tail.match(self.re.user)[0].length
}
return 0
},
normalize: function (match) {
let prefix = match.url
prefix = prefix.startsWith('u/') ? prefix.slice(2) : prefix.slice(1)
match.url = `/u/${prefix}`
},
},
},
{
fuzzyEmail: false,
},
)
const regexes = {
post: /^https:\/\/([a-zA-Z0-9.-]+)\/post\/(\d+)$/i,
comment: /^https:\/\/([a-zA-Z0-9.-]+)\/comment\/(\d+)$/i,
user: /^https:\/\/([a-zA-Z0-9.-]+)(\/u\/)([a-zA-Z0-9.-_]+)$/i,
community: /^https:\/\/([a-zA-Z0-9.-]+)(\/c\/)([a-zA-Z0-9.-_]+)$/i,
implicitUser: /^mailto:([a-z0-9_.-]+)@(([\da-z.-]+)\.([a-z]{2,63}))/i,
}
/**
* Convert links to photon links
*/
export const photonify = (link) => {
if (regexes.community.test(link)) {
const match = link.match(regexes.community)
if (!match) return
// If the match[3] includes @, the URL included an instance already, so don't add one.
if (match?.[3].includes('@')) return `/c/${match?.[3]}`
else return `/c/${match?.[3]}@${match?.[1]}`
}
if (regexes.post.test(link)) {
const match = link.match(regexes.post)
if (!match) return
return `/post/${match?.[1]}/${match?.[2]}`
}
if (regexes.comment.test(link)) {
const match = link.match(regexes.comment)
if (!match) return
return `/comment/${match?.[1]}/${match?.[2]}`
}
if (regexes.user.test(link)) {
const match = link.match(regexes.user)
if (!match) return
// Same as above for the community.
if (match?.[3].includes('@')) return `/u/${match?.[3]}`
else return `/u/${match?.[3]}@${match?.[1]}`
}
// Support implicit user syntax (no preceding @), by messing with mailto links.
if (regexes.implicitUser.test(link)) {
const exec = regexes.implicitUser.exec(link)
if (!exec?.[1] || !exec?.[2]) return
return `/u/${exec[1]}@${exec[2]}`
}
}
export function subSupscriptExtension(tokensExtractor) {
return {
name: 'subscriptSuperscript',
level: 'inline',
start(src) {
return src.match(/[~^]/)?.index
},
// eslint-disable-next-line
tokenizer(src, tokens) {
const subscriptRule = /^~([^~\s](?:[^~]*[^~\s])?)~/
const superscriptRule = /^\^([^^\s](?:[^^]*[^^\s])?)\^/
let match
if ((match = subscriptRule.exec(src))) {
return tokensExtractor({
type: 'subscript',
content: match[1],
raw: match[0],
lexer: this.lexer,
})
}
if ((match = superscriptRule.exec(src))) {
return tokensExtractor({
type: 'superscript',
content: match[1],
raw: match[0],
lexer: this.lexer,
})
}
},
}
}
@@ -0,0 +1,100 @@
/**
* Container extension is a marked extension that parses a block of text surrounded by :::
*
* @param tokensExtractor Converts the container input into a custom token that svelte components will receive.
* If this function returns a value that contains an array of `tokens`,
* this array will be populated with the tokens that are found inside the container,
* allowing to nest markdown inside the container.
*
* @example
*
* Given the following markdown:
*
* :::container option="option-1" option-2="option-2" boolean-option
* Something inside the container
* :::
*
* The token extractor would receive the following parameters:
* **type**: `container`
* **content**: `Something inside the container`
* **options**: { 'option': 'option-1', 'option-2': 'option-2', 'boolean-option': true }
*/
export default function (tokensExtractor) {
return {
name: 'container',
level: 'block',
start(src) {
return src.match(/:::[^:\n]/)?.index
},
tokenizer(src) {
const rule =
/:::[\s]?(?<type>[a-z0-9-]+)(?<options>.*)?\n(?<content>(?:.|\n)*)\n:::(?:\n)*/i
const match = rule.exec(findRawContainer(src))
if (!match || !match.groups) return null
const type = match.groups.type.toLocaleLowerCase()
const options = parseOptions(match.groups.options || '')
const content = match.groups.content || ''
const result = tokensExtractor({
type: type,
content: content,
raw: match[0],
options: options,
lexer: this.lexer,
})
if (result?.tokens) {
this.lexer.blockTokens(content, result.tokens)
}
return result
},
}
}
function findRawContainer(src) {
if (!src.startsWith(':::')) return undefined
const lines = src.split('\n')
let open = 1
let lineNumber = 1
for (lineNumber = 1; lineNumber < lines.length; lineNumber++) {
const line = lines[lineNumber]
if (line.startsWith(':::')) {
if (/:::[^:\n\s]/.test(line)) {
open++
} else if (/^:::(\n|$)/.test(line)) {
open -= 1
}
}
if (open === 0) {
break
}
}
return lines.slice(0, lineNumber + 1).join('\n')
}
function parseOptions(options) {
const output = {}
let remaining = options
while (true) {
const regex = /(?<name>[a-z0-9]+)(?:="(?<value>(?:.*?))")?/i
const match = regex.exec(remaining)
if (!match) break
const name = match?.groups?.name
if (name) {
output[name] = match?.groups?.value ?? true
}
remaining = remaining.slice(match.index + match[0].length)
}
return output
}
@@ -0,0 +1,11 @@
<script lang="ts">
import type { Snippet } from 'svelte'
interface Props {
children: Snippet
}
let { children }: Props = $props()
</script>
<code>{@render children?.()}</code>
@@ -0,0 +1,11 @@
<script lang="ts">
import type { Snippet } from 'svelte'
interface Props {
children: Snippet
}
let { children }: Props = $props()
</script>
<del>{@render children?.()}</del>
@@ -0,0 +1,11 @@
<script lang="ts">
import type { Snippet } from 'svelte'
interface Props {
children: Snippet
}
let { children }: Props = $props()
</script>
<em>{@render children?.()}</em>
@@ -0,0 +1,11 @@
<script lang="ts">
import type { Snippet } from 'svelte'
interface Props {
children: Snippet
}
let { children }: Props = $props()
</script>
<strong>{@render children?.()}</strong>
@@ -0,0 +1,48 @@
<script lang="ts">
let { children } = $props()
</script>
<div class="overflow-auto w-full table-container">
<table class="w-full table-fixed rounded-xl min-w-md">
{@render children?.()}
</table>
</div>
<style>
@reference "../../../../../app.css";
.table-container {
border: 1px solid var(--color-slate-200);
background-color: white;
border-radius: var(--radius-2xl);
@variant dark {
background-color: var(--color-zinc-950);
border: 1px solid var(--color-zinc-800);
}
}
.table-container table {
table-layout: fixed !important;
:global(thead tr td) {
padding: calc(var(--spacing) * 1.5) calc(var(--spacing) * 3);
border-bottom: 1px solid var(--color-slate-200);
font-weight: var(--font-weight-medium);
font-size: var(--text-base);
background-color: var(--color-slate-25);
@variant dark {
background-color: var(--color-zinc-900);
border-bottom: 1px solid var(--color-zinc-800);
}
}
}
.table-container table {
:global(tbody tr td) {
font-size: var(--text-sm);
padding: calc(var(--spacing) * 1) calc(var(--spacing) * 3);
}
}
</style>
@@ -0,0 +1,11 @@
<script>
/**
* @typedef {Object} Props
* @property {import('svelte').Snippet} [children]
*/
/** @type {Props} */
let { children } = $props()
</script>
<tbody>{@render children?.()}</tbody>
@@ -0,0 +1,19 @@
<script lang="ts">
interface Props {
header: boolean
align?: 'left' | 'center' | 'right' | 'justify' | 'char' | null | undefined
children?: import('svelte').Snippet
}
let { header, align = undefined, children }: Props = $props()
</script>
{#if header}
<th {align}>
{@render children?.()}
</th>
{:else}
<td {align}>
{@render children?.()}
</td>
{/if}
@@ -0,0 +1,5 @@
<script lang="ts">
let { children } = $props()
</script>
<thead>{@render children?.()}</thead>
@@ -0,0 +1,11 @@
<script>
/**
* @typedef {Object} Props
* @property {import('svelte').Snippet} [children]
*/
/** @type {Props} */
let { children } = $props()
</script>
<tr>{@render children?.()}</tr>