Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let debug_mode = false;
- let container = $('#pdf_editor_pages');
- class DeftMobileEditor {
- constructor(base64 = "") {
- this.base64 = base64;
- this.data = false;
- this.fonts = ["Arial", "Helvetica", "HelveticaNeue", "Times-Roman", "serif", "sans-serif"];
- this.initialScreenSize = $(document).height();
- this.bind();
- }
- scrollToPage(page = 1) {
- // let parent_offset = $("#pdf_editor_pages").offset().top,
- // page_offset = $(`#page_outer_${page}`).offset().top;
- // let parent_offset = $("#pdf_editor_pages")[0].scrollTop,
- // page_offset = $(`#page_outer_${page}`).offset().top;
- $(`#page_outer_${page}`)[0].scrollIntoView()
- //alert("scroll to page?" + (parent_offset-page_offset));
- //scroller.mCustomScrollbar("scrollTo",parent_offset-page_offset);
- }
- selectPage(page, isScrolling = true) {
- if (this.page == page) return false;
- this.page = parseInt(page);
- console.log(`event:select_page: ${this.page}`);
- viewer.current_page = parseInt(page);
- try {
- if (isScrolling) {
- this.scrollToPage(this.page);
- //document.getElementById(`page_outer_${this.page}`).scrollIntoView();
- }
- } catch (err) {
- console.error(err);
- }
- const currentPage = document.getElementById('page_outer_' + page);
- if (currentPage) {
- currentPage.classList.remove('hidden');
- document.querySelector('.fix_pages').classList.remove('disable_events');
- $(document).trigger("before_pages_render", [viewer.total_pages]);
- TextEditor.showMobileMenu();
- }
- }
- addFilePart(part = "") {
- this.base64 += part;
- }
- showPage(page = 1) {
- viewer.document_loaded = true;
- //viewer.pages = {};
- // viewer.fonts = {};
- viewer.init(false, this.data, page);
- }
- bind() {
- $(document).on("click", ".add_new_text", this.addText);
- $(document).on("click", ".delete_text", this.removeObject);
- $(document).on("click", ".text_styles", this.showTextStyles);
- $(document).on("click", ".text_styles", function (e) {
- e.preventDefault();
- $(".text_styles").addClass("active");
- $(".editor_bottom_menu").removeClass("hidden");
- });
- $(document).on("click", ".close_text_styles", function (e) {
- $(".text_styles").removeClass("active");
- $(".editor_bottom_menu").addClass("hidden");
- });
- $(document).on("click", `.set_bold`, TextEditor.changeBold);
- $(document).on("click", `.set_italic`, TextEditor.changeItalic);
- $(document).on("click", `.set_underline`, TextEditor.changeUnderline);
- $(document).on("click", `.set_stroke`, TextEditor.changeLinethrough);
- $(document).on("change", `.set_font_size`, TextEditor.changeFontSize);
- $(document).on("change", `.set_font_family`, TextEditor.changeFont);
- $(document).on("change", `.set_text_color`, TextEditor.changeFontColor);
- $(document).on("click", ".text_copy", function () {
- let obj = viewer.pages[mobileEditor.page].fcanvas.getActiveObject();
- obj.clone(function (cloned) {
- cloned.top += 50;
- cloned.positions = obj.positions;
- cloned.customLineHeights = obj.customLineHeights;
- cloned.from_pdf = obj.from_pdf;
- viewer.pages[mobileEditor.page].fcanvas.add(cloned);
- });
- });
- }
- async createDocument() {
- let createPDF = new CreatePDF();
- let result = await createPDF.createDoc();
- return result;
- }
- removeObject() {
- let obj = viewer.pages[mobileEditor.page].fcanvas.getActiveObject();
- if (obj) {
- viewer.pages[mobileEditor.page].fcanvas.remove(obj);
- }
- }
- addText(text = false, center = false, options = {}) {
- let first_page_canvas = viewer.pages[mobileEditor.page].fcanvas;
- let point = { x: (first_page_canvas.width / 2) - (62 / 2), y: first_page_canvas.height / 4 };
- let obj = TextEditor.addText(first_page_canvas, point, text, options);
- setTimeout(() => {
- obj.initHiddenTextarea();
- obj.hiddenTextarea.focus();
- }, 100);
- if (window.mp) window.mp.editedCheck();
- return obj;
- }
- elementSelected(e) {
- let obj = e.target, text_selected_menu = $(".text_selected"), text_not_selected_menu = $(".text_not_selected"), bottom_menu = $(".editor_bottom_menu");
- TextEditor.obj = obj;
- mobileEditor.updateSelectionRange();
- if (!obj) {
- text_selected_menu.addClass("hidden");
- text_not_selected_menu.removeClass("hidden");
- bottom_menu.addClass("hidden");
- $(".text_styles").removeClass("active");
- $(".editor_bottom_menu").addClass("hidden");
- return;
- } else {
- e.target.canvas.setActiveObject(e.target).renderAll();
- }
- text_selected_menu.removeClass("hidden");
- text_not_selected_menu.addClass("hidden");
- if (['i-text', 'textbox'].includes(obj.type)) {
- let parsed_styles = mobileEditor.parseStyles();
- let ff_select = $(".set_font_family");
- ff_select.html("");
- let fontF = (obj.getSelectionStyles(0, obj.text.length))[0].fontFamily;
- if (!fontF) fontF = obj.fontFamily;
- let current_fonts = fontF.split(", ");
- current_fonts = [...new Set(current_fonts)].join(",");
- ff_select.find("option[data-embeded-font=1]").remove();
- let font_name = current_fonts;
- try {
- font_name = current_fonts.replace(/(g_d.*?)\,/, "").split(",")[0];
- } catch (e) {
- console.warn("cath on font split");
- }
- ff_select.prepend(`<option data-embeded-font=1 value='${current_fonts}'>${font_name}</option>`);
- let fonts = mobileEditor.fonts.filter((f) => { return f == current_fonts ? false : true });
- fonts.forEach((font) => {
- let font_name = font;
- ff_select.append(`<option value="${font}">${font_name}</option>`);
- });
- if (parsed_styles.bold) {
- $(".set_bold").addClass("active");
- } else {
- $(".set_bold").removeClass("active");
- }
- if (parsed_styles.italic) {
- $(".set_italic").addClass("active");
- } else {
- $(".set_italic").removeClass("active");
- }
- if (parsed_styles.underline) {
- $(".set_underline").addClass("active");
- } else {
- $(".set_underline").removeClass("active");
- }
- if (parsed_styles.stroke) {
- $(".set_stroke").addClass("active");
- } else {
- $(".set_stroke").removeClass("active");
- }
- const setFontSize = fontSize => {
- if (window.mp) {
- window.mp.rangesElements.fontSize.update({ from: fontSize });
- }
- };
- window.mp.rangesElements.opacity.update({ from: parsed_styles.opacity });
- window.mp.rangesElements.angle.update({ from: parsed_styles.angle });
- if (parsed_styles.fontSize) {
- setFontSize(parsed_styles.fontSize);
- $(".set_font_size").val(parsed_styles.fontSize);//find(`option[value=${parsed_styles.fontSize}]`).;
- } else {
- setFontSize(8);
- $(".set_font_size").val(8);
- }
- if (parsed_styles.color) {
- if (window.mp) {
- window._lockColorChanges = true;
- window.mp.colorPicker.fontColor.setColor(parsed_styles.color);
- }
- $(".pdf-mobile-colorpicker .set_text_color_text_color").css("background", parsed_styles.color);
- $(".pdf-mobile-colorpicker .set_text_color_text").text(parsed_styles.color);
- }
- } else if (['rect', 'circle'].includes(obj.type)) {
- if (window.mp) {
- window._lockColorChanges = true;
- window.mp.colorPicker.borderColorShape.setColor(obj.stroke);
- window._lockColorChanges = true;
- window.mp.colorPicker.fillShapeColor.setColor(obj.fill);
- window.mp.rangesElements.borderShape.update({ from: obj.strokeWidth });
- }
- }
- return false;
- }
- parseStyles() {
- let range = this.updateSelectionRange();
- let ret = {
- bold: false,
- italic: false,
- underline: false,
- stroke: false,
- fontSize: 8,
- fontFamily: "Arial",
- color: "rgb(0,0,0)",
- opacity: TextEditor.obj && TextEditor.obj.opacity ? TextEditor.obj.opacity : 1,
- angle: TextEditor.obj && TextEditor.obj.angle ? TextEditor.obj.angle : 0,
- };
- if (range && range[0] == range[1]) {
- range[1] += 1;
- }
- if (range) {
- let selection_styles = TextEditor.obj.getSelectionStyles(range[0], range[1], true);
- let bold_styles = [],
- italic_styles = [],
- underline_styles = [],
- stroke_styles = [],
- font_sizes = [],
- font_families = [],
- colors = [];
- selection_styles.forEach((char_style) => {
- if (char_style.fontWeight) {
- bold_styles.push(char_style.fontWeight);
- }
- if (char_style.fontStyle) {
- italic_styles.push(char_style.fontStyle);
- }
- if (typeof char_style.underline != 'undefined') {
- underline_styles.push(char_style.underline ? "underline" : "normal");
- }
- font_sizes.push(char_style.fontSize);
- colors.push(char_style.fill ? char_style.fill : "rgb(0,0,0)");
- font_families.push(...char_style.fontFamily.split(",").map((f) => { return f.trim() }));
- });
- let bold_set = [...new Set(bold_styles)],
- italic_set = [...new Set(italic_styles)],
- underline_set = [...new Set(underline_styles)],
- stroke_set = [],
- fontsize_set = [...new Set(font_sizes)],
- fontfamily_set = [...new Set(font_families)],
- colors_set = [...new Set(colors)];
- ret.fontFamily = fontfamily_set.join(",");
- if (colors_set.length > 1) {
- ret.color = "rgb(0,0,0)";
- } else {
- ret.color = colors_set[0];
- }
- if (fontsize_set.length) {
- if (fontsize_set.length > 1) {
- ret.fontSize = TextEditor.obj.fontSize || "";
- } else if (fontsize_set.length == 1) {
- let scale = 1;
- if (viewer.pages[mobileEditor.page]) {
- scale = viewer.pages[mobileEditor.page].scale;
- }
- ret.fontSize = Math.ceil(fontsize_set[0] / scale);
- } else {
- ret.fontSize = TextEditor.obj.fontSize || "";
- }
- } else {
- ret.fontSize = 8;
- }
- if (underline_set.length) {
- if (underline_set.length > 1) {
- ret.underline = false;
- } else if (underline_set[0] == 'underline' && underline_set.length == 1) {
- ret.underline = true;
- } else {
- ret.underline = false;
- }
- } else {
- ret.underline = false;
- }
- if (italic_set.length) {
- if (italic_set.length > 1) {
- ret.italic = false;
- } else if (italic_set[0] == 'italic' && italic_set.length == 1) {
- ret.italic = true;
- } else {
- ret.italic = false;
- }
- } else {
- ret.italic = false;
- }
- if (bold_set.length) {
- if (bold_set.length > 1) {
- ret.bold = false;
- } else if (bold_set[0] == 'bold' && bold_set.length) {
- ret.bold = true;
- } else {
- ret.bold = false;
- }
- } else {
- ret.bold = false;
- }
- return ret;
- }
- return ret;
- }
- updateSelectionRange() {
- if (TextEditor.obj && ['textbox', 'i-text', 'text'].includes(TextEditor.obj.type)) {
- if (TextEditor.obj && TextEditor.obj.isEditing) {
- TextEditor.start = TextEditor.obj.selectionStart ? TextEditor.obj.selectionStart : 0;
- TextEditor.end = TextEditor.obj.selectionEnd ? (TextEditor.obj.selectionEnd) : TextEditor.obj.text.length;
- return [TextEditor.start, TextEditor.end];
- } else if (TextEditor.obj && !TextEditor.obj.isEditing) {
- TextEditor.start = 0;
- TextEditor.end = TextEditor.obj.text.length;
- return [TextEditor.start, TextEditor.end];
- } else {
- TextEditor.start = 0;
- TextEditor.end = 0;
- return false;
- }
- }
- return false;
- }
- selectionUpdate(e) {
- mobileEditor.updateSelectionRange();
- }
- showTextStyles() {
- }
- }
- let mobileEditor = new DeftMobileEditor("");
- async function savePDF() {
- try {
- let pages = [];
- Object.entries(viewer.pages).forEach(([pn, page], i) => {
- if (page && page.modified) pages.push([pages.length + 1, pn]);
- });
- if (!pages || !pages.length) pages = [mobileEditor.page, mobileEditor.page];
- const blob = await mobileEditor.createDocument();
- const url = URL.createObjectURL(blob) + `#pages=${JSON.stringify(pages)}`;
- if (debug_mode) {
- window.open(url);
- } else {
- window.location = url;
- }
- } catch (e) {
- console.error(e);
- alert("Error...");
- }
- }
- async function addPagePart(data = "") {
- mobileEditor.addFilePart(data);
- }
- $(document).on('before_pages_render', (e, countPages) => {
- const page = mobileEditor.page;
- Array.from(document.querySelectorAll('.btn_p')).forEach(el => el.classList.remove('disabled'));
- if (page == countPages) document.querySelector('.next_page_btn').classList.add('disabled');
- if (page <= 1) document.querySelector('.prev_page_btn').classList.add('disabled');
- document.querySelector('.title_page').innerHTML = `${page} / ${countPages}`;
- });
- async function mobileInit(page = 1, editorChange = false) {
- try {
- document.querySelector('.fix_pages').classList.add('disable_events');
- mobileEditor.page = page;
- if (!viewer.document_loaded) {
- let b1 = await fetch(mobileEditor.base64).then(res => res.blob());
- let data = await viewer.getBlob(b1);
- mobileEditor.data = data;
- }
- // Object.keys(viewer.pages).forEach((p) => {
- // viewer.pages[p].fcanvas.dispose();
- // delete viewer.pages[p];
- // });
- if (!editorChange) $("#pdf_editor_pages").html("");
- Array.from(document.querySelectorAll('.page-main-part'))
- .forEach(el => el.classList.add('hidden'));
- const currentPage = document.getElementById('page_outer_' + page);
- if (currentPage) {
- currentPage.classList.remove('hidden');
- document.querySelector('.fix_pages').classList.remove('disable_events');
- $(document).trigger("before_pages_render", [viewer.total_pages]);
- TextEditor.showMobileMenu();
- } else {
- mobileEditor.showPage(page);
- }
- } catch (e) {
- alert("error: " + e.message);
- }
- }
- const mp = new class {
- constructor() {
- this.draw_enabled = false;
- this.texts_active = false;
- this.images_active = false;
- this.image_is_watermark = false;
- this.now_scrolling = false;
- this.rangesElements = {
- fontSize: false,
- };
- this.text_menu_opened = false;
- this.images_menu_opened = false;
- this.last_touched_page = false;
- this.touch = {
- events: [],
- use_scroll: true,
- use_fabric: false,
- };
- this.colorPicker = {
- fontColor: false
- };
- this.annotationElements = {
- add: document.getElementById('add_annotation'),
- delete: document.getElementById('delete_annotation'),
- title: document.querySelector('[name="title_annotation"]'),
- message: document.querySelector('[name="title_message"]')
- };
- this.elements = {
- tools: {
- textEdit: document.querySelector('[data-button="text_edit"]'),
- text: document.querySelector('[data-button="text"]'),
- delete: document.querySelector('[data-button="delete"]'),
- annotations: document.querySelector('[data-button="annotations"]'),
- setting: document.querySelector('[data-button="setting"]'),
- watermark: document.querySelector('[data-button="watermark"]'),
- setting_dropdown: document.querySelector('[data-button="setting_dropdown"]'),
- deselect_dropdown: document.querySelector('[data-button="deselect_dropdown"]'),
- },
- mfp: document.querySelector('.mobile-footer--pdf'),
- footer: {
- text: document.querySelector('[data-footer="add_text"]'),
- watermark: document.querySelector('[data-footer="add_watermark"]'),
- form: document.querySelector('[data-footer="add_form"]'),
- image: document.querySelector('[data-footer="add_image"]'),
- shape: document.querySelector('[data-footer="add_shape"]'),
- whiteout: document.querySelector('[data-footer="add_shiteout"]'),
- freestyle: document.querySelector('[data-footer="add_freestyle"]'),
- },
- f_footer: {
- check_on: document.querySelector('[data-fk="check_on"]'),
- check_off: document.querySelector('[data-fk="check_off"]'),
- radio: document.querySelector('[data-fk="radio"]'),
- input: document.querySelector('[data-fk="input"]'),
- textarea: document.querySelector('[data-fk="textarea"]'),
- checkbox: document.querySelector('[data-fk="checkbox"]'),
- dropdown: document.querySelector('[data-fk="dropdown"]'),
- },
- s_footer: {
- circle: document.querySelector('[data-fk="circle"]'),
- rect: document.querySelector('[data-fk="rect"]'),
- },
- freestyle: {
- colorChecks: document.querySelector('[data-tab="color_checks"]'),
- brushType: document.querySelector('[data-tab="brush_type"]'),
- applyDrawing: document.querySelector('[data-tab="applyDrawing"]'),
- },
- watermark: {
- settings: document.querySelector('[data-tab="watermark_settings"]'),
- types: document.querySelector('[data-tab="watermark_type"]'),
- },
- texts: {
- modify_text: document.querySelector('[data-tab="text_tools"] [data-type="modify_text"]'),
- add_text: document.querySelector('[data-tab="text_tools"] [data-type="add_text"]'),
- },
- images: {
- modify_images: document.querySelector('[data-tab="images_tools"] [data-type="modify_images"]'),
- add_image: document.querySelector('[data-tab="images_tools"] [data-type="add_image"]'),
- },
- closeFooter: document.querySelectorAll('[data-tab="closeFooterMenu"]'),
- modals: {
- shapeStyle: document.getElementById('mobile-settings-style'),
- textStyle: document.getElementById('mobile-text-style'),
- watermarkSetting: document.getElementById('mobile-watermark-setting'),
- selectSetting: document.getElementById('mobile-select-setting'),
- annotations: document.getElementById('mobile-annotation'),
- }
- };
- this.annotationElements.add.addEventListener('click', () => this.addAnnotation({}));
- this.annotationElements.delete.addEventListener('click', () => this.deleteAnnotation());
- this.initFooterEvents();
- this.initToolsEvents();
- this.initRangesElements();
- }
- // disableScroll() {
- // this.scroll_enabled = false;
- // container.css({ overflow: "hidden" })
- // //scroller.mCustomScrollbar("disable");
- // }
- // enableScroll() {
- // this.scroll_enabled = true;
- // if (mp.last_touched_page && viewer.pages[mp.last_touched_page] && viewer.pages[mp.last_touched_page].fcanvas) {
- // viewer.pages[mp.last_touched_page].fcanvas.renderAll();
- // }
- // container.css({
- // "overflow": "scroll",
- // });
- // }
- disableScroll() {
- this.scroll_enabled = false;
- container.css({ overflow: "hidden", 'touch-action': 'pinch-zoom' });
- //scroller.mCustomScrollbar("disable");
- }
- enableScroll() {
- this.scroll_enabled = true;
- if (mp.last_touched_page && viewer.pages[mp.last_touched_page] && viewer.pages[mp.last_touched_page].fcanvas) {
- viewer.pages[mp.last_touched_page].fcanvas.renderAll();
- }
- container.css({
- "overflow": "scroll",
- 'touch-action': 'auto'
- });
- }
- clearStylesFooter(type = false) {
- if (type != 'text') {
- this.text_menu_opened = false;
- }
- this.elements.mfp.classList.remove('mobmenu--active');
- Array.from(document.querySelectorAll('.mobile-list-control'))
- .forEach(el => el.classList.remove('mobile-list-control--active'));
- if (viewer.pages[mobileEditor.page]) {
- let canvas = viewer.pages[mobileEditor.page].fcanvas;
- canvas.isDrawingMode = false;
- }
- }
- openTextStylesMenu() {
- if (!TextEditor.obj) {
- TextEditor.obj = viewer.pages[mobileEditor.page].fcanvas.getActiveObject();
- mobileEditor.elementSelected({ target: TextEditor.obj });
- mobileEditor.parseStyles();
- }
- if (TextEditor.obj && TextEditor.obj.is_watermark) {
- document.querySelectorAll(".only_for_watermark").forEach(function (el) {
- el.classList.remove('hidden')
- });
- } else {
- document.querySelectorAll(".only_for_watermark").forEach(function (el) {
- el.classList.add('hidden')
- });
- }
- this.showModal('textStyle', true);
- }
- renderWatermarkTextPage(page) {
- const canvas = page.fcanvas;
- if (!canvas) return false;
- const padding = 10;
- const tx = 'сreаtеd by DеftPDF';
- //canvas.getObjects().forEach(obj => obj.subtype == 'watermark_deft' ? canvas.remove(obj) : '');
- canvas.getObjects().forEach(obj => (obj.text == tx || obj.unicode_string == tx) ? canvas.remove(obj) : '');
- if (!this.isEnabledWaterText) return;
- const text = new fabric.IText(tx, { fontSize: 14 });
- text.set({
- left: canvas.width - text.width - padding,
- top: canvas.height - text.height - padding,
- subtype: 'watermark_deft',
- selectable: false,
- evented: false,
- lockMovementX: true,
- lockMovementY: true
- });
- canvas.add(text);
- }
- mobileUI(key, data) {
- switch (key) {
- case 'watermark_deft': {
- if (data) this.isEnabledWaterText = data.isEnabled;
- // data.isEnabled
- Object.values(viewer.pages).forEach(page => this.renderWatermarkTextPage(page));
- break;
- }
- case 'discard_active': {
- try {
- const canvas = viewer.pages[mobileEditor.page].fcanvas;
- const active = canvas.getActiveObject();
- canvas.discardActiveObject();
- active.moveTo(active.zIndex || 0);
- } catch (e) {
- console.error(e);
- }
- break;
- }
- case 'modify_text': {
- enableAllTexts();
- this.texts_active = true;
- // if (this.texts_active) {
- // this.deactivateTexts();
- // this.enableScroll();
- // this.texts_active = false;
- // } else {
- // enableAllTexts();
- // this.texts_active = true;
- // this.disableScroll();
- // }
- break;
- }
- case 'disable_text':
- this.deactivateTexts();
- //this.enableScroll();
- this.texts_active = false;
- break;
- case 'add_text':
- mobileEditor.addText();
- this.texts_active = true;
- break;
- case 'watermark': // fix
- // this.addWatermarkOnPage();
- this.elements.mfp.classList.add('mobmenu--active');
- this.elements.footer['watermark'].classList.add('mobile-list-control--active');
- break;
- case 'check_on':
- case 'check_off':
- case 'radio':
- case 'input':
- case 'textarea':
- case 'checkbox':
- case 'dropdown':
- return this.addFormItem(key);
- case 'modify_images': {
- // if (this.images_active) {
- // dissableAllImages();
- // this.enableScroll();
- // this.images_active = false;
- // } else {
- // enableAllImages();
- // //this.elements.images.modify_images.classList.add("active");
- // this.images_active = true;
- // this.disableScroll();
- // }
- enableAllImages();
- this.images_active = true;
- break;
- }
- case 'add_image':
- document.querySelector('.ts').click();
- break;
- case 'circle':
- case 'rect':
- case 'whiteout':
- return this.addShape(key);
- case 'enable_draw':
- return this.enableDraw(data); // { brush, color }
- case 'disable_draw':
- return this.disableDraw(); // { brush, color }
- case 'next_page': {
- if (mobileEditor.page >= viewer.total_pages) return;
- mobileEditor.selectPage(mobileEditor.page + 1);
- break;
- }
- case 'prev_page': {
- if (mobileEditor.page <= 1) return;
- mobileEditor.selectPage(mobileEditor.page - 1);
- break;
- }
- case 'open_page': {
- if (data && data.page && data.page >= 1 && data.page <= viewer.total_pages) {
- mobileEditor.selectPage(data.page);
- }
- break;
- }
- }
- }
- addWatermarkOnPage() {
- const canvas = viewer.pages[mobileEditor.page].fcanvas;
- const active = canvas.getActiveObject();
- if (active && active.is_watermark) {
- mp.rangesElements.angle_watermark.update({ from: active.angle });
- mp.rangesElements.opacity_watermark.update({ from: active.opacity });
- }
- this.showModal('watermarkSetting', true);
- }
- initToolsEvents() {
- document.querySelector("#apply_select_modal").addEventListener("click", (e) => {
- e.preventDefault();
- const options = document.querySelector('[name="textarea_select"]').value.split('\n').filter(q => q);
- if (options && options.length) {
- const canvas = viewer.pages[mobileEditor.page].fcanvas;
- const active = canvas.getActiveObject();
- active.set({ options }).canvas.renderAll();
- if (formElements) formElements.renderOptions(active);
- }
- e.target.closest('.modal--mobile').classList.remove('modal--show--mobile');
- });
- //// document.querySelector('[name="textarea_select"]').addEventListener('input', e => {
- //// const options = e.target.value.split('\n').filter(q => q);
- //// if (options && options.length) {
- //// const canvas = viewer.pages[mobileEditor.page].fcanvas;
- //// const active = canvas.getActiveObject();
- //// active.set({ options }).canvas.renderAll();
- //// if (formElements) formElements.renderOptions(active);
- //// }
- //// });
- this.elements.tools.annotations.addEventListener('click', e => this.openAnnotationsPopup());
- this.elements.tools.delete.addEventListener('click', e => this.removeObject());
- this.elements.tools.setting.addEventListener('click', e => this.showModal('shapeStyle', true));
- this.elements.texts.modify_text.addEventListener("click", (e) => {
- e.preventDefault();
- if (this.texts_active) {
- this.deactivateTexts();
- this.enableScroll();
- this.texts_active = false;
- } else {
- enableAllTexts();
- this.elements.texts.modify_text.classList.add("active");
- this.texts_active = true;
- this.disableScroll();
- //this.disableScroll();
- }
- });
- this.elements.texts.add_text.addEventListener("click", (e) => {
- e.preventDefault();
- mobileEditor.addText();
- });
- this.elements.images.modify_images.addEventListener("click", (e) => {
- e.preventDefault();
- //alert(this.images_active);
- if (this.images_active) {
- dissableAllImages();
- this.enableScroll();
- this.images_active = false;
- } else {
- enableAllImages();
- this.elements.images.modify_images.classList.add("active");
- this.images_active = true;
- this.disableScroll();
- }
- });
- this.elements.images.add_image.addEventListener("click", (e) => {
- const ts = document.querySelector('.ts');
- ts.click();
- });
- this.elements.tools.watermark.addEventListener('click', e => this.addWatermarkOnPage());
- this.elements.tools.setting_dropdown.addEventListener('click', e => {
- const active = viewer.pages[mobileEditor.page].fcanvas.getActiveObject();
- if (active) {
- const options = active.options;
- document.querySelector('[name="textarea_select"]').value = options.join('\n');
- this.showModal('selectSetting', true);
- }
- });
- this.elements.tools.deselect_dropdown.addEventListener('click', e => {
- this.mobileUI('discard_active');
- });
- this.elements.tools.text.addEventListener('click', e => this.openTextStylesMenu());
- this.elements.tools.textEdit.addEventListener('click', e => {
- const active = this.getActiveObject();
- if (active) active.enterEditing();
- });
- }
- deactivateTexts() {
- if (this.texts_active) {
- dissableAllTexts();
- this.texts_active = false;
- }
- this.elements.texts.modify_text.classList.remove("active");
- //this.enableScroll();
- //scroller.mCustomScrollbar("update");
- }
- toggleTextsMenu(key, e) {
- if (this.text_menu_opened) {
- this.text_menu_opened = false;
- //this.enableScroll();
- this.closeMenu(key);
- //this.texts_active = false;
- } else {
- this.text_menu_opened = true;
- //this.disableScroll();
- this.texts_active = true;
- this.openMenu(key);
- enableAllTexts();
- this.elements.texts.modify_text.classList.add("active");
- }
- }
- openMenu(key) {
- this.elements.mfp.classList.add('mobmenu--active');
- this.elements.footer[key].classList.add('mobile-list-control--active');
- }
- closeMenu(key) {
- this.elements.mfp.classList.remove("mobmenu--active");
- this.elements.footer[key].classList.remove('mobile-list-control--active');
- }
- openPopupMenu(key) {
- this.elements.mfp.classList.add('mobmenu--active-popup');
- this.elements.footer[key].classList.add('mobile-list-control--active');
- }
- defaultEventListener(e) {
- e.preventDefault();
- e.stopPropagation();
- this.disableDraw();
- //document.getElementById(`page_outer_${mobileEditor.page}`).scrollIntoView();
- }
- initFooterEvents() {
- this.clearStylesFooter();
- const addElement = (type = false, e = false) => {
- this.closePopupButtons();
- this.deactivateTexts();
- dissableAllImages();
- if (type == 'text') {
- } else {
- }
- this.clearStylesFooter(type);
- switch (type) {
- //case 'text': return mobileEditor.addText();
- case 'text': return this.toggleTextsMenu('text', e);
- case 'watermark': return this.openPopupMenu('watermark');
- case 'image': return this.openImage('image', e);
- case 'whiteout': return this.addShape('whiteout');
- case 'form': return this.openMenu('form');
- case 'shape': return this.openMenu('shape');
- case 'freestyle': return this.openFreeStyle('freestyle');
- }
- };
- for (const key in this.elements.footer) {
- this.elements.footer[key].querySelector('.btn--link').addEventListener('click', (e) => {
- this.defaultEventListener(e);
- addElement(key, e);
- });
- }
- for (const key in this.elements.f_footer) {
- this.elements.f_footer[key].addEventListener('click', e => {
- this.defaultEventListener(e);
- this.clearStylesFooter();
- this.addFormItem(key);
- });
- }
- for (const key in this.elements.s_footer) {
- this.elements.s_footer[key].addEventListener('click', e => {
- this.defaultEventListener(e);
- this.clearStylesFooter();
- this.addShape(key);
- });
- }
- const ch = this.elements.freestyle.colorChecks;
- Array.from(ch.querySelectorAll('.element-mob')).forEach((el, i, arr) => {
- el.addEventListener('click', e => {
- this.defaultEventListener(e);
- arr.forEach(element => element.classList.remove('active-menu-box'));
- el.classList.add('active-menu-box');
- this.enableDraw();
- });
- });
- if (true) {
- let w_types = this.elements.watermark.types;
- Array.from(w_types.querySelectorAll('.element-mob')).forEach((el, i, arr) => {
- el.addEventListener('click', e => {
- this.defaultEventListener(e);
- e.preventDefault();
- let wattermark_type = e.target.dataset.type;
- this.addWatermark(wattermark_type);
- });
- });
- }
- const bt = this.elements.freestyle.brushType;
- Array.from(bt.querySelectorAll('.element-mob')).forEach((el, i, arr) => {
- el.addEventListener('click', e => {
- this.defaultEventListener(e);
- arr.forEach(element => element.classList.remove('active-brush'));
- el.classList.add('active-brush');
- this.enableDraw();
- });
- });
- this.elements.freestyle.applyDrawing.addEventListener('click', e => {
- e.preventDefault();
- this.applyDraw();
- });
- Array.from(this.elements.closeFooter).forEach(el => {
- el.addEventListener('click', (e) => {
- this.applyDraw(e);
- //this.clearStylesFooter()
- });
- });
- }
- applyDraw() {
- // let pages = allViewedPages();
- // pages.forEach((page)=>{
- // let canvas = viewer.pages[page].fcanvas;
- // canvas.isDrawingMode = false;
- // });
- // this.draw_enabled = false;
- // this.enableScroll();
- this.disableDraw();
- this.clearStylesFooter();
- }
- openFreeStyle(key) {
- this.openMenu('freestyle');
- this.enableDraw();
- }
- watermarksRemove() {
- let watermaks = this.getWatermarks(),
- canvas = this.getCanvas();
- watermaks.forEach((obj) => {
- canvas.remove(obj);
- });
- canvas.renderAll();
- }
- getWatermarks() {
- let watermarks = [];
- let canvas = this.getCanvas();
- canvas.getObjects().forEach((obj) => {
- if (obj.is_watermark) {
- watermarks.push(obj);
- }
- });
- return watermarks;
- }
- closePopupButtons() {
- this.elements.mfp.classList.remove('mobmenu--active-popup');
- this.elements.footer.watermark.classList.remove('mobile-list-control--active');
- }
- addWatermark(type = "", x = 0, y = 0, angle = 45) {
- this.closePopupButtons();
- let obj = false;
- let canvas = this.getCanvas();
- switch (type) {
- case 'text':
- let font_size = viewer.pages[mobileEditor.page].height / 10;
- if (font_size > 72) font_size = 72;
- obj = mobileEditor.addText("Watermark...", true, { subtype: 'text_watermark', is_watermark: true });
- obj.is_watermark = true;
- obj.setSelectionStyles({ fontSize: font_size }, 0, 999);
- obj.fontSize = font_size;
- obj.originX = "center";
- obj.originY = "center";
- obj.angle = angle;
- obj.opacity = 0.5;
- obj.left = canvas.width / 2;
- obj.top = (canvas.height / 2) + (obj.height / 2);
- // obj.setControlsVisibility({
- // mtr: true
- // });
- break;
- case 'image':
- const ts = document.querySelector('.ts');
- this.image_is_watermark = true;
- ts.click();
- break;
- }
- canvas.renderAll();
- }
- getCanvas() {
- return viewer.pages[mobileEditor.page].fcanvas;;
- }
- disableDraw() {
- this.draw_enabled = false;
- this.enableScroll();
- //let viewed_pages = allViewedPages();
- let pages = Object.keys(viewer.pages);
- for (let i = 0; i < pages.length; i++) {
- let page = pages[i]
- //viewed_pages.forEach((page)=>{
- let canvas = viewer.pages[page].fcanvas;
- if (canvas) {
- canvas.isDrawingMode = false;
- canvas.discardActiveObject();
- canvas.renderAll();
- }
- }
- }
- enableDraw(data = false) {
- this.draw_enabled = true;
- this.disableScroll();
- const colorElement = document.querySelector('.active-menu-box');
- const brushelement = document.querySelector('.active-brush');
- let color = colorElement ? colorElement.dataset.color : '#f03b3d';
- let brush = brushelement ? brushelement.dataset.type : 'pencil';
- //this.clearStylesFooter();
- if (data) {
- if (data.color) color = data.color;
- if (data.brush) brush = data.brush;
- }
- this.enableDrawingMode({ color, width: brush == 'pencil' ? 5 : 1 });
- }
- openImage(key, e) {
- if (this.images_menu_opened) {
- this.images_menu_opened = false;
- this.closeMenu(key);
- dissableAllImages();
- } else {
- this.images_menu_opened = true;
- this.images_active = true;
- this.openMenu(key);
- enableAllImages();
- //alert("enable images?");
- //enableAllTexts();
- this.elements.images.modify_images.classList.add("active");
- }
- //toggleTextsMenu
- // const ts = document.querySelector('.ts');
- // ts.click();
- }
- getActiveObject() {
- let canvas = viewer.pages[mobileEditor.page].fcanvas;
- return canvas.getActiveObject();
- }
- deleteAnnotation() {
- const active = this.getActiveObject();
- if (!active) return false;
- active.annotation = false;
- this.showModal('annotations', false);
- }
- addAnnotation() {
- const active = this.getActiveObject();
- if (!active) return false;
- active.annotation = {
- title: this.annotationElements.title.value,
- message: this.annotationElements.message.value
- };
- this.showModal('annotations', false);
- }
- showModal(k, isShow = false) {
- if (!k) return;
- let key = !isShow ? 'remove' : 'add';
- this.elements.modals[k].classList[key]('modal--show--mobile');
- }
- editedCheck() {
- if (viewer.pages[mobileEditor.page]) {
- viewer.pages[mobileEditor.page].modified = true;
- }
- }
- openAnnotationsPopup() {
- const ae = this.getActiveObject();
- if (!ae) return false;
- const title = ae && ae.annotation && ae.annotation.title ? ae.annotation.title : '';
- const message = ae && ae.annotation && ae.annotation.message ? ae.annotation.message : '';
- this.annotationElements.title.value = title;
- this.annotationElements.message.value = message;
- this.showModal('annotations', true);
- }
- selectedEventCanvas(event, key) {
- if (key == 'object:added' && (event.target.subtype == 'image_group' || event.target.subtype == 'image')) {
- this.addElementBase(event.target);
- }
- if (['selection:cleared', 'selection:created', 'selection:updated'].includes(key)) {
- if (formElements) formElements.selectedUpdate(event);
- }
- if (key == 'selection:cleared') return this.renderPosition(false);
- if (key == 'path:created') return this.addDrawingPath(event.path);
- if (['object:removed'].includes(key)) {
- this.editedCheck();
- return;
- }
- this.renderPosition(event.target);
- }
- removeObject(target = false) {
- let canvas = viewer.pages[mobileEditor.page].fcanvas;
- const dis = () => {
- canvas.discardActiveObject();
- canvas.renderAll();
- };
- if (!target) target = canvas.getActiveObject();
- if (!target) return dis();
- const element = document.querySelector(`[data-element="${target.id}"]`);
- if (element) { element.remove(); }
- canvas.remove(target);
- dis();
- }
- enableDrawingMode(options = {}) {
- let viewed_pages = allViewedPages();
- viewed_pages.forEach((page) => {
- let canvas = viewer.pages[page].fcanvas;
- const brush = new fabric.PencilBrush(canvas);
- for (const key in options) brush[key] = options[key];
- canvas.freeDrawingBrush = brush;
- canvas.isDrawingMode = true;
- })
- }
- addDrawingPath(path) {
- let canvas = path.canvas || viewer.pages[mobileEditor.page].fcanvas;
- //canvas.isDrawingMode = false;
- path.subtype = 'drawing';
- return this.addElement(path, true, false);
- }
- addElementBase(object, isViewer = false, show_buttons = true) {
- if (!object) return;
- //evented
- if (isViewer) {
- if (!['i-text'].includes(object.type)) return;
- if (!object.subtype == 'text_watermark')
- object.set({ subtype: 'text' });
- }
- ['moving', 'scaling', 'rotating', 'resizing']
- .forEach(ev => object.on(ev, e => this.renderPosition(e.target)));
- object.set({ _controlsVisibility: { br: true }, borderDashArray: [4, 4] });
- if (['textbox'].includes(object.type)) {
- object.set({ _controlsVisibility: { mr: true } });
- }
- if (['i-text'].includes(object.type)) {
- if (object.subtype == 'text_watermark') {
- object.customiseCornerIcons({
- settings: {
- borderColor: '#7b4ef9',
- cornerSize: 20,
- cornerShape: 'rect',
- cornerBackgroundColor: 'rgba(0, 0, 0, 0)',
- cornerPadding: 0
- },
- br: { icon: './assets/img/resize.svg' },
- tl: { icon: './assets/img/rotate.svg' },
- });
- if (object.is_watermark) {
- object.centeredRotation = true;
- object.set({ _controlsVisibility: { br: true, tl: true } });
- } else {
- object.set({ _controlsVisibility: { br: true } });
- }
- object.on('modified', e => {
- if (e.by != 'equally') return;
- const target = e.target;
- const scaleX = target.scaleX;
- if (scaleX != 1) {
- const fontSize = (target.styles && target.styles[0] && target.styles[0][0]
- ? target.styles[0][0].fontSize : target.fontSize) || target.fontSize;
- target.setSelectionStyles({ fontSize: fontSize * target.scaleX }, 0, target.text.length);
- target.set({ scaleX: 1, scaleY: 1 });
- target.canvas.renderAll();
- }
- });
- } else {
- object.set({ _controlsVisibility: {} });
- }
- object.set({
- evented: mp.texts_active
- });
- }
- if (object.type == 'image') {
- object.set({
- evented: mp.images_active
- });
- }
- if (object.type == 'image' && object.is_watermark) {
- object.centeredRotation = true;
- object.set({ _controlsVisibility: { br: true, tl: true } });
- }
- object.customiseCornerIcons({
- settings: {
- borderColor: '#7b4ef9',
- cornerSize: 20,
- cornerShape: 'rect',
- cornerBackgroundColor: 'rgba(0, 0, 0, 0)',
- cornerPadding: 0
- },
- tl: { icon: './assets/img/rotate.svg' },
- mr: { icon: './assets/img/resize-rl.svg' },
- br: { icon: './assets/img/resize.svg' },
- mb: { icon: './assets/img/resize-bc.svg' },
- });
- }
- addElement(object, lockAdding = false, center = true) {
- if (!object) return false;
- let canvas = viewer.pages[mobileEditor.page].fcanvas;
- let point = { x: (canvas.width / 2) - (62 / 2), y: canvas.height / 4 };
- object.set(point);
- if (center) {
- object.left = (canvas.width / 2) - (object.width * object.scaleX / 2);
- object.top = (canvas.height / 2) - (object.height * object.scaleY / 2);
- }
- //alert("before add");
- this.addElementBase(object);
- if (!lockAdding) canvas.add(object);
- canvas.setActiveObject(object).renderAll();
- this.renderPosition(object);
- this.editedCheck();
- }
- async addShape(type) {
- switch (type) {
- case 'rect':
- return this.addElement(new fabric.Rect({
- width: 100, height: 100,
- stroke: 'red', fill: 'rgba(0, 0, 0, 0)',
- strokeWidth: 1, strokeUniform: true,
- subtype: 'rectangle'
- }));
- case 'circle': return this.addElement(new fabric.Circle({
- radius: 100, stroke: 'red', fill: 'rgba(0, 0, 0, 0)',
- strokeWidth: 1, strokeUniform: true,
- subtype: 'circle'
- }));
- case 'whiteout': return this.addElement(new fabric.Rect({
- width: 150, height: 50, fill: '#fff',
- strokeWidth: 0, strokeUniform: true,
- subtype: 'whiteout'
- }));
- }
- }
- async addFormItem(type) {
- let canvas = viewer.pages[mobileEditor.page].fcanvas;
- let imageURL = false;
- switch (type) {
- case 'check_on':
- imageURL = '../web/assets/img/check.svg';
- break;
- case 'check_off':
- imageURL = '../web/assets/img/x.svg';
- break;
- case 'radio':
- imageURL = '../web/assets/img/radio.svg';
- break;
- case 'input':
- let el = new fabric.Textbox('Input text', {
- subtype: type,
- fontSize: 16,
- width: 100,
- element_type: 'input'
- });
- el.left = (canvas.width / 2) - (el.width / 2);
- el.top = (canvas.height / 2) - (el.height / 2);
- return this.addElement(el);
- break;
- case 'textarea':
- formElements.addObject(viewer.pages[mobileEditor.page].fcanvas, {});
- break;
- case 'checkbox':
- formElements.addObject(viewer.pages[mobileEditor.page].fcanvas, { opts: { element_type: 'checkbox', width: 30, height: 30 } })
- break;
- case 'dropdown':
- formElements.addObject(viewer.pages[mobileEditor.page].fcanvas, { opts: { element_type: 'dropdown', height: 30, width: 150 } })
- break;
- }
- if (!imageURL) return false;
- const img = await new Promise((resolve, reject) => {
- fabric.Image.fromURL(imageURL, (img, err) => {
- if (err) return reject(err);
- resolve(img);
- })
- });
- const scale = Math.min(50 / img.width, 50 / img.height);
- img.set({ scaleX: scale, scaleY: scale });
- img.subtype = type;
- if (type == 'radio') img.set({
- field_name: 'New field 2',
- element_type: 'radio',
- subtype: 'radio'
- });
- img.left = (canvas.width / 2) - (img.width / 2);
- img.top = (canvas.height / 2) - (img.height / 2);
- return this.addElement(img);
- }
- hideControlls() {
- const controls = document.querySelector('.controlls_q');
- controls.classList.add('hidden_q');
- }
- async renderPosition(target = false) {
- if (target && (target.canvas && target.canvas.skip_render)) {
- return false;
- }
- let canvas = target ? target.canvas : false;
- if (!canvas) canvas = viewer.pages[mobileEditor.page].fcanvas;
- const controls = document.querySelector('.controlls_q');
- if (!target || !target.canvas) {
- return controls.classList.add('hidden_q');
- }
- const tools = this.elements.tools;
- for (const key in tools) {
- tools[key].parentElement.classList.add('hidden_q_b');
- }
- const show = arr => {
- arr.forEach(key => tools[key].parentElement.classList.remove('hidden_q_b'));
- if (arr && arr.length) controls.classList.remove('hidden_q');
- };
- canvas.uniScaleTransform = ['whiteout', 'rectangle'].includes(target.subtype || '');
- console.log("target.subtype", target.subtype);
- if (target.subtype) {
- switch (target.subtype) {
- case 'circle':
- case 'rectangle':
- show(['delete', 'annotations', 'setting']);
- break;
- case 'input':
- case 'text':
- case 'text_watermark':
- if (target.is_watermark) {
- show(['textEdit', 'text', 'delete']);
- } else {
- show(['textEdit', 'text', 'delete', 'annotations']);
- }
- break;
- case 'drawing':
- show(['delete', 'annotations'])
- break;
- case 'form_element_outer':
- if (target.element_type == 'dropdown') {
- show(['delete', 'annotations', 'setting_dropdown']);
- } else {
- show(['delete', 'annotations']);
- }
- break;
- case 'image':
- case 'image_group':
- if (target.is_watermark) {
- show(['watermark', 'delete', 'annotations', 'deselect_dropdown']);
- } else {
- show(['delete', 'annotations', 'deselect_dropdown']);
- }
- break;
- case 'radio':
- case 'check_on':
- case 'check_off':
- case 'whiteout':
- show(['delete', 'annotations'])
- break;
- default:
- console.log("default?");
- break;
- }
- } else if (canvas.getActiveObject()) {
- switch (target.type) {
- case 'i-text':
- case 'textbox':
- if (target.is_watermark) {
- show(['textEdit', 'text', 'delete']);
- } else {
- show(['textEdit', 'text', 'delete', 'annotations']);
- }
- break;
- }
- }
- // let bounds = canvas.upperCanvasEl.getBoundingClientRect();
- // let css_scale_top = bounds.height/$(canvas.upperCanvasEl).height();
- // let viewport_scale = window.visualViewport.scale;
- // console.log("scales is ", css_scale_top, viewport_scale);
- // const sx = 0;//window.scrollX;
- // const sy = 0;//window.scrollY;
- // let target_width = target.width;
- // if (target.originX == 'center') {
- // console.log("origin center?");
- // const sx = window.scrollX;
- // const sy = window.scrollY;
- // let left = target.left - sx,
- // top = target.top - controls.clientHeight - 3 - sy;
- // if (left < 0) { left = 0; }
- // if (top < 0) { top = 0; }
- // controls.style = `display: flex;left: ${left}px;top:${top}px;`;
- // } else {
- // let left = target.left - sx + (target.width * target.scaleX / 2),
- // top = ((target.top) + (bounds.top) - controls.clientHeight - 3 - sy);
- // // console.log("====debug:====");
- // // console.log("target.top", target.top);
- // // console.log("bounds.top", bounds.top);
- // // console.log("controls.clientHeight", controls.clientHeight);
- // // console.log("window.scrollY", window.scrollY);
- // let buttons_size = document.querySelector(".control-widget-el-actions").getBoundingClientRect();
- // if (left - (buttons_size.width / 2) < 0) {
- // left = left - (left - (buttons_size.width / 2));
- // }
- // if (left + (buttons_size.width / 2) > target.canvas.width) {
- // left = left + (target.canvas.width - (left + buttons_size.width / 2)); //(left-(buttons_size.width/2));
- // }
- // top = top+window.visualViewport.offsetTop;
- // controls.style = `display: flex;left: ${left}px;top:${top}px;`;
- // }
- let bounds = canvas.upperCanvasEl.getBoundingClientRect();
- let css_scale_top = bounds.height / $(canvas.upperCanvasEl).height();
- let viewport_scale = window.visualViewport.scale;
- //console.log("scales is ", css_scale_top, viewport_scale);
- const sx = 0;//window.scrollX;
- const sy = 0;//window.scrollY;
- let target_width = target.width;
- const fixPositons = (left, top, el) => {
- if (left < 0) left = 0;
- if (top < 100) top = 50;
- return { left, top };
- };
- if (target.originX == 'center') {
- const sx = window.scrollX;
- const sy = window.scrollY;
- let left = target.left - sx,
- top = target.top - controls.clientHeight - 3 - sy;
- const fix = fixPositons(left, top, controls);
- controls.style = `display: flex;left: ${fix.left}px;top:${fix.top}px;`;
- } else {
- let left = target.left - sx + (target.width * target.scaleX / 2),
- top = ((target.top) + (bounds.top) - controls.clientHeight - 3 - sy);
- // console.log("====debug:====");
- // console.log("target.top", target.top);
- // console.log("bounds.top", bounds.top);
- // console.log("controls.clientHeight", controls.clientHeight);
- // console.log("window.scrollY", window.scrollY);
- let buttons_size = document.querySelector(".control-widget-el-actions").getBoundingClientRect();
- if (left - (buttons_size.width / 2) < 0) {
- left = left - (left - (buttons_size.width / 2));
- }
- if (left + (buttons_size.width / 2) > target.canvas.width) {
- left = left + (target.canvas.width - (left + buttons_size.width / 2)); //(left-(buttons_size.width/2));
- }
- // top = top + window.visualViewport.offsetTop;
- // left += visualViewport.offsetLeft;
- const fix = fixPositons(left, top, controls);
- controls.style = `display: flex;left: ${fix.left}px;top:${fix.top}px;`;
- }
- }
- createColorPicker(elementBody, key = false, callback = () => { }) { // fontColor
- if (typeof elementBody == 'string') elementBody = document.querySelector(elementBody);
- const picker = new EasyLogicColorPicker({
- outputFormat: 'hex',
- container: elementBody,
- onChange: _.debounce(function (color) {
- if (window._lockColorChanges) {
- window._lockColorChanges = false;
- return;
- }
- const parent = elementBody.parentElement;
- parent.querySelector('.info-color').innerHTML = color;
- parent.querySelector('.pick-ico-color').style.background = color;
- callback(color);
- // TextEditor.changeFontColor_(color);
- }, 30),
- onInit: function (element) {
- let close_generate = document.createElement("a");
- close_generate.setAttribute("class", "close-color");
- close_generate.setAttribute("href", "#")
- close_generate.innerHTML = `<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
- <path d="M6 6L18 18" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
- <path d="M18 6L6 18" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
- </svg>`;
- let el_find = element.$el.el;
- if (el_find) {
- el_find.appendChild(close_generate);
- let close_btn_find = el_find.querySelector(".close-color");
- close_btn_find.addEventListener("click", (ev) => {
- ev.preventDefault();
- ev.stopPropagation();
- let parent_dropdown = elementBody.closest("[data-dropdown--mob]");
- parent_dropdown.classList.toggle("active-drp");
- })
- }
- }
- });
- if (key) this.colorPicker[key] = picker;
- }
- createRange(slider = '', input = '', key = false, options = {}, callback = () => { }) {
- try {
- const range = $(document.querySelector(slider)).ionRangeSlider({
- min: 0, max: 10, from: 0,
- ...options,
- onChange: data => {
- $(input).val(data.from);
- callback(data.from);
- },
- onUpdate: data => $(input).val(data.from)
- }).data('ionRangeSlider');
- if (key) this.rangesElements[key] = range;
- } catch (err) {
- console.error(err);
- }
- }
- setStylesForShapes(styles = {}) {
- const active = this.getActiveObject();
- if (active) {
- active.set(styles);
- active.canvas.renderAll();
- }
- }
- initRangesElements() {
- Array.from(document.querySelectorAll('[data-type="close_modal"]')).forEach(el => {
- el.addEventListener('click', e => {
- e.target.closest('.modal--mobile').classList.remove('modal--show--mobile');
- });
- });
- this.createRange('[name="border_shape"]', '[name="border_shape_input"]', 'borderShape', {
- min: 0, max: 10, step: 1, from: 0
- }, from => this.setStylesForShapes({ strokeWidth: from }));
- this.createRange('[name="range_font_size"]', '[name="input_font_size"]', 'fontSize', {
- min: 6, max: 72, step: 1, from: 0
- }, from => {
- TextEditor.changeFontSize_(from);
- });
- this.createRange('[name="range_opacity"]', '[name="input_opacity"]', 'opacity', {
- min: 0.01, max: 1, step: 0.05, from: 0
- }, from => {
- TextEditor.changeOpacity_(from);
- });
- this.createRange('[name="range_opacity_watermark"]', '[name="input_opacity_watermark"]', 'opacity_watermark', {
- min: 0.01, max: 1, step: 0.05, from: 0
- }, from => {
- TextEditor.changeOpacity_(from);
- });
- this.createRange('[name="range_rotate_watermark"]', '[name="input_rotate_watermark"]', 'angle_watermark', {
- min: -360, max: 360, step: 1, from: 0
- }, from => {
- TextEditor.changeRotate_(from);
- });
- this.createRange('[name="range_rotate"]', '[name="input_rotate"]', 'angle', {
- min: -360, max: 360, step: 1, from: 0
- }, from => {
- TextEditor.changeRotate_(from);
- });
- this.createColorPicker('[data-type="text_color_picker"]', 'fontColor', color => TextEditor.changeFontColor_(color));
- this.createColorPicker('[data-type="border_color_shape"]', 'borderColorShape', color => {
- this.setStylesForShapes({ stroke: color });
- });
- this.createColorPicker('[data-type="fill_shape_color"]', 'fillShapeColor', color => {
- this.setStylesForShapes({ fill: color });
- });
- }
- getCoords(obj) {
- const coords = obj.getCoords();
- const left = Math.min(...coords.map(c => c.x));
- const top = Math.min(...coords.map(c => c.y));
- const right = Math.max(...coords.map(c => c.x));
- const bottom = Math.max(...coords.map(c => c.y));
- return { left, top, right, bottom, width: right - left, height: bottom - top };
- }
- };
- window.mp = mp;
- let mob_btn_drop = $("[data-dropdown--mob]");
- $.each(mob_btn_drop, function (index, element) {
- let el = $(element);
- el.on("click", function (event) {
- event.preventDefault();
- let closest_drop_mob = el.closest("[data-dropdown--mob]");
- closest_drop_mob.addClass("active-drp");
- });
- });
- $(document).on("click", function (event) {
- if (!event.target.closest("[data-dropdown--mob]")) {
- mob_btn_drop.removeClass("active-drp");
- }
- });
- if (false) {
- window.lockerScroll = amoutTouch => {
- console.log('amoutTouch', amoutTouch);
- viewer.pages[mobileEditor.page].fcanvas.allowTouchScrolling = amoutTouch > 1;
- document.querySelector('#pdf_editor_pages').style['touch-action'] = amoutTouch > 1 ? 'auto' : 'none';
- };
- document.addEventListener('touchstart', e => lockerScroll(e.touches.length));
- document.addEventListener('touchend', e => lockerScroll(e.touches.length));
- }
- document.querySelector(".page-counter").addEventListener("click", function (e) {
- e.preventDefault();
- let input = document.querySelector(".page_input");
- input.setAttribute("max", mobileEditor.total_pages);
- input.value = mobileEditor.page;
- input.classList.remove("hidden");
- document.querySelector(".page-counter").classList.add("hidden");
- input.focus();
- input.select();
- });
- document.querySelector(".page_input").addEventListener("input", debounce(function (e) {
- e.preventDefault();
- if (this.value > mobileEditor.total_pages) {
- this.value = mobileEditor.total_pages;
- }
- if (this.value < 1) {
- this.value = 1;
- }
- mobileEditor.selectPage(this.value);
- // mobileInit(parseInt(this.value), true);
- }, 1000));
- document.querySelector(".page_input").addEventListener("focusout", function () {
- document.querySelector(".page_input").classList.add("hidden");
- document.querySelector(".page-counter").classList.remove("hidden");
- });
- //mobileInit(mobileEditor.page + 1, true);
- const ts = document.querySelector('.ts');
- ts.addEventListener('change', async e => {
- const file = e.target.files[0];
- if (file) {
- const imageURL = URL.createObjectURL(file);
- const image = await new Promise((resolve, reject) => {
- fabric.Image.fromURL(imageURL, (image, err) => {
- if (err) return reject(err);
- resolve(image);
- });
- });
- image.subtype = 'image';
- let canvas = viewer.pages[mobileEditor.page].fcanvas;
- const minSize = Math.min(canvas.width * .3, canvas.height * .3);
- const scale = Math.min(minSize / image.width, minSize / image.height);
- image.set({ scaleX: scale, scaleY: scale });
- e.target.value = '';
- if (mp.image_is_watermark) {
- image.is_watermark = true;
- image.opacity = 0.5;
- mp.image_is_watermark = false;
- }
- //mp.addElement(image, false, image.is_watermark ? true : false);
- mp.addElement(image, false, true);
- }
- });
- function debounce(func, wait, immediate) {
- var timeout;
- return function () {
- var context = this, args = arguments;
- var later = function () {
- timeout = null;
- if (!immediate) func.apply(context, args);
- };
- var callNow = immediate && !timeout;
- clearTimeout(timeout);
- timeout = setTimeout(later, wait);
- if (callNow) func.apply(context, args);
- };
- };
- $(document).on("after_page_render", function (e, page) {
- viewer.pending_pages = [];
- let prev_page = page - 1,
- next_page = page + 1;
- if (prev_page > 0 && viewer.rendered_pages_array.indexOf(prev_page) == -1) {
- viewer.pending_pages.push(prev_page);
- }
- if (next_page <= viewer.total_pages && viewer.rendered_pages_array.indexOf(next_page) == -1) {
- viewer.pending_pages.push(next_page);
- }
- });
- setInterval(function () {
- viewer.pending_pages = viewer.pending_pages.filter(function (p) {
- return elementInViewport(document.querySelector(`#page_outer_${p}`));
- });
- if (!viewer.now_render && viewer.pending_pages.length) {
- viewer.renderSinglePage(viewer.pending_pages.pop());
- }
- }, 1000);
- function allViewedPages() {
- let pages = Object.values(document.querySelectorAll(".m_page_outer"));
- let ret = [];
- for (let i = 0; i < pages.length; i++) {
- let el = pages[i];
- if (elementInViewport(el)) {
- ret.push(parseInt(el.dataset.pageId));
- }
- }
- return ret;
- }
- function firstViewedPage() {
- let pages = Object.values(document.querySelectorAll(".m_page_outer"));
- for (let i = 0; i < pages.length; i++) {
- let el = pages[i];
- if (elementInViewport(el)) {
- return parseInt(el.dataset.pageId);
- break;
- }
- }
- return 1;
- }
- function preventScroll(e) {
- e.preventDefault();
- e.stopPropagation();
- return false;
- }
- let allow_fabric = false,
- fabric_has_active_element = false,
- touched_canvas = false;
- let scrolled = false;
- let touch_up = true;
- let allow_fabric_move = false;
- if (true) {
- container[0].addEventListener("scroll", async function (e) {
- scrolled = true;
- mp.hideControlls();
- if (viewer.pages[mp.last_touched_page] && viewer.pages[mp.last_touched_page].fcanvas) {
- if (viewer.pages[mp.last_touched_page].fcanvas._activeObject) {
- viewer.pages[mp.last_touched_page].fcanvas.discardActiveObject();
- viewer.pages[mp.last_touched_page].fcanvas.renderAll();
- }
- viewer.pages[mp.last_touched_page].fcanvas._prev_target = null;
- }
- });
- container[0].addEventListener("touchstart", async function (e) {
- touch_up = false;
- mp.last_touched_page = $(e.target).closest(".m_page_outer").data("page-id");
- }, { passive: false })
- container[0].addEventListener("touchmove", function (e) {
- scrolled = true;
- }, { passive: false })
- container[0].addEventListener("touchend", function (e) {
- if (!mp.draw_enabled) {
- scrolled = false;
- touch_up = true;
- setTimeout(() => {
- if (!mp.texts_active) {
- mp.enableScroll();
- }
- }, 200);
- }
- }, { passive: false });
- }
- container.on('scroll', () => {
- document.querySelector(".scroll_current_page").innerHTML = firstViewedPage();
- });
- container.on('scroll', debounce(() => {
- if (viewer.loadingTask) {
- viewer.pending_pages = [];
- document.querySelectorAll(".m_page_outer:not(.canvas_ready)").forEach(function (el) {
- if (elementInViewport(el)) {
- viewer.renderSinglePage(parseInt(el.dataset.pageId));
- }
- });
- console.log("selected page?", firstViewedPage());
- mobileEditor.selectPage(parseInt(firstViewedPage()), false)
- }
- if (viewer.pages[viewer.current_page] && viewer.pages[viewer.current_page].fcanvas) {
- try {
- const active = viewer.pages[viewer.current_page].fcanvas.getActiveObject();
- mp.renderPosition(active);
- } catch (e) {
- console.warn(e);
- }
- }
- }, 100));
- function elementInViewport(myElement) {
- //var myElement = document.getElementById('my-element')
- var bounding = myElement.getBoundingClientRect();
- var myElementHeight = myElement.offsetHeight;
- var myElementWidth = myElement.offsetWidth;
- var bounding = myElement.getBoundingClientRect();
- if (bounding.top >= -myElementHeight
- && bounding.left >= -myElementWidth
- && bounding.right <= (window.innerWidth || document.documentElement.clientWidth) + myElementWidth
- && bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) + myElementHeight) {
- return true;
- } else {
- return false;
- }
- }
- function sendTouchEvent(x, y, element, eventType) {
- const touchObj = new Touch({
- identifier: Date.now(),
- target: element,
- clientX: x,
- clientY: y,
- radiusX: 2.5,
- radiusY: 2.5,
- rotationAngle: 10,
- force: 0.5,
- });
- const touchEvent = new TouchEvent(eventType, {
- cancelable: true,
- bubbles: false,
- touches: [touchObj],
- targetTouches: [],
- changedTouches: [touchObj],
- shiftKey: true,
- });
- element.dispatchEvent(touchEvent);
- }
Add Comment
Please, Sign In to add comment