56 lines
1.8 KiB
JavaScript
56 lines
1.8 KiB
JavaScript
(function (root, factory) {
|
|
const createSearchPreview = factory();
|
|
if (typeof module === 'object' && module.exports) module.exports = createSearchPreview;
|
|
if (root) root.createSearchPreview = createSearchPreview;
|
|
})(typeof globalThis !== 'undefined' ? globalThis : this, function () {
|
|
return function createSearchPreview({ fetchJson, mutate, onState }) {
|
|
let generation = 0;
|
|
let current = null;
|
|
let mutationRequest = null;
|
|
|
|
function run(action, pending, success, detail) {
|
|
if (mutationRequest) return mutationRequest;
|
|
onState({ status: pending, item: current, detail });
|
|
mutationRequest = mutate(detail, action).then(result => {
|
|
onState({ status: success, item: current, detail, result });
|
|
return result;
|
|
}).catch(error => {
|
|
onState({ status: 'ready', item: current, detail, error });
|
|
throw error;
|
|
}).finally(() => { mutationRequest = null; });
|
|
return mutationRequest;
|
|
}
|
|
|
|
return {
|
|
open(item) {
|
|
generation += 1;
|
|
const requestGeneration = generation;
|
|
current = { ...item };
|
|
onState({ status: 'loading', item: current });
|
|
return fetchJson(current).then(detail => {
|
|
if (requestGeneration === generation) {
|
|
onState({ status: 'ready', item: current, detail });
|
|
}
|
|
return detail;
|
|
}).catch(error => {
|
|
if (requestGeneration === generation) {
|
|
onState({ status: 'error', item: current, error });
|
|
}
|
|
throw error;
|
|
});
|
|
},
|
|
close() {
|
|
generation += 1;
|
|
current = null;
|
|
onState({ status: 'closed' });
|
|
},
|
|
claim(detail) {
|
|
return run('claim', 'claiming', 'claimed', detail);
|
|
},
|
|
reopen(detail) {
|
|
return run('reopen', 'reopening', 'reopened', detail);
|
|
},
|
|
};
|
|
};
|
|
});
|