|
| 1 | +import React, {useEffect, useState} from 'react'; |
| 2 | +import { ProgressBar } from '@yoast/components'; |
| 3 | +import getProgressColor from '../helpers/progressColor'; |
| 4 | +import { assessments } from 'yoastseo'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Gets the description progress. |
| 8 | + * |
| 9 | + * @param {string} description The description. |
| 10 | + * @param {string} date The meta description date |
| 11 | + * |
| 12 | + * @returns {Object} The description progress. |
| 13 | + */ |
| 14 | +const getDescriptionProgress = (description, date) => { |
| 15 | + let descriptionLength = description.length; |
| 16 | + /* If the meta description is preceded by a date, two spaces and a hyphen (" - ") are added as well. Therefore, |
| 17 | + three needs to be added to the total length. */ |
| 18 | + if (date !== "" && descriptionLength > 0) { |
| 19 | + descriptionLength += date.length + 3; |
| 20 | + } |
| 21 | + const metaDescriptionLengthAssessment = new assessments.seo.MetaDescriptionLengthAssessment(); |
| 22 | + const score = metaDescriptionLengthAssessment.calculateScore(descriptionLength); |
| 23 | + const maximumLength = metaDescriptionLengthAssessment.getMaximumLength(); |
| 24 | + |
| 25 | + return { |
| 26 | + max: maximumLength, |
| 27 | + actual: descriptionLength, |
| 28 | + score: score, |
| 29 | + }; |
| 30 | +} |
| 31 | + |
| 32 | +const DescriptionProgressBar = ({description = '', date = ''}) => { |
| 33 | + const [descriptionProgress, setDescriptionProgress] = useState({ |
| 34 | + progress: null, |
| 35 | + description: '' |
| 36 | + }); |
| 37 | + |
| 38 | + useEffect(() => { |
| 39 | + setDescriptionProgress(prevState => { |
| 40 | + return { |
| 41 | + ...prevState, ...{ |
| 42 | + progress: getDescriptionProgress(description, date), |
| 43 | + description: description |
| 44 | + } |
| 45 | + } |
| 46 | + }) |
| 47 | + }, [description]); |
| 48 | + |
| 49 | + if (descriptionProgress.progress !== null) { |
| 50 | + return <ProgressBar min={0} max={descriptionProgress.progress.max} value={descriptionProgress.progress.actual} progressColor={getProgressColor(descriptionProgress.progress.score)} /> |
| 51 | + } |
| 52 | + return <></> |
| 53 | +} |
| 54 | + |
| 55 | +export default DescriptionProgressBar; |
0 commit comments