Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Experiment with text mode #1340

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 19 additions & 8 deletions src/BookReader.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import { BookModel } from './BookReader/BookModel.js';
import { Mode1Up } from './BookReader/Mode1Up.js';
import { Mode2Up } from './BookReader/Mode2Up.js';
import { ModeThumb } from './BookReader/ModeThumb';
import { ModeText } from './BookReader/ModeText';
import { ImageCache } from './BookReader/ImageCache.js';
import { PageContainer } from './BookReader/PageContainer.js';
import { NAMED_REDUCE_SETS } from './BookReader/ReduceSet';
Expand All @@ -62,6 +63,8 @@ BookReader.constMode1up = 1;
BookReader.constMode2up = 2;
/** thumbnails view */
BookReader.constModeThumb = 3;
/** text view */
BookReader.constModeText = 4;
/** image cache */
BookReader.imageCache = null;

Expand Down Expand Up @@ -117,6 +120,8 @@ BookReader.prototype.setup = function(options) {
this.constMode2up = BookReader.constMode2up;
/** thumbnails view */
this.constModeThumb = BookReader.constModeThumb;
/** text view */
this.constModeText = BookReader.constModeText;

// Private properties below. Configuration should be done with options.
/** @type {number} TODO: Make private */
Expand Down Expand Up @@ -225,6 +230,7 @@ BookReader.prototype.setup = function(options) {
mode1Up: new Mode1Up(this, this.book),
mode2Up: new Mode2Up(this, this.book),
modeThumb: new ModeThumb(this, this.book),
modeText: new ModeText(this, this.book),
};

/** Stores classes which we want to expose (selectively) some methods as overridable */
Expand All @@ -235,6 +241,7 @@ BookReader.prototype.setup = function(options) {
'_modes.mode1Up': this._modes.mode1Up,
'_modes.mode2Up': this._modes.mode2Up,
'_modes.modeThumb': this._modes.modeThumb,
'_modes.modeText': this._modes.modeText,
};

/** Image cache for general image fetching */
Expand Down Expand Up @@ -285,6 +292,7 @@ Object.defineProperty(BookReader.prototype, 'activeMode', {
1: this._modes.mode1Up,
2: this._modes.mode2Up,
3: this._modes.modeThumb,
4: this._modes.modeText,
}[this.mode]; },
});

Expand Down Expand Up @@ -444,7 +452,7 @@ BookReader.prototype.readQueryString = function() {
* Determines the initial mode for starting if a mode is not already
* present in the params argument
* @param {object} params
* @return {1 | 2 | 3} the initial mode
* @return {1 | 2 | 3 | 4} the initial mode
*/
BookReader.prototype.getInitialMode = function(params) {
// if mobile breakpoint, we always show this.constMode1up mode
Expand Down Expand Up @@ -1044,14 +1052,10 @@ BookReader.prototype.switchMode = function(
// See https://bugs.edge.launchpad.net/gnubook/+bug/416682

// XXX maybe better to preserve zoom in each mode
if (this.constMode1up == mode) {
this._modes.mode1Up.prepare();
} else if (this.constModeThumb == mode) {
if (this.constModeThumb == mode) {
this.reduce = this.quantizeReduce(this.reduce, this.reductionFactors);
this._modes.modeThumb.prepare();
} else {
this._modes.mode2Up.prepare();
}
this.activeMode.prepare?.();

if (!(this.suppressFragmentChange || suppressFragmentChange)) {
this.trigger(BookReader.eventNames.fragmentChange);
Expand Down Expand Up @@ -1190,7 +1194,7 @@ BookReader.prototype.exitFullScreen = async function () {
*/
BookReader.prototype.currentIndex = function() {
// $$$ we should be cleaner with our idea of which index is active in 1up/2up
if (this.mode == this.constMode1up || this.mode == this.constModeThumb) {
if (this.mode == this.constMode1up || this.mode == this.constModeThumb || this.mode == this.constModeText) {
return this.firstIndex; // $$$ TODO page in center of view would be better
} else if (this.mode == this.constMode2up) {
// Only allow indices that are actually present in book
Expand Down Expand Up @@ -1380,6 +1384,9 @@ BookReader.prototype.bindNavigationHandlers = function() {
twopg: () => {
this.switchMode(self.constMode2up);
},
textpg: () => {
this.switchMode(self.constModeText);
},
zoom_in: () => {
this.trigger(BookReader.eventNames.stop);
this.zoom(1);
Expand Down Expand Up @@ -1783,6 +1790,8 @@ BookReader.prototype.paramsFromFragment = function(fragment) {
params.mode = this.constMode2up;
} else if ('thumb' == urlHash['mode']) {
params.mode = this.constModeThumb;
} else if ('text' == urlHash['mode']) {
params.mode = this.constModeText;
}

// Index and page
Expand Down Expand Up @@ -1842,6 +1851,8 @@ BookReader.prototype.fragmentFromParams = function(params, urlMode = 'hash') {
fragments.push('mode', '2up');
} else if (params.mode == this.constModeThumb) {
fragments.push('mode', 'thumb');
} else if (params.mode == this.constModeText) {
fragments.push('mode', 'text');
} else {
throw 'fragmentFromParams called with unknown mode ' + params.mode;
}
Expand Down
19 changes: 19 additions & 0 deletions src/BookReader/BookModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,15 @@ export class PageModel {
.next().value;
}

/** Gets the next `count` pages */
*iterNext({ combineConsecutiveUnviewables = false, count = 1 } = {}) {
for (const page of this.book.pagesIterator({ start: this.index + 1, combineConsecutiveUnviewables })) {
if (count <= 0) return;
yield page;
count--;
}
}

/**
* @param {object} [arg0]
* @param {boolean} [arg0.combineConsecutiveUnviewables] Whether to only yield the first page
Expand All @@ -514,6 +523,16 @@ export class PageModel {
}
}

/** Get the `count` previous pages */
*iterPrev({ combineConsecutiveUnviewables = false, count = 1 } = {}) {
let page = this;
for (let i = 0; i < count; i++) {
page = page.findPrev({ combineConsecutiveUnviewables });
if (!page) return;
yield page;
}
}

/**
* @param {object} [arg0]
* @param {boolean} [arg0.combineConsecutiveUnviewables] Whether to only yield the first page
Expand Down
60 changes: 36 additions & 24 deletions src/BookReader/Mode1UpLit.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,9 @@ export class Mode1UpLit extends LitElement {

/************** CONSTANT PROPERTIES **************/

/** Number of pages to render around the visible pages */
BUFFER_AROUND = 2;

/** Vertical space between/around the pages in inches */
SPACING_IN = 0.2;

Expand Down Expand Up @@ -187,8 +190,9 @@ export class Mode1UpLit extends LitElement {
this.worldDimensions = this.computeWorldDimensions();
this.pageTops = this.computePageTops(this.pages, this.SPACING_IN);
}
if (changedProps.has('visibleRegion')) {
this.visiblePages = this.computeVisiblePages();
// FIXME: `actualPositions` should be only in ModeTextLit
if (changedProps.has('visibleRegion') || changedProps.has('actualPositions')) {
this.visiblePages = this.pages.filter(page => this.isPageVisible(page));
}
if (changedProps.has('visiblePages')) {
this.throttledUpdateRenderedPages();
Expand Down Expand Up @@ -260,29 +264,32 @@ export class Mode1UpLit extends LitElement {
}

/** @param {PageModel} page */
renderPage = (page) => {
getPageTransform(page) {
const wToR = this.coordSpace.worldUnitsToRenderedPixels;
const wToV = this.coordSpace.worldUnitsToVisiblePixels;
const containerWidth = this.coordSpace.visiblePixelsToWorldUnits(this.htmlDimensionsCacher.clientWidth);

const width = wToR(page.widthInches);
const height = wToR(page.heightInches);
const containerWidth = this.coordSpace.visiblePixelsToWorldUnits(this.htmlDimensionsCacher.clientWidth);
const left = Math.max(this.SPACING_IN, (containerWidth - page.widthInches) / 2);
const top = this.pageTops[page.index];
return `translate(${wToR(left)}px, ${wToR(top)}px)`;
}

/** @param {PageModel} page */
renderPage(page) {
const wToR = this.coordSpace.worldUnitsToRenderedPixels;
const wToV = this.coordSpace.worldUnitsToVisiblePixels;

const transform = `translate(${wToR(left)}px, ${wToR(top)}px)`;
const pageContainerEl = this.createPageContainer(page)
.update({
dimensions: {
width,
height,
width: wToR(page.widthInches),
height: wToR(page.heightInches),
top: 0,
left: 0,
},
reduce: page.width / wToV(page.widthInches),
}).$container[0];

pageContainerEl.style.transform = transform;
pageContainerEl.style.transform = this.getPageTransform(page);
pageContainerEl.classList.toggle('BRpage-visible', this.visiblePages.includes(page));
return pageContainerEl;
}
Expand Down Expand Up @@ -314,10 +321,12 @@ export class Mode1UpLit extends LitElement {
computeRenderedPages() {
// Also render 1 page before/after
// @ts-ignore TS doesn't understand the filtering out of null values
const first = this.visiblePages[0];
const last = this.visiblePages[this.visiblePages.length - 1];
return [
this.visiblePages[0]?.prev,
...(first?.iterPrev({ combineConsecutiveUnviewables: true, count: this.BUFFER_AROUND }) ?? []),
...this.visiblePages,
this.visiblePages[this.visiblePages.length - 1]?.next,
...(last?.iterNext({ combineConsecutiveUnviewables: true, count: this.BUFFER_AROUND }) ?? []),
]
.filter(p => p)
// Never render more than 10 pages! Usually means something is wrong
Expand All @@ -332,11 +341,13 @@ export class Mode1UpLit extends LitElement {
/**
* @param {PageModel[]} pages
* @param {number} spacing
* @param {number} [initialTop]
* @param {Record<PageIndex, number>} [inPlace]
*/
computePageTops(pages, spacing) {
computePageTops(pages, spacing, initialTop = spacing, inPlace = null) {
/** @type {{ [pageIndex: string]: number }} */
const result = {};
let top = spacing;
const result = inPlace || {};
let top = initialTop;
for (const page of pages) {
result[page.index] = top;
top += page.heightInches + spacing;
Expand All @@ -363,15 +374,16 @@ export class Mode1UpLit extends LitElement {
};
}

computeVisiblePages() {
return this.pages.filter(page => {
const PT = this.pageTops[page.index];
const PB = PT + page.heightInches;
/**
* @param {PageModel} page
*/
isPageVisible(page) {
const PT = this.pageTops[page.index];
const PB = PT + page.heightInches;

const VT = this.visibleRegion.top;
const VB = VT + this.visibleRegion.height;
return PT <= VB && PB >= VT;
});
const VT = this.visibleRegion.top;
const VB = VT + this.visibleRegion.height;
return PT <= VB && PB >= VT;
}

/************** INPUT HANDLERS **************/
Expand Down
100 changes: 100 additions & 0 deletions src/BookReader/ModeText.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// @ts-check
import { ModeTextLit } from './ModeTextLit.js';
/** @typedef {import('../BookReader.js').default} BookReader */
/** @typedef {import('./BookModel.js').BookModel} BookModel */
/** @typedef {import('./BookModel.js').PageIndex} PageIndex */

export class ModeText {
/**
* @param {BookReader} br
* @param {BookModel} bookModel
*/
constructor(br, bookModel) {
this.br = br;
this.book = bookModel;
this.modeTextLit = new ModeTextLit(bookModel, br);

/** @private */
this.$el = $(this.modeTextLit)
// We CANNOT use `br-mode-1up` as a class, because it's the same
// as the name of the web component, and the webcomponents polyfill
// uses the name of component as a class for style scoping 😒
.addClass('br-mode-1up__root BRmode1up br-mode-text__root BRmodeTextLit');

/** Has mode1up ever been rendered before? */
this.everShown = false;
}

// TODO: Might not need this anymore? Might want to delete.
/** @private */
get $brContainer() { return this.br.refs.$brContainer; }

/**
* This is called when we switch to one page view
*/
prepare() {
const startLeaf = this.br.currentIndex();
this.$brContainer
.empty()
.css({ overflow: 'hidden' })
.append(this.$el);

// Need this in a setTimeout so that it happens after the browser has _actually_
// appended the element to the DOM
setTimeout(async () => {
if (!this.everShown) {
this.modeTextLit.initFirstRender(startLeaf);
this.everShown = true;
this.modeTextLit.requestUpdate();
await this.modeTextLit.updateComplete;
}
this.modeTextLit.jumpToIndex(startLeaf);
setTimeout(() => {
// Must explicitly call updateVisibleRegion, since no
// scroll event seems to fire.
this.modeTextLit.updateVisibleRegion();
});
});
this.br.updateBrClasses();
}

/**
* BREAKING CHANGE: No longer supports pageX/pageY
* @param {PageIndex} index
* @param {number} [pageX] x position on the page (in pixels) to center on
* @param {number} [pageY] y position on the page (in pixels) to center on
* @param {boolean} [noAnimate]
*/
jumpToIndex(index, pageX, pageY, noAnimate) {
// Only smooth for small distances
const distance = Math.abs(this.br.currentIndex() - index);
const smooth = !noAnimate && distance > 0 && distance <= 4;
this.modeTextLit.jumpToIndex(index, { smooth });
}

/**
* @param {'in' | 'out'} direction
*/
zoom(direction) {
throw new Error('Not implemented');
switch (direction) {

Check failure on line 80 in src/BookReader/ModeText.js

View workflow job for this annotation

GitHub Actions / tests

Unreachable code
case 'in':
this.modeTextLit.zoomIn();
break;
case 'out':
this.modeTextLit.zoomOut();
break;
default:
console.error(`Unsupported direction: ${direction}`);
}
}

/**
* Resize the current one page view
* Note this calls drawLeafs
*/
resizePageView() {
this.modeTextLit.htmlDimensionsCacher.updateClientSizes();
this.modeTextLit.requestUpdate();
}
}
Loading
Loading