본문 바로가기
React

React Quill Clipboard keyboard customizing 방법

by 집요한 개발자 2022. 4. 18.

react quill을 사용해 무료 wysiwyg에디터로 게시판 글쓰기를 구현하던중

 enter를 눌러 줄바꿈을 할 경우 header 설정이 자동으로 nomal로 바뀌는 기능을 해제하고 싶어 분석후 적용한 내용 정리입니다.

 

function preserveSizeFormat(node, delta) {
        const match = node.className.match(/ql-size-(.*)/)
        const fontSize = node.style['font-size']
        // HACK: when className is not present, check style attribute
        const styleMatch = fontSize && fontSize !== '16px'
        console.log(match)
        console.log(styleMatch)
        console.log(fontSize)
        if (match || styleMatch) {
            delta.map(function (op) {
                if (!op.attributes) op.attributes = {}
                // grab the size from `ql-size-{x}`
                if (match) {
                    op.attributes.size = match[1]
                } else if (styleMatch) {
                    const large = fontSize <= '13px' || fontSize <= '0.8125rem'
                    op.attributes.size = large ? 'large' : 'huge'
                }
                return op
            })
        }
        return delta
    }

    const modules = useMemo(() => {
        return ({
            clipboard: {
                matchers: [
                    [Node.ELEMENT_NODE, function (node, delta) {
                        return delta.compose(new Delta().retain(delta.length(), // 거의 동일하게 복사 붙여넣기 위한 코드
                            {
                                header: 3,
                            }
                        ));
                    }
                    ],
                    ['span', preserveSizeFormat]
                ]
            },
            keyboard: {
                bindings: {
                    'header enter': {
                        key: 'Enter',
                        format: ['header', 'size', 'color'],
                        handler(range, context) { // enter 입력시 (줄바뀜) 폰트 사이즈, 헤더 설정 유지를 위한 코드 
                            return true
                        },
                    },
                },
            },
            toolbar: [
                [{ 'size': [] }],
                [{ 'font': [] }],
                [{ 'header': [] }],
                ['bold', 'italic', 'underline', 'strike', 'blockquote'],
                [{ 'list': 'ordered' }, { 'list': 'bullet' }, { 'indent': '-1' }, { 'indent': '+1' }],

                [{ 'align': [] }, { 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
                ['clean']
            ],
        })
    }, [])

    let formats = [
        'size',
        'font',
        'header',
        'bold', 'italic', 'underline', 'strike', 'blockquote',
        'list', 'bullet', 'indent',
        'link', 'image',
        'align', 'color', 'background',
    ]

<ReactQuill ref={okRef}
                        style={{ height: height - 150 }}
                        placeholder="공지사항을 작성해 주세요."
                        modules={modules}
                        formats={formats}
                        onChange={(a, b, c, editor) => {
                            // console.log(editor.getHTML())
                            if (editor.getHTML().length > 7 && disabled === true) {
                                setDisabled(false)
                            }

                            if (editor.getHTML() === '<p><br></p>' && disabled === false) {
                                setDisabled(true)
                            }
                        }}
                        onBlur={(previousRange, source, editor) => getNotice(previousRange, source, editor)}
                    />

 

모듈 부분의 clipboard 부분은 붙여넣기 할때 행동을 정의하는 곳

keyboard : binding 부분은 특정 키입력시 행동 정의하는 곳입니다. addbinding사용은 기본 설정보다 후순위이며

모듈로 설정할경우 기본 설정보다 우선순위로 정의할 수 있습니다. 

header을 한줄 입력후 엔터 입력시 header설정 변경되는 기능을 막고 싶다면 header enter이름으로 바인딩한후

handler 함수를 정의하세요 이때 return true을 하면 header설정이 유지됩니다.

 

preserveSizeFont함수는 붙여넣기 할때 특정사이즈를 비교해 quill에 그나마 맞게 수정한 부분입니다.

 

'React' 카테고리의 다른 글

React socket io client 적용 방법  (1) 2022.04.28
React CKeditor5 기본 컴포넌트 사용법  (0) 2022.04.01
React Recoil 사용하기1  (0) 2021.12.20
Link vs Redirect vs history.push  (0) 2021.12.17

댓글