78 lines
3.1 KiB
JavaScript
78 lines
3.1 KiB
JavaScript
// Text drafts stay in this visitor's browser, independently for each conversation.
|
|
var ChatDrafts = {
|
|
create(options){
|
|
const scope = /^[0-9a-f]{64}$/.test(options.scope || '') ? options.scope : null;
|
|
const prefix = scope ? 'baiyue-draft-v1:' + scope + ':' : null;
|
|
const activeKey = scope ? 'baiyue-active-chat-v1:' + scope : null;
|
|
const memory = new Map();
|
|
const dirty = new Set();
|
|
let current = 'new';
|
|
function id(value){
|
|
if(value === null || value === 'new') return 'new';
|
|
const key = String(value);
|
|
return /^[1-9][0-9]{0,18}$/.test(key) ? key : null;
|
|
}
|
|
function storage(name){
|
|
try{ return options[name](); }catch(error){ return null; }
|
|
}
|
|
function read(value){
|
|
const key = id(value);
|
|
if(!key) return '';
|
|
if(dirty.has(key)) return memory.get(key) || '';
|
|
if(prefix){
|
|
try{
|
|
const saved = storage('storage').getItem(prefix + key);
|
|
if(saved !== null){
|
|
const data = JSON.parse(saved);
|
|
if(data && data.version === 1 && typeof data.text === 'string'){
|
|
memory.set(key, data.text);
|
|
return data.text;
|
|
}
|
|
}
|
|
memory.delete(key);
|
|
return '';
|
|
}catch(error){}
|
|
}
|
|
return memory.get(key) || '';
|
|
}
|
|
function write(value, text){
|
|
const key = id(value);
|
|
if(!key || typeof text !== 'string') return false;
|
|
if(text) memory.set(key, text); else memory.delete(key);
|
|
dirty.add(key);
|
|
if(!prefix) return false;
|
|
try{
|
|
const target = storage('storage');
|
|
if(text) target.setItem(prefix + key, JSON.stringify({version:1,text:text}));
|
|
else target.removeItem(prefix + key);
|
|
dirty.delete(key);
|
|
return true;
|
|
}catch(error){ return false; }
|
|
}
|
|
function active(value){
|
|
if(arguments.length){
|
|
current = id(value) || 'new';
|
|
if(activeKey) try{ storage('tabStorage').setItem(activeKey, current); }catch(error){}
|
|
}else if(activeKey){
|
|
try{ const saved=storage('tabStorage').getItem(activeKey); if(saved !== null) current = id(saved) || current; }catch(error){}
|
|
}
|
|
return current;
|
|
}
|
|
function clear(){
|
|
memory.clear();
|
|
dirty.clear();
|
|
if(prefix){
|
|
try{
|
|
const target = storage('storage');
|
|
for(let index = target.length - 1; index >= 0; index--){
|
|
const key = target.key(index);
|
|
if(key && key.startsWith(prefix)) target.removeItem(key);
|
|
}
|
|
}catch(error){}
|
|
}
|
|
active('new');
|
|
}
|
|
return {read:read,write:write,active:active,remove:value=>write(value,''),clear:clear};
|
|
}
|
|
};
|