74 lines
1.4 KiB
JavaScript
74 lines
1.4 KiB
JavaScript
const DRAFT_PREFIX = 'miniDraft:'
|
|
|
|
function buildDraftKey(key) {
|
|
return `${DRAFT_PREFIX}${key}`
|
|
}
|
|
|
|
function loadDraft(key, defaultValue) {
|
|
if (!key) {
|
|
return defaultValue
|
|
}
|
|
try {
|
|
const value = wx.getStorageSync(buildDraftKey(key))
|
|
return value === undefined || value === '' ? defaultValue : value
|
|
} catch (error) {
|
|
return defaultValue
|
|
}
|
|
}
|
|
|
|
function saveDraft(key, value) {
|
|
if (!key) {
|
|
return
|
|
}
|
|
try {
|
|
wx.setStorageSync(buildDraftKey(key), {
|
|
savedAt: Date.now(),
|
|
value
|
|
})
|
|
} catch (error) {}
|
|
}
|
|
|
|
function clearDraft(key) {
|
|
if (!key) {
|
|
return
|
|
}
|
|
try {
|
|
wx.removeStorageSync(buildDraftKey(key))
|
|
} catch (error) {}
|
|
}
|
|
|
|
function getDraftValue(key, defaultValue) {
|
|
const record = loadDraft(key, null)
|
|
if (!record || typeof record !== 'object' || !Object.prototype.hasOwnProperty.call(record, 'value')) {
|
|
return defaultValue
|
|
}
|
|
return record.value
|
|
}
|
|
|
|
function scheduleDraftSave(context, key, buildValue, delay) {
|
|
if (!context) {
|
|
return
|
|
}
|
|
if (context.__draftSaveTimer) {
|
|
clearTimeout(context.__draftSaveTimer)
|
|
}
|
|
context.__draftSaveTimer = setTimeout(() => {
|
|
saveDraft(key, buildValue())
|
|
}, delay || 300)
|
|
}
|
|
|
|
function clearDraftTimer(context) {
|
|
if (context && context.__draftSaveTimer) {
|
|
clearTimeout(context.__draftSaveTimer)
|
|
context.__draftSaveTimer = null
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
getDraftValue,
|
|
saveDraft,
|
|
clearDraft,
|
|
scheduleDraftSave,
|
|
clearDraftTimer
|
|
}
|