|
| 1 | +import Helper from '@ember/component/helper'; |
| 2 | +import { inject as service } from '@ember/service'; |
| 3 | +import IntlService from 'ember-intl/services/intl'; |
| 4 | + |
| 5 | +import { LanguageText } from 'ember-osf-web/models/index-card'; |
| 6 | + |
| 7 | +/** |
| 8 | + * This helper is used to get a locale-appropriate string for a property from a metadata hash. |
| 9 | + * It is used to fetch metadata fields from a index-card's resourceMetadata attribute, but can be used for any |
| 10 | + * hash that contains an array of LangaugeText objects. |
| 11 | + * If the property is not found, the first value in the array is returned, or if the property is found, |
| 12 | + * but there is no locale-appropriate value, the first value in the array is returned. |
| 13 | + * |
| 14 | + * @example |
| 15 | + * ```handlebars |
| 16 | + * {{get-localized-property indexCard.resourceMetadata 'title'}} |
| 17 | + * ``` |
| 18 | + * where `indexCard` is an index-card model instance. |
| 19 | + * @class get-localized-property |
| 20 | + * @param {Object} metadataHash The metadata hash to search for the property |
| 21 | + * @param {String} propertyName The name of the property to search for |
| 22 | + * @return {String} The locale-appropriate string or the first value in the array or 'Not provided' message |
| 23 | + */ |
| 24 | +export default class GetLocalizedPropertyHelper extends Helper { |
| 25 | + @service intl!: IntlService; |
| 26 | + |
| 27 | + compute([metadataHash, propertyName]: [Record<string, LanguageText[]>, string]): string { |
| 28 | + const locale = this.intl.locale; |
| 29 | + const valueOptions = metadataHash?.[propertyName]; |
| 30 | + if (!metadataHash || !valueOptions || valueOptions.length === 0) { |
| 31 | + return this.intl.t('helpers.get-localized-property.not-provided'); |
| 32 | + } |
| 33 | + |
| 34 | + const index = valueOptions.findIndex((valueOption: LanguageText) => valueOption['@language'] === locale); |
| 35 | + if (index === -1) { |
| 36 | + return valueOptions[0]['@value']; |
| 37 | + } |
| 38 | + return valueOptions[index]['@value']; |
| 39 | + } |
| 40 | +} |
0 commit comments