feat: 1.0 viewer

This commit is contained in:
丁锐
2021-12-01 12:08:03 +08:00
commit c6805f2dac
32 changed files with 9109 additions and 0 deletions
+57
View File
@@ -0,0 +1,57 @@
<script>
import Vue from 'vue'
import style from '!!css-loader!!sass-loader!./iframe.scss'
export default {
props: {
css: String,
},
render(h) {
return h('iframe', {
on: { load: this.renderChildren },
style: { width: '100%', height: '100%', border: 'none' },
})
},
beforeUpdate() {
// freezing to prevent unnessessary Reactifiation of vNodes
this.iApp.children = Object.freeze(this.$slots.default)
},
methods: {
getContentWindow() {
return this.$el.contentWindow
},
appendStyle(style) {
const cssEl = document.createElement('STYLE')
cssEl.textContent = style
this.$el.contentDocument.head.appendChild(cssEl)
},
renderChildren() {
// inject iframe styles
this.appendStyle(style)
if (this.css) {
// inject component style
this.appendStyle(this.css)
}
const children = this.$slots.default
const body = this.$el.contentDocument.body
const el = document.createElement('DIV') // we will mount or nested app to this element
body.appendChild(el)
const iApp = new Vue({
name: 'iApp',
// freezing to prevent unnessessary Reactifiation of vNodes
data: { children: Object.freeze(children) },
render(h) {
return h('div', this.children)
},
})
iApp.$mount(el) // mount into iframe
this.iApp = iApp // cache instance for later updates
},
},
}
</script>
+4
View File
@@ -0,0 +1,4 @@
* {
padding: 0;
margin: 0;
}
+48
View File
@@ -0,0 +1,48 @@
<template>
<button :disabled="disabled" class="icon-btn" @click="$emit('click')">
<Iconfont :name="name" />
</button>
</template>
<script>
import Iconfont from './Iconfont.vue'
export default {
name: 'IconButton',
components: {
Iconfont,
},
props: {
name: String,
disabled: Boolean,
},
}
</script>
<style lang="scss" scoped>
.icon-btn {
margin-inline-start: 4px;
width: 36px;
height: 36px;
display: flex;
justify-content: center;
align-items: center;
border-radius: 50%;
transition: all 200ms ease;
cursor: pointer;
background: transparent;
border: none;
color: white;
&:hover {
background: #5c5c5c;
}
&:first-child {
margin-inline-start: 0px;
}
&:disabled {
background: transparent;
cursor: not-allowed;
color: rgb(134, 134, 134);
}
}
</style>
+53
View File
@@ -0,0 +1,53 @@
<template>
<i v-if="isFontClass" :class="className" @click="$emit('click')">
<slot />
</i>
<svg v-else class="icon" aria-hidden="true">
<use :xlink:href="icon" />
</svg>
</template>
<script>
export default {
props: {
name: {
type: String,
required: true,
},
useSymbol: {
type: Boolean,
default: false,
},
prefix: {
type: String,
default: 'pdf-viewer--',
},
},
computed: {
icon() {
return this.useSymbol
? `#icon-${this.name}`
: `${this.prefix}${this.name}`
},
className() {
return `iconfont ${this.icon}`
},
isFontClass() {
return !this.useSymbol
},
},
}
</script>
<style lang="scss" scoped>
.icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
.iconfont {
font-size: 14px;
}
</style>
+114
View File
@@ -0,0 +1,114 @@
.viewer-container {
display: flex;
background: rgb(82, 86, 89);
height: 100%;
.scroller {
height: 100%;
// scroll-behavior: smooth;
overflow: auto;
&.catalog {
background: #323639;
width: 300px;
flex-shrink: 0;
flex-grow: 0;
transition: all 500ms ease;
margin-left: -300px;
&.visible {
margin-left: 0;
}
.catalog-content {
padding-bottom: 20px;
.catalog-item {
color: white;
padding-top: 20px;
text-align: center;
font-size: 0;
&:first-child {
// margin-top: 0;
}
.catalog-index {
text-align: center;
margin-top: 10px;
font-size: 13px;
height: 14px;
line-height: 14px;
}
.canvas {
width: 110px;
// height: 152px;
opacity: 0.8;
&.active {
box-shadow: 0 0 0 4px rgb(84, 201, 255);
opacity: 1;
}
&:hover {
opacity: 1;
}
}
}
}
}
&.viewer {
flex: 1;
.viewer-content {
padding-top: 20px;
.viewer-item {
padding-bottom: 20px;
font-size: 0;
display: flex;
justify-content: center;
align-items: center;
width: 100%;
page-break-after: always;
.canvas {
white-space: nowrap;
// margin: 0 auto;
// display: block;
margin: initial;
max-width: initial;
// margin-bottom: 20px;
box-shadow: 0px 0px 7px 6px rgba($color: #000000, $alpha: 0.25);
transition: transform 300ms ease;
}
}
}
}
}
}
@media print {
html, body {
width: 210mm;
height: 297mm;
}
.viewer-container {
height: auto !important;
overflow: initial !important;
background-color: white!important;
.catalog {
display: none !important;
}
.viewer {
overflow: initial !important;
height: auto !important;
&-content {
padding: 0!important;
.viewer-item {
page-break-after: always!important;
padding: 0!important;
.canvas {
width: 100% !important;
box-shadow: none!important;
}
}
}
}
}
}
@media screen and (max-width: 800px) {
.viewer-container {
.catalog {
margin-left: -300px!important;
}
}
}
+328
View File
@@ -0,0 +1,328 @@
<template>
<IFrame :css="$options.style" ref="iframe">
<div class="viewer-container" ref="container">
<div
class="scroller catalog"
ref="catalogScroller"
:class="{
visible: catalogVisible,
}"
>
<div class="catalog-content" ref="catalogContent">
<div
ref="catalogItem"
v-for="page in pages"
class="catalog-item"
:key="page"
>
<div class="test" :style="thumbnailItemStyle">
<canvas
ref="catalogCanvas"
class="canvas"
:class="activePage === page && 'active'"
:style="thumbnailStyle"
@click="handleSwitchPage(page)"
/>
</div>
<div class="catalog-index">
{{ page }}
</div>
</div>
</div>
</div>
<div
class="scroller viewer"
ref="viewerScroller"
@scroll="handleViewerScroll"
>
<div class="viewer-content" ref="viewerContent">
<div
v-for="page in pages"
:key="page"
class="viewer-item"
:style="viewerItemStyle"
>
<canvas ref="viewerCanvas" class="canvas" :style="viewerStyle" />
</div>
</div>
</div>
</div>
</IFrame>
</template>
<script>
import * as PDF from 'pdfjs-dist/es5/build/pdf.js'
import PDFWorker from 'pdfjs-dist/es5/build/pdf.worker.js'
import IFrame from '../IFrame/IFrame.vue'
import throttle from '../../utils/throttle'
import style from '!!css-loader!!sass-loader!./Viewer.scss'
PDF.GlobalWorkerOptions.workerPort = new PDFWorker()
const MARGIN_OFFSET = 20
const NORMAL_RATIO = 2
export default {
name: 'Viewer',
props: {
page: Number,
total: Number,
zoom: Number,
rotate: Number,
catalogVisible: Boolean,
isFullpage: Boolean,
source: {
type: [Object, String],
required: true,
},
},
style: style.toString(),
components: {
IFrame,
},
data() {
return {
document: null,
viewerContentHeight: 0,
viewportHeight: 0,
viewportWidth: 0,
}
},
computed: {
isHorizontalViewer() {
return (this.rotate / 90) % 2 === 1
},
activePage() {
return this.page
},
pages() {
return [...Array(this.total + 1).keys()].slice(1)
},
viewerStyle() {
return {
// height: `${this.zoom / NORMAL_RATIO}%`,
width: `${(this.zoom / NORMAL_RATIO / 100) * this.viewportWidth}px`,
transform: `rotate(${this.rotate}deg)`,
}
},
viewerItemStyle() {
return this.isHorizontalViewer
? {
height: `${
(this.zoom / NORMAL_RATIO / 100) * this.viewportWidth
}px`,
}
: {}
},
thumbnailItemStyle() {
return this.isHorizontalViewer
? {
height: `${
(this.zoom / NORMAL_RATIO / 100) * 300 // + 14 // catalog width: 300px; index height: 14px
}px`,
}
: {}
},
thumbnailStyle() {
return {
transform: `rotate(${this.rotate}deg)`,
}
},
},
watch: {
isFullpage(n, o) {
if (n !== o && n) {
this.updateZoomFullpage()
}
},
viewerStyle: {
deep: true,
async handler() {
await this.$nextTick()
this.viewerContentHeight = this.$refs.viewerContent.clientHeight
},
},
page(n, o) {
if (n === o) return
this.scrollToPage(n)
},
source: {
immediate: true,
async handler() {
await this.load()
this.render()
},
},
},
activated() {
this.$nextTick(() => {
this.handleResize()
})
this.render()
},
mounted() {
// TODO: element resize replace window resize with Observe
this.handleResize = throttle(() => {
this.viewportHeight = this.$refs.container.clientHeight
this.viewportWidth = this.$refs.viewerScroller.clientWidth
}, 100)
window.addEventListener('resize', this.handleResize)
this.$nextTick(() => {
this.handleResize()
})
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
},
methods: {
print() {
const contentWindow = this.$refs.iframe.getContentWindow()
contentWindow?.print()
},
updateZoomFullpage() {
const perViewerHeight = this.viewerContentHeight / this.total
const rate = this.viewportHeight / (perViewerHeight - MARGIN_OFFSET)
this.$emit('update:zoom', this.zoom * rate)
this.scrollToPage(this.page)
},
handleViewerScroll(evt) {
this.isScrolling = true
const yOffset = evt.target.scrollTop
const perHeight = (this.viewerContentHeight + MARGIN_OFFSET) / this.total
const halfViewportOffset = (perHeight - this.viewportHeight) / 2
const currentPosition = (yOffset - halfViewportOffset) / perHeight + 1
const delta = currentPosition - this.page
let pageOffset = 0
if (delta > 0.5) {
pageOffset += 1
} else if (delta < -0.5) {
pageOffset -= 1
}
this.$emit('update:page', this.page + pageOffset)
this.$nextTick(() => {
this.isScrolling = false
})
},
startLoading() {
this.$emit('isLoading', true)
},
endLoading() {
this.$emit('isLoading', false)
},
handleSwitchPage(page) {
this.$emit('update:page', page)
},
async load() {
if (!this.source) {
return
}
this.startLoading()
try {
const filename = PDF.getFilenameFromUrl(this.source)
this.$emit('update:filename', filename)
const documentLoadingTask = PDF.getDocument(this.source)
documentLoadingTask.onPassword = (callback, reason) => {
const retry = reason === PDF.PasswordResponses.INCORRECT_PASSWORD
this.$emit('password-requested', {
callback,
retry,
})
}
this.document = await documentLoadingTask.promise
this.$emit('loaded', {
total: this.document.numPages,
})
} catch (e) {
this.document = null
this.$emit('loading-failed', e)
} finally {
this.endLoading()
}
},
async render() {
if (!this.document) {
return
}
try {
await this.$nextTick()
await Promise.all(
this.pages.map(async (pageNum, i) => {
const page = await this.document.getPage(pageNum)
const pageWidth = page.view[2]
const containerWidth = this.$el.clientWidth
const targetWidth = containerWidth * 0.9
const scale = targetWidth / pageWidth
// const scale = Math.ceil(this.$el.clientWidth / page.view[2]) + 1
const viewport = page.getViewport({
scale: scale,
})
// render viewer
const viewerCanvas = this.$refs.viewerCanvas[i]
viewerCanvas.width = viewport.width
viewerCanvas.height = viewport.height
const renderViewer = page.render({
canvasContext: viewerCanvas.getContext('2d'),
viewport,
}).promise
// render catalog
const catalogScale = 110 / pageWidth
const catalogViewport = page.getViewport({
scale: catalogScale,
})
const catalogCanvas = this.$refs.catalogCanvas[i]
catalogCanvas.width = catalogViewport.width
catalogCanvas.height = catalogViewport.height
const renderCatalog = page.render({
canvasContext: catalogCanvas.getContext('2d'),
viewport: catalogViewport,
})
await Promise.all([renderViewer, renderCatalog])
})
)
this.$emit('rendered')
await this.$nextTick()
this.viewerContentHeight = this.$refs.viewerContent.clientHeight
} catch (e) {
this.document = null
this.$emit('rendering-failed', e)
}
},
scrollToPage(page) {
this.syncViewerOffset(page)
this.syncCatalogOffset(page)
},
syncViewerOffset(page) {
if (this.isScrolling) return
this.$refs.viewerCanvas[page - 1].scrollIntoView()
},
syncCatalogOffset(page) {
const target = this.$refs.catalogItem[page - 1]
target.scrollIntoView({
block: 'nearest',
// FIXME: scroll smooth failed sometimes. wtf?
// behavior: 'smooth',
})
},
},
}
</script>
<style lang="scss" scoped></style>
+352
View File
@@ -0,0 +1,352 @@
<template>
<span class="header__preview">
<div class="start">
<IconButton
v-if="catalogVisible"
name="catalog"
@click="handleToggleCatalog"
/>
<div class="title">
{{ filename }}
</div>
</div>
<div class="center">
<div id="content" v-if="switchPageVisible">
<input
part="input"
type="text"
id="pageselector"
aria-label="页码"
:value="page"
@blur="handleUpdatePage"
@keyup.enter="handleUpdatePage"
/>
<span id="divider">/</span>
<span id="pagelength">{{ total }}</span>
</div>
<span class="vertical-separator"></span>
<span id="zoom-controls" v-if="zoomVisible">
<IconButton
name="minus"
:disabled="isLowest"
@click="handleModifyZoomLevel(false)"
/>
<input
type="text"
aria-label="缩放级别"
:value="formatZoom"
@blur="handleUpdateZoom($event.target.value)"
@keyup.enter="handleUpdateZoom($event.target.value)"
/>
<IconButton
name="plus"
:disabled="isHighest"
@click="handleModifyZoomLevel(true)"
/>
</span>
<span class="vertical-separator"></span>
<IconButton
v-if="fullpageVisible"
:name="mode"
@click="handleToggleFullpage"
/>
<IconButton v-if="rotateVisible" name="rotate" @click="handleRotate" />
</div>
<div class="end">
<IconButton
v-if="downloadVisible"
name="download"
@click="handleDownload"
/>
<IconButton v-if="printVisible" name="printer" @click="handlePrint" />
<!-- TODO: more action. (infos, fullscreen...) -->
<!-- <IconButton v-if="moreVisible" name="dots" @click="handleToggleMore" /> -->
</div>
</span>
</template>
<script>
import IconButton from './IconButton.vue'
import {
DOWNLOAD,
PRINT,
DOUBLE,
FULLSCREEN,
ABOUT,
FULLPAGE,
ROTATE,
ZOOM,
CATALOG,
SWITCH_PAGE,
} from '../constants/controls'
const NORMAL_ZOOM_LEVEL = [
25, 33, 50, 67, 75, 80, 90, 100, 110, 125, 150, 175, 200, 250, 300, 400, 500,
]
const string2Number = str => Number(str.replace(/[^\d]/g, '')) || 1
export default {
name: 'ViewerPageSelector',
components: {
IconButton,
},
props: {
total: Number,
page: Number,
zoom: Number,
rotate: Number,
controls: Array,
isFullpage: Boolean,
filename: String,
},
data() {
return {
tmpZoom: null,
}
},
computed: {
formatZoom() {
return parseInt(this.zoom)
},
mode() {
return !this.isFullpage ? 'fullpage' : 'auto-width'
},
lowestValue() {
return NORMAL_ZOOM_LEVEL[0]
},
highestValue() {
return NORMAL_ZOOM_LEVEL[NORMAL_ZOOM_LEVEL.length - 1]
},
isLowest() {
return this.zoom <= this.lowestValue
},
isHighest() {
return this.zoom >= this.highestValue
},
catalogVisible() {
return this.controls.includes(CATALOG)
},
downloadVisible() {
return this.controls.includes(DOWNLOAD)
},
printVisible() {
return this.controls.includes(PRINT)
},
doubleVisible() {
return this.controls.includes(DOUBLE)
},
fullscreenVisible() {
return this.controls.includes(FULLSCREEN)
},
aboutVisible() {
return this.controls.includes(ABOUT)
},
fullpageVisible() {
return this.controls.includes(FULLPAGE)
},
rotateVisible() {
return this.controls.includes(ROTATE)
},
zoomVisible() {
return this.controls.includes(ZOOM)
},
switchPageVisible() {
return this.controls.includes(SWITCH_PAGE)
},
moreVisible() {
return [
this.doubleVisible,
this.aboutVisible,
this.fullscreenVisible,
].some(i => i)
},
},
methods: {
handleToggleFullpage() {
// Make a copy for recovery
if (!this.isFullpage) {
this.tmpZoom = this.zoom
} else {
this.handleUpdateZoom(this.tmpZoom)
}
this.$emit('toggleFullpage')
},
handleRotate() {
this.$emit('update:rotate', this.rotate + 90)
},
handleDownload() {
this.$emit('download')
},
handlePrint() {
this.$emit('print')
},
handleToggleMore() {
// TODO: toggle more
},
handleFullscreen() {
// TODO: fullscreen
},
handleModifyZoomLevel(isLevelUp) {
const targetLevel = NORMAL_ZOOM_LEVEL.reduce((target, zoom, i) => {
if (target) {
return target
}
const next = NORMAL_ZOOM_LEVEL[i + 1]
const condition = isLevelUp
? zoom <= this.zoom && this.zoom < next
: zoom < this.zoom && this.zoom <= next
if (condition) {
if (isLevelUp) {
return next
} else {
return zoom
}
}
return null
}, null)
this.handleUpdateZoom(targetLevel)
},
handleToggleCatalog() {
this.$emit('toggleCatalog')
},
handleUpdatePage(evt) {
const value = string2Number(evt.target.value)
this.$emit('update:page', value > this.total ? this.total : value)
},
handleUpdateZoom(value) {
if (typeof value !== 'number') {
value = string2Number(value)
}
const finalValue =
value > this.highestValue
? this.highestValue
: value < this.lowestValue
? this.lowestValue
: value
this.$emit('update:zoom', finalValue)
},
},
}
</script>
<style lang="scss" scoped>
.header__preview {
--page-length-digits: 1;
display: flex;
width: 100%;
.start,
.end {
flex: 1;
}
.start {
align-items: center;
display: flex;
overflow: hidden;
padding-inline-end: 20px;
min-width: 36px;
.title {
font-size: 13px;
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.catalog-icon {
> svg {
pointer-events: none;
display: block;
width: 20px;
height: 20px;
position: relative;
vertical-align: middle;
fill: var(--iron-icon-fill-color, currentcolor);
stroke: var(--iron-icon-stroke-color, none);
width: var(--iron-icon-width, 24px);
height: var(--iron-icon-height, 24px);
}
}
}
.center {
align-items: center;
display: flex;
#content {
align-items: center;
color: #fff;
direction: ltr;
display: flex;
font-size: 0.81rem;
text-align: center;
--page-selector-spacing: 4px;
#pageselector::selection {
background-color: var(--viewer-text-input-selection-color);
}
input,
#pagelength {
width: calc(max(2, var(--page-length-digits)) * 1ch + 1px);
}
input {
background: rgba(0, 0, 0, 0.5);
border: none;
color: white;
font-family: inherit;
line-height: inherit;
outline: none;
padding: 0 var(--page-selector-spacing);
text-align: center;
max-height: var(--viewer-pdf-toolbar-height);
font-size: 13px;
}
#divider {
margin: 0 var(--page-selector-spacing);
}
}
#zoom-controls {
align-items: center;
display: flex;
padding: 0 4px;
input {
background: rgba(0, 0, 0, 0.5);
border: none;
caret-color: currentColor;
color: inherit;
font-family: inherit;
line-height: inherit;
margin-left: 4px;
outline: none;
padding: 0 4px;
text-align: center;
width: 5ch;
font-size: 13px;
}
}
}
.end {
display: flex;
justify-content: flex-end;
padding-inline-start: 20px;
text-align: end;
white-space: nowrap;
}
}
@media screen and (max-width: 500) {
.header__preview {
.start {
display: none;
}
}
}
</style>