Spaces:
Running
Running
File size: 8,108 Bytes
3d4293e 00385f7 3d4293e | 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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | import { useCallback, useEffect, useRef, useState } from 'react'
export const GENRE: Record<string, string> = {
short: '婚恋/亲情短故事', urban: '都市职场生活', nocp: '大女主事业', era: '年代文', ancient: '古言',
xianxia: '玄幻仙侠', rule: '规则怪谈', crime: '悬疑刑侦', other: '其他',
}
export const KIND: Record<string, string> = { story: '完整事件', emotion: '情绪独白', quote: '原创文案', plot: '故事梗概', qa: '求助问答' }
export const DECISION: Record<string, string> = { keep: '原样可用', edit: '已改写', recheck: '复检通过' }
export const ROLE: Record<string, { t: string; d: string }> = {
main: { t: '主线', d: '撑起整本书的矛盾' },
hook: { t: '钩子', d: '开篇第一句的抓手' },
twist: { t: '反转', d: '中后段的真相翻面' },
person: { t: '人物', d: '可借用的人物性格' },
emotion: { t: '情绪', d: '情绪弧线与心理变化' },
detail: { t: '细节', d: '能让场景变真的小东西' },
}
export const CHAPTER_STATUS: Record<string, string> = { planned: '待写', draft: '草稿', rolled_back: '已回滚', revising: '修改中', done: '定稿' }
export const PROJECT_STATUS: Record<string, string> = { planning: '构思中', writing: '连载中', paused: '暂停', finished: '已完结' }
export const VERSION_KIND: Record<string, string> = { draft: '草稿', revision: '修订', ai: 'AI 稿', final: '定稿', import: '导入' }
export const countWords = (s: string) => {
// 按番茄口径:去除空白后的字符数
return [...String(s || '').replace(/\s/g, '')].length
}
export const fmtNum = (n: number | null | undefined) => {
if (n == null || Number.isNaN(n)) return '—'
if (n >= 10000) return `${(n / 10000).toFixed(n >= 1000000 ? 0 : 1)} 万`
return String(n)
}
export const fmtDate = (s?: string | null, withTime = true) => {
if (!s) return '—'
const d = new Date(s)
if (Number.isNaN(d.getTime())) return '—'
const pad = (x: number) => String(x).padStart(2, '0')
const now = new Date()
const sameYear = d.getFullYear() === now.getFullYear()
const date = `${sameYear ? '' : d.getFullYear() + '年'}${d.getMonth() + 1}月${d.getDate()}日`
return withTime ? `${date} ${pad(d.getHours())}:${pad(d.getMinutes())}` : date
}
export const fmtAgo = (s?: string | null) => {
if (!s) return '—'
const t = new Date(s).getTime()
if (Number.isNaN(t)) return '—'
const diff = (Date.now() - t) / 1000
if (diff < 60) return '刚刚'
if (diff < 3600) return `${Math.floor(diff / 60)} 分钟前`
if (diff < 86400) return `${Math.floor(diff / 3600)} 小时前`
if (diff < 86400 * 30) return `${Math.floor(diff / 86400)} 天前`
return fmtDate(s, false)
}
export const cnNum = (n: number) => {
const d = '零一二三四五六七八九'
if (n <= 0 || n >= 10000) return String(n)
const units = ['', '十', '百', '千']
const s = String(n)
let out = ''
for (let i = 0; i < s.length; i++) {
const digit = Number(s[i])
const u = units[s.length - 1 - i]
if (digit === 0) { if (!out.endsWith('零')) out += '零' }
else out += d[digit] + u
}
out = out.replace(/零+$/, '')
if (out.startsWith('一十')) out = out.slice(1)
return out
}
/* ---------- 路由(hash) ---------- */
export function useRoute(): [string[], (path: string) => void] {
const parse = () => (location.hash.replace(/^#\/?/, '').split('?')[0] || '').split('/').filter(Boolean).map(decodeURIComponent)
const [parts, setParts] = useState<string[]>(parse)
useEffect(() => {
const on = () => setParts(parse())
window.addEventListener('hashchange', on)
return () => window.removeEventListener('hashchange', on)
}, [])
const go = useCallback((path: string) => { location.hash = path.startsWith('#') ? path : `#/${path.replace(/^\//, '')}` }, [])
return [parts, go]
}
export const go = (path: string) => { location.hash = `#/${path.replace(/^\//, '')}` }
/* ---------- 本地存储 ---------- */
export function useLocal<T>(key: string, initial: T): [T, (v: T | ((p: T) => T)) => void] {
const [v, setV] = useState<T>(() => {
try { const raw = localStorage.getItem(key); return raw ? JSON.parse(raw) : initial } catch { return initial }
})
const set = useCallback((next: T | ((p: T) => T)) => {
setV(prev => {
const val = typeof next === 'function' ? (next as (p: T) => T)(prev) : next
try { localStorage.setItem(key, JSON.stringify(val)) } catch {}
return val
})
}, [key])
return [v, set]
}
export function useDebounced<T>(value: T, ms = 350) {
const [v, setV] = useState(value)
useEffect(() => { const t = setTimeout(() => setV(value), ms); return () => clearTimeout(t) }, [value, ms])
return v
}
/* 通用异步加载 */
export function useAsync<T>(fn: () => Promise<T>, deps: any[]) {
const [state, setState] = useState<{ data: T | null; error: string | null; loading: boolean }>({ data: null, error: null, loading: true })
const seq = useRef(0)
const run = useCallback(() => {
const n = ++seq.current
setState(s => ({ ...s, loading: true, error: null }))
return fn().then(
data => { if (n === seq.current) setState({ data, error: null, loading: false }); return data },
e => { if (n === seq.current) setState(s => ({ ...s, error: e?.message || String(e), loading: false })) },
)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps)
useEffect(() => { run() }, [run])
return { ...state, reload: run, setData: (d: T | null | ((p: T | null) => T | null)) => setState(s => ({ ...s, data: typeof d === 'function' ? (d as any)(s.data) : d })) }
}
/* ---------- 素材篮(与旧版共用 fq-basket) ---------- */
export const BASKET_KEY = 'fq-basket'
export function readBasket(): any[] {
try { const v = JSON.parse(localStorage.getItem(BASKET_KEY) || '[]'); return Array.isArray(v) ? v : [] } catch { return [] }
}
const basketListeners = new Set<() => void>()
export function writeBasket(items: any[]) {
try { localStorage.setItem(BASKET_KEY, JSON.stringify(items)) } catch {}
basketListeners.forEach(f => f())
}
export function useBasket(): [any[], (items: any[]) => void] {
const [items, setItems] = useState<any[]>(readBasket)
useEffect(() => {
const on = () => setItems(readBasket())
basketListeners.add(on)
window.addEventListener('storage', on)
return () => { basketListeners.delete(on); window.removeEventListener('storage', on) }
}, [])
return [items, writeBasket]
}
/* ---------- 文本对比(按段落 LCS) ---------- */
export type DiffRow = { type: 'same' | 'add' | 'del'; text: string }
export function diffParagraphs(a: string, b: string): DiffRow[] {
const A = a.split(/\n+/).filter(s => s.trim())
const B = b.split(/\n+/).filter(s => s.trim())
const n = A.length, m = B.length
if (n * m > 4_000_000) return [...A.map(t => ({ type: 'del' as const, text: t })), ...B.map(t => ({ type: 'add' as const, text: t }))]
const dp: Uint32Array[] = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1))
for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) dp[i][j] = A[i] === B[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1])
const out: DiffRow[] = []
let i = 0, j = 0
while (i < n && j < m) {
if (A[i] === B[j]) { out.push({ type: 'same', text: A[i] }); i++; j++ }
else if (dp[i + 1][j] >= dp[i][j + 1]) out.push({ type: 'del', text: A[i++] })
else out.push({ type: 'add', text: B[j++] })
}
while (i < n) out.push({ type: 'del', text: A[i++] })
while (j < m) out.push({ type: 'add', text: B[j++] })
return out
}
export async function copyText(text: string) {
try { await navigator.clipboard.writeText(text); return true } catch {
const ta = document.createElement('textarea')
ta.value = text; ta.style.position = 'fixed'; ta.style.opacity = '0'
document.body.appendChild(ta); ta.select()
try { document.execCommand('copy'); return true } catch { return false } finally { ta.remove() }
}
}
export const cx = (...xs: any[]) => xs.filter(Boolean).join(' ')
|