chore: refine plugins and astro config

This commit is contained in:
radishzzz 2025-01-14 05:31:58 +00:00
parent 5d77abf77c
commit 77fc6eff6c
10 changed files with 346 additions and 460 deletions

View file

@ -1,8 +1,6 @@
---
import Welcome from '@/components/Welcome.astro'
import Layout from '@/layouts/Layout.astro'
---
<Layout>
<Welcome />
</Layout>

View file

@ -1,5 +1,4 @@
import type { Element, Properties as HastProperties, Node } from 'hast'
/// <reference types="mdast" />
import { h } from 'hastscript'
interface AdmonitionProperties extends HastProperties {
@ -7,25 +6,19 @@ interface AdmonitionProperties extends HastProperties {
'has-directive-label'?: boolean
}
/**
* Creates an admonition component.
*
* @param properties - The properties of the component.
* @param type - The admonition type.
* @param children - The children elements of the component.
* @returns The created admonition component as a Hast Element.
*/
type AdmonitionType = 'tip' | 'note' | 'important' | 'caution' | 'warning'
const ADMONITION_CLASS_PREFIX = 'bdm-'
const DEFAULT_ERROR_MESSAGE = 'Invalid admonition directive. (Admonition directives must be of block type ":::note{name="name"} <content> :::")'
export function AdmonitionComponent(
properties: AdmonitionProperties,
type: 'tip' | 'note' | 'important' | 'caution' | 'warning',
type: AdmonitionType,
children: Node[],
): Element {
if (!Array.isArray(children) || children.length === 0) {
return h(
'div',
{ class: 'hidden' },
'Invalid admonition directive. (Admonition directives must be of block type ":::note{name="name"} <content> :::")',
)
console.warn('Invalid admonition directive: empty or invalid children')
return h('div', { class: 'hidden' }, DEFAULT_ERROR_MESSAGE)
}
let label: Element | string | null = null
@ -36,14 +29,14 @@ export function AdmonitionComponent(
if (firstChild && firstChild.type === 'element') {
label = firstChild as Element
label.tagName = 'div' // Change the tag <p> to <div>
label.tagName = 'div'
}
else {
label = ''
}
}
return h('blockquote', { class: `admonition bdm-${type}` }, [
return h('blockquote', { class: `${ADMONITION_CLASS_PREFIX}${type}` }, [
h('span', { class: 'bdm-title' }, label || type.toUpperCase()),
...(children as Element[]),
] as Element[])

View file

@ -1,17 +1,10 @@
/// <reference types="mdast" />
import type { RootContent } from 'mdast'
import { h } from 'hastscript'
/**
* Creates a GitHub Card component.
*
* @param {object} properties - The properties of the component.
* @param {string} properties.repo - The GitHub repository in the format "owner/repo".
* @param {import('mdast').RootContent[]} children - The children elements of the component.
* @returns {import('mdast').Parent} The created GitHub Card component.
*/
export function GithubCardComponent(
properties: { repo: string },
children: import('mdast').RootContent[],
children: RootContent[],
): import('mdast').Parent {
if (Array.isArray(children) && children.length !== 0) {
return h('div', { class: 'hidden' }, [
@ -28,7 +21,7 @@ export function GithubCardComponent(
}
const repo = properties.repo
const cardUuid = `GC${Math.random().toString(36).slice(-6)}` // Collisions are not important
const cardUuid = `GC${Math.random().toString(36).slice(-6)}`
const nAvatar = h(`div#${cardUuid}-avatar`, { class: 'gc-avatar' })
const nLanguage = h(
@ -63,29 +56,39 @@ export function GithubCardComponent(
`script#${cardUuid}-script`,
{ type: 'text/javascript', defer: true },
`
fetch('https://api.github.com/repos/${repo}', { referrerPolicy: "no-referrer" }).then(response => response.json()).then(data => {
if (data.description) {
document.getElementById('${cardUuid}-description').innerText = data.description.replace(/:[a-zA-Z0-9_]+:/g, '');
} else {
document.getElementById('${cardUuid}-description').innerText = "Description not set"
fetch('https://api.github.com/repos/${repo}', {
referrerPolicy: "no-referrer",
headers: {
'Accept': 'application/vnd.github.v3+json',
},
signal: AbortSignal.timeout(5000)
}).then(response => {
if (!response.ok)
throw new Error(\`HTTP error! status: \${response.status}\`)
return response.json()
}).then(data => {
const elements = {
description: document.getElementById('${cardUuid}-description'),
language: document.getElementById('${cardUuid}-language'),
stars: document.getElementById('${cardUuid}-stars'),
}
document.getElementById('${cardUuid}-language').innerText = data.language;
document.getElementById('${cardUuid}-forks').innerText = Intl.NumberFormat('en-us', { notation: "compact", maximumFractionDigits: 1 }).format(data.forks).replaceAll("\\u202F", '');
document.getElementById('${cardUuid}-stars').innerText = Intl.NumberFormat('en-us', { notation: "compact", maximumFractionDigits: 1 }).format(data.stargazers_count).replaceAll("\\u202F", '');
const avatarEl = document.getElementById('${cardUuid}-avatar');
avatarEl.style.backgroundImage = 'url(' + data.owner.avatar_url + ')';
avatarEl.style.backgroundColor = 'transparent';
if (data.license?.spdx_id) {
document.getElementById('${cardUuid}-license').innerText = data.license?.spdx_id
} else {
document.getElementById('${cardUuid}-license').innerText = "no-license"
};
document.getElementById('${cardUuid}-card').classList.remove("fetch-waiting");
console.log("[GITHUB-CARD] Loaded card for ${repo} | ${cardUuid}.")
elements.description.innerText = data.description?.replace(/:[a-zA-Z0-9_]+:/g, '') ?? 'Description not set'
elements.language.innerText = data.language
elements.stars.innerText = Intl.NumberFormat('en-us', { notation: "compact", maximumFractionDigits: 1 }).format(data.stargazers_count).replaceAll("\\u202F", '')
const avatarEl = document.getElementById('${cardUuid}-avatar')
avatarEl.style.backgroundImage = 'url(' + data.owner.avatar_url + ')'
avatarEl.style.backgroundColor = 'transparent'
document.getElementById('${cardUuid}-license').innerText = data.license?.spdx_id ?? 'no-license'
document.getElementById('${cardUuid}-card').classList.remove("fetch-waiting")
console.log("[GITHUB-CARD] Loaded card for ${repo} | ${cardUuid}.")
}).catch(err => {
const c = document.getElementById('${cardUuid}-card');
c.classList.add("fetch-error");
console.warn("[GITHUB-CARD] (Error) Loading card for ${repo} | ${cardUuid}.")
const c = document.getElementById('${cardUuid}-card')
c.classList.add("fetch-error")
document.getElementById('${cardUuid}-description').innerText = "Failed to load repository data"
console.warn("[GITHUB-CARD] (Error) Loading card for ${repo} | ${cardUuid}:", err.message)
})
`,
)
@ -98,11 +101,6 @@ export function GithubCardComponent(
target: '_blank',
repo,
},
[
nTitle,
nDescription,
h('div', { class: 'gc-infobar' }, [nStars, nForks, nLicense, nLanguage]),
nScript,
],
[nTitle, nDescription, h('div', { class: 'gc-infobar' }, [nStars, nForks, nLicense, nLanguage]), nScript],
) as unknown as import('mdast').Parent
}

View file

@ -28,14 +28,11 @@ export function parseDirectiveNode() {
) {
const data = directiveNode.data || (directiveNode.data = {})
directiveNode.attributes = directiveNode.attributes || {}
if (
directiveNode.children.length > 0
&& directiveNode.children[0].data?.directiveLabel
) {
directiveNode.attributes['has-directive-label'] = true
}
const hast = h(directiveNode.name, directiveNode.attributes)
if (directiveNode.children[0]?.data?.directiveLabel)
directiveNode.attributes['has-directive-label'] = true
const hast = h(directiveNode.name, directiveNode.attributes)
data.hName = hast.tagName
data.hProperties = hast.properties
}

View file

@ -4,18 +4,9 @@ import { toString } from 'mdast-util-to-string'
export function remarkExcerpt() {
return function (tree: Root, file: VFile) {
let excerpt = ''
for (const node of tree.children) {
if (node.type === 'paragraph') {
excerpt = toString(node)
break
}
}
// 确保 data.astro.frontmatter 存在
file.data.astro = file.data.astro || {}
file.data.astro.frontmatter = file.data.astro.frontmatter || {}
file.data.astro.frontmatter.excerpt = excerpt
const firstParagraph = tree.children.find(node => node.type === 'paragraph')
const excerpt = firstParagraph ? toString(firstParagraph) : ''
const frontmatter = (file.data.astro ??= {}).frontmatter ??= {}
frontmatter.excerpt = excerpt
}
}

View file

@ -7,12 +7,8 @@ export function remarkReadingTime() {
return function (tree: Root, file: VFile) {
const textOnPage = toString(tree)
const readingTime = getReadingTime(textOnPage)
// 确保 data.astro.frontmatter 存在
file.data.astro = file.data.astro || {}
file.data.astro.frontmatter = file.data.astro.frontmatter || {}
file.data.astro.frontmatter.minutes = Math.max(1, Math.round(readingTime.minutes))
file.data.astro.frontmatter.words = readingTime.words
const frontmatter = (file.data.astro ??= {}).frontmatter ??= {}
frontmatter.minutes = Math.max(1, Math.round(readingTime.minutes))
frontmatter.words = readingTime.words
}
}

5
src/styles/global.css Normal file
View file

@ -0,0 +1,5 @@
:root {
--uno-colors-primary: theme('colors.primary');
--uno-colors-backgroundStart: theme('colors.backgroundStart');
--uno-colors-backgroundEnd: theme('colors.backgroundEnd');
}