-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
PostExcerpt.astro
95 lines (78 loc) · 2.32 KB
/
PostExcerpt.astro
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
---
// Author: Igor Dimitrijević (@igorskyflyer)
import { stripFile } from '@igor.dvlpr/strip-yaml-front-matter'
import type { Props } from './dist/Props.mjs'
import { getPlainText, isMdx, isPriorV2, isV2 } from './dist/utils.mjs'
export type { Props }
const symbolEllipsis: string = '…'
const punctuationSymbols: string[] = ['.', ',', '?', '!', ';', symbolEllipsis]
let {
post,
words = 40,
maxLength = 0,
addEllipsis = true,
smartEllipsis = true,
ellipsis = symbolEllipsis
} = Astro.props as Props
let postExcerpt: string = ''
if (!post || (!isPriorV2(post) && !isV2(post) && !isMdx(post))) {
throw new TypeError('The required prop post is not valid, aborting now.')
}
if (typeof words !== 'number' || words < 0) {
words = 40
console.warn('The optional prop words is not valid, defaulting to 40.')
}
if (typeof maxLength !== 'number' || maxLength < 0) {
maxLength = 0
console.warn('The optional prop maxLength is not valid, defaulting to 0.')
}
if (typeof addEllipsis !== 'boolean') {
addEllipsis = true
console.warn(
'The optional prop addEllipsis is not valid, defaulting to true.'
)
}
if (typeof smartEllipsis !== 'boolean') {
smartEllipsis = true
console.warn(
'The optional prop smartEllipsis is not valid, defaulting to true.'
)
}
if (typeof ellipsis !== 'string' || ellipsis.length < 1) {
ellipsis = symbolEllipsis
console.warn('The optional prop ellipsis is not valid, defaulting to "…".')
}
if (isV2(post)) {
// Astro >= v2 detected
postExcerpt = post['body']
} else if (isPriorV2(post)) {
// Astro < v2 detected
postExcerpt = post.rawContent()
} else if (isMdx(post)) {
// MDX file detected
// cannot be used directly from Astro 😔
postExcerpt = stripFile(post.file)
}
postExcerpt = postExcerpt.trim()
postExcerpt = getPlainText(postExcerpt)
if (words > 0) {
postExcerpt = postExcerpt.split(' ').slice(0, words).join(' ')
}
if (maxLength > 0) {
postExcerpt = postExcerpt.substring(0, maxLength)
}
if (addEllipsis) {
const postLength: number = postExcerpt.length
if (postLength > 0) {
if (smartEllipsis) {
const lastChar: string | undefined = postExcerpt.at(-1)
if (lastChar && !punctuationSymbols.includes(lastChar)) {
postExcerpt += ellipsis
}
} else {
postExcerpt += ellipsis
}
}
}
---
<Fragment set:html={postExcerpt} />