Merge pull request #396 from Xyphyn/svelte-markdown

feat: switch to svelte-markdown
This commit is contained in:
Xylight authored and GitHub committed 2024-08-02 14:29:45 -07:00
commit 6fa728236a
30 files changed
+641 -323

No files matched your search

BIN
View File
Binary file not shown.
+3
View File
@@ -18,10 +18,12 @@
"autoprefixer": "^10.4.16",
"jsdom": "^22.1.0",
"lemmy-js-client": "latest",
"linkify-it": "^5.0.0",
"markdown-it": "^14.1.0",
"markdown-it-container": "^3.0.0",
"markdown-it-sub": "^1.0.0",
"markdown-it-sup": "^1.0.0",
"marked-linkify-it": "^3.1.10",
"mono-svelte": "^1.5.14",
"nprogress": "^0.2.0",
"postcss": "^8.4.30",
@@ -30,6 +32,7 @@
"svelte-check": "^3.0.1",
"svelte-hero-icons": "^5.0.0",
"svelte-infinite-scroll": "^2.0.1",
"svelte-markdown": "^0.4.1",
"sveltekit-i18n": "^2.4.2",
"tailwindcss": "^3.3.3",
"tslib": "^2.4.1",
+3 -3
View File
@@ -79,9 +79,9 @@ export const mediaType = (url?: string, view: View = 'cozy'): MediaType => {
return 'none'
}
export const iframeType = (post: Post): IframeType => {
if (isVideo(post.url)) return 'video'
if (isYoutubeLink(post.url)) return 'youtube'
export const iframeType = (url: string): IframeType => {
if (isVideo(url)) return 'video'
if (isYoutubeLink(url)) return 'youtube'
return 'none'
}
@@ -41,6 +41,7 @@
export let thumbnail: string | undefined = undefined
export let url: string
export let opened = !$userSettings.embeds.clickToView
export let autoplay: boolean = $userSettings.embeds.clickToView
const urlToEmbed = (inputUrl: string) => {
if (type == 'video') {
@@ -52,11 +53,10 @@
const videoID = youtubeVideoID(inputUrl)
if ($userSettings.embeds.clickToView)
url.searchParams.set('autoplay', '1')
if (autoplay) url.searchParams.set('autoplay', '1')
return `https://${youtubeDomain(
$userSettings.embeds.youtube,
$userSettings.embeds.youtube
)}/embed/${videoID}?${url.searchParams.toString()}`
}
@@ -64,7 +64,7 @@
}
const typeData = (
type: IframeType,
type: IframeType
): {
icon: IconSource
text: string
@@ -102,11 +102,7 @@
{#if opened}
{#if type == 'video'}
<!-- svelte-ignore a11y-media-has-caption -->
<video
autoplay={$userSettings.embeds.clickToView}
controls
class="rounded-xl aspect-video"
>
<video {autoplay} controls class="rounded-xl aspect-video">
<source src={url} />
</video>
{:else}
@@ -116,7 +112,7 @@
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen
class="aspect-video rounded-xl dark:bg-zinc-900"
class="aspect-video rounded-xl dark:bg-zinc-900 {$$props.class ?? ''}"
/>
{/if}
{:else}
@@ -102,7 +102,7 @@
{:else if (type == 'iframe' || type == 'video') && (view == 'cozy' || view == 'card') && post.url}
<PostIframe
thumbnail={post.thumbnail_url}
type={iframeType(post)}
type={iframeType(post.url)}
url={post.url}
{opened}
/>
+79 -142
View File
@@ -1,156 +1,93 @@
<script lang="ts" context="module">
import { marked } from 'marked'
marked.setOptions({
pedantic: false,
mangle: false,
headerIds: false,
})
marked.use(linkify, {
extensions: [
containerExtension((params: any) => {
if (params.type == 'spoiler') {
return {
type: 'spoiler',
raw: params.raw,
title: params.options,
tokens: [],
}
}
return null
}),
],
})
export const renderers = {
heading: MdHeading,
image: MdImage,
link: MdLink,
blockquote: MdQuote,
hr: MdHr,
html: MdHtml,
text: MdText,
code: MdCode,
list: MdList,
del: MdText,
// @ts-ignore
spoiler: MdSpoiler,
table: MdTable,
tablebody: MdTableBody,
tablecell: MdTableCell,
tablehead: MdTableHead,
tablerow: MdTableRow,
}
export const options = {
mangle: false,
headerIds: false,
}
</script>
<script lang="ts">
import { page } from '$app/stores'
import { env } from '$env/dynamic/public'
import { md, mdInline, photonify } from '$lib/components/markdown/markdown'
import { onMount } from 'svelte'
import SvelteMarkdown from 'svelte-markdown'
import { linkify } from './renderers/plugins'
import {
MdCode,
MdHeading,
MdHr,
MdHtml,
MdImage,
MdLink,
MdQuote,
MdText,
} from './renderers'
import MdList from './renderers/MdList.svelte'
import containerExtension from './renderers/spoiler/spoiler'
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'
export let source: string = ''
export let inline: boolean = false
export let noStyle: boolean = false
let rendered = ''
function replaceURLs(node: HTMLElement, source: string) {
if (!div) return
const links = node.querySelectorAll('a')
links.forEach((l) => {
const photonified = photonify(l.href)
if (photonified) l.href = photonified
else if (!l.href.startsWith($page.url.origin)) {
l.target = '_blank'
l.rel = 'noopener noreferrer'
}
})
}
let div: HTMLElement
function render(source: string): string {
if (!source || source == '') return ''
try {
return inline ? mdInline.render(source) : md.render(source)
} catch (err) {
console.error(err)
return ''
}
}
$: rendered = render(source)
$: replaceURLs(div, rendered)
/*
Horrendous hack to get @html reactivity working
From server to client, the rendered html won't change for some reason
I have no clue why this fixes it, but it does.
*/
if (env?.PUBLIC_SSR_ENABLED?.toLowerCase() == 'true') {
onMount(() => {
rendered = `${rendered} `
replaceURLs(div, rendered)
})
}
$: tokens = marked.lexer(source)
</script>
<div
bind:this={div}
class="{noStyle
? ''
: 'break-words flex flex-col markdown gap-2 leading-[1.5]'} {$$props.class}"
: 'break-words flex flex-col gap-2 leading-[1.5]'} {$$props.class}"
style={$$props.style}
>
{@html rendered}
<SvelteMarkdown
bind:source={tokens}
{renderers}
{options}
isInline={inline || undefined}
/>
</div>
<style lang="postcss">
.markdown :global(h1) {
@apply text-3xl font-bold;
}
.markdown :global(h2) {
@apply text-2xl font-bold;
}
.markdown :global(h3) {
@apply text-xl font-bold;
}
.markdown :global(details) {
@apply cursor-pointer;
}
.markdown :global(hr) {
@apply w-full mx-auto my-2 border-slate-300 dark:border-zinc-800;
}
:global(.dark .markdown hr) {
@apply w-full mx-auto my-2 border-zinc-800;
}
.markdown :global(img) {
@apply max-h-[40vh] border rounded-lg border-slate-200 dark:border-zinc-800;
}
:global(.dark .markdown img) {
@apply border-zinc-800;
}
.markdown :global(a) {
@apply text-sky-500 hover:underline;
}
.markdown :global(ul) {
@apply list-disc pl-4 leading-3;
}
.markdown :global(ol) {
@apply list-decimal pl-4 leading-3;
}
.markdown :global(ul > *) {
@apply leading-[20px];
}
.markdown :global(ol > *) {
@apply leading-[20px];
}
.markdown :global(li) {
@apply m-0 leading-[1.5] !important;
}
.markdown :global(li > p) {
@apply m-0 leading-[1.5] !important;
}
.markdown :global(li > p) {
@apply contents !important;
}
.markdown :global(blockquote) {
@apply leading-[1px] border-l-2 border-slate-400 dark:border-zinc-600 pl-2 my-1 h-max;
}
.markdown :global(p) {
@apply leading-[1.5] max-w-3xl;
word-break: break-word;
}
.markdown :global(table) {
@apply rounded-xl w-full overflow-auto min-w-0 table-fixed relative;
}
.markdown :global(table thead tr th) {
@apply border border-slate-200 px-4 py-2;
}
.markdown :global(table tr td) {
@apply border border-slate-200 px-4 py-2 overflow-auto;
}
:global(.dark) .markdown :global(table tr td) {
@apply border border-zinc-800 px-4 py-2 overflow-auto;
}
:global(.dark) .markdown :global(table thead tr th) {
@apply border border-zinc-800 bg-zinc-900 px-4 py-2;
}
</style>
-159
View File
@@ -1,159 +0,0 @@
import MarkdownIt from 'markdown-it'
import markdown_it_container from 'markdown-it-container'
// @ts-ignore
import markdown_it_sub from 'markdown-it-sub'
// @ts-ignore
import markdown_it_sup from 'markdown-it-sup'
export const md = new MarkdownIt({
html: false,
linkify: true,
})
.use(markdown_it_container, 'spoiler', {
validate: (params: string) => {
return params.trim().match(/^spoiler+(.*)/)
},
render: (tokens: any, idx: any) => {
var m = tokens[idx].info.trim().match(/^spoiler+(.*)/)
if (tokens[idx].nesting === 1) {
// opening tag
return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`
} else {
// closing tag
return '</details>\n'
}
},
})
.use(markdown_it_sub)
.use(markdown_it_sup)
export const mdInline: MarkdownIt = new MarkdownIt('zero')
.enable(['emphasis', 'backticks', 'strikethrough', 'link', 'list', 'heading'])
.use(markdown_it_container, 'spoiler', {
validate: (params: string) => {
return params.trim().match(/^spoiler+(.*)/)
},
render: (tokens: any, idx: any) => {
var m = tokens[idx].info.trim().match(/^spoiler+(.*)/)
if (tokens[idx].nesting === 1) {
// opening tag
return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`
} else {
// closing tag
return '</details>\n'
}
},
})
.use(markdown_it_sub)
.use(markdown_it_sup)
const communityLinks = {
validate: function (text: any, pos: any, self: any) {
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: any) {
let prefix = match.url
prefix = prefix.startsWith('c/') ? prefix.slice(2) : prefix.slice(1)
match.url = `/c/${prefix}`
},
}
const userLinks = {
validate: function (text: any, pos: any, self: any) {
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: any) {
let prefix = match.url
prefix = prefix.startsWith('u/') ? prefix.slice(2) : prefix.slice(1)
match.url = `/u/${prefix}`
},
}
md.linkify.add('!', {
validate: communityLinks.validate,
normalize: communityLinks.normalize,
})
md.linkify.add('c/', {
validate: communityLinks.validate,
normalize: communityLinks.normalize,
})
md.linkify.add('@', {
validate: userLinks.validate,
normalize: userLinks.normalize,
})
md.linkify.add('u/', {
validate: userLinks.validate,
normalize: userLinks.normalize,
})
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,
}
/**
* Convert links to photon links
*/
export const photonify = (link: string) => {
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
return `/u/${match?.[3]}@${match?.[1]}`
}
if (regexes.community.test(link)) {
const match = link.match(regexes.community)
if (!match) return
return `/c/${match?.[3]}@${match?.[1]}`
}
}
@@ -0,0 +1,56 @@
<script lang="ts">
import { t } from '$lib/translations'
import { Button, Material, toast } from 'mono-svelte'
import { Icon, ClipboardDocument } from 'svelte-hero-icons'
export let raw: string
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('```', '') }
}
}
$: codeblock = parseCodeblock(raw)
</script>
<Material
padding="none"
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"
on:click={() => {
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,20 @@
<script lang="ts">
export let depth: number = 0
export let raw: string | undefined = undefined
</script>
{#if depth === 1}
<h1 class="font-bold text-4xl"><slot></slot></h1>
{:else if depth === 2}
<h2 class="font-bold text-3xl"><slot></slot></h2>
{:else if depth === 3}
<h3 class="font-bold text-2xl"><slot></slot></h3>
{:else if depth === 4}
<h4 class="font-semibold text-xl"><slot></slot></h4>
{:else if depth === 5}
<h5 class="font-semibold text-lg"><slot></slot></h5>
{:else if depth === 6}
<h6 class="font-semibold text-base"><slot></slot></h6>
{:else}
{raw}
{/if}
@@ -0,0 +1 @@
<hr class="border-slate-200 dark:border-zinc-800" />
@@ -0,0 +1,7 @@
<script lang="ts">
export let text: string
</script>
<p>
{text}
</p>
@@ -0,0 +1,39 @@
<script lang="ts">
import { showImage } from '$lib/components/ui/ExpandableImage.svelte'
import {
iframeType,
mediaType,
optimizeImageURL,
} from '$lib/components/lemmy/post/helpers'
import PostIframe from '$lib/components/lemmy/post/media/PostIframe.svelte'
export let href: string
export let title: string | undefined = undefined
export let text: string = ''
$: type = mediaType(href, 'cozy')
</script>
<div
class="max-w-xl h-auto rounded-2xl p-2 border border-slate-200 dark:border-zinc-800
inline-block"
>
{#if type == 'video' || type == 'embed' || type == 'iframe'}
<PostIframe
type={iframeType(href)}
url={href}
opened={true}
autoplay={false}
class="w-full"
/>
{:else}
<button on:click={() => showImage(href, text)}>
<img
src={optimizeImageURL(href, 1024)}
{title}
alt={text}
class="rounded-lg"
/>
</button>
{/if}
</div>
@@ -0,0 +1,24 @@
<script lang="ts">
import { photonify } from './plugins'
export let href = ''
export let title = undefined
export const parseURL = (href: string) => {
try {
return new URL(href)
} catch (e) {
return undefined
}
}
$: photonified = photonify(href)
</script>
<a
href={photonified ?? href}
{title}
class="hover:underline text-sky-600 dark:text-sky-500"
>
<slot />
</a>
@@ -0,0 +1,19 @@
<script lang="ts">
export let ordered: boolean
export let start: number
</script>
{#if ordered}
<ol
{start}
class="pl-5 list-decimal *:marker:font-medium *:marker:text-primary-900 *:marker:dark:text-primary-100"
>
<slot />
</ol>
{:else}
<ul
class="list-disc pl-4 *:marker:text-primary-900 *:marker:dark:text-primary-100"
>
<slot />
</ul>
{/if}
@@ -0,0 +1,3 @@
<p class="leading-[1.5]">
<slot />
</p>
@@ -0,0 +1,3 @@
<blockquote class="border-l-2 dark:border-zinc-700 border-slate-300 p-1 px-3">
<slot />
</blockquote>
@@ -0,0 +1,37 @@
<script lang="ts">
import { marked } from 'marked'
import SvelteMarkdown from 'svelte-markdown'
import { options, renderers } from '../Markdown.svelte'
import { Disclosure } from 'mono-svelte'
import { Icon } from 'svelte-hero-icons'
import Expandable from '$lib/components/ui/Expandable.svelte'
export let raw: string
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],
}
}
$: data = extractTitle(raw)
$: console.log(data.content)
</script>
<Expandable class="border-y border-slate-200 dark:border-zinc-800 py-2">
<div slot="title" class="text-left">
<SvelteMarkdown source={data.title} {renderers} {options} isInline />
</div>
<SvelteMarkdown source={data.content} {renderers} {options} />
</Expandable>
@@ -0,0 +1,16 @@
<script lang="ts">
export let raw: string
function preprocess(src: string): string {
// superscript, subscript support
src = src
.replaceAll(/~([^~]+)~/g, '<sub>$1</sub>')
.replaceAll(/\^([^^]+)\^/g, '<sup>$1</sup>')
return src
}
$: processed = preprocess(raw)
</script>
{@html processed}
@@ -0,0 +1,35 @@
import MdHeading from './MdHeading.svelte'
import MdImage from './MdImage.svelte'
import MdLink from './MdLink.svelte'
import MdQuote from './MdQuote.svelte'
import MdHr from './MdHr.svelte'
import MdCode from './MdCode.svelte'
import MdHtml from './MdHtml.svelte'
import MdText from './MdText.svelte'
import MdList from './MdList.svelte'
import MdSpoiler from './MdSpoiler.svelte'
import MdTable from './table/MdTable.svelte'
import MdTableBody from './table/MdTableBody.svelte'
import MdTableCell from './table/MdTableCell.svelte'
import MdTableHead from './table/MdTableHead.svelte'
import MdTableRow from './table/MdTableRow.svelte'
import MdParagraph from './MdParagraph.svelte'
export {
MdCode,
MdHeading,
MdHr,
MdHtml,
MdImage,
MdLink,
MdQuote,
MdText,
MdList,
MdSpoiler,
MdTable,
MdTableBody,
MdTableCell,
MdTableHead,
MdTableRow,
MdParagraph,
}
@@ -0,0 +1,121 @@
import { marked } from 'marked'
import markedLinkifyIt from 'marked-linkify-it'
export const spoilerPlugin = {
name: 'spoiler',
level: 'block',
start(src: string) {
return src.match(/^:::/)?.index
},
tokenizer(src: string, tokens: marked.TokensList) {
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: any) {
return `
<details>
<summary>${marked.parseInline(token.title)}</summary>
${marked.parse(token.text)}
</details>
`
},
}
export const linkify = markedLinkifyIt(
{
'!': {
validate: function (text: any, pos: any, self: any) {
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: any) {
let prefix = match.url
prefix = prefix.startsWith('c/') ? prefix.slice(2) : prefix.slice(1)
match.url = `/c/${prefix}`
},
},
'@': {
validate: function (text: any, pos: any, self: any) {
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: any) {
let prefix = match.url
prefix = prefix.startsWith('u/') ? prefix.slice(2) : prefix.slice(1)
match.url = `/u/${prefix}`
},
},
},
{}
)
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,
}
/**
* Convert links to photon links
*/
export const photonify = (link: string) => {
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
return `/u/${match?.[3]}@${match?.[1]}`
}
if (regexes.community.test(link)) {
const match = link.match(regexes.community)
if (!match) return
return `/c/${match?.[3]}@${match?.[1]}`
}
}
@@ -0,0 +1,129 @@
import { Lexer } from 'marked'
export type ContainerOptions = Record<string, boolean | string>
export type TokenExtractionParameters = {
/**
* The type of container
*/
type: string
/**
* The content inside the container
*/
content: string
/**
* The raw full container block
*/
raw: string
/**
* The options of the container
*/
options: ContainerOptions
/**
* The lexer that can be used to render nested tokens if needed
*/
lexer: Lexer
}
export type TokenExtractor = (params: any) => any
/**
* 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: any): any {
return {
name: 'container',
level: 'block',
start(src: any) {
return src.match(/^:::[^:\n]/)?.index
},
tokenizer(src: any): any {
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: any): any {
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: string): ContainerOptions {
const output: any = {}
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,3 @@
<table class="overflow-auto w-full table-fixed rounded-xl">
<slot />
</table>
@@ -0,0 +1 @@
<tbody><slot /></tbody>
@@ -0,0 +1,27 @@
<script lang="ts">
export let header: boolean
export let align:
| 'left'
| 'center'
| 'right'
| 'justify'
| 'char'
| null
| undefined = undefined
</script>
{#if header}
<th
class="bg-slate-50 dark:bg-zinc-900 border border-slate-200 dark:border-zinc-800 py-2 px-3"
{align}
>
<slot />
</th>
{:else}
<td
class="bg-slate-25 dark:bg-zinc-950 border border-slate-200 dark:border-zinc-800 py-2 px-3"
{align}
>
<slot />
</td>
{/if}
@@ -0,0 +1 @@
<thead><slot /></thead>
@@ -0,0 +1 @@
<tr><slot /></tr>
+2 -2
View File
@@ -2,7 +2,7 @@ export const isImage = (url: string | undefined) => {
try {
if (!url) return false
return /\.(jpeg|jpg|gif|png|svg|bmp|webp)$/i.test(new URL(url).pathname)
return /\.(jpeg|jpg|gif|png|svg|bmp|webp)$/i.test(url)
} catch (err) {
return false
}
@@ -12,7 +12,7 @@ export const isVideo = (url: string | undefined) => {
try {
if (!url) return false
return /\.(mp4|mov|webm|mkv)$/i.test(new URL(url).pathname)
return /\.(mp4|mov|webm|mkv)$/i.test(url)
} catch (err) {
return false
}
@@ -234,9 +234,7 @@
opened
/>
{#if post.post_view.post.body}
<div
class="text-sm text-slate-800 dark:text-zinc-300 rounded-md leading-[22px]"
>
<div class="text-base text-slate-800 dark:text-zinc-300 leading-[1.5]">
<Markdown source={post.post_view.post.body} />
</div>
{/if}
+1 -1
View File
@@ -1,5 +1,5 @@
<script lang="ts">
import { photonify } from '$lib/components/markdown/markdown.js'
import { photonify } from '$lib/components/markdown/renderers/plugins'
import { TextInput } from 'mono-svelte'
let link = ''
+2 -2
View File
@@ -54,12 +54,12 @@ body {
z-index: 999 !important;
}
pre {
pre:not(.code-baseline) {
@apply bg-slate-100 p-2 rounded-xl my-2 max-w-full whitespace-pre-wrap
border-slate-200 border dark:bg-zinc-950 dark:border-zinc-900 text-xs;
}
:not(pre) > code {
:not(pre) > code:not(.code-baseline) {
@apply bg-slate-100 dark:bg-zinc-950;
padding-left: 0.25rem;
padding-right: 0.25rem;