Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

toast ui #41

Closed
Tracked by #5
arch-spatula opened this issue Feb 14, 2023 · 9 comments
Closed
Tracked by #5

toast ui #41

arch-spatula opened this issue Feb 14, 2023 · 9 comments
Assignees
Labels
enhancement 새로운 기능

Comments

@arch-spatula
Copy link
Collaborator

No description provided.

@arch-spatula arch-spatula mentioned this issue Feb 14, 2023
9 tasks
@arch-spatula
Copy link
Collaborator Author

문제

ReferenceError: self is not defined

실패

해결

팀프로젝트 회고(22/07/13), ReferenceError: self is not defined

Dynamic Import

패턴을 보면 컴포넌트화를 한번 해주고 import 합니다.

arch-spatula added a commit that referenced this issue Feb 14, 2023
- toast ui를 추가합니다.

#5 #41
@hyoloui
Copy link
Collaborator

hyoloui commented Feb 14, 2023

https://curryyou.tistory.com/470
useRef 사용하는 이유, 참고 블로그

hyoloui added a commit that referenced this issue Feb 14, 2023
@arch-spatula
Copy link
Collaborator Author

arch-spatula commented Feb 15, 2023

next.js에서 react-quill 이미지 업로드 하기

getS3PresignedURL로 처리하기

addImageBlobHook

https://solve-programming.tistory.com/29

<Editor
      initialValue="hello react editor world!"
      previewStyle="vertical"
      height="600px"
      initialEditType="wysiwyg"
      useCommandShortcut
      toolbarItems={toolbarItems}
      hooks={{
        addImageBlobHook(blob, callback) {
          const uploadedImageURL = uploadImage(blob);
          callback(uploadedImageURL, "alt text");
          return false;
        },
      }}
      plugins={[
        colorSyntax,
        // 기본 색상 preset 적용
        // {
        //   preset: ["#1F2E3D", "#4c5864", "#ED7675"],
        // },
      ]}
    />

TUI 에디터 이미지 업로드 시 hook으로 파일 경로 전달하기

Toast UI Editor (TUI Editor) 에서 이미지 업로드시 base64 문자열

import React, { useRef, useEffect } from "react";
import "@toast-ui/editor/dist/toastui-editor.css";
import { Editor } from "@toast-ui/react-editor";
import axios from "axios";
import { backUrl } from "../../config/config";

const TextEditor = ({ setText }) => {
  const editorRef = useRef();
  useEffect(() => {
    if (editorRef.current) {
      editorRef.current.getInstance().removeHook("addImageBlobHook");
      editorRef.current
        .getInstance()
        .addHook("addImageBlobHook", (blob, callback) => {
          (async () => {
            let formData = new FormData();
            formData.append("file", blob);

            axios.defaults.withCredentials = true;
            const { data: url } = await axios.post(
              `${backUrl}image.do`,
              formData,
              {
                header: { "content-type": "multipart/formdata" },
              }
            );
            callback(url, "alt text");
          })();

          return false;
        });
    }

    return () => {};
  }, [editorRef]);
  return (
    <div>
      <Editor
        usageStatistics={false}
        initialValue="스터디에 대한 정보를 간략히 작성해주세요 '-'"
        previewStyle="tab"
        height="600px"
        initialEditType="wysiwyg"
        useCommandShortcut={true}
        onChange={() => {
          const innerTxt = editorRef.current.getInstance().getMarkdown();
          setText(innerTxt);
        }}
        ref={editorRef}
      />
    </div>
  );
};

export default TextEditor;

@arch-spatula
Copy link
Collaborator Author

export const onFileChange = async (event) => {
  const uploadedFile = event.target.files[0];

  /** @see https://developer.mozilla.org/ko/docs/Web/API/FileReader */
  const reader = new FileReader();
  reader.readAsDataURL(uploadedFile);
  reader.onload = (finishedEvent) => {
    const imgDataUrl = finishedEvent.currentTarget.result;
    localStorage.setItem("imgDataUrl", imgDataUrl);
    document.getElementById("Profile-img").src = imgDataUrl;
  };
};

@hyoloui
Copy link
Collaborator

hyoloui commented Feb 15, 2023

@hyoloui
Copy link
Collaborator

hyoloui commented Feb 15, 2023

import { useRef, useEffect } from 'react' 
import { initializeApp } from "firebase/app";
import { getStorage, ref, uploadBytes, getDownloadURL } from "firebase/storage" 

const firebaseConfig = { 
	apiKey: process.env.NEXT_PUBLIC_APIKEY, 
    authDomain: process.env.NEXT_PUBLIC_AUTHDOMAIN, 
    projectId: process.env.NEXT_PUBLIC_PROJECTID, 
    storageBucket: process.env.NEXT_PUBLIC_STORAGEBUCKET, 
    messagingSenderId: process.env.NEXT_PUBLIC_MESSAGINGSENDERID, 
    appId: process.env.NEXT_PUBLIC_APPID, 
}; 
    
const firebaseApp = initializeApp(firebaseConfig); 
const storage = getStorage(firebaseApp); 

const WysiwygEditor = () => {

	const editorRef = useRef(null);
    useEffect(()=> { 
    	const editorIns = editorRef.current.getInstance(); 
        editorIns.removeHook("addImageBlobHook"); 
        editorIns.addHook('addImageBlobHook', addImage); 
    }, []); 
    
// ------------- image Function ------------- // 에디터에 이미지 추가 
	
    const addImage = async(blob, dropImage) => { 
    	const img = await compressImg(blob); //이미지 압축 
        const url = await uploadImage(img); //업로드된 이미지 서버 url 
        dropImage(url, 'alt_text'); //에디터에 이미지 추가 
    } 
    //이미지 업로드 
    
    const uploadImage = async(blob) => { 
    	try{ 								//firebase Storage Create Reference 파일 경로 / 파일 명 . 확장자 
        	const storageRef = ref(storage, `post_images/${generateName() + '.' + blob.type.substring(6, 10)}`); 
            //firebase upload const snapshot = await uploadBytes(storageRef, blob); 
            
            return await getDownloadURL(storageRef); 
        } catch (err){ 
        	console.log(err) return false; } 
        } 
        
    //이미지 압축 
    const compressImg = async(blob) => { 
    	try{ 
        	const options = { 
            	maxSize: 1, 
                initialQuality: 0.55 //initial 0.7 
            } 
            return await imageCompression(blob, options); 
        } catch(e){ console.log(e); } } 
        
    //랜덤 파일명 생성 
    const generateName = () => { 
    	const ranTxt = Math.random().toString(36).substring(2,10); //랜덤 숫자를 36진수로 문자열 변환 
        const date = new Date(); 
        const randomName = ranTxt+'_'+date.getFullYear()+''+date.getMonth()+1+''+date.getDate()+''+date.getHours()+''+date.getMinutes()+''+date.getMinutes()+''+date.getSeconds(); 
        return randomName; 
    } 
    
    const getContent = () => { //글 내용 HTML 문자열로 불러오기 
    	const editorIns = editorRef.current.getInstance(); 
        return editorIns.getHTML(); 
    } 
    
    const getMarkDown = () => { //글 내용 마크다운 문자열로 불러오기 
    	const editorIns = editorRef.current.getInstance(); 
        return editorIns.getMarkdown(); 
    } 
    
    return( 
    <> 
    	<Editor ref={editorRef} 
        		initialEditType='wysiwyg' 
                hideModeSwitch={true} 
                height='500px' 
                theme={''} 
                usageStatistics={false} 
                toolbarItems={toolbarItems} 
                plugins={[colorSyntax,]} 
        /> 
    </> 
    ) 
    
} export default WysiwygEditor

@Jeremy-Kr Jeremy-Kr added the enhancement 새로운 기능 label Feb 15, 2023
@arch-spatula
Copy link
Collaborator Author

supabase/supabase#1761

hyoloui added a commit that referenced this issue Feb 15, 2023
- imageCompression 라이브러리 사용하여 이미지 압축
- Editor hook 커스텀
- supabase 스토리지에 이미지 서버통신 성공

#5 #41
by @arch-spatula  @hyoloui
hyoloui added a commit that referenced this issue Feb 15, 2023
- dynamic route 정상 작동

#5 #41
@hyoloui
Copy link
Collaborator

hyoloui commented Feb 15, 2023

https://curryyou.tistory.com/470

hyoloui added a commit that referenced this issue Feb 15, 2023
- useRef.current.getinstance()

#5 #41
arch-spatula added a commit that referenced this issue Feb 15, 2023
- state추가
- post에 state 중앙화

#5 #41
hyoloui added a commit that referenced this issue Feb 15, 2023
- 페어 작업중 페어 변경

#5 #41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement 새로운 기능
Projects
None yet
Development

No branches or pull requests

3 participants