jetpack
/
jetpack_vendor
/
automattic
/
jetpack-forms
/
src
/
modules
/
field-rating
Last commit date
helpers.js
6 months ago
view.js
6 months ago
view.js
38 lines
| 1 | import { store, getContext, getElement } from '@wordpress/interactivity'; |
| 2 | import { renderRatingIconsHtml } from '../../blocks/field-rating/rating-icons.js'; |
| 3 | // Re-export helpers for use by other modules. |
| 4 | export { getRating, isRatingValue, getRatingDisplayValue } from './helpers.js'; |
| 5 | |
| 6 | const NAMESPACE = 'jetpack/form'; |
| 7 | |
| 8 | store( NAMESPACE, { |
| 9 | callbacks: { |
| 10 | watchRatingIcons() { |
| 11 | const { ref } = getElement(); |
| 12 | const context = getContext(); |
| 13 | |
| 14 | // Try to get rating data from context (AJAX submissions) or data attribute (server-rendered). |
| 15 | let rating = context.submission?.rating; |
| 16 | |
| 17 | // For server-rendered content, read rating data from data attribute. |
| 18 | if ( ! rating && ref?.dataset?.rating ) { |
| 19 | try { |
| 20 | rating = JSON.parse( ref.dataset.rating ); |
| 21 | } catch { |
| 22 | // Invalid JSON, ignore. |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | // If no rating data is available, don't render icons. |
| 27 | if ( ! rating ) { |
| 28 | return; |
| 29 | } |
| 30 | |
| 31 | const { rating: ratingValue, maxRating, iconStyle, screenReaderText } = rating; |
| 32 | |
| 33 | // Render icons using the shared function. |
| 34 | ref.innerHTML = renderRatingIconsHtml( ratingValue, maxRating, iconStyle, screenReaderText ); |
| 35 | }, |
| 36 | }, |
| 37 | } ); |
| 38 |