Advertisement:

Author Topic: Select text and paste URL to create a text-link (like Slack)  (Read 2173 times)

Offline Kolya

  • Full Member
  • ***
  • Posts: 456
  • systemshock.org
Select text and paste URL to create a text-link (like Slack)
« on: September 01, 2020, 05:08:04 PM »
If you're using Slack you may know this feature. You select some text that you wrote, then just paste a URL and the selected text magically turns into a link.

Well, I like this feature anyway, because it doesn't require fumbling with a link button. It's simply the fastest way to create text-links, so I wrote it for SMF.

Make sure your editors (quick reply and full editor textareas) have an id="message". Then load this script before the closing body tag.

Code: [Select]
const messageBox = document.getElementById('message')
messageBox.addEventListener('paste', function(e) {
  const clipboard = (e.originalEvent || e).clipboardData.getData('text/plain')
  const regex = RegExp('https?://[^\s/$.?#].[^\s]*')
  const isUrl = regex.test(clipboard)
  if (isUrl) {
    const start = messageBox.selectionStart
    const finish = messageBox.selectionEnd
    const allText = messageBox.value
    const selected = allText.substring(start, finish)
    if (selected) {
      const newText = `${allText.substring(0, start)}[url=${clipboard}]${selected}[/url]${allText.substring(finish, allText.length)}`
      messageBox.value = newText
      e.preventDefault()
    }
  }
})

Offline Antechinus

  • SMF Friend
  • SMF Master
  • *
  • Posts: 25,505
  • Master of BBC Abuse
Re: Select text and paste URL to create a text-link (like Slack)
« Reply #1 on: September 06, 2020, 05:43:24 PM »
Nifty. :) Just to be clear: I assume this works for 2.0.x. Will it also work with 2.1?

Offline Kolya

  • Full Member
  • ***
  • Posts: 456
  • systemshock.org
Re: Select text and paste URL to create a text-link (like Slack)
« Reply #2 on: September 07, 2020, 07:36:40 AM »
It works for any textarea with an id="message". So yeah, also for SMF2.1.


It does not work for the richText-Editor, because it's not a texarea, but an iframe with a contenteditable body.
I'm personally not interested in the richText-Editor. I might put some work into it in future, in the context of my involvement with SMF2.1.

Offline Antechinus

  • SMF Friend
  • SMF Master
  • *
  • Posts: 25,505
  • Master of BBC Abuse
Re: Select text and paste URL to create a text-link (like Slack)
« Reply #3 on: September 07, 2020, 08:53:05 AM »
Nobody uses the 2.0 wisiwyg editor anyway. It's too buggy. I wouldn't waste time on it.
SCE (used in 2.1) is pretty good, but personally I still tend to prefer using it in BBC mode.

Offline sima002

  • Newbie
  • *
  • Posts: 2
Re: Select text and paste URL to create a text-link (like Slack)
« Reply #4 on: October 05, 2020, 05:21:33 AM »
I'm trying to do this, but its dosen't looks good, May be I don't have privilege to put URL  in my answer section.