var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/preview/PdfViewer.tsx
var PdfViewer_exports = {};
__export(PdfViewer_exports, {
  default: () => Viewer
});
module.exports = __toCommonJS(PdfViewer_exports);
var import_react = __toESM(require("react"));
var import_whatwg_fetch = require("whatwg-fetch");
var import_context = require("../config-provider/context");
var import_utils = require("../locale/utils");
var import_PdfViewer = require("./PdfViewer.less");
var TOOLBAR_HEIGHT = 40;
var AUTO_SCALE = 1.25;
var Viewer = class extends import_react.Component {
  constructor(props) {
    super(props);
    this.initilized = false;
    this.pageHeight = 0;
    this.pageWidth = 0;
    this.scrollHideControls = false;
    // eslint-disable-next-line react/sort-comp
    this.initViewer = () => {
      this.initilized = false;
      const { file, startPage, host } = this.props;
      const link = document.createElement("link");
      link.rel = "stylesheet";
      link.href = host + `/api/office/km/file/convert/info/${file}?fileName=index.css`;
      link.onload = () => {
        setTimeout(() => {
          this.resetScale();
          const pageDiv = document.querySelector(".pdf2html-viewer-page");
          this.pageWidth = (pageDiv == null ? void 0 : pageDiv.clientWidth) || 0;
          this.pageHeight = (pageDiv == null ? void 0 : pageDiv.clientHeight) || 0;
          this.setState({ pages: {}, scaleValue: "width" });
          this.gotoPage(startPage);
          this.updatePageIndex();
          this.fitWidth();
          setTimeout(() => {
            this.scrollTop = this.container.scrollTop;
            this.initilized = true;
          }, 0);
        }, 0);
      };
      document.head.appendChild(link);
      this.styleLink = link;
    };
    this.hideScrollbar = () => {
      const pagesDiv = document.querySelector(".pdf2html-viewer-pages");
      if (pagesDiv) {
        const scrollbarWidth = (pagesDiv == null ? void 0 : pagesDiv.offsetWidth) - (pagesDiv == null ? void 0 : pagesDiv.clientWidth);
        pagesDiv.style.right = `${-scrollbarWidth}px`;
      }
    };
    this.scrollListener = () => {
      const { scrollTop } = this.container;
      if (this.scrollHideControls && !this.hidingControls && scrollTop > 100 && scrollTop > this.scrollTop) {
        this.hideControls();
      }
      if (this.container.scrollTop <= 100 || scrollTop < this.scrollTop) {
        this.showControls();
      }
      this.scrollTop = scrollTop;
      const time = Date.now();
      if (!this.lastUpdateTime) {
        this.lastUpdateTime = time;
      }
      if (time - this.lastUpdateTime > 50) {
        this.updatePageIndex();
        this.lastUpdateTime = time;
      } else {
        clearTimeout(this.scrollTimer);
        this.scrollTimer = setTimeout(() => this.updatePageIndex(), 50);
      }
    };
    this.updatePageIndex = () => {
      const { pageCount } = this.props;
      const minY = this.container.scrollTop + TOOLBAR_HEIGHT;
      const maxY = minY + this.container.clientHeight;
      const pageDivs = [].slice.call(document.querySelectorAll(".pdf2html-viewer-page"));
      let start = 0;
      let end = pageCount - 1;
      while (start < end) {
        const middleIndex = Math.floor((start + end) / 2);
        const middleDiv = pageDivs[middleIndex];
        const divBottom = (middleDiv == null ? void 0 : middleDiv.offsetTop) + (middleDiv == null ? void 0 : middleDiv.offsetHeight);
        if (divBottom > minY) {
          end = middleIndex;
        } else {
          start = middleIndex + 1;
        }
      }
      const visibleIndexes = [];
      let maxVisibleHeight = 0;
      let maxVisibleIndex = start;
      let i;
      let len;
      for (i = start, len = pageCount; i < len; i++) {
        const pageDiv = pageDivs[i];
        const visibleHeight = Math.min(maxY, (pageDiv == null ? void 0 : pageDiv.offsetTop) + (pageDiv == null ? void 0 : pageDiv.offsetHeight)) - Math.max(minY, pageDiv.offsetTop);
        if (visibleHeight > 0) {
          visibleIndexes.push(i);
          if (visibleHeight > maxVisibleHeight) {
            maxVisibleHeight = visibleHeight;
            maxVisibleIndex = i;
          }
        } else {
          break;
        }
      }
      if (start > 0)
        visibleIndexes.push(start - 1);
      if (i < pageCount)
        visibleIndexes.push(i);
      this.setState({ currentPage: maxVisibleIndex + 1, visibleIndexes });
      this.pageInput.value = maxVisibleIndex + 1;
      visibleIndexes.forEach((index) => index >= 0 && index < pageCount && this.loadPage(index));
    };
    this.loadPage = (index) => {
      const { file, onPageLoaded, host } = this.props;
      const { pages, scaleValue } = this.state;
      const page = pages[index];
      if (!file)
        return;
      if (page && (page.loaded || page.loading))
        return;
      const url = host + `/api/office/km/file/convert/info/${file}?page=${index + 1}`;
      this.setState(
        {
          pages: {
            ...pages,
            [index]: page ? { ...page, loading: true } : { loading: true }
          }
        },
        () => {
          fetch(url, { credentials: "same-origin" }).then((res) => {
            return res.text();
          }).then((json) => {
            const html = new DOMParser().parseFromString(json, "text/html");
            const { pages: pages2 } = this.state;
            const page2 = pages2[index];
            const prefixUrl = host + `/api/office/km/file/convert/info/${file}`;
            const targetHtml = html.querySelector(".pf");
            const imgEles = targetHtml == null ? void 0 : targetHtml.querySelectorAll("img");
            if (imgEles) {
              imgEles.forEach((img) => {
                const path = img.src || "";
                const name = path.lastIndexOf("/") ? path.substring(path.lastIndexOf("/") + 1, path.length) : "";
                img.src = `${prefixUrl}?fileName=${name}`;
              });
            }
            this.setState(
              {
                pages: {
                  ...pages2,
                  [index]: page2 ? {
                    ...page2,
                    html: targetHtml,
                    loading: false,
                    loaded: true
                  } : { html: targetHtml, loaded: true }
                }
              },
              () => {
                if (scaleValue === "width") {
                  this.fitWidth();
                }
              }
            );
            onPageLoaded && onPageLoaded(index + 1);
          });
        }
      );
    };
    this.gotoPage = (page, delta = 0) => {
      if (!page)
        return;
      this.container.scrollTop = 0;
      const pageDiv = document.querySelector(`div[data-page-no="${page}"]`);
      if (pageDiv) {
        this.container.scrollTop = pageDiv.offsetTop - TOOLBAR_HEIGHT - delta;
      }
    };
    this.prevPage = () => {
      const { currentPage } = this.state;
      this.gotoPage(Math.max(1, currentPage - 1));
    };
    this.nextPage = () => {
      const { pageCount } = this.props;
      const { currentPage } = this.state;
      this.gotoPage(Math.min(pageCount, currentPage + 1));
    };
    this.enterPage = (e) => {
      const { value } = e.target;
      if (!/^\d+$/.test(value))
        return;
      const page = parseInt(value, 10);
      if (page < 1 || page > this.props.pageCount)
        return;
      this.gotoPage(page);
      e.target.blur();
    };
    this.resetScale = () => {
      const pageDivs = [].slice.call(document.querySelectorAll(".pdf2html-viewer-page"));
      pageDivs.forEach((div) => {
        div.style.width = "";
        div.style.height = "";
        div.style.opacity = "";
      });
      this.setState({ currentScale: 1 });
    };
    this.setScale = (scale) => {
      var _a;
      const { currentPage } = this.state;
      const pageDiv = document.querySelector(`div[data-page-no="${currentPage}"]`);
      const delta = (pageDiv == null ? void 0 : pageDiv.offsetTop) - ((_a = this.container) == null ? void 0 : _a.scrollTop) - TOOLBAR_HEIGHT;
      const pageDivs = [].slice.call(document.querySelectorAll(".pdf2html-viewer-page"));
      pageDivs.forEach((div) => {
        div.style.width = `${Math.round(this.pageWidth * scale)}px`;
        div.style.height = `${Math.round(this.pageHeight * scale)}px`;
        div.style.opacity = "1";
      });
      this.setState({ currentScale: scale || 1 }, () => {
        this.gotoPage(currentPage, delta);
        this.updatePageIndex();
      });
    };
    this.zoomOut = () => {
      const { currentScale } = this.state;
      let nextScale;
      if (currentScale <= 1.1) {
        nextScale = currentScale + 0.1 + 1e-4;
      } else if (currentScale <= 2) {
        nextScale = currentScale + 0.2 + 1e-4;
      } else if (currentScale <= 3) {
        nextScale = currentScale + 0.3 + 1e-4;
      } else {
        nextScale = currentScale + 0.4 + 1e-4;
      }
      if (nextScale > 4) {
        nextScale = 4;
      }
      nextScale = Math.floor(nextScale * 10) / 10;
      const scaleValue = `${Math.round(nextScale * 100)}%`;
      this.setScale(nextScale);
      this.setState({ scaleValue });
      this.scaleSelect.value = scaleValue;
    };
    this.zoomIn = () => {
      const { currentScale } = this.state;
      let nextScale;
      if (currentScale > 3) {
        nextScale = currentScale - 0.4 - 1e-4;
      } else if (currentScale > 2) {
        nextScale = currentScale - 0.3 - 1e-4;
      } else if (currentScale > 1.1) {
        nextScale = currentScale - 0.2 - 1e-4;
      } else {
        nextScale = currentScale - 0.1 - 1e-4;
      }
      if (nextScale < 0.5) {
        nextScale = 0.5;
      }
      nextScale = Math.ceil(nextScale * 10) / 10;
      const scaleValue = `${Math.round(nextScale * 100)}%`;
      this.setScale(nextScale);
      this.setState({ scaleValue });
      this.scaleSelect.value = scaleValue;
    };
    this.changeScale = (value) => {
      switch (value) {
        case "auto":
          this.autoScale();
          break;
        case "actual":
          this.setScale(1);
          this.setState({ scaleValue: "actual" });
          break;
        case "fit":
          this.fitPage();
          break;
        case "width":
          this.fitWidth();
          break;
        default:
          this.setScale(value - 0);
          this.setState({ scaleValue: `${Math.round(value * 100)}%` });
          break;
      }
    };
    this.autoScale = () => {
      const pageDiv = document.querySelector(".pdf2html-viewer-page");
      const scaleX = (pageDiv == null ? void 0 : pageDiv.parentElement) ? pageDiv.parentElement.clientWidth / this.pageWidth : 1;
      const scale = Math.min(AUTO_SCALE, scaleX);
      this.setScale(scale);
      this.setState({ scaleValue: "auto" });
    };
    this.fitPage = () => {
      const pageDiv = document.querySelector(".pdf2html-viewer-page");
      const scaleX = (pageDiv == null ? void 0 : pageDiv.parentElement) ? pageDiv.parentElement.clientWidth / this.pageWidth : 1;
      const scaleY = (pageDiv == null ? void 0 : pageDiv.parentElement) ? (pageDiv.parentElement.offsetHeight - TOOLBAR_HEIGHT) / this.pageHeight : 1;
      const scale = Math.min(scaleX, scaleY);
      this.setScale(scale);
      this.setState({ scaleValue: "fit" });
    };
    this.fitWidth = () => {
      const pageDiv = document.querySelector(".pdf2html-viewer-page");
      const childDiv = pageDiv == null ? void 0 : pageDiv.querySelector(".pf");
      if (childDiv) {
        this.pageWidth = childDiv.clientWidth;
        this.pageHeight = childDiv.clientHeight;
      }
      const scale = (pageDiv == null ? void 0 : pageDiv.parentElement) ? ((pageDiv.parentElement.clientWidth - 20) / this.pageWidth).toFixed(2) : 1;
      this.setScale(Number(scale));
      this.setState({ scaleValue: "width" });
    };
    this.toggleFullScreen = () => {
      const { onFullScreenChange } = this.props;
      const { fullscreen, scaleValue } = this.state;
      fullscreen ? document.body.style.overflow = "" : document.body.style.overflow = "hidden";
      this.setState({ fullscreen: !fullscreen }, () => {
        const { fullscreen: nextFullscreen } = this.state;
        if (["auto", "fit", "width"].includes(scaleValue)) {
          this.changeScale(scaleValue);
        }
        this.updatePageIndex();
        onFullScreenChange && onFullScreenChange(nextFullscreen);
      });
    };
    // eslint-disable-next-line consistent-return
    this.handleKeyDown = (e) => {
      switch (e.keyCode) {
        case 38:
          e.preventDefault();
          return this.prevPage();
        case 40:
          e.preventDefault();
          return this.nextPage();
        default:
      }
    };
    this.handleMouseMove = (e) => {
      if (!this.initilized)
        return;
      const rect = e.currentTarget.getBoundingClientRect();
      const offsetTop = e.clientY - rect.top;
      const offsetLeft = e.clientX - rect.left;
      const offsetRight = rect.right - e.clientX;
      if (offsetTop < 80 || offsetLeft < 80 || offsetRight < 80) {
        this.scrollHideControls = false;
        this.showControls();
      } else {
        this.scrollHideControls = true;
      }
    };
    this.hideControls = () => {
      this.hidingControls = true;
      this.hideControlsTimer = setTimeout(() => {
        this.setState({ hideControls: true }, () => TOOLBAR_HEIGHT = 0);
        this.hidingControls = false;
      }, 2e3);
    };
    this.showControls = () => {
      clearTimeout(this.hideControlsTimer);
      this.setState({ hideControls: false }, () => TOOLBAR_HEIGHT = 40);
      this.hidingControls = false;
    };
    this.state = {
      currentPage: 1,
      currentScale: 1,
      fullscreen: props.fullscreen,
      hideControls: false,
      pages: {},
      scaleValue: "",
      visibleIndexes: []
    };
  }
  componentDidMount() {
    this.initViewer();
    this.hideScrollbar();
    this.container.addEventListener("scroll", this.scrollListener);
  }
  componentDidUpdate(prevProps, prevState) {
    const { file, onPageChanged, onToggleControls } = this.props;
    const { currentPage, hideControls } = this.state;
    if (file !== prevProps.file) {
      this.styleLink && document.head.removeChild(this.styleLink);
      this.initViewer();
    }
    if (currentPage !== prevState.currentPage && onPageChanged) {
      onPageChanged(currentPage);
    }
    if (hideControls !== prevState.hideControls && onToggleControls) {
      onToggleControls(!hideControls);
    }
  }
  componentWillUnmount() {
    this.styleLink && document.head.removeChild(this.styleLink);
    this.container.removeEventListener("scroll", this.scrollListener);
    document.body.style.overflow = "";
  }
  render() {
    const { pageCount, title, allowDownload, onDownload } = this.props;
    const { pages, visibleIndexes, currentScale, scaleValue, currentPage, fullscreen, hideControls } = this.state;
    const classCls = `pdf2html-viewer-container pdf2html-viewer-container${fullscreen ? " pdf2html-viewer-fullscreen" : ""}${hideControls ? " hide-controls" : ""}`;
    return /* @__PURE__ */ import_react.default.createElement(import_context.ConfigConsumer, null, (props) => {
      const { uiLocale } = props;
      return /* @__PURE__ */ import_react.default.createElement("div", { className: classCls, tabIndex: -1, onKeyDown: this.handleKeyDown, onMouseMove: this.handleMouseMove }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pdf2html-viewer-toolbar" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "toolbar-title" }, title), /* @__PURE__ */ import_react.default.createElement("div", { className: "toolbar-center" }, /* @__PURE__ */ import_react.default.createElement("button", { onClick: this.zoomIn, className: "toolbar-btn btn-zoom-in", type: "button" }, " "), /* @__PURE__ */ import_react.default.createElement("button", { onClick: this.zoomOut, className: "toolbar-btn btn-zoom-out", type: "button" }, " "), /* @__PURE__ */ import_react.default.createElement("span", { className: "toolbar-scale-select" }, /* @__PURE__ */ import_react.default.createElement(
        "select",
        {
          value: scaleValue,
          onChange: (e) => this.changeScale(e.target.value),
          ref: (el) => this.scaleSelect = el
        },
        /* @__PURE__ */ import_react.default.createElement("option", { value: "auto" }, uiLocale.Preview.auto),
        /* @__PURE__ */ import_react.default.createElement("option", { value: "actual" }, uiLocale.Preview.actual),
        /* @__PURE__ */ import_react.default.createElement("option", { value: "fit" }, uiLocale.Preview.fitPage),
        /* @__PURE__ */ import_react.default.createElement("option", { value: "width" }, uiLocale.Preview.fitWidth),
        /* @__PURE__ */ import_react.default.createElement("option", { value: scaleValue, disabled: true, hidden: true }, scaleValue),
        [50, 75, 100, 125, 150, 200, 300, 400].map((value) => /* @__PURE__ */ import_react.default.createElement("option", { value: value / 100, key: value }, `${value}%`))
      ))), /* @__PURE__ */ import_react.default.createElement("div", { className: "toolbar-right" }, allowDownload && /* @__PURE__ */ import_react.default.createElement("button", { onClick: () => onDownload && onDownload(), className: "toolbar-btn btn-download", type: "button" }, " "), /* @__PURE__ */ import_react.default.createElement("button", { onClick: this.prevPage, className: "toolbar-btn btn-prev-page", disabled: currentPage <= 1, type: "button" }, " "), /* @__PURE__ */ import_react.default.createElement("button", { onClick: this.nextPage, className: "toolbar-btn btn-next-page", disabled: currentPage >= pageCount, type: "button" }, " "), /* @__PURE__ */ import_react.default.createElement("span", { className: "toolbar-current-page" }, /* @__PURE__ */ import_react.default.createElement(
        "input",
        {
          ref: (input) => {
            this.pageInput = input;
          },
          onKeyUp: (e) => e.key === "Enter" && this.enterPage(e)
        }
      ), "/ ", pageCount), /* @__PURE__ */ import_react.default.createElement(
        "button",
        {
          onClick: this.toggleFullScreen,
          className: `toolbar-btn ${fullscreen ? "btn-exit-fullscreen" : "btn-fullscreen"}`,
          type: "button"
        },
        " "
      ))), /* @__PURE__ */ import_react.default.createElement("div", { className: "pdf2html-viewer-pages-wrapper" }, /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: "pdf2html-viewer-pages",
          ref: (div) => {
            this.container = div;
          }
        },
        Array.from({ length: pageCount }, (item, index) => index).map((index) => {
          const page = pages[index];
          if (page && page.loading) {
            return /* @__PURE__ */ import_react.default.createElement("div", { key: index, "data-page-no": `${index + 1}`, className: "pdf2html-viewer-page w0 h0 is-loading" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pdf2html-viewer-spin" }));
          }
          let inner = null;
          if (page && page.html) {
            inner = page.html;
            inner.style.transform = `scale(${currentScale})`;
          }
          return /* @__PURE__ */ import_react.default.createElement(
            "div",
            {
              className: "pdf2html-viewer-page w0 h0",
              key: index,
              "data-page-no": `${index + 1}`,
              dangerouslySetInnerHTML: {
                __html: inner && visibleIndexes.includes(index) ? inner.outerHTML : ""
              }
            }
          );
        })
      )), /* @__PURE__ */ import_react.default.createElement("div", { className: "pdf2html-viewer-progress" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "progress-bar", style: { width: `${currentPage / pageCount * 100}%` } }), /* @__PURE__ */ import_react.default.createElement("span", { className: "progress-text" }, (0, import_utils.replaceMessage)(uiLocale.Preview.readPercent, { percent: `${Math.round(currentPage / pageCount * 100)}` }))));
    });
  }
};
// eslint-disable-next-line react/sort-comp
Viewer.defaultProps = {
  pageCount: 1,
  fullscreen: false
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {});
