仰望星辰工作室

starmusic-mobile

starmusic-mobile/ common/background.js 7.9 KB · 225 行 原始文件
1/**
2 * 自定义背景图片(除播放详情页外的页面共用)
3 *
4 * 图片持久化:统一存为 base64 dataURL(CSS background-image 用 base64 不依赖本地路径协议,
5 * 在 App / H5 上表现一致;早期版本存过 file:// 路径,见 clearBgImage 的兼容清理)。
6 * - H5 端:canvas 等比压缩为 jpeg 后转 base64
7 * - App 端:读取临时文件为 base64(选图时已按 compressed 压缩)
8 * - 其它平台(小程序等):uni.saveFile 保存文件,storage 记录路径
9 * 开关与模糊程度存设置项(common.bgImageEnabled / common.bgImageBlur)。
10 */
11import { getSetting } from './setting.js'
12import { getData, saveData, removeData } from './data.js'
13
14/** 背景图数据存储键 */
15export const BG_IMAGE_KEY = 'starmusic_bg_image'
16
17/** H5 压缩:最长边与 jpeg 质量 */
18const H5_MAX_SIDE = 1920
19const H5_JPEG_QUALITY = 0.82
20/** base64 体积上限(约 4MB,超出会拖慢同步存储读写) */
21const MAX_BASE64_LENGTH = 4 * 1024 * 1024
22
23/** 内存缓存:避免每个页面初始化时同步读取大字符串 */
24let cachedImage = null
25
26/** 当前背景图(base64 dataURL,或小程序的本地文件路径) */
27export const getBgImage = () => {
28 if (cachedImage === null) cachedImage = getData(BG_IMAGE_KEY, '') || ''
29 return cachedImage
30}
31
32const setBgImage = (value) => {
33 cachedImage = value || ''
34 if (cachedImage) saveData(BG_IMAGE_KEY, cachedImage)
35 else removeData(BG_IMAGE_KEY)
36}
37
38/** 背景图是否可用(开关打开且已选图) */
39export const isBgImageOn = () => !!getSetting()['common.bgImageEnabled'] && !!getBgImage()
40
41/** 已保存路径 → 可用于 CSS 的 URL(带缓存,避免每个组件创建时重复调用原生转换) */
42let cachedCssUrl = ''
43let cachedCssUrlSource = ''
44const toCssUrl = (path) => {
45 if (!path) return ''
46 if (path === cachedCssUrlSource) return cachedCssUrl
47 cachedCssUrlSource = path
48 cachedCssUrl = path
49 if (path.indexOf('data:') === 0) return cachedCssUrl
50 // 小程序等平台的本地路径无需转换,仅 App 端需要转绝对路径
51 // #ifdef APP-PLUS
52 try {
53 const abs = plus.io.convertLocalFileSystemURL(path)
54 if (abs) cachedCssUrl = abs.indexOf('file://') === 0 || abs.indexOf('http') === 0 ? abs : `file://${abs}`
55 } catch (e) {
56 // 转换失败时退回原路径
57 }
58 // #endif
59 return cachedCssUrl
60}
61
62/**
63 * 背景图启用时下发给页面根元素的"内容层透明"变量。
64 * 各页面容器以 var(--card-bg, #fff) 之类形式引用,未启用背景图时回退原本的不透明底色,
65 * 从而做到"只在有背景图时半透明",不影响默认外观。
66 */
67export const buildBgVars = () => {
68 if (!isBgImageOn()) return {}
69 return {
70 // 卡片 / 栏 / 列表项
71 '--card-bg': 'rgba(255, 255, 255, 0.72)',
72 // 弹层(需要更高的可读性)
73 '--card-bg-strong': 'rgba(255, 255, 255, 0.92)',
74 // 浅色填充(输入框 / 未选中标签 / 占位图)
75 '--fill-bg': 'rgba(255, 255, 255, 0.48)',
76 // 次要 / 提示文字:卡片透出背景图后灰色对比度不足,加深到黑色系(仍保留深浅层次)
77 '--text-secondary': '#1f2329',
78 '--text-muted': '#33373d',
79 // 磨砂玻璃开关(性能):backdrop-filter 在 Android WebView 上合成开销大,
80 // 且只有背景图开启(玻璃后真正有内容可透出)时才有视觉意义,纯色底上模糊等于白算。
81 // 玻璃组件统一引用 var(--glass-blur/--glass-bar, none),未开启背景图时回退 none,
82 // WebView 直接跳过模糊合成,切 tab 的首帧渲染明显提速。
83 '--glass-blur': 'blur(20px)',
84 '--glass-bar': 'blur(20px) saturate(180%) brightness(1.06)',
85 }
86}
87
88/**
89 * 构建页面背景层的内联样式(未启用或未选图时返回 null)
90 * 返回 null 时页面不渲染背景层,等同于普通背景色
91 */
92export const buildBgStyle = () => {
93 if (!isBgImageOn()) return null
94 const url = toCssUrl(getBgImage())
95 if (!url) return null
96 const blur = Number(getSetting()['common.bgImageBlur'])
97 return {
98 backgroundImage: `url("${url}")`,
99 filter: blur > 0 ? `blur(${blur}px)` : 'none',
100 }
101}
102
103// ============ 选择 / 移除图片 ============
104
105// #ifdef H5
106/** H5:等比压缩为 jpeg base64(同时避免超出 localStorage 容量) */
107const compressImageH5 = (src) =>
108 new Promise((resolve, reject) => {
109 const img = new Image()
110 img.onload = () => {
111 try {
112 const scale = Math.min(1, H5_MAX_SIDE / Math.max(img.width, img.height))
113 const width = Math.max(1, Math.round(img.width * scale))
114 const height = Math.max(1, Math.round(img.height * scale))
115 const canvas = document.createElement('canvas')
116 canvas.width = width
117 canvas.height = height
118 const ctx = canvas.getContext('2d')
119 ctx.drawImage(img, 0, 0, width, height)
120 resolve(canvas.toDataURL('image/jpeg', H5_JPEG_QUALITY))
121 } catch (e) {
122 reject(new Error('图片处理失败'))
123 }
124 }
125 img.onerror = () => reject(new Error('图片读取失败'))
126 img.src = src
127 })
128// #endif
129
130// #ifdef APP-PLUS
131/** App:读取本地文件为 base64 dataURL */
132const readFileAsDataUrl = (path) =>
133 new Promise((resolve, reject) => {
134 plus.io.resolveLocalFileSystemURL(
135 path,
136 (entry) => {
137 entry.file(
138 (file) => {
139 const reader = new plus.io.FileReader()
140 reader.onloadend = (e) => {
141 const result = e && e.target && e.target.result
142 if (result) resolve(result)
143 else reject(new Error('图片读取失败'))
144 }
145 reader.onerror = () => reject(new Error('图片读取失败'))
146 reader.readAsDataURL(file)
147 },
148 () => reject(new Error('图片读取失败')),
149 )
150 },
151 () => reject(new Error('图片读取失败')),
152 )
153 })
154// #endif
155
156/** 持久化选中的图片,返回最终存储值 */
157const persistImage = (tempPath) => {
158 // #ifdef H5
159 return compressImageH5(tempPath).then((base64) => {
160 if (base64.length > MAX_BASE64_LENGTH) throw new Error('图片过大,请选择更小的图片')
161 setBgImage(base64)
162 return base64
163 })
164 // #endif
165 // #ifdef APP-PLUS
166 return readFileAsDataUrl(tempPath).then((base64) => {
167 if (base64.length > MAX_BASE64_LENGTH) throw new Error('图片过大,请选择更小的图片')
168 setBgImage(base64)
169 return base64
170 })
171 // #endif
172 // #ifndef H5 || APP-PLUS
173 // 其它平台:保存为持久文件,storage 记录路径
174 return new Promise((resolve, reject) => {
175 uni.saveFile({
176 tempFilePath: tempPath,
177 success: (res) => {
178 const old = getBgImage()
179 if (old && old !== res.savedFilePath) {
180 try {
181 uni.removeSavedFile({ filePath: old })
182 } catch (e) {
183 // ignore
184 }
185 }
186 setBgImage(res.savedFilePath)
187 resolve(res.savedFilePath)
188 },
189 fail: (err) => reject(new Error(err.errMsg || '保存图片失败')),
190 })
191 })
192 // #endif
193}
194
195/** 选择并设置背景图(返回存储值) */
196export const chooseBgImage = () =>
197 new Promise((resolve, reject) => {
198 uni.chooseImage({
199 count: 1,
200 sizeType: ['compressed'],
201 sourceType: ['album', 'camera'],
202 success: (res) => {
203 const tempPath = (res.tempFilePaths || [])[0]
204 if (!tempPath) {
205 reject(new Error('未选择图片'))
206 return
207 }
208 persistImage(tempPath).then(resolve, reject)
209 },
210 fail: (err) => reject(new Error(err.errMsg || '选择图片失败')),
211 })
212 })
213
214/** 移除背景图(兼容清理早期用 uni.saveFile 保存的本地文件) */
215export const clearBgImage = () => {
216 const old = getBgImage()
217 if (old && old.indexOf('data:') !== 0 && old.indexOf('file://') !== 0 && old.indexOf('/') >= 0) {
218 try {
219 uni.removeSavedFile({ filePath: old })
220 } catch (e) {
221 // ignore
222 }
223 }
224 setBgImage('')
225}