Pick top N tags from posts

This commit is contained in:
Nick Pegg 2017-10-11 21:35:19 -07:00
parent 2446ec7f95
commit b696005d89

View file

@ -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 = (
<ul>
{this.state.topTags.map(tag => (
<ListLink icon="tag" key={tag} name={tag} href={"/tag/" + tag} />
))}
</ul>
);
let tags = "";
if (this.state.topTags.length > 0) {
tags = (
<div>
<h5 className="nav-header">Top Tags</h5>
<ul>
{this.state.topTags.map(tag => (
<ListLink icon="tag" key={tag} name={tag} href={"/tag/" + tag} />
))}
</ul>
</div>
);
}
return (
<Row>
<h5 className="nav-header">Top Tags</h5>
{ tags }
</Row>
);