Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Basic from "./basic.js";
- class Resize extends Basic {
- constructor() {
- super();
- this.app = app;
- this.deletedPages = [];
- this.sizesConfig = [];
- this.marginConfig = [];
- this.changeViewLocked = false;
- this.viewAs = 'document';
- this.selected = {};
- this.toolName = 'resize-pdf';
- this.init();
- }
- async init() {
- console.log(`METHOD init`); //! LOG
- let that = this;
- fetch("/pdfcpu/pdfcpu.wasm").then((x) => {
- console.log("🟢️ wasm loaded");
- });
- $(document).on('click', '#view-as-documents', function (e) {
- $('.doc-item--selected').removeClass('doc-item--selected');
- that.viewAsDocumens();
- })
- $(document).on('click', '#view-as-pages', function (e) {
- $('.doc-item--selected').removeClass('doc-item--selected');
- that.viewAsPages();
- })
- $(document).on('click', '[data-fid]', function (e) {
- e.preventDefault();
- that.selectPage($(this));
- })
- // type of resizing buttons (margns&padding or page size)
- $('.resize-type-selector').click(e => {
- setTimeout(() => {
- this.renderChangeSizes();
- $('.doc-item--selected').removeClass('doc-item--selected');
- }, 200);
- });
- // page seize inputs
- ['left', 'top', 'right', 'bottom'].forEach(key => {
- $(`[name="margins-${key}"]`).on('change', e => this.setupUniqueSizes());
- });
- // margns&padding selectors
- $("[data-optional] input").on("change", e => {
- console.log(`CHANGE: [data-optional] input`); //! LOG
- // if (e.target.closest('#selectPageSize')) {
- this.setupUniqueSizes();
- // }
- });
- // custom page size (margns&padding -> custom size)
- ['custom_paper_height', 'custom_paper_width'].forEach(key => {
- $(`.${key}`).on('change', e => this.setupUniqueSizes());
- });
- }
- getPageSizesValues() {
- let resize_type = $('.resize-type-selector.active-tab').data('type');
- let new_paper_size = false;
- if (resize_type == 2) {
- new_paper_size = $('[name="page-size"]:checked').val();
- if (new_paper_size == 'custom_size') {
- let w = parseFloat($(".custom_paper_width").val());
- let h = parseFloat($(".custom_paper_height").val());
- if (w < 0) { $(".custom_paper_width").val(0); w = 0; }
- if (h < 0) { $(".custom_paper_height").val(0); h = 0; }
- new_paper_size = `${w}in,${h}in`;
- }
- new_paper_size = new_paper_size.replace(/in/g, '').split(',').map(size => parseFloat(size));
- } else if (resize_type == 1) {
- new_paper_size = {
- top: parseFloat($('[name="margins-top"]').val()),
- left: parseFloat($('[name="margins-left"]').val()),
- right: parseFloat($('[name="margins-right"]').val()),
- bottom: parseFloat($('[name="margins-bottom"]').val())
- };
- ['left', 'top', 'right', 'bottom'].forEach(key => {
- if (new_paper_size[key] < 0 || isNaN(new_paper_size[key])) {
- $(`[name="margins-${key}"]`).val(0);
- new_paper_size[key] = 0;
- }
- });
- }
- return new_paper_size;
- }
- getUpdateSizeKey() {
- const selectedType = document.querySelector('.resize-type-selector.active-tab').dataset.type;
- return selectedType == 1 ? 'marginConfig' : 'sizesConfig';
- }
- setupUniqueSizes() {
- const sizes = this.getPageSizesValues();
- const key = this.getUpdateSizeKey();
- console.log(`METHOD setupUniqueSizes`, sizes, key); //! LOG
- if (this.viewAs == 'pages') {
- console.log(` pages`); //! LOG
- const documentList = document.querySelector('.documents_list');
- const pagesSelected = Array.from(documentList.querySelectorAll('.doc-item--selected')).map(el => {
- return { fid: el.dataset.fid, page: el.dataset.fpage };
- }).filter(data => data.fid && data.page);
- if (pagesSelected && pagesSelected.length) {
- this[key] = this[key].filter(sc => !pagesSelected.find(ps => ps.fid == sc.fid && ps.page == sc.page));
- this[key].push(...pagesSelected.map(page => ({ ...page, sizes })));
- } else {
- this.setupCurrentSizeToAllPages();
- }
- } else {
- console.log(` docs`); //! LOG
- // fileid надо, тогда проставиться сайз для всех страниц
- const files = Array.from($('.documents_list').find('.doc-item--selected')).map(element => ({ id: element.dataset.fid }));
- this.setupCurrentSizeToAllPages(files && files.length ? files : this.files);
- }
- this.renderChangeSizes();
- }
- renderChangeSizes() {
- for (const file of this.files) {
- const fileData = this.loaded_files[file.id];
- if (!fileData || !fileData._pdfInfo) continue;
- new Array(fileData._pdfInfo.numPages).fill(false).forEach((t, i) => {
- this.renderPageSizePreview(i + 1, file.id, false);
- });
- }
- }
- setupCurrentSizeToAllPages(files = false) {
- if (!files) files = this.files;
- const sizes = this.getPageSizesValues();
- const replacedConfig = files.reduce((result, file) => {
- const pagesConfig = this.loaded_files[file.id];
- if (!pagesConfig || !pagesConfig._pdfInfo) return result;
- const data = new Array(pagesConfig._pdfInfo.numPages)
- .fill(false).map((q, i) => i + 1)
- .filter(pn => !this.deletedPages.find(dp => dp.page == pn && dp.id == file.id));
- if (data && data.length) {
- result.push(...data.map(pn => ({ fid: file.id, page: pn, sizes })));
- }
- return result;
- }, []);
- this[this.getUpdateSizeKey()] = replacedConfig;
- console.log('REPLACED CONFIG', replacedConfig);
- }
- selectPage(el) {
- let page = el.data('fpage');
- let id = el.data('fid');
- let selectedClass = 'doc-item--selected';
- let selected = this.selected[id].includes(page);
- if (selected) {
- el.removeClass(selectedClass);
- this.selected[id].splice(this.selected[id].indexOf(page), 1);
- } else {
- el.addClass(selectedClass);
- this.selected[id].push(page);
- }
- }
- unselectAll() {
- let that = this;
- Object.keys(this.selected).forEach(function (fid, index) {
- that.selected[fid] = [];
- });
- }
- viewAsDocumens() {
- if (this.changeViewLocked || this.viewAs == 'document') {
- return;
- }
- this.lockChangeView();
- this.unselectAll();
- $(".documents_list:not(:last-of-type)").remove();
- $(".documents_list").empty();
- $('.list-docs--header').addClass('hidden');
- for (let i = 0; i < this.files.length; i++) {
- this.documentPreview(this.files[i]);
- }
- this.viewAs = 'document';
- this.lockChangeView(false);
- }
- viewAsPages() {
- if (this.changeViewLocked || this.viewAs == 'pages') { return; }
- this.lockChangeView();
- this.unselectAll();
- $(".list-doc:not(:last-child)").remove();
- $(".documents_list").empty();
- for (let i = 0; i < this.files.length; i++) {
- let file = this.files[i];
- this.documentPagesPreview(file, this.loaded_files[file.id]._pdfInfo.numPages);
- if (i < this.files.length - 1) {
- this.createWraperForDocPages();
- }
- }
- this.viewAs = 'pages';
- this.lockChangeView(false);
- }
- createWraperForDocPages() {
- let prevWrapper = $(".list-doc:last-child");
- let clone = prevWrapper.clone();
- clone.appendTo(prevWrapper.parent());
- clone.find('.documents_list').empty();
- }
- lockChangeView(lock = true) {
- let el = $('.change-view-type');
- this.changeViewLocked = lock;
- lock ? el.addClass('c-wait') : el.removeClass('c-wait');
- }
- getResizeType() {
- let resize_type = $('.resize-type-selector.active-tab').data('type');
- switch (resize_type) {
- case 1:
- resize_type = 'margins';
- break;
- case 2:
- resize_type = 'paper';
- break;
- }
- return resize_type;
- }
- collectParams(fid) {
- let new_paper_size = $('[name="page-size"]:checked').val();
- let dims = {};
- let defDims = {};
- let resize_type = this.getResizeType();
- if (new_paper_size == 'custom_size') {
- new_paper_size = $(".custom_paper_width").val() + "in," + $(".custom_paper_height").val() + "in";
- }
- if (resize_type == 'margins') {
- dims.top = $('[name="margins-top"]').val();
- dims.left = $('[name="margins-left"]').val();
- dims.right = $('[name="margins-right"]').val();
- dims.bottom = $('[name="margins-bottom"]').val();
- defDims.top = defDims.left = defDims.right = defDims.bottom = 0;
- } else if (resize_type == 'paper') {
- let ps = new_paper_size.replace(/\s/g, '');
- ps = ps.split('in,');
- dims.width = ps[0];
- dims.heigth = ps[1].replace(/in/g, '');
- defDims.width = defDims.heigth = 0;
- }
- let pages = false;
- if (resize_type == 'paper') {
- let sizes = this.sizesConfig.filter(sc => sc.fid == fid);
- pages = sizes.reduce((result, item) => {
- const [width, height] = item.sizes;
- result[item.page] = {
- page_num: item.page,
- rotation: 0,
- new: { width, height }
- };
- return result;
- }, {});
- } else if (resize_type == 'margins') {
- let margins = this.marginConfig.filter(mc => mc.fid == fid);
- pages = margins.reduce((result, item) => {
- result[item.page] = {
- page_num: item.page,
- rotation: 0,
- new: item.sizes
- };
- return result;
- }, {});
- }
- let result = { resize_type, pages, new_paper_size };
- const deletePages = this.deletedPages.filter(dp => dp.id == fid).reduce((res, item) => {
- res.push(item.page);
- return res;
- }, []);
- return { ...result, deletePages };
- }
- async processPdf() {
- this.showLoading(".after_upload");
- const resize_type = this.getResizeType();
- const isEmptySizes = !this.sizesConfig && !this.sizesConfig.length && resize_type == 'paper';
- const isEmptyMargins = !this.marginConfig && !this.marginConfig.length && resize_type == 'margins';
- if (isEmptySizes || isEmptyMargins) this.setupCurrentSizeToAllPages();
- // try{
- await store.fs.uploadFiles(this.files);
- for (let i = 0; i < this.files.length; i++) {
- let file = this.files[i];
- this.updateLoadingValue(file, i + 1, this.files.length, 0);
- const params = this.collectParams(file.id);
- let resp = await app.components.resize.apply(file.name, params);
- this.results[resp.name] = resp;
- };
- this.afterProcessPdf();
- // }catch(e){
- // console.error("⛔️", e);
- // alert("error (1)");
- // }
- this.hideLoading(".after_upload");
- }
- async afterFilesSelected(files) {
- try {
- $(".footer").addClass("hidden");
- for (let i = 0; i < files.length; i++) {
- let file = files[i];
- this.selected[file.id] = [];
- this.loadPdf(file).then((res) => {
- if (this.viewAs == 'pages') {
- this.createWraperForDocPages();
- this.documentPagesPreview(res.file, res.pdf_doc._pdfInfo.numPages);
- } else {
- this.documentPreview(res.file);
- }
- });
- }
- } catch (e) {
- console.error(e);
- }
- this.showAfterUpload();
- }
- deletePageCallback(el) {
- const parent = el.closest('.doc-item');
- const data = parent.dataset;
- if (data.fpage) {
- this.deletedPages.push({ id: data.fid, page: data.fpage });
- this.sizesConfig = this.sizesConfig.filter(sc => !(sc.page == data.fpage && sc.fid == data.fid));
- this.marginConfig = this.marginConfig.filter(mc => !(mc.page == data.fpage && mc.fid == data.fid));
- parent.remove();
- return;
- }
- this.deletedPages = this.deletedPages.filter(dp => dp.id != data.fid);
- return this.deleteFile(parent.data('fid'), false, $(parent));
- }
- async documentPreview(file, page = null) {
- let previewSelector = `preview-${file.id}`;
- let name = file.name;
- let pagedata = '';
- if (page) {
- previewSelector += `-${page}`;
- name = 'Page ' + page;
- pagedata = `data-fpage="${page}"`;
- if (this.deletedPages.find(dp => dp.page == page && dp.id == file.id)) {
- console.log('DELETED PAGE NOT RENDER!', file.id, page);
- return false;
- }
- }
- let template = `<div class="doc-item doc_outer" data-fid="${file.id}" ${pagedata}>
- <div class="doc-page">
- <div class="doc-page--img">
- <canvas id="${previewSelector}"></canvas>
- </div>
- <div class="doc-page--text">
- ${name}
- </div>
- <div class="doc-page--text" data-type="size">8.5″ x 11″</div>
- <div class="doc-page--controls">
- <div class="flex flex-col items-end mb--8">
- ${this.getPreviewBtn(!page)}
- ${this.getDeleteBtn()}
- </div>
- </div>
- </div>
- </div>`;
- $(".list-doc:last-child .documents_list").append(template);
- const { viewport } = await this.renderPreviewImage(file, page ?? 1, 181, 243, '#' + previewSelector);
- await this.renderPageSizePreview(page, file.id, viewport);
- return template;
- }
- async renderPageSizePreview(pn, fid, dataViewport = false) {
- if(!pn || pn == undefined) pn = 1;
- let viewport = this.cloneDeep(dataViewport);
- const sizeConfig = this.sizesConfig.find(sc => sc.fid == fid && sc.page == pn);
- const type = this.getResizeType();
- if (sizeConfig && type != 'margins') {
- viewport = {
- width: sizeConfig.sizes[0],
- height: sizeConfig.sizes[1],
- type: 'inch'
- };
- } else if (!viewport) {
- viewport = await this.getViewportByFIDAndPageNumber(fid, pn);
- }
- if (viewport.type != 'inch') {
- viewport.width = this.app.utils.pointsToInch(viewport.width / viewport.scale);
- viewport.height = this.app.utils.pointsToInch(viewport.height / viewport.scale);
- }
- if (type == 'margins') {
- const margin = this.marginConfig.find(mc => mc.fid == fid && mc.page == pn);
- if (margin) {
- viewport.width += margin.sizes.left + margin.sizes.right;
- viewport.height += margin.sizes.top + margin.sizes.bottom;
- }
- }
- if (this.sizesConfig)
- if (this.viewAs == 'pages') {
- const sizeElement = $(`[data-fid="${fid}"][data-fpage="${pn}"]`).find('[data-type="size"]')[0];
- sizeElement.innerHTML = `${viewport.width.toFixed(2)}″ x ${viewport.height.toFixed(2)}″`;
- } else {
- const sizeElement = $(`[data-fid="${fid}"]`).find('[data-type="size"]')[0];
- if (sizeElement) {
- sizeElement.innerHTML = `${viewport.width.toFixed(2)}″ x ${viewport.height.toFixed(2)}″`;
- }
- }
- }
- documentPagesPreview(file, pages) {
- for (let j = 0; j < pages; j++) {
- this.documentPreview(file, j + 1);
- }
- let wrapper = $(".list-doc:last-child");
- wrapper.find('.list-docs--header').removeClass('hidden');
- wrapper.find('.line-name-text').html(file.name);
- }
- }
- let resize_tool = new Resize();
- window.new_pdf_tool = window.resize_tool = resize_tool;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement