forked from
jollywhoppers.com/witchsky.app
Bluesky app fork with some witchin' additions 💫
1import {type RichText} from '@atproto/api'
2import {countGraphemes} from 'unicode-segmenter/grapheme'
3
4import {shortenLinks} from './rich-text-manip'
5
6export function enforceLen(
7 str: string,
8 len: number,
9 ellipsis = false,
10 mode: 'end' | 'middle' = 'end',
11): string {
12 str = str || ''
13 if (str.length > len) {
14 if (ellipsis) {
15 if (mode === 'end') {
16 return str.slice(0, len) + '…'
17 } else if (mode === 'middle') {
18 const half = Math.floor(len / 2)
19 return str.slice(0, half) + '…' + str.slice(-half)
20 } else {
21 // fallback
22 return str.slice(0, len)
23 }
24 } else {
25 return str.slice(0, len)
26 }
27 }
28 return str
29}
30
31export function isOverMaxGraphemeCount({
32 text,
33 maxCount,
34}: {
35 text: string | RichText
36 maxCount: number
37}) {
38 if (typeof text === 'string') {
39 return countGraphemes(text) > maxCount
40 } else {
41 return shortenLinks(text).graphemeLength > maxCount
42 }
43}
44
45export function countLines(str: string | undefined): number {
46 if (!str) return 0
47 return str.match(/\n/g)?.length ?? 0
48}
49
50// Augments search query with additional syntax like `from:me`
51export function augmentSearchQuery(query: string, {did}: {did?: string}) {
52 // Don't do anything if there's no DID
53 if (!did) {
54 return query
55 }
56
57 // replace “smart quotes” with normal ones
58 // iOS keyboard will add fancy unicode quotes, but only normal ones work
59 query = query.replaceAll(/[“”]/g, '"')
60
61 // We don't want to replace substrings that are being "quoted" because those
62 // are exact string matches, so what we'll do here is to split them apart
63
64 // Even-indexed strings are unquoted, odd-indexed strings are quoted
65 const splits = query.split(/("(?:[^"\\]|\\.)*")/g)
66
67 return splits
68 .map((str, idx) => {
69 if (idx % 2 === 0) {
70 return str.replaceAll(/(^|\s)from:me(\s|$)/g, `$1${did}$2`)
71 }
72
73 return str
74 })
75 .join('')
76}