mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1import {useCallback, useMemo} from 'react'
2import Graphemer from 'graphemer'
3
4export function enforceLen(
5 str: string,
6 len: number,
7 ellipsis = false,
8 mode: 'end' | 'middle' = 'end',
9): string {
10 str = str || ''
11 if (str.length > len) {
12 if (ellipsis) {
13 if (mode === 'end') {
14 return str.slice(0, len) + '…'
15 } else if (mode === 'middle') {
16 const half = Math.floor(len / 2)
17 return str.slice(0, half) + '…' + str.slice(-half)
18 } else {
19 // fallback
20 return str.slice(0, len)
21 }
22 } else {
23 return str.slice(0, len)
24 }
25 }
26 return str
27}
28
29export function useEnforceMaxGraphemeCount() {
30 const splitter = useMemo(() => new Graphemer(), [])
31
32 return useCallback(
33 (text: string, maxCount: number) => {
34 if (splitter.countGraphemes(text) > maxCount) {
35 return splitter.splitGraphemes(text).slice(0, maxCount).join('')
36 } else {
37 return text
38 }
39 },
40 [splitter],
41 )
42}
43
44// https://stackoverflow.com/a/52171480
45export function toHashCode(str: string, seed = 0): number {
46 let h1 = 0xdeadbeef ^ seed,
47 h2 = 0x41c6ce57 ^ seed
48 for (let i = 0, ch; i < str.length; i++) {
49 ch = str.charCodeAt(i)
50 h1 = Math.imul(h1 ^ ch, 2654435761)
51 h2 = Math.imul(h2 ^ ch, 1597334677)
52 }
53 h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507)
54 h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909)
55 h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507)
56 h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909)
57
58 return 4294967296 * (2097151 & h2) + (h1 >>> 0)
59}
60
61export function countLines(str: string | undefined): number {
62 if (!str) return 0
63 return str.match(/\n/g)?.length ?? 0
64}
65
66// Augments search query with additional syntax like `from:me`
67export function augmentSearchQuery(query: string, {did}: {did?: string}) {
68 // Don't do anything if there's no DID
69 if (!did) {
70 return query
71 }
72
73 // We don't want to replace substrings that are being "quoted" because those
74 // are exact string matches, so what we'll do here is to split them apart
75
76 // Even-indexed strings are unquoted, odd-indexed strings are quoted
77 const splits = query.split(/("(?:[^"\\]|\\.)*")/g)
78
79 return splits
80 .map((str, idx) => {
81 if (idx % 2 === 0) {
82 return str.replaceAll(/(^|\s)from:me(\s|$)/g, `$1${did}$2`)
83 }
84
85 return str
86 })
87 .join('')
88}