Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat (choice-input): custom input for radio #2243

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/weak-bottles-accept.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@lion/ui': minor
---

Add CustomChoiceGroupMixin and LionRadioWithUserValue
68 changes: 68 additions & 0 deletions docs/components/radio-group/use-cases.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
import { html } from '@mdjs/mdjs-preview';
import '@lion/ui/define/lion-radio-group.js';
import '@lion/ui/define/lion-radio.js';
import '@lion/ui/define/lion-radio-with-user-value.js';
import { LionRadioWithUserValue } from '@lion/ui/radio-group.js';
import { LionCollapsible } from '@lion/ui/collapsible.js';
```

## Model value
Expand Down Expand Up @@ -138,3 +141,68 @@ export const event = ({ shadowRoot }) => html`
<span>Selected dinosaur: <strong id="selectedDinosaur">N/A</strong></span>
`;
```

## Option by user input

You can add an option where user can set the value.

```js preview-story
export const userValue = ({ shadowRoot }) => html`
<lion-radio-group
name="dinosTwo"
label="Favourite dinosaur"
@model-value-changed=${ev =>
(ev.target.parentElement.querySelector('#selectedDinosaurWithUserValue').innerText =
ev.target.modelValue)}
>
<lion-radio label="allosaurus" .choiceValue=${'allosaurus'}></lion-radio>
<lion-radio label="brontosaurus" .choiceValue=${'brontosaurus'}></lion-radio>
<lion-radio label="diplodocus" .choiceValue=${'diplodocus'}></lion-radio>
<lion-radio-with-user-value label="other:"></lion-radio-with-user-value>
</lion-radio-group>
<br />
<span>Selected dinosaur: <strong id="selectedDinosaurWithUserValue">N/A</strong></span>
`;
```

The `user-input` can observe whether it is selected or not by using the `createMutationObserver` class method.

```js preview-story
export const userValueObservingOption = ({ shadowRoot }) => {
class CollapsibleUserInput extends LionCollapsible {
connectedCallback() {
super.connectedCallback();
const observer = LionRadioWithUserValue.createMutationObserver(mutation => {
if (mutation.target.dataset.checked === 'true') {
this.opened = true;
} else {
this.opened = false;
}
});
observer.observe(this.shadowRoot?.host, { attributes: true });
}
}
customElements.define('collapsible-user-input', CollapsibleUserInput);

return html`
<lion-radio-group
name="dinosTwo"
label="Favourite dinosaur"
@model-value-changed=${ev =>
(ev.target.parentElement.querySelector('#selectedDinosaurWithUserValue2').innerText =
ev.target.modelValue)}
>
<lion-radio label="allosaurus" .choiceValue=${'allosaurus'}></lion-radio>
<lion-radio label="brontosaurus" .choiceValue=${'brontosaurus'}></lion-radio>
<lion-radio label="diplodocus" .choiceValue=${'diplodocus'}></lion-radio>
<lion-radio-with-user-value label="other">
<collapsible-user-input slot="user-input">
<input slot="content"></input>
</collapsible-user-input>
</lion-radio-with-user-value>
</lion-radio-group>
<br />
<span>Selected dinosaur: <strong id="selectedDinosaurWithUserValue2">N/A</strong></span>
`;
};
```
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ const ChoiceInputMixinImplementation = superclass =>
<div class="choice-field__label">
<slot name="label"></slot>
</div>
${this._afterLabel()}
<small class="choice-field__help-text">
<slot name="help-text"></slot>
</small>
Expand All @@ -189,6 +190,13 @@ const ChoiceInputMixinImplementation = superclass =>
return nothing;
}

/**
* @protected
*/
_afterLabel() {
return nothing;
}

/**
* @protected
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
import { dedupeMixin } from '@open-wc/dedupe-mixin';
import { html } from 'lit';
import { ChoiceInputMixin } from './ChoiceInputMixin.js';
import { LionInput } from '../../../input/src/LionInput.js';

/**
* @typedef {import('../FormControlMixin.js').HTMLElementWithValue} HTMLElementWithValue
*/

/**
* @param {import('@open-wc/dedupe-mixin').Constructor<import('lit').LitElement>} superclass
*/
const CustomChoiceInputMixinImplementation = superclass =>
class CustomChoiceInputMixin extends ChoiceInputMixin(superclass) {
/** @type {(mutationHandler: (mutation: MutationRecord) => void) => MutationObserver} */
static createMutationObserver = mutationHandler =>
new MutationObserver(mutations => {
const mutation = mutations.find(
({ type, attributeName }) => type === 'attributes' && attributeName === 'data-checked',
);

if (mutation) {
mutationHandler(mutation);
}
});

get slots() {
return {
...super.slots,
'user-input': () => {
const native = document.createElement('input');
native.setAttribute('value', this.choiceValue);

return native;
},
};
}

connectedCallback() {
super.connectedCallback();

this.shadowRoot?.addEventListener('slotchange', e => {
if (/** @type {{ target: HTMLSlotElement | null }} */ (e).target?.name === 'user-input') {
this.__syncChoiceValueToUserValue();
this._listenToUserInput();
if (this._userInputSlotNode) {
/** @type {HTMLElement} */ (this._userInputSlotNode).dataset.checked =
this.checked.toString();
}
}
});
}

/**
* @override
*/
// eslint-disable-next-line class-methods-use-this
_afterLabel() {
return html`<slot name="user-input"></slot>`;
}

/**
* @param {string} [name]
* @param {unknown} [oldValue]
* @param {import('lit').PropertyDeclaration} [options]
* @returns {void}
*/
requestUpdate(name, oldValue, options) {
super.requestUpdate(name, oldValue, options);

if (name === 'checked') {
if (this.checked) {
this._focusToUserInput();
}
if (this._userInputSlotNode) {
/** @type {HTMLElement} */ (this._userInputSlotNode).dataset.checked =
this.checked.toString();
}
}
}

get _userInputNode() {
if (this.__userInputNode === null) {
this._updateUserInput();
}

return this.__userInputNode;
}

_updateUserInput() {
const slot = this._userInputSlotNode;
if (!slot) {
this.__userInputType = null;
this.__userInputNode = null;
return;
}

const nodeIterator = document.createNodeIterator(slot, NodeFilter.SHOW_ELEMENT);

let currentNode = null;
while (currentNode === null) {
currentNode = nodeIterator.nextNode();
if (currentNode instanceof LionInput) {
this.__userInputType = 'lioninput';
this.__userInputNode = currentNode;
return;
}
}

if (slot?.tagName === 'INPUT') {
this.__userInputType = 'native';
this.__userInputNode = /** @type {HTMLInputElement} */ (slot);
return;
}

const inputInsideSlot = slot?.querySelector('input');
if (inputInsideSlot) {
this.__userInputType = 'native';
}

this.__userInputNode = inputInsideSlot;
}

_getUserValue() {
if (this.__userInputType === 'lioninput') {
return /** @type { LionInput } */ (this._userInputNode).modelValue;
}

if (this.__userInputType === 'native') {
return /** @type { HTMLElementWithValue } */ (this._userInputNode).value;
}

return undefined;
}

_listenToUserInput() {
this._listenToUserValue();
this._listenToUserInputFocus();
}

_listenToUserValue() {
this._userInputNode?.addEventListener('input', this.__syncUserValueToChoiceValue.bind(this));
}

_listenToUserInputFocus() {
this._userInputNode?.addEventListener('focus', () => {
this.checked = true;
});
}

_focusToUserInput() {
this._userInputNode?.focus();
}

get _userInputSlotNode() {
return /** @type {HTMLSlotElement | null} */ (
this.shadowRoot?.querySelector('slot[name="user-input"]')
)?.assignedElements()?.[0];
}

__syncUserValueToChoiceValue() {
const userValue = this._getUserValue();

if (userValue !== undefined) {
this._isHandlingUserInput = true;
this.choiceValue = userValue;
this._isHandlingUserInput = false;
}
}

__syncChoiceValueToUserValue() {
if (this.__userInputType === null) {
this._updateUserInput();
}
if (this.__userInputType === 'lioninput') {
// @ts-ignore -- because the _userInputNode is guaranteed to be LionInput when __userInputType is lioninput
this._userInputNode.modelValue = this.choiceValue;
} else if (this.__userInputType === 'native') {
// @ts-ignore -- because the _userInputNode is guaranteed to be input when __userInputType is native
this._userInputNode.setAttribute('value', this.choiceValue);
}
}

/** @type {'native' | 'lioninput' | null} */
__userInputType = null;

/** @type { HTMLElementWithValue | HTMLInputElement | HTMLTextAreaElement | LionInput | null } */
__userInputNode = null;
};

export const CustomChoiceInputMixin = dedupeMixin(CustomChoiceInputMixinImplementation);
Loading
Loading