Skip to content

Commit

Permalink
chore(atomic): fix display-if directive for lit components (#4988)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexprudhomme authored Feb 20, 2025
1 parent a8ed5e9 commit d6ef356
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 3 deletions.
53 changes: 53 additions & 0 deletions packages/atomic/src/directives/display-if.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import {html, LitElement} from 'lit';
import {customElement, property} from 'lit/decorators.js';
import {describe, beforeEach, test, expect} from 'vitest';
import {displayIf} from './display-if';

describe('displayIf', () => {
let element: TestElement;

@customElement('test-element')
class TestElement extends LitElement {
@property({type: Boolean, reflect: true}) shouldDisplay = true;

render() {
return html`${displayIf(
this.shouldDisplay,
html`<span id="content">Visible</span>`
)}`;
}
}

beforeEach(() => {
element = document.createElement('test-element') as TestElement;
document.body.appendChild(element);
});

afterEach(() => {
document.body.removeChild(element);
});

test('should not add "atomic-hidden" when the condition is "true"', async () => {
element.shouldDisplay = true;
await element.updateComplete;
expect(element.classList.contains('atomic-hidden')).toBe(false);
});

test('should add "atomic-hidden" when the condition is "false"', async () => {
element.shouldDisplay = false;
await element.updateComplete;
expect(element.classList.contains('atomic-hidden')).toBe(true);
});

test('should render the children when the condition is "true"', async () => {
element.shouldDisplay = true;
await element.updateComplete;
expect(element.shadowRoot?.querySelector('#content')).not.toBeNull();
});

test('should not render the children when the condition is "false"', async () => {
element.shouldDisplay = false;
await element.updateComplete;
expect(element.shadowRoot?.querySelector('#content')).toBeNull();
});
});
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import {LitElement, noChange} from 'lit';
import {directive, Directive, Part, PartType} from 'lit/directive.js';

// TODO: KIT-3973: Add unit tests for this directive.
class DisplayIfDirective extends Directive {
render<T>(_condition: boolean, _children: T) {
return noChange;
Expand All @@ -18,8 +17,8 @@ class DisplayIfDirective extends Directive {
throw new Error('The directive must be applied to a host element.');
}

part.options.host.classList.toggle('atomic-hidden', displayCondition);
if (displayCondition) {
part.options.host.classList.toggle('atomic-hidden', !displayCondition);
if (!displayCondition) {
return;
}
return children;
Expand Down

0 comments on commit d6ef356

Please sign in to comment.