-
-
Notifications
You must be signed in to change notification settings - Fork 101
/
render.js
383 lines (330 loc) · 10.5 KB
/
render.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import clsx from 'clsx'
import React from 'react'
import OpenSeaDragon from 'openseadragon'
import OSDConfig from '@/osd.config'
import RenderError from '@/components/renderError'
import ToolbarConsumer from '@/components/toolbar'
import { ReaderContext } from '../context'
import { getKeyByValue, debounce } from '@/lib/utils'
import { getNestedFocus } from '@/hooks/use-focus'
import { memoizeZoomClamp, memoizeZoomPercent } from '@/lib/zoom-parser'
import { fullscreenElement, onFullscreenChange } from '@/lib/full-screen'
// Icons
import { mdiImageBrokenVariant } from '@mdi/js'
class CanvasRender extends React.Component {
static defaultProps = {
initialPage: 0,
}
constructor(props) {
super(props)
this.viewer = null
this.browser = null
this.isScrolling = false
this.OSDContainer = React.createRef()
this.clearScrollingDelay = null
}
// Get the max target zoom
getTargetZoom = (scale = 1) => {
let zooms = []
const { viewport, world } = this.viewer
const count = world.getItemCount()
for (let i = 0; i < count; i++) {
zooms[i] = world.getItemAt(i).imageToViewportZoom(scale)
}
return Math.max(zooms) || zooms[0]
}
updateZoomLimits = () => {
const { viewport } = this.viewer
const targetZoom = 0.9
const realTargetZoom = this.getTargetZoom()
const imageBounds = this.viewer.world.getHomeBounds()
const viewportBounds = viewport.getBounds()
const imageAspect = imageBounds.width / imageBounds.height
const viewportAspect = viewportBounds.width / viewportBounds.height
const aspectFactor = imageAspect / viewportAspect
const zoomFactor = (aspectFactor >= 1 ? 1 : aspectFactor) * targetZoom
const zoom = zoomFactor / imageBounds.width
const minZoom = realTargetZoom <= zoom ? realTargetZoom : zoom
viewport.defaultZoomLevel = minZoom
viewport.minZoomLevel = minZoom
viewport.maxZoomLevel = realTargetZoom
}
updateZoom = (scale = 1) => {
const { viewport } = this.viewer
const max = viewport.getMaxZoom()
const min = viewport.getMinZoom()
if (scale) {
// Clamp zoom value
let zoom = memoizeZoomClamp(scale, max, min)
// Update
viewport.zoomTo(zoom, true)
viewport.ensureVisible(true)
}
}
zoomIn = () => {
const { viewport } = this.viewer
const max = viewport.getMaxZoom()
const zoom = viewport.getZoom()
const currentZoom = memoizeZoomPercent(zoom, max)
this.updateZoom(currentZoom + 10)
}
zoomOut = () => {
const { viewport } = this.viewer
const max = viewport.getMaxZoom()
const zoom = viewport.getZoom()
const currentZoom = memoizeZoomPercent(zoom, max)
this.updateZoom(currentZoom - 10)
}
zoomToOriginalSize = () => {
const targetZoom = this.getTargetZoom()
this.viewer.viewport.zoomTo(targetZoom, null, true)
}
handleError = error => {
const { updateCotextState } = this.props
this.viewer.close()
updateContextState({ renderError: true })
// Debug error
console.error(error)
}
handleFullscreenChange = () => {
const { updateContextState } = this.props
const fullscreen = fullscreenElement() !== null
updateContextState({ fullscreen })
this.updateZoomLimits()
}
handleZoom = ({ zoom }) => {
const { viewport } = this.viewer
const { updateContextState } = this.props
const min = viewport.getMinZoom()
const max = viewport.getMaxZoom()
const currentZoom = memoizeZoomPercent(zoom, max)
const canZoomIn = zoom < max && currentZoom < 100
const canZoomOut = zoom > min
updateContextState({ currentZoom, canZoomIn, canZoomOut })
}
handleZoomOptimized = debounce(event => {
// Unable to update zoom on scroll inside this event handler:
// - Bad peformance from multiple context update state calls
// - Small delay for text updating noticeable.
if (!this.isScrolling) {
this.handleZoom(event)
}
}, 200)
handleScrollOptimized = () => {
// Reset scrolling flag
this.isScrolling = true
// Clear our timeout throughout the scroll
window.clearTimeout(this.clearScrollingDelay)
// Set a timeout to run after scrolling ends
this.clearScrollingDelay = setTimeout(() => {
this.isScrolling = false
this.handleZoomOptimized({ zoom: this.viewer.viewport.getZoom() })
}, 400)
}
initOpenSeaDragon = () => {
const { id, container, pages, renderError, updateContextState } = this.props
// Detect browser vendor
this.browser = getKeyByValue(OpenSeaDragon.BROWSERS, OpenSeaDragon.Browser.vendor)
// Create viewer
this.viewer = OpenSeaDragon({
element: this.OSDContainer.current,
tileSources: pages[0],
...OSDConfig,
})
// Events handler
this.viewer.addHandler('open', () => {
this.renderLayout()
this.fitBounds()
// Prevent unessesart context updates
if (renderError) {
updateContextState({ renderError: false })
}
})
// Events handler
this.viewer.addHandler('resize', () => {
this.updateZoomLimits()
})
// Fallback to improve peformance on zoom upodates"
// Fix issue with animations and peformance, see:
// https://github.com/btzr-io/Villain/issues/66
this.viewer.addHandler('zoom', this.handleZoomOptimized)
// Optimized scroll event
this.viewer.addHandler('canvas-scroll', this.handleScrollOptimized)
this.viewer.addHandler('open-failed', this.handleError)
onFullscreenChange(container, 'add', this.handleFullscreenChange)
}
renderPage(index) {
const page = this.props.getPage(index)
page && this.viewer.open(page)
}
renderCover() {
this.renderPage(0)
}
fitBounds() {
const { viewport } = this.viewer
this.fitPages()
this.updateZoomLimits()
viewport.zoomTo(viewport.getMinZoom(), null, true)
}
renderLayout() {
const { world } = this.viewer
const { mangaMode, bookMode } = this.props
const pos = new OpenSeaDragon.Point(0, 0)
const count = world.getItemCount()
// Cache tile data
let bounds = null
// first page
let firstPage = null
let firstPageIndex = bookMode && mangaMode && count > 1 ? 1 : 0
let firstPageBounds = null
// Next page
let nextPage = null
let nextPageBounds = null
let nextPageIndex = bookMode && mangaMode ? 0 : 1
if (count > 0) {
// Page view (single page)
firstPage = world.getItemAt(firstPageIndex)
firstPageBounds = firstPage.getBounds()
// Book view ( two pages )
if (count > 1) {
nextPage = world.getItemAt(nextPageIndex)
nextPageBounds = nextPage.getBounds()
// Auto resize page to fit first page height
if (firstPageBounds.height > nextPageBounds.height) {
nextPage.setHeight(firstPageBounds.height, true)
// Recalculate bounds
nextPageBounds = nextPage.getBounds()
}
// Auto resize page to fit next page height
if (nextPageBounds.height > firstPageBounds.height) {
firstPage.setHeight(nextPageBounds.height, true)
// Recalculate bounds
firstPageBounds = firstPage.getBounds()
}
}
// Set position for first page
if (firstPage && firstPageBounds) {
firstPage.setPosition(pos, true)
pos.x += firstPageBounds.width
}
// Set position for next page
if (nextPage && nextPageBounds) {
nextPage.setPosition(pos, true)
pos.x += nextPageBounds.width
}
}
}
fitPagesLegacy() {
const { viewport, world } = this.viewer
const bounds = world.getHomeBounds()
viewport.fitBoundsWithConstraints(bounds, true)
}
fitPages(orientation) {
const { viewport, world } = this.viewer
if (!orientation) {
this.fitPagesLegacy()
}
if (orientation === 'vertical') {
viewport.fitVertically(true)
}
if (orientation === 'horizontal') {
viewport.fitHorizontally(true)
}
}
componentDidMount() {
const { initialPage } = this.props
this.initOpenSeaDragon()
this.renderPage(initialPage)
}
componentWillUnmount() {
const { container } = this.props
// Remove event listeners
onFullscreenChange(container, 'remove', this.handleFullscreenChange)
// Destroy OpenSeaDragon viewer
this.viewer.destroy()
this.viewer = null
}
componentDidUpdate(prevProps) {
const { bookMode, mangaMode, totalPages, currentPage } = this.props
// Page changed
if (currentPage !== prevProps.currentPage || bookMode !== prevProps.bookMode) {
// Render new valid page
if (currentPage >= 0 && currentPage < totalPages) {
this.renderPage(currentPage)
}
}
// Page changed
if (bookMode !== prevProps.bookMode) {
if (bookMode) {
// Trigger re-render layout
this.renderLayout()
this.fitBounds()
}
}
// Re-render layout when mangaMode and there and book mode is active
if (mangaMode !== prevProps.mangaMode && bookMode) {
this.renderLayout()
}
}
render() {
const { id, container, renderError } = this.props
return (
<React.Fragment>
<ToolbarConsumer
container={container}
updateZoom={this.updateZoom}
zoomIn={this.zoomIn}
zoomOut={this.zoomOut}
/>
<div ref={this.OSDContainer} className={'villain-canvas'} />
{renderError && (
<RenderError message={'Invalid image'} icon={mdiImageBrokenVariant} />
)}
</React.Fragment>
)
}
}
const CanvasRenderConsumer = React.memo(({ container }) => {
return (
<ReaderContext.Consumer>
{({
// State
ready,
error,
hover,
pages,
bookMode,
mangaMode,
totalPages,
currentPage,
renderError,
allowFullScreen,
allowGlobalShortcuts,
// Actions
getPage,
updateState,
}) => {
const shouldRender = ready && !error
return (
shouldRender && (
<CanvasRender
hover={hover}
pages={pages}
container={container}
currentPage={currentPage}
getPage={getPage}
bookMode={bookMode}
mangaMode={mangaMode}
totalPages={totalPages}
renderError={renderError}
allowFullScreen={allowFullScreen}
allowGlobalShortcuts={allowGlobalShortcuts}
updateContextState={updateState}
/>
)
)
}}
</ReaderContext.Consumer>
)
})
export default CanvasRenderConsumer