Files
Folo/packages/utils/src/utils.ts
T
edd4f9e5a6 feat: mobile design (#1568)
* init

Signed-off-by: Innei <i@innei.in>

* feat: feed column

Signed-off-by: Innei <i@innei.in>

* feat: float bar

Signed-off-by: Innei <tukon479@gmail.com>

* feat: profile button

Signed-off-by: Innei <tukon479@gmail.com>

* chore: comment

Signed-off-by: Innei <tukon479@gmail.com>

* feat: layout

Signed-off-by: Innei <tukon479@gmail.com>

* feat: split mobile entry content

Signed-off-by: Innei <tukon479@gmail.com>

* feat: add history stack

Signed-off-by: Innei <tukon479@gmail.com>

* feat: return back

Signed-off-by: Innei <tukon479@gmail.com>

* fix: return back position

Signed-off-by: Innei <tukon479@gmail.com>

* feat: entry list header

Signed-off-by: Innei <tukon479@gmail.com>

* feat: sync selector

Signed-off-by: Innei <tukon479@gmail.com>

* feat: modal stack mobile

Signed-off-by: Innei <tukon479@gmail.com>

* fix: modal selector

Signed-off-by: Innei <tukon479@gmail.com>

* cleanup

Signed-off-by: Innei <tukon479@gmail.com>

* fix: sheet and optimize entry readers

Signed-off-by: Innei <tukon479@gmail.com>

* fix: scroller

Signed-off-by: Innei <tukon479@gmail.com>

* feat: entry contents

Signed-off-by: Innei <tukon479@gmail.com>

* feat: entry content

Signed-off-by: Innei <tukon479@gmail.com>

* update

Signed-off-by: Innei <tukon479@gmail.com>

* feat: user profile sheet

Signed-off-by: Innei <tukon479@gmail.com>

* fix: entry content header

Signed-off-by: Innei <tukon479@gmail.com>

* fix: entry header

Signed-off-by: Innei <tukon479@gmail.com>

* chore: auto-fix linting and formatting issues

* fix: return back

Signed-off-by: Innei <tukon479@gmail.com>

* feat: image view

Signed-off-by: Innei <tukon479@gmail.com>

* feat: audio

Signed-off-by: Innei <tukon479@gmail.com>

* feat: inline player

Signed-off-by: Innei <tukon479@gmail.com>

* feat: pull to refresh

Signed-off-by: Innei <tukon479@gmail.com>

* cleanup

Signed-off-by: Innei <tukon479@gmail.com>

* update

Signed-off-by: Innei <tukon479@gmail.com>

* chore: auto-fix linting and formatting issues

* chore: fix import, remove no support display

* chore: auto-fix linting and formatting issues

* feat: achievement modal in mobile

Signed-off-by: Innei <tukon479@gmail.com>

* fix: subview mobile

Signed-off-by: Innei <tukon479@gmail.com>

* feat: power

Signed-off-by: Innei <tukon479@gmail.com>

* feat: wallet mobile design

Signed-off-by: Innei <tukon479@gmail.com>

* feat: pwa support (#1575)

Co-authored-by: hyoban <hyoban@users.noreply.github.com>

* chore: auto-fix linting and formatting issues

* fix import

* discover

* fix: border color

Signed-off-by: Innei <tukon479@gmail.com>

* fix: modal async

Signed-off-by: Innei <tukon479@gmail.com>

* feat: mobile setting

Signed-off-by: Innei <tukon479@gmail.com>

* fix: entry header width

Signed-off-by: Innei <tukon479@gmail.com>

* fix: remove unused hide filter

* feat: settings

Signed-off-by: Innei <tukon479@gmail.com>

* feat: setting done

Signed-off-by: Innei <tukon479@gmail.com>

* action card

* fix discover feed form

* popular filter

* inbox table

* fix: picture masonry pull to refresh

Signed-off-by: Innei <tukon479@gmail.com>

* fix: scroll element

Signed-off-by: Innei <tukon479@gmail.com>

* fix: radio in mobile

Signed-off-by: Innei <tukon479@gmail.com>

* feat: to scientific notation

Signed-off-by: Innei <tukon479@gmail.com>

* fix: login

Signed-off-by: Innei <tukon479@gmail.com>

* ResponsiveSelect for action card

* chore: remove theme color

Signed-off-by: Innei <tukon479@gmail.com>

* type check

* type check

* fix: setting import circular

Signed-off-by: Innei <tukon479@gmail.com>

* refactor: remove hijack pushState

Signed-off-by: Innei <tukon479@gmail.com>

* fix: float bar

Signed-off-by: Innei <tukon479@gmail.com>

* fix: scroll end trigger

Signed-off-by: Innei <tukon479@gmail.com>

* fix: dark theme color

Signed-off-by: Innei <tukon479@gmail.com>

* fix: overscroll-behavior only in destop

Signed-off-by: Innei <tukon479@gmail.com>

* fix: ux

Signed-off-by: Innei <tukon479@gmail.com>

* fix: color

Signed-off-by: Innei <tukon479@gmail.com>

* fix: list scroll area

Signed-off-by: Innei <tukon479@gmail.com>

* update

Signed-off-by: Innei <tukon479@gmail.com>

* merge

* update

* update favicon link

* fix: reload prompt on mobile

* test

Signed-off-by: Innei <i@innei.in>

* test

Signed-off-by: Innei <i@innei.in>

* fix: ios

Signed-off-by: Innei <i@innei.in>

* try patch precaching

* try

* try

* build

* try

* try

* feat: ctx menu on safari

Signed-off-by: Innei <tukon479@gmail.com>

* try

* clear timeout

Signed-off-by: Innei <tukon479@gmail.com>

* try

* fix

* deny og

* fix patch

* pre cache exclude

* feat: add all

Signed-off-by: Innei <tukon479@gmail.com>

* i18n

Signed-off-by: Innei <tukon479@gmail.com>

* feat: slide

Signed-off-by: Innei <tukon479@gmail.com>

* feat: ico

Signed-off-by: Innei <tukon479@gmail.com>

* fix: build

Signed-off-by: Innei <tukon479@gmail.com>

* test network first

Signed-off-by: Innei <tukon479@gmail.com>

* test

Signed-off-by: Innei <tukon479@gmail.com>

* fix: icon padding

* test

Signed-off-by: Innei <tukon479@gmail.com>

* use react-ios-pwa-prompt

* fix: icon path

* update

* fix: prompt

Signed-off-by: Innei <tukon479@gmail.com>

* feat: redesign toc

Signed-off-by: Innei <tukon479@gmail.com>

* ctx

Signed-off-by: Innei <tukon479@gmail.com>

* ready to prod

Signed-off-by: Innei <tukon479@gmail.com>

* feat: startup screen

Signed-off-by: Innei <tukon479@gmail.com>

* feat: floatbar

Signed-off-by: Innei <tukon479@gmail.com>

* fix: switch view

Signed-off-by: Innei <tukon479@gmail.com>

* fix: keep scroll map

Signed-off-by: Innei <tukon479@gmail.com>

* enable hoverOnlyWhenSupported

* fix: count

Signed-off-by: Innei <tukon479@gmail.com>

* fix: hoverOnlyWhenSupported only in web

Signed-off-by: Innei <tukon479@gmail.com>

* fix

Signed-off-by: Innei <tukon479@gmail.com>

* chore: auto-fix linting and formatting issues

---------

Signed-off-by: Innei <i@innei.in>
Signed-off-by: Innei <tukon479@gmail.com>
Co-authored-by: Innei <Innei@users.noreply.github.com>
Co-authored-by: Stephen Zhou <38493346+hyoban@users.noreply.github.com>
Co-authored-by: hyoban <hyoban@users.noreply.github.com>
Co-authored-by: lawvs <18554747+lawvs@users.noreply.github.com>
Co-authored-by: lawvs <lawvs@users.noreply.github.com>
2024-11-22 19:32:39 +08:00

237 lines
6.3 KiB
TypeScript

import type { ClassValue } from "clsx"
import { clsx } from "clsx"
import { memoize } from "es-toolkit/compat"
import { twMerge } from "tailwind-merge"
import { parse } from "tldts"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export { clsx } from "clsx"
export type OS = "macOS" | "iOS" | "Windows" | "Android" | "Linux" | ""
declare const window: {
platform: NodeJS.Platform
navigator: Navigator
}
declare const ELECTRON: boolean
export const getOS = memoize((): OS => {
if (window.platform) {
switch (window.platform) {
case "darwin": {
return "macOS"
}
case "win32": {
return "Windows"
}
case "linux": {
return "Linux"
}
}
}
const { userAgent } = window.navigator,
macosPlatforms = ["Macintosh", "MacIntel", "MacPPC", "Mac68K"],
windowsPlatforms = ["Win32", "Win64", "Windows", "WinCE"],
iosPlatforms = ["iPhone", "iPad", "iPod"]
// @ts-expect-error
const platform = window.navigator.userAgentData?.platform || window.navigator.platform
let os = platform
if (macosPlatforms.includes(platform)) {
os = "macOS"
} else if (iosPlatforms.includes(platform)) {
os = "iOS"
} else if (windowsPlatforms.includes(platform)) {
os = "Windows"
} else if (/Android/.test(userAgent)) {
os = "Android"
} else if (!os && /Linux/.test(platform)) {
os = "Linux"
}
return os as OS
})
export function detectBrowser() {
const { userAgent } = navigator
if (userAgent.includes("Edg")) {
return "Microsoft Edge"
} else if (userAgent.includes("Chrome")) {
return "Chrome"
} else if (userAgent.includes("Firefox")) {
return "Firefox"
} else if (userAgent.includes("Safari")) {
return "Safari"
} else if (userAgent.includes("Opera")) {
return "Opera"
} else if (userAgent.includes("Trident") || userAgent.includes("MSIE")) {
return "Internet Explorer"
}
return "Unknown"
}
export const isSafari = memoize(() => {
if (ELECTRON) return false
const ua = window.navigator.userAgent
return ua.includes("Safari") && !ua.includes("Chrome")
})
// eslint-disable-next-line no-control-regex
export const isASCII = (str) => /^[\u0000-\u007F]*$/.test(str)
const EPOCH = 1712546615000n // follow repo created
const MAX_TIMESTAMP_BITS = 41n // Maximum number of bits typically used for timestamp
export const isBizId = (id: string): boolean => {
if (!id || !/^\d{13,19}$/.test(id)) return false
const snowflake = BigInt(id)
// Extract the timestamp assuming it's in the most significant bits after the sign bit
const timestamp = (snowflake >> (63n - MAX_TIMESTAMP_BITS)) + EPOCH
const date = new Date(Number(timestamp))
// Check if the date is reasonable (between 2024 and 2050)
if (date.getFullYear() >= 2024 && date.getFullYear() <= 2050) {
// Additional validation: check if the ID is not larger than the maximum possible value
const maxPossibleId = (1n << 63n) - 1n // Maximum possible 63-bit value
if (snowflake <= maxPossibleId) {
return true
}
}
return false
}
export function formatXml(xml: string, indent = 4) {
const PADDING = " ".repeat(indent)
let formatted = ""
const regex = /(>)(<)(\/*)/g
xml = xml.replaceAll(regex, "$1\r\n$2$3")
let pad = 0
xml.split("\r\n").forEach((node) => {
let indent = 0
if (/.+<\/\w[^>]*>$/.test(node)) {
indent = 0
} else if (/^<\/\w/.test(node) && pad !== 0) {
pad -= 1
} else if (/^<\w(?:[^>]*[^/])?>.*$/.test(node)) {
indent = 1
} else {
indent = 0
}
formatted += `${PADDING.repeat(pad) + node}\r\n`
pad += indent
})
return formatted.trim()
}
export const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
export const capitalizeFirstLetter = (string: string) =>
string.charAt(0).toUpperCase() + string.slice(1)
export const omitObjectUndefinedValue = (obj: Record<string, any>) => {
const newObj = {}
for (const key in obj) {
if (obj[key] !== undefined) {
newObj[key] = obj[key]
}
}
return newObj
}
export const sortByAlphabet = (a: string, b: string) => {
const isALetter = /^[a-z]/i.test(a)
const isBLetter = /^[a-z]/i.test(b)
if (isALetter && !isBLetter) {
return -1
}
if (!isALetter && isBLetter) {
return 1
}
if (isALetter && isBLetter) {
return a.localeCompare(b)
}
return a.localeCompare(b, "zh-CN")
}
export const isEmptyObject = (obj: Record<string, any>) => Object.keys(obj).length === 0
export const parseSafeUrl = (url: string) => {
try {
return new URL(url)
} catch {
return null
}
}
export const getUrlIcon = (url: string, fallback?: boolean | undefined) => {
let src: string
let fallbackUrl = ""
try {
const { host } = new URL(url)
const pureDomain = parse(host).domainWithoutSuffix
fallbackUrl = `https://avatar.vercel.sh/${pureDomain}.svg?text=${pureDomain
?.slice(0, 2)
.toUpperCase()}`
src = `https://unavatar.webp.se/${host}?fallback=${fallback || false}`
} catch {
const pureDomain = parse(url).domainWithoutSuffix
src = `https://avatar.vercel.sh/${pureDomain}.svg?text=${pureDomain?.slice(0, 2).toUpperCase()}`
}
const ret = {
src,
fallbackUrl,
}
return ret
}
export { parse as parseUrl } from "tldts"
export const clamp = (value: number, min: number, max: number) =>
Math.min(Math.max(value, min), max)
export function shallowCopy<T>(input: T): T {
if (Array.isArray(input)) {
return [...input] as T
} else if (input && typeof input === "object") {
return { ...input } as T
}
return input
}
export function isKeyForMultiSelectPressed(e: MouseEvent) {
if (getOS() === "macOS") {
return e.metaKey || e.shiftKey
}
return e.ctrlKey || e.shiftKey
}
export const toScientificNotation = (num: string, threshold: number) => {
const cleanNum = num.replaceAll(",", "")
const [intPart, decimalPart = ""] = cleanNum.split(".")
const numLength = intPart.replace(/^0+/, "").length
if (numLength > threshold) {
const fullNum = intPart + decimalPart
const firstDigit = fullNum.match(/[1-9]/)?.[0] || "0"
const position = fullNum.indexOf(firstDigit)
const exponent = intPart.length - position - 1
const significand = fullNum.slice(position, position + 3)
const formattedSignificand = `${significand[0]}.${significand.slice(1)}`
return `${formattedSignificand}e+${exponent}`
}
return num
}