Advertisement
Guest User

editor.js

a guest
Apr 11th, 2022
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import {db} from './firebase.js';
  2. import { doc, setDoc } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-firestore.js";
  3. import { getAuth, signOut, onAuthStateChanged } from 'https://www.gstatic.com/firebasejs/9.6.10/firebase-auth.js';
  4. import {app} from '../../js/firebase.js';
  5.  
  6.  
  7. let current_nickname = '';
  8.  
  9. console.log(app);
  10. const auth = getAuth(app);
  11. onAuthStateChanged(auth, (user) => {
  12.   if (user) {
  13.     // User is signed in, see docs for a list of available properties
  14.     // https://firebase.google.com/docs/reference/js/firebase.User
  15.     const uid = user.uid;
  16.     console.log('Текущий пользователь:', user);
  17.     current_nickname = user.displayName;
  18.     //document.getElementById("email").innerText += ' ' + user.displayName;
  19.     // ...
  20.   } else {
  21.     // User is signed out
  22.     // ...
  23.     console.log("User not found")
  24.     window.location.href = "/login";
  25.   }
  26. });
  27.  
  28.  
  29. const blogTitleField = document.querySelector('.title');
  30. const articleField = document.querySelector('.article');
  31.  
  32. // banner
  33. const bannerImage = document.querySelector('#banner-upload');
  34. const banner = document.querySelector('.banner');
  35. let bannerPath;
  36.  
  37. const publishBtn = document.querySelector('.publish-btn');
  38. const uploadInput = document.querySelector('#image-upload');
  39.  
  40.  
  41. bannerImage.addEventListener('change', () => {
  42.     uploadImage(bannerImage, "banner");
  43. })
  44.  
  45. uploadInput.addEventListener('change', () => {
  46.     uploadImage(uploadInput, "image");
  47. })
  48.  
  49. const uploadImage = (uploadFile, uploadType) => {
  50.     const [file] = uploadFile.files;
  51.     if (file && file.type.includes("image")){
  52.         const formdata = new FormData();
  53.         formdata.append('image', file);
  54.    
  55.         console.log("Картинка выбрана");
  56.  
  57.         // Список пар ключ/значение
  58.         for(let [name, value] of formdata) {
  59.             console.log(`${name}`, value); // key1=value1, потом key2=value2
  60.         }
  61.  
  62.         const csrfToken = getCookie('XSRF-TOKEN');
  63.         console.log(csrfToken);
  64.         const headers = new Headers({
  65.             'Content-Type': 'x-www-form-urlencoded',
  66.             'X-CSRF-Token': csrfToken
  67.         });
  68.  
  69.         fetch('/upload', {
  70.             method: 'post',
  71.             headers: headers,
  72.             credentials: 'include',
  73.             body: formdata
  74.         }).then(res => res.json())
  75.         .then(data => {
  76.             if (uploadType == 'image')
  77.             {
  78.                 addImage(data, file.name);
  79.             }
  80.             else if (uploadType == 'banner')
  81.             {
  82.                 bannerPath = `${location.origin}/${data}`;
  83.                 banner.style.backgroundImage = `url("${bannerPath}")`
  84.             }
  85.             else
  86.             {
  87.                 console.error('Данный тип файла не поддерживается');
  88.             }
  89.         })
  90.     } else
  91.     {
  92.         alert('Upload image only');
  93.     }
  94. }
  95.  
  96. // добавление ссылки на файл в записи
  97. const addImage = (imagepath, alt) => {
  98.     let curPos = articleField.selectionStart;
  99.     let textToInsert = `\r![${alt}](${imagepath})\r`;
  100.     articleField.value = articleField.value.slice(0, curPos) + textToInsert + articleField.value.slice(curPos);
  101. }
  102.  
  103. let mouths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  104.  
  105. // Публикация записи
  106. publishBtn.addEventListener('click', () => {
  107.     if(articleField.value.length && blogTitleField.value.length){ // если ввели название и содержание
  108.         // генерация id
  109.         let letters = 'abcdefghijklmnopqrstuvwxyz';
  110.         let blogTitle = blogTitleField.value.split(" ").join("-");
  111.         let id = '';
  112.         for(let i = 0; i < 4; i++)
  113.         {
  114.             id += letters[Math.floor(Math.random() * letters.length)];
  115.         }
  116.  
  117.         // Установка названия документа
  118.         let docName = `${blogTitle}-${id}`;
  119.         let date = new Date(); // для даты публикации
  120.  
  121.         console.log(db);
  122.         // для доступа firestore переменной db
  123.         /*db.collection("blogs").doc(docName).set({
  124.             title: blogTitleField.value,
  125.             article: articleField.value,
  126.             bannerImage: bannerPath,
  127.             publishedAt: `${date.getDate()} ${mouths[date.getMonth()]} ${date.getFullYear()}`
  128.         })*/
  129.         setDoc(doc(db, 'blogs', docName), {
  130.             title: blogTitleField.value,
  131.             article: articleField.value,
  132.             bannerImage: bannerPath,
  133.             publishedAt: `${date.getDate()} ${mouths[date.getMonth()]} ${date.getFullYear()}`,
  134.             author: current_nickname
  135.         })
  136.         .then(() => {
  137.             console.log('date entered');
  138.             location.href = `/${docName}`;
  139.         })
  140.         .catch((err) => {
  141.             console.error(err);
  142.         })
  143.     }
  144. })
  145.  
  146. function getCookie(name) {
  147.     if (!document.cookie) {
  148.       return null;
  149.     }
  150.  
  151.     const xsrfCookies = document.cookie.split(';')
  152.       .map(c => c.trim())
  153.       .filter(c => c.startsWith(name + '='));
  154.  
  155.     if (xsrfCookies.length === 0) {
  156.       return null;
  157.     }
  158.     return decodeURIComponent(xsrfCookies[0].split('=')[1]);
  159.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement