Skip to content

Commit

Permalink
feat(esl-utils): add provider to default value in attr
Browse files Browse the repository at this point in the history
(cherry picked from commit e482aaf)
  • Loading branch information
nattallius authored and ala-n committed Apr 9, 2024
1 parent a96d5d7 commit f13cc98
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/modules/esl-utils/decorators/attr.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import {identity} from '../misc/functions';
import {identity, resolveProperty} from '../misc/functions';
import {parseString, toKebabCase} from '../misc/format';
import {getAttr, setAttr} from '../dom/attr';

import type {PropertyProvider} from '../misc/functions';
import type {ESLAttributeDecorator} from '../dom/attr';
import type {ESLDomElementTarget} from '../abstract/dom-target';

Expand All @@ -17,7 +18,7 @@ type AttrDescriptor<T = string> = {
/** Use data-* attribute */
dataAttr?: boolean;
/** Default property value. Used if no attribute is present on the element. Empty string by default. */
defaultValue?: T;
defaultValue?: T | PropertyProvider<T>;
/** Parser from attribute value */
parser?: AttrParser<T>;
/** Serializer to transform passed value to attribute value */
Expand All @@ -38,7 +39,9 @@ export const attr = <T = string>(config: AttrDescriptor<T> = {}): ESLAttributeDe

function get(): T | null {
const val = getAttr(this, attrName);
if (val === null && 'defaultValue' in config) return config.defaultValue as T;
if (val === null && 'defaultValue' in config) {
return resolveProperty(config.defaultValue, this) as T;
}
return (config.parser || parseString as AttrParser<any>)(val);
}
function set(value: T): void {
Expand Down
5 changes: 5 additions & 0 deletions src/modules/esl-utils/decorators/test/attr.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ describe('Decorator: attr', () => {
public readonlyField: string | null;
@attr({defaultValue: 'def'})
public defField: string | boolean;
@attr({defaultValue: () => 'test-provider'})
public defProvider: string;
}
customElements.define('test-el-attr', TestElement);
const el = new TestElement();
Expand Down Expand Up @@ -99,6 +101,9 @@ describe('Decorator: attr', () => {
el.defField = false;
expect(el.defField).toBe('def');
expect(el.hasAttribute('def-field')).toBe(false);
expect(el.defProvider).toBe('test-provider');
el.defProvider = '';
expect(el.defProvider).toBe('');
});

afterAll(() => {
Expand Down

0 comments on commit f13cc98

Please sign in to comment.