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

+157
View File
@@ -0,0 +1,157 @@
<script lang="ts" module>
import { marked } from 'marked'
import { linkify, subSupscriptExtension } from './renderers/plugins.js'
import containerExtension from './renderers/spoiler/spoiler.js'
marked.setOptions({
gfm: true,
breaks: false,
})
marked.use(linkify, {
extensions: [
// @ts-expect-error hell with marked
containerExtension((params: any) => {
if (params.type == 'spoiler') {
return {
type: 'spoiler',
raw: params.raw,
title: params.options,
tokens: [],
}
}
return null
}),
// @ts-expect-error hell with marked
subSupscriptExtension((params: any) => {
if (params.type == 'subscript') {
return {
type: 'subscript',
raw: params.raw,
text: params.content,
}
}
if (params.type == 'superscript') {
return {
type: 'superscript',
raw: params.raw,
text: params.content,
}
}
return null
}),
],
})
export const renderers = {
heading: MdHeading,
image: MdImage,
link: MdLink,
blockquote: MdQuote,
hr: MdHr,
html: MdHtml,
code: MdCode,
list: MdList,
spoiler: MdSpoiler,
table: MdTable,
tablebody: MdTableBody,
tablecell: MdTableCell,
tablehead: MdTableHead,
tablerow: MdTableRow,
paragraph: MdParagraph,
listitem: MdListItem,
subscript: MdSubscript,
superscript: MdSuperscript,
space: MdParagraph,
list_item: MdListItem,
text: MdText,
em: MdEm,
strong: MdStrong,
del: MdDel,
codespan: MdCodespan,
}
export const inlineRenderers = {
paragraph: MdParagraph,
subscript: MdSubscript,
superscript: MdSuperscript,
text: MdText,
link: MdLink,
em: MdEm,
strong: MdStrong,
del: MdDel,
codespan: MdCodespan,
}
export type Renderer = keyof typeof renderers
</script>
<script lang="ts">
import { setContext } from 'svelte'
import type { ClassValue } from 'svelte/elements'
import MdTree from './MdTree.svelte'
import MdEm from './renderers/subtext/MdEm.svelte'
import MdHeading from './renderers/MdHeading.svelte'
import MdImage from './renderers/MdImage.svelte'
import MdLink from './renderers/MdLink.svelte'
import MdQuote from './renderers/MdQuote.svelte'
import MdHr from './renderers/MdHr.svelte'
import MdHtml from './renderers/MdHtml.svelte'
import MdCode from './renderers/MdCode.svelte'
import MdList from './renderers/MdList.svelte'
import MdSpoiler from './renderers/MdSpoiler.svelte'
import MdTable from './renderers/table/MdTable.svelte'
import MdTableBody from './renderers/table/MdTableBody.svelte'
import MdTableCell from './renderers/table/MdTableCell.svelte'
import MdTableHead from './renderers/table/MdTableHead.svelte'
import MdTableRow from './renderers/table/MdTableRow.svelte'
import MdParagraph from './renderers/MdParagraph.svelte'
import MdListItem from './renderers/MdListItem.svelte'
import MdSubscript from './renderers/MdSubscript.svelte'
import MdSuperscript from './renderers/MdSuperscript.svelte'
import MdText from './renderers/MdText.svelte'
import MdStrong from './renderers/subtext/MdStrong.svelte'
import MdDel from './renderers/subtext/MdDel.svelte'
import MdCodespan from './renderers/subtext/MdCodespan.svelte'
interface RendererOptions {
autoloadImages: boolean
}
interface Props {
source?: string
inline?: boolean
noStyle?: boolean
style?: string
class?: ClassValue
rendererOptions?: RendererOptions
}
let {
source = '',
inline = false,
noStyle = false,
style = '',
class: clazz = '',
rendererOptions = {
autoloadImages: true,
},
}: Props = $props()
setContext('options', {
...rendererOptions,
inline: inline,
noStyle: noStyle,
})
let tokens = $derived(marked.lexer(source))
</script>
<svelte:element
this={inline ? 'div' : 'article'}
dir="auto"
class={[!noStyle && 'break-words space-y-4 leading-normal', clazz]}
{style}
>
<MdTree {tokens} renderers={inline ? inlineRenderers : renderers} />
</svelte:element>
+337
View File
@@ -0,0 +1,337 @@
<script lang="ts">
import MultiSelect from '$comp/input/Switch.svelte'
import Markdown from '$lib/app/markdown/Markdown.svelte'
import { t } from '$lib/app/i18n'
import { Button, Label, Modal, TextArea } from 'mono-svelte'
import type { TextAreaProps } from 'mono-svelte/forms/TextArea.svelte'
import { tick } from 'svelte'
import {
Bold,
CodeBracket,
ExclamationTriangle,
H1,
Icon,
Italic,
Link,
ListBullet,
Photo,
Strikethrough,
} from 'svelte-hero-icons'
import type { ClassValue } from 'svelte/elements'
import ImageAttachForm from '../form/ImageAttachForm.svelte'
let textArea: HTMLTextAreaElement | undefined = $state()
function replaceTextAtIndices(
str: string,
startIndex: number,
endIndex: number,
replacement: string,
) {
return str.substring(0, startIndex) + replacement + str.substring(endIndex)
}
function wrapSelection(start: string, end: string) {
if (!textArea) return
const startPos = textArea.selectionStart
const endPos = textArea.selectionEnd
const substring = textArea.value.substring(startPos, endPos)
let newText = `${start}${substring}${end}`
textArea.value = replaceTextAtIndices(
textArea.value,
startPos,
endPos,
newText,
)
textArea.focus()
textArea.selectionStart = startPos + start.length
textArea.selectionEnd = endPos + start.length
value = textArea.value
}
let uploadingImage = $state(false)
let image = $state<FileList | null | undefined>(null)
const shortcuts = {
b: () => wrapSelection('**', '**'),
i: () => wrapSelection('*', '*'),
s: () => wrapSelection('~~', '~~'),
h: () => wrapSelection('\n# ', ''),
k: () => wrapSelection('[](', ')'),
}
async function adjustHeight() {
await tick()
if (textArea) {
textArea.style.height = 'auto' // Reset height to auto to calculate new height
textArea.style.height = `${textArea.scrollHeight}px` // Set height to the scrollHeight
}
}
function handleKeydown(
event: KeyboardEvent & {
currentTarget: EventTarget & HTMLTextAreaElement
},
) {
if (event.ctrlKey && event.key === 'Enter') {
event.preventDefault()
const form = textArea?.closest('form')
if (form) form.requestSubmit() // Automatically submits the form
}
}
interface Props extends TextAreaProps {
images?: boolean
value?: string
label?: string | undefined
previewButton?: boolean
tools?: boolean
disabled?: boolean
rows?: number
beforePreview?: (input: string) => string
previewing?: boolean
class?: ClassValue
customLabel?: import('svelte').Snippet
children?: import('svelte').Snippet
}
let {
images = true,
value = $bindable(''),
label = undefined,
previewButton = true,
tools = true,
disabled = false,
rows = 2,
// should be preprocess instead
beforePreview = (input) => input,
previewing = $bindable(false),
class: clazz = '',
customLabel,
children,
...rest
}: Props = $props()
$effect(() => {
if (!previewing && value) adjustHeight()
})
</script>
{#if uploadingImage && images}
<Modal title={$t('form.post.uploadImage')} bind:open={uploadingImage}>
<ImageAttachForm
bind:image
onupload={(e) => {
e.forEach((i) => {
wrapSelection(`![](${i})\n\n`, '')
})
}}
/>
</Modal>
{/if}
<div>
{#if label || customLabel}
<Label>
{#if label}
{label}
{:else if customLabel}
{@render customLabel?.()}
{/if}
</Label>
{/if}
<div
class={[
'flex flex-col border border-slate-200 border-b-slate-300 dark:border-zinc-800',
'focus-within:border-primary-900 dark:focus-within:border-primary-100 focus-within:ring-3 ring-slate-300 dark:ring-zinc-700',
'bg-white dark:bg-zinc-950',
'rounded-2xl overflow-hidden transition-colors',
label && 'mt-1',
clazz,
]}
>
{#if previewing}
<div
class="p-5 overflow-auto text-sm resize-y bg-white dark:bg-zinc-950 min-h-48"
>
<Markdown source={beforePreview(value)} />
</div>
{:else}
{#if tools}
<!--Toolbar-->
<div
class={[
'*:shrink-0 flex flex-row overflow-auto p-1.5 gap-1.5',
disabled && 'opacity-60 pointer-events-none',
]}
>
<Button
onclick={() => wrapSelection('**', '**')}
title="Bold"
size="custom"
class="w-8 h-8"
rounding="lg"
>
<Icon src={Bold} size="15" micro />
</Button>
<Button
onclick={() => wrapSelection('*', '*')}
title="Italic"
size="custom"
class="w-8 h-8"
rounding="lg"
>
<Icon src={Italic} size="15" micro />
</Button>
<Button
onclick={() => wrapSelection('[', '](https://example.com)')}
title="Link"
size="custom"
class="w-8 h-8"
rounding="lg"
>
<Icon src={Link} size="15" micro />
</Button>
<Button
onclick={() => wrapSelection('\n# ', '')}
title="Header"
size="custom"
class="w-8 h-8"
rounding="lg"
>
<Icon src={H1} size="15" micro />
</Button>
<Button
onclick={() => wrapSelection('~~', '~~')}
title="Strikethrough"
size="custom"
class="w-8 h-8"
rounding="lg"
>
<Icon src={Strikethrough} size="15" micro />
</Button>
<Button
onclick={() => wrapSelection('\n> ', '')}
title="Quote"
size="custom"
class="w-8 h-8"
rounding="lg"
>
<span class="font-bold font-serif text-lg">"</span>
</Button>
<Button
onclick={() => wrapSelection('\n- ', '')}
title="List"
size="custom"
class="w-8 h-8"
rounding="lg"
>
<Icon src={ListBullet} micro size="15" />
</Button>
<Button
onclick={() => wrapSelection('`', '`')}
title="Code"
size="custom"
class="w-8 h-8"
rounding="lg"
>
<Icon src={CodeBracket} micro size="15" />
</Button>
<Button
onclick={() =>
wrapSelection('::: spoiler <spoiler title>\n', '\n:::')}
title="Spoiler"
size="custom"
class="w-8 h-8"
rounding="lg"
>
<Icon src={ExclamationTriangle} micro size="15" />
</Button>
<Button
onclick={() => wrapSelection('~', '~')}
title="Subscript"
size="custom"
class="w-8 h-8"
rounding="lg"
>
<span class="font-bold">
X
<sub>1</sub>
</span>
</Button>
<Button
onclick={() => wrapSelection('^', '^')}
title="Superscript"
size="custom"
class="w-8 h-8"
rounding="lg"
>
<span class="font-bold">
X
<sup>1</sup>
</span>
</Button>
{#if images}
<Button
onclick={() => (uploadingImage = !uploadingImage)}
title="Image"
size="custom"
class="w-8 h-8"
rounding="lg"
>
<Icon src={Photo} size="15" micro />
</Button>
{/if}
</div>
{/if}
<!--Actual text area-->
<TextArea
class="bg-inherit z-0 border-0 rounded-none ring-0! focus:ring-transparent! transition-none! resize-none"
bind:value
bind:element={textArea}
onkeydown={(e) => {
if (disabled) return
if (e.ctrlKey || e.metaKey) {
handleKeydown(e)
// @ts-expect-error yes it can
let shortcut = shortcuts[e.key]
if (shortcut) {
e.preventDefault()
shortcut?.(e)
}
}
}}
oninput={adjustHeight}
onpaste={(e) => {
if (!e.clipboardData?.files) return
const files = Array.from(e.clipboardData.files)
if (files[0]?.type.startsWith('image/')) {
image = e.clipboardData.files[0] as unknown as FileList | null
uploadingImage = true
}
}}
{rows}
{...rest}
/>
{/if}
{#if previewButton}
<div
class="p-2 flex flex-row items-center w-full bg-slate-50 border-t border-slate-200 dark:border-zinc-900 dark:bg-zinc-925 gap-1"
>
{#if previewButton}
<MultiSelect
bind:selected={previewing}
options={[false, true]}
optionNames={[$t('form.edit'), $t('form.preview')]}
/>
{/if}
{@render children?.()}
</div>
{/if}
</div>
</div>
+115
View File
@@ -0,0 +1,115 @@
<script lang="ts">
import type { Tokens } from 'marked'
import type { Renderer } from './Markdown.svelte'
import Self from './MdTree.svelte'
interface Props {
type?: Renderer
raw?: string
renderers: any
tokens?: Tokens.Generic[]
text?: string
align?: string
header?: boolean
}
let {
type,
tokens = [],
renderers,
raw,
text,
header,
...rest
}: Props = $props()
function decodeHtmlEntities(input: string) {
return input
.replace(/&#39;/g, "'")
.replace(/&quot;/g, '"')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&amp;/g, '&')
}
if (header) {
type = 'tablecell'
}
</script>
{#if type}
{#if renderers[type]}
{@const Renderer = renderers[type]}
<Renderer {...rest} {raw} {text}>
{#each tokens as token}
{#if type != 'list' && type != 'table'}
{#if token.tokens && token.tokens.length > 0}
<Self
tokens={token.tokens as Tokens.Generic[]}
{renderers}
{...rest}
/>
{:else if token.text}
{decodeHtmlEntities(token.text)}
{:else if text}
{text}
{/if}
{:else if type == 'list' && token.items}
{#each token.items as item}
<Self type="list_item" {renderers} tokens={[item]} {...rest} />
{/each}
{:else if type == 'table'}
{@const THead = renderers['tablehead']}
{@const TBody = renderers['tablebody']}
{@const TRow = renderers['tablerow']}
{#if token.header}
<THead>
<TRow>
{#each token.header as heading, index}
<Self
{...rest}
type="tablecell"
{renderers}
tokens={heading.tokens}
align={token.align[index]}
/>
{/each}
</TRow>
</THead>
<!-- <Self {renderers} tokens={token.header} {...rest} /> -->
{/if}
{#if token.rows}
<TBody>
{#each token.rows as row}
<TRow>
{#each row as cell, index}
<Self
{...rest}
type="tablecell"
{renderers}
tokens={cell.tokens}
align={token.align[index]}
/>
{/each}
</TRow>
{/each}
</TBody>
{/if}
{/if}
{/each}
</Renderer>
{/if}
{:else}
{#each tokens as token}
<Self
{...token}
tokens={[token]}
type={token.type as Renderer}
{renderers}
raw={token.raw}
text={token.text}
{...rest}
/>
{/each}
{/if}
@@ -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>