-
Notifications
You must be signed in to change notification settings - Fork 63
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add upvote supports to post (#48)
添加文章点赞的支持。 /kind feature <img width="1106" alt="image" src="https://user-images.githubusercontent.com/21301288/218495333-6363ab53-7511-40fa-8d63-d10d3987cb6b.png"> ```release-note 为文章添加点赞的支持 ```
- Loading branch information
Showing
5 changed files
with
68 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
interface PostUpvote { | ||
upvotedNames: string[]; | ||
init(): void; | ||
upvoted(id: string): boolean; | ||
handleUpvote(name: string): void; | ||
} | ||
|
||
export default (): PostUpvote => ({ | ||
upvotedNames: [], | ||
init() { | ||
this.upvotedNames = JSON.parse(localStorage.getItem("halo.upvoted.post.names") || "[]"); | ||
}, | ||
upvoted(id: string) { | ||
return this.upvotedNames.includes(id); | ||
}, | ||
async handleUpvote(name) { | ||
if (this.upvoted(name)) { | ||
return; | ||
} | ||
|
||
const xhr = new XMLHttpRequest(); | ||
|
||
xhr.open("POST", "/apis/api.halo.run/v1alpha1/trackers/upvote"); | ||
xhr.setRequestHeader("Content-Type", "application/json"); | ||
|
||
xhr.onload = () => { | ||
this.upvotedNames = [...this.upvotedNames, name]; | ||
localStorage.setItem("halo.upvoted.post.names", JSON.stringify(this.upvotedNames)); | ||
|
||
const upvoteNode = document.querySelector('[data-upvote-post-name="' + name + '"]'); | ||
|
||
if (!upvoteNode) { | ||
return; | ||
} | ||
|
||
const upvoteCount = parseInt(upvoteNode.textContent || "0"); | ||
upvoteNode.textContent = upvoteCount + 1 + " 点赞"; | ||
}; | ||
xhr.onerror = function () { | ||
alert("网络请求失败,请稍后再试"); | ||
}; | ||
xhr.send( | ||
JSON.stringify({ | ||
group: "content.halo.run", | ||
plural: "posts", | ||
name: name, | ||
}) | ||
); | ||
}, | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters