Update progress on last page (#105)

This commit is contained in:
Alex Ling 2020-09-21 04:35:23 +00:00
parent ddbba5d596
commit 96463641f9
2 changed files with 52 additions and 18 deletions

View File

@ -1,3 +1,7 @@
let lastSavedPage = page;
let items = [];
let longPages = false;
$(() => {
getPages();
@ -28,7 +32,7 @@ const getPages = () => {
throw new Error(resp.error);
const dimensions = data.dimensions;
const items = dimensions.map((d, i) => {
items = dimensions.map((d, i) => {
return {
id: i + 1,
url: `${base_url}api/page/${tid}/${eid}/${i+1}`,
@ -37,6 +41,13 @@ const getPages = () => {
};
});
const avgRatio = items.reduce((acc, cur) => {
return acc + cur.height / cur.width
}, 0) / items.length;
console.log(avgRatio);
longPages = avgRatio > 2;
setProp('items', items);
setProp('loading', false);
@ -136,26 +147,49 @@ const setupScroller = () => {
});
};
let lastSavedPage = page;
/**
* Update the backend reading progress if the current page is more than
* five pages away from the last saved page
* Update the backend reading progress if:
* 1) the current page is more than five pages away from the last
* saved page, or
* 2) the average height/width ratio of the pages is over 2, or
* 3) the current page is the first page, or
* 4) the current page is the last page
*
* @function saveProgress
* @param {number} idx - One-based index of the page
* @param {function} cb - Callback
*/
const saveProgress = (idx) => {
if (Math.abs(idx - lastSavedPage) < 5) return;
lastSavedPage = idx;
const saveProgress = (idx, cb) => {
idx = parseInt(idx);
if (Math.abs(idx - lastSavedPage) >= 5 ||
longPages ||
idx === 1 || idx === items.length
) {
lastSavedPage = idx;
console.log('saving progress', idx);
const url = `${base_url}api/progress/${tid}/${idx}?${$.param({entry: eid})}`;
$.post(url)
.then(data => {
if (data.error) throw new Error(data.error);
})
.catch(e => {
console.error(e);
alert('danger', e);
});
const url = `${base_url}api/progress/${tid}/${idx}?${$.param({entry: eid})}`;
$.post(url)
.then(data => {
if (data.error) throw new Error(data.error);
if (cb) cb();
})
.catch(e => {
console.error(e);
alert('danger', e);
});
}
};
/**
* Mark progress to 100% and redirect to the next entry
* Used as the onclick handler for the "Next Entry" button
*
* @function nextEntry
* @param {string} nextUrl - URL of the next entry
*/
const nextEntry = (nextUrl) => {
saveProgress(items.length, () => {
redirect(nextUrl);
});
};

View File

@ -31,7 +31,7 @@
/>
</template>
<%- if next_entry_url -%>
<button id="next-btn" class="uk-align-center uk-button uk-button-primary" @click="redirect('<%= next_entry_url %>')">Next Entry</button>
<button id="next-btn" class="uk-align-center uk-button uk-button-primary" @click="nextEntry('<%= next_entry_url %>')">Next Entry</button>
<%- else -%>
<button id="next-btn" class="uk-align-center uk-button uk-button-primary" @click="redirect('<%= exit_url %>')">Exit Reader</button>
<%- end -%>