Custom Top Navigation Links

I can’t say I’ve found an ideal solution, but I found what the problem was for me.

The problem can be found here

Specifically, this part:

    api.modifyClass("component:navigation-item", {
      pluginId: 'discourse-nav-links-component',
      active: Ember.computed("contentFilterMode", "filterMode", function() {
        let contentFilterMode = this.get("content").get("filterMode");

        if (window.location.pathname === location) {
          return contentFilterMode === filter;
        } else {
          return this._super(contentFilterMode, this.get("filterMode"));
        }
      })
    });

It looks like this sets the “active” on each navigation link. Frankly, the logic of how it decides and what all these variables are is pretty opaque to me. But the problem is here:

        if (window.location.pathname === location) {
          return contentFilterMode === filter;
        } else {
          return this._super(contentFilterMode, this.get("filterMode"));
        }

To me, this is checking if the page URL is the same as the location of the nav bar URL, and if so it returns the result of contentFilterMode === filter, both variables being a bit unclear to me. If the condition fails, it looks like it just runs the regular logic of whether something should be marked as active (which is why my non-custom links seem to work fine). The problem is that while this code properly runs once per navigation link, the location variable always seems to be “categories” so the if statement is always false for custom links. Furthermore, even if I fix the “location” variable by replacing it with this.get("content").href, the return value is also always false because the filter variable is also always set to “categories”.

Normally I’d just do a PR to fix this, but the actual root problem still eludes me. I have come up with a workaround that works for me but slightly alters the documented functionality of this component so I’d rather not PR it. I think there will be edge cases where it doesn’t work also, like if your hompage is set to /latest

    api.modifyClass("component:navigation-item", {
      pluginId: 'discourse-nav-links-component',
      active: Ember.computed("contentFilterMode", "filterMode", function() {
        return window.location.pathname.includes(this.get("content").href);
      })
    });

Basically it just checks if the current URL includes the nav bar URL as a substring. If yes, it highlights it.

4 Likes