forked from
jollywhoppers.com/witchsky.app
Bluesky app fork with some witchin' additions 馃挮
1import {AppBskyRichtextFacet, type RichText, UnicodeString} from '@atproto/api'
2
3import {toShortUrl} from './url-helpers'
4
5export function shortenLinks(rt: RichText): RichText {
6 if (!rt.facets?.length) {
7 return rt
8 }
9 rt = rt.clone()
10 // enumerate the link facets
11 if (rt.facets) {
12 for (const facet of rt.facets) {
13 const isLink = !!facet.features.find(AppBskyRichtextFacet.isLink)
14 if (!isLink) {
15 continue
16 }
17
18 // extract and shorten the URL
19 const {byteStart, byteEnd} = facet.index
20 const url = rt.unicodeText.slice(byteStart, byteEnd)
21 const shortened = new UnicodeString(toShortUrl(url))
22
23 // insert the shorten URL
24 rt.insert(byteStart, shortened.utf16)
25 // update the facet to cover the new shortened URL
26 facet.index.byteStart = byteStart
27 facet.index.byteEnd = byteStart + shortened.length
28 // remove the old URL
29 rt.delete(byteStart + shortened.length, byteEnd + shortened.length)
30 }
31 }
32 return rt
33}
34
35// filter out any mention facets that didn't map to a user
36export function stripInvalidMentions(rt: RichText): RichText {
37 if (!rt.facets?.length) {
38 return rt
39 }
40 rt = rt.clone()
41 if (rt.facets) {
42 rt.facets = rt.facets?.filter(facet => {
43 const mention = facet.features.find(AppBskyRichtextFacet.isMention)
44 if (mention && !mention.did) {
45 return false
46 }
47 return true
48 })
49 }
50 return rt
51}