soscripted / sox

Stack Overflow Extras: a userscript for the Stack Exchange websites to add a bunch of optional toggle-able features
http://stackapps.com/q/6091/
MIT License
72 stars 15 forks source link

Check if selectionStart is less than selectionEnd and vice versa before the assignment #437

Closed double-beep closed 4 years ago

double-beep commented 4 years ago

I tried to edit a post and I noticed there were some keys which needed kbd formatting. I selected the text and clicked kbd, but the result was strange. The text looked before:

image

Afterwards, it looked like:

image

While in the desired result the SHIFTs should not have been there.

Interestingly, trying again worked, and worked and then failed. This seemed interesting on me, so I started testing to find the bug.

After a bit of digging, I realized there were 2 interesting variable assignments in sox.common.js surroundSelectedText() function:

const selS = textarea.selectionStart;
const selE = textarea.selectionEnd;

This however, doesn't seem write. What if I select the text with my cursor from right to left? Then selS would have selectionEnd and selE selectionStart actually. This appeared to produce the strange results.

A fix is to check if selectionStart is less than selectionEnd and vice versa and assign accordingly. After all, the feature now works regardless of how you select the text.

shu8 commented 4 years ago

Another nice catch! :D Thanks :)