diff --git a/src/Nav.js b/src/Nav.js index fd38ee2..804e771 100644 --- a/src/Nav.js +++ b/src/Nav.js @@ -69,33 +69,82 @@ class TagNav extends Component { constructor (props) { super(props); + // TODO: fetch this number from config + // Number of top tags to display + this.numTop = 5; + this.state = { - topTags: [ - 'Tag 1', - 'Tag 2', - 'Really long tag', - 'Really really really long tag', - 'Another tag', - ], + topTags: [], } } - topTags () { + fetchTopTags () { + fetch('/site.json') + .then(resp => resp.json()) + .then(blob => { + let counts = new Map(); + + // Count up the tags + blob.posts.forEach(post => { + post.tags.forEach(tag => { + let count = counts.get(tag); + if (count === undefined) { + count = 0; + } + + counts.set(tag, count + 1); + }); + }); + + // Sort the tags + let tags = [...counts.entries()]; + tags.sort(function(t1, t2) { + let tag1 = t1[0]; + let tag2 = t2[0]; + let count1 = t1[1]; + let count2 = t2[1] + + let diff = count2 - count1; + + if (diff !== 0) { + return diff + } else { + // We have a tie, sort by the strings + return tag1.localeCompare(tag2); + } + }); + + // Get just the tag names + tags = tags.map(t => t[0]); + + // Get top N + tags = tags.slice(0, this.numTop); + + this.setState({topTags: tags}); + }); + } + + componentDidMount() { + this.fetchTopTags(); } render() { - // TODO: Populate these tags from the top tags in the post - let tags = ( - - ); + let tags = ""; + if (this.state.topTags.length > 0) { + tags = ( +
+
Top Tags
+ +
+ ); + } return ( -
Top Tags
{ tags }
);