Toggle hiding/showing text with script


#1

I searched, but didn’t find what i was looking for.

I’m trying to write a script in my init.coffee file to toggle the visibility of the URI part of links in Markdown files.

What I’ve tried is to add this to my styles.less:

.syntax--md.syntax--uri.collapsed {
  display: none;
}

And this to my init.coffee:

atom.commands.add 'atom-text-editor',
  'user:collapse-uris': (e) ->
    textEditor = atom.workspace.getActiveTextEditor();
    uris = atom.views.getView(textEditor).getElementsByClassName('syntax--uri');
    for uri in uris
      uri.classList.toggle('collapsed');

This seems to work at first, but it only changes what’s actually visible on the screen. When I scroll down, the others aren’t hidden, and scrolling back up brings back the ones that were hidden at first.

Does anyone know some other way I can go about this? Also, it would be great if they started out hidden, and I could use the toggle if I want to see them.


#2

I suspect that your code is changing all of the elements that have been rendered, but then Atom creates more and they aren’t being given the collapsed class. It might be easier to approach this from the other direction. Instead of having a CSS rule and toggling a class on and off, you could make use of Less variables and have the command toggle display:none on and off for anything in syntax--md.syntax--uri.


#3

Thanks for the input @DamnedScholar. It got me looking in the right direction.

I ended up digging into the Atom source code, as well as the devTools, a bit more, and eventually got what I needed.

This is in my styles.less:

// .syntax--destination is a wrapper around .syntax--uri
.syntax--md.syntax--destination {
  display: none;
}

.cursor-line .syntax--md.syntax--destination {
  display: inline;
}

And this in my init.coffee:

do ->
  disposable = null;

  atom.commands.add 'atom-text-editor',
    'user:toggle-markdown-uris': (e) ->
      if not disposable
        disposable = atom.styles.addStyleSheet('.syntax--md.syntax--destination {display: inline !important;}')
      else
        disposable.dispose()
        disposable = null

Now, by default, the URIs are not shown unless the cursor is on that line. And I can run the user:toggle-markdown-uris command to show/hide all of them.