80 lines
2.1 KiB
JavaScript
80 lines
2.1 KiB
JavaScript
const { writeFile } = require('./wx-promisify')
|
|
|
|
function sanitizeFilename(filename) {
|
|
return String(filename || 'font2svg')
|
|
.replace(/[<>:"/\\|?*\x00-\x1F]/g, '_')
|
|
.replace(/\s+/g, '_')
|
|
.slice(0, 80)
|
|
}
|
|
|
|
function buildFilename(fontName, text, ext) {
|
|
const safeFont = sanitizeFilename(fontName || 'font')
|
|
const safeText = sanitizeFilename(Array.from(text || '').slice(0, 8).join('') || 'text')
|
|
return `${safeFont}_${safeText}.${ext}`
|
|
}
|
|
|
|
async function writeTextToUserPath(text, ext, preferredName) {
|
|
const filename = preferredName || `font2svg_${Date.now()}.${ext}`
|
|
const filePath = `${wx.env.USER_DATA_PATH}/${filename}`
|
|
await writeFile(filePath, text, 'utf8')
|
|
return filePath
|
|
}
|
|
|
|
async function saveSvgToUserPath(svgText, fontName, text) {
|
|
const filename = buildFilename(fontName, text, 'svg')
|
|
return writeTextToUserPath(svgText, 'svg', filename)
|
|
}
|
|
|
|
function saveSvgToUserPathSync(svgText, fontName, text) {
|
|
const filename = buildFilename(fontName, text, 'svg')
|
|
const filePath = `${wx.env.USER_DATA_PATH}/${filename}`
|
|
const fs = wx.getFileSystemManager()
|
|
fs.writeFileSync(filePath, svgText, 'utf8')
|
|
return {
|
|
filePath,
|
|
fileName: filename,
|
|
}
|
|
}
|
|
|
|
async function shareLocalFile(filePath, fileName) {
|
|
if (typeof wx.shareFileMessage !== 'function') {
|
|
throw new Error('当前微信版本不支持文件分享')
|
|
}
|
|
|
|
return new Promise((resolve, reject) => {
|
|
wx.shareFileMessage({
|
|
filePath,
|
|
fileName,
|
|
success: resolve,
|
|
fail: reject,
|
|
})
|
|
})
|
|
}
|
|
|
|
function shareSvgFromUserTap(svgText, fontName, text) {
|
|
if (typeof wx.shareFileMessage !== 'function') {
|
|
throw new Error('当前微信版本不支持文件分享')
|
|
}
|
|
|
|
const { filePath, fileName } = saveSvgToUserPathSync(svgText, fontName, text)
|
|
|
|
return new Promise((resolve, reject) => {
|
|
wx.shareFileMessage({
|
|
filePath,
|
|
fileName,
|
|
success: resolve,
|
|
fail: reject,
|
|
})
|
|
})
|
|
}
|
|
|
|
module.exports = {
|
|
sanitizeFilename,
|
|
buildFilename,
|
|
writeTextToUserPath,
|
|
saveSvgToUserPath,
|
|
saveSvgToUserPathSync,
|
|
shareLocalFile,
|
|
shareSvgFromUserTap,
|
|
}
|