diff --git a/src/trait_manager/index.ts b/src/trait_manager/index.ts index f1c1036a3..d96d5388d 100644 --- a/src/trait_manager/index.ts +++ b/src/trait_manager/index.ts @@ -11,6 +11,7 @@ import TraitColorView from './view/TraitColorView'; import TraitButtonView from './view/TraitButtonView'; import EditorModel from '../editor/model/Editor'; import Component from '../dom_components/model/Component'; +import Trait from './model/Trait'; export const evAll = 'trait'; export const evPfx = `${evAll}:`; @@ -89,11 +90,14 @@ export default class TraitManager extends Module void; } +type TraitOption = { + id: string; + label?: string; +}; + /** * @typedef Trait * @property {String} id Trait id, eg. `my-trait-id`. @@ -187,6 +193,55 @@ export default class Trait extends Model { } } + /** + * Get default value. + */ + getDefault() { + return this.get('default'); + } + + /** + * Get trait options. + */ + getOptions(): TraitOption[] { + return (this.get('options') as TraitOption[]) || []; + } + + /** + * Get current selected option or by id. + * @param {String} [id] Option id. + * @returns {Object | null} + */ + getOption(id?: string): TraitOption | undefined { + const idSel = isDef(id) ? id : this.getValue(); + return this.getOptions().filter(o => this.getOptionId(o) === idSel)[0]; + } + + /** + * Get the option id from the option object. + * @param {Object} option Option object + * @returns {String} Option id + */ + getOptionId(option: TraitOption) { + return option.id || (option as any).value; + } + + /** + * Get option label. + * @param {String|Object} id Option id or the option object + * @param {Object} [opts={}] Options + * @param {Boolean} [opts.locale=true] Use the locale string from i18n module + * @returns {String} Option label + */ + getOptionLabel(id: string | TraitOption, opts: { locale?: boolean } = {}): string { + const { locale = true } = opts; + const option = (isString(id) ? this.getOption(id) : id)!; + const optId = this.getOptionId(option); + const label = option.label || (option as any).name || optId; + const propName = this.getName(); + return (locale && this.em?.t(`traitManager.traits.options.${propName}.${optId}`)) || label; + } + props() { return this.attributes; }