jakiestfu / Medium.js

A tiny JavaScript library for making contenteditable beautiful (Like Medium's editor)

Home Page:http://jakiestfu.github.io/Medium.js/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Change toolbar state to indicate that a selection is bold, italic etc.

nrkn opened this issue · comments

commented

Hi - wondering if anyone has figured this out yet

Say you have a custom toolbar that uses invokeElement to toggle tags on and off, eg bold or whatever - pretty standard use case - how can you tell that the currently selected text is already in a certain state, so that you can change the button appearance accordingly?

I was looking at the MDN docs for select events and there doesn't seem to be any useful event that isn't experimental and unsupported

How do other contenteditable controls handle it? Polling or something? Handling the various keyup/mouseup/etc events and checking the selection has changed? Something else?

Any hints or suggestions?

I was looking at the MDN docs for select events and there doesn't seem to be any useful event that isn't experimental and unsupported

The implementation of contenteditable is a complete mess, that is why this library and the hoards of others exist.

Rangy's class applier is really at the heart of this, with that said a few minutes of digging and I arrived at selecting the node at the cursor:

var element = rangy.getSelection().anchorNode.parentNode;

then you could iterate through the parents, while (element = element.parentNode) { /*logic here*/ } and find out which of the elements have which classes. This seems terribly inefficient, though, and in the end, I'd probably try and find a more efficient means if it is absolutely necessary.

Please note: I did say "seems terribly inefficient". I may end up eating my own words.

commented

Yeah I've noticed that in many other contenteditable controls, there's a small but noticeable delay between (for example) selecting some bolded text and the bold button on the toolbar getting highlighted - so I suspect either a) polling (using settimeout or similar to check the current selection every whatever ms) or b) that it's terribly inefficent walking the DOM like you say, or maybe a bit of both.

Thanks for the tip on rangy.