How to add a new header icon

Hi,

I am trying to add a new icon to the header (for a light/dark theme switcher) and I’ve taken inspiration from another comment here but it isn’t quite working as expected. The icon disappears when I scroll down a post page, can anyone help me make it stay there the entire time.

Thanks a lot :grin:

(I tried adding the keep class but it still disappeared)

<script type="text/discourse-plugin" version="0.8">
  var h = require('virtual-dom').h;
  var ajax = require('discourse/lib/ajax').ajax;
  var themeSelector = require('discourse/lib/theme-selector');
  var light = 94;
  var dark = 98;
  
  const { iconNode } = require("discourse-common/lib/icon-library");
  let icon = iconNode('adjust');

  api.createWidget("header-theme-selector", {
      tagName: "span.header-theme-selector",
      buildKey: attrs => `header-theme-selector`,
      click(event){
          let $target = $(event.target);
          let id = light;
          let user = api.getCurrentUser();
          if(user){
              console.log(themeSelector.currentThemeId());
            if (themeSelector.currentThemeId() == light) {
              id = dark;
            }
            user.findDetails().then(user => {
                  seq = user.get("user_option.theme_key_seq");
                  this.setTheme(id, seq);
              });
          }else{
              this.setTheme(id);
          };
          return true;
      },
      setTheme(themeId, seq = 0){
          themeSelector.setLocalTheme([themeId], seq);
          window.location.reload();
          this.scheduleRerender();
      },
      html(attrs, state){
            return [h('div', {attributes: {"class": "switcher keep"}}, icon)];
      }
  });
  
  api.decorateWidget('header-buttons:after', (helper)=>{
    const showExtraInfo = helper.attrs.topic;
    if(!showExtraInfo) {
        return [helper.widget.attach('header-theme-selector')];
      }
  });
</script>

It disappears because the code tells it to with !showExtraInfo (showExtraInfo is the scrolled state of the header):

  if(!showExtraInfo) {
        return [helper.widget.attach('header-theme-selector')];
      }

If you change that entire api.decorateWidget block to:

api.decorateWidget('header-buttons:after', (helper)=>{
  return [helper.widget.attach('header-theme-selector')];  
});

Then it should continue to appear even when scrolled.

2 Likes

Darn I’m feeling stupid now, I spent way too long staring at that. What I get for trying to tweak some of your code! Thanks a lot, have a nice day :grin:

1 Like