66 lines
2.5 KiB
JavaScript
66 lines
2.5 KiB
JavaScript
function createUnfiledCaptures({
|
|
storage,
|
|
getCaptureLogin = () => '',
|
|
getCurrentLogin = () => '',
|
|
createId = () => globalThis.crypto?.randomUUID?.() || String(Date.now()) + '-' + Math.random().toString(16).slice(2),
|
|
now = () => Date.now(),
|
|
maxItems = 20,
|
|
}) {
|
|
const storageKey = 'stackchain.unfiled-issues.v1';
|
|
|
|
function read() {
|
|
try {
|
|
const record = JSON.parse(storage?.getItem(storageKey) || 'null');
|
|
if (record?.version !== 1 || !Array.isArray(record.items)) return [];
|
|
return record.items.filter(item =>
|
|
item && typeof item.id === 'string' && typeof item.ownerLogin === 'string' &&
|
|
typeof item.title === 'string' && item.title.trim() && typeof item.body === 'string'
|
|
);
|
|
} catch (_error) { return []; }
|
|
}
|
|
|
|
function write(items) {
|
|
storage?.setItem(storageKey, JSON.stringify({version:1, items}));
|
|
}
|
|
|
|
function list() {
|
|
const currentLogin = String(getCurrentLogin() || '').trim();
|
|
return read().slice().sort((left, right) => Number(right.savedAt) - Number(left.savedAt))
|
|
.map(item => ({...item, quarantined: !currentLogin || currentLogin !== item.ownerLogin}));
|
|
}
|
|
|
|
function save(note) {
|
|
const title = String(note?.title || '').trim().slice(0, 255);
|
|
const body = String(note?.body || '').trim().slice(0, 10000);
|
|
if (!title) throw new Error('Add a title before saving.');
|
|
const ownerLogin = String(getCaptureLogin() || '').trim();
|
|
if (!ownerLogin) throw new Error('Offline identity is unavailable. Reconnect once before saving private work.');
|
|
const item = {id:String(createId()), ownerLogin, title, body, savedAt:Number(now())};
|
|
const items = [item, ...read().filter(existing => existing.id !== item.id)].slice(0, maxItems);
|
|
write(items);
|
|
return item;
|
|
}
|
|
|
|
function discard(id) {
|
|
const items = read();
|
|
const remaining = items.filter(item => item.id !== id);
|
|
if (remaining.length === items.length) return false;
|
|
write(remaining);
|
|
return true;
|
|
}
|
|
|
|
function resume(id, confirmedLogin) {
|
|
const item = read().find(candidate => candidate.id === id);
|
|
if (!item) throw new Error('This capture is no longer available.');
|
|
if (!confirmedLogin || String(confirmedLogin).trim() !== item.ownerLogin) {
|
|
throw new Error('Reconnect with the account that saved this capture.');
|
|
}
|
|
discard(id);
|
|
return {repository:'', title:item.title, body:item.body, labelIds:[]};
|
|
}
|
|
|
|
return {list, save, discard, resume};
|
|
}
|
|
|
|
if (typeof module !== 'undefined' && module.exports) module.exports = createUnfiledCaptures;
|