import Swiper from "swiper"; import { Navigation, Pagination } from "swiper/modules"; import { SwiperOptions } from "swiper/types/swiper-options"; import { ModuleControl } from "queenjs"; import { EditorModule } from "../../module"; import { RxValue } from "../ReactCtrl/rxValue"; export class PreviewCtrl extends ModuleControl { swiper: any = ""; state = RxValue.create({ scale: 1, }); container: HTMLElement | undefined; initDom(element: HTMLElement) { this.container = element; const page = this.controls.pageCtrl; const { value } = page.rootPage; const isPcDesign = value.useFor == "pc"; if (isPcDesign) this.getContainerScale(); } initEvent() { // 重置缩放比例 window.addEventListener("resize", () => this.resizeWindow()); // 监听上下左右键翻页 document.addEventListener("keydown", (event) => this.keyEvent(event)); } destroyEvent() { document.removeEventListener("keydown", this.keyEvent); document.removeEventListener("resize", this.resizeWindow); } resizeWindow() { this.getContainerScale(); } keyEvent(event: KeyboardEvent) { switch (event.keyCode) { case 37: case 38: this.swiper.slidePrev(); break; case 39: case 40: this.swiper.slideNext(); break; } } initSwiper(el: HTMLElement) { const page = this.controls.pageCtrl; const { value } = page.rootPage; const isPcDesign = value.useFor == "pc"; let options: SwiperOptions = { loop: true, direction: "vertical", pagination: { el: ".swiper-pagination", type: isPcDesign ? "progressbar" : "fraction", verticalClass: "vertical_mobile_progress", }, navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", }, }; if (isPcDesign) { options = { ...options, direction: "horizontal", watchSlidesProgress: true, pagination: { el: ".swiper-pagination", type: "progressbar", }, }; } this.swiper = new Swiper(el, { modules: [Navigation, Pagination], ...options, }); if (isPcDesign) this.initEvent(); } getContainerScale() { if (!this.container) { this.state.setScale(1); return; } const layout = { height: this.container.clientHeight, width: this.container.clientWidth, }; const pageRatio = layout.width / layout.height; const windowRatio = document.body.clientWidth / document.body.clientHeight; let scale = 1; if (pageRatio > windowRatio) { // calc width scale = document.body.clientWidth / layout.width; } else { // calc height scale = document.body.clientHeight / layout.height; } this.state.setScale(scale); } }