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

コピペ後にスクロール位置がトップに戻る #27

Open
h-yabi2 opened this issue Sep 11, 2024 · 0 comments
Open

コピペ後にスクロール位置がトップに戻る #27

h-yabi2 opened this issue Sep 11, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@h-yabi2
Copy link
Owner

h-yabi2 commented Sep 11, 2024

結論

  • 以下のコードを使用することでURLがペーストされた時にリンクに変換
import { Quill } from 'react-quill'

const Clipboard = Quill.import('modules/clipboard')

class CreateLinkFromURL extends Clipboard {
  onPaste(e: ClipboardEvent): void {
    let clipboardData = e.clipboardData || (window as any).clipboardData
    let pastedText = clipboardData.getData('Text')

    // URLを検出する正規表現パターン
    // クエリパラメータやフラグメントを含むURLにも対応
    const urlPattern = /^(https?:\/\/[\w\.-]+(?:\:[0-9]+)?(?:\/[^\s]*)?)/

    // ペーストされたテキストがURLかどうかをチェック
    if (urlPattern.test(pastedText)) {
      e.preventDefault() // デフォルトのペースト処理をキャンセル
      const matchedUrl = pastedText.match(urlPattern)[0]
      // リンクとして挿入
      const index =
        (this.quill.getSelection(true) || {}).index || this.quill.getLength()
      this.quill.insertText(index, matchedUrl, 'link', matchedUrl)
    } else {
      super.onPaste(e)
    }
  }
}

CreateLinkFromURL.blotName = 'createLinkFromURL'
CreateLinkFromURL.className = 'create-link-from-url'

export default CreateLinkFromURL

登録時は以下のようにする

Quill.register('modules/clipboard', CreateLinkFromURL)

CSSも以下を設定していた方が確実かも

  • 以下の設定を追加することで、スクロール位置が移動しないようになった
.ql-clipboard {
  position: fixed !important;
  left: 50% !important;
  top: 50% !important;
  display: none;
}

解決までの過程

  • .ql-clipboard が影響してるっぽい
  • 作業環境では、以下のcssを適用することで解消されたが、URLコピペ時にリンクに変換してくれる quill-auto-links が機能しなくなった
    .ql-clipboard {
      position: fixed !important;
      left: 50% !important;
      top: 50% !important;
      display: none;
    }
    
  • clipboard のカスタマイズは以下をもとに行う
      const Clipboard = Quill.import('modules/clipboard')
      class CustomClipboard extends Clipboard {
        onPaste(e: ClipboardEvent): void {
          alert('onPaste')
          super.onPaste(e)
        }
      }
      Quill.register('modules/clipboard', CustomClipboard)
    

参考

@h-yabi2 h-yabi2 added the bug Something isn't working label Sep 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant