|
| 1 | +import _isEmpty from "lodash/isEmpty"; |
| 2 | +import { useEffect, useState } from "react"; |
| 3 | +import { FormattedMessage } from "react-intl"; |
| 4 | +import { fetchTopTags } from "../../services/Challenge/TopTags"; |
| 5 | +import messages from "./Messages"; |
| 6 | + |
| 7 | +/** |
| 8 | + * TopTagSuggestions displays the most popular tags for a challenge |
| 9 | + * and allows users to quickly add them to their task |
| 10 | + * |
| 11 | + * @param {Object} props - Component props |
| 12 | + * @param {number} props.challengeId - The id of the challenge to fetch top tags for |
| 13 | + * @param {string} props.currentTags - Comma-separated string of current tags |
| 14 | + * @param {Function} props.onAddTag - Callback function when a tag is clicked |
| 15 | + */ |
| 16 | +const TopTagSuggestions = (props) => { |
| 17 | + const [loading, setLoading] = useState(true); |
| 18 | + const [tags, setTags] = useState([]); |
| 19 | + |
| 20 | + useEffect(() => { |
| 21 | + if (props.challengeId) { |
| 22 | + setLoading(true); |
| 23 | + fetchTopTags(props.challengeId) |
| 24 | + .then((topTags) => { |
| 25 | + if (topTags) { |
| 26 | + setTags(topTags); |
| 27 | + } |
| 28 | + setLoading(false); |
| 29 | + }) |
| 30 | + .catch(() => setLoading(false)); |
| 31 | + } |
| 32 | + }, [props.challengeId]); |
| 33 | + |
| 34 | + // Don't render if there are no tags |
| 35 | + if (!loading && _isEmpty(tags)) { |
| 36 | + return null; |
| 37 | + } |
| 38 | + |
| 39 | + // Parse current tags to avoid duplicates |
| 40 | + const currentTagsArray = props.currentTags ? props.currentTags.split(/,\s*/) : []; |
| 41 | + |
| 42 | + return ( |
| 43 | + <div className="mr-mt-4"> |
| 44 | + {loading ? ( |
| 45 | + <span className="mr-text-sm mr-text-grey-light"> |
| 46 | + <FormattedMessage {...messages.loading} /> |
| 47 | + </span> |
| 48 | + ) : ( |
| 49 | + <> |
| 50 | + <div className="mr-text-sm mr-text-grey-light mr-mb-1"> |
| 51 | + <FormattedMessage {...messages.topTagsLabel} /> |
| 52 | + </div> |
| 53 | + <div className="mr-flex mr-flex-wrap"> |
| 54 | + {tags.map((tag) => { |
| 55 | + const isAlreadyAdded = currentTagsArray.includes(tag.name); |
| 56 | + |
| 57 | + return ( |
| 58 | + <button |
| 59 | + key={tag.id} |
| 60 | + className={`mr-button mr-button--small mr-py-1 mr-text-xs mr-mr-2 mr-mb-2 ${ |
| 61 | + isAlreadyAdded ? "mr-button--disabled" : "" |
| 62 | + }`} |
| 63 | + onClick={() => !isAlreadyAdded && props.onAddTag(tag.name)} |
| 64 | + disabled={isAlreadyAdded} |
| 65 | + title={isAlreadyAdded ? "Already added" : `Add tag: ${tag.name}`} |
| 66 | + > |
| 67 | + <span>{tag.name}</span> |
| 68 | + </button> |
| 69 | + ); |
| 70 | + })} |
| 71 | + </div> |
| 72 | + </> |
| 73 | + )} |
| 74 | + </div> |
| 75 | + ); |
| 76 | +}; |
| 77 | + |
| 78 | +export default TopTagSuggestions; |
0 commit comments