shoelace/src/components/textarea/textarea.ts

367 wiersze
12 KiB
TypeScript
Czysty Zwykły widok Historia

2022-08-17 15:37:37 +00:00
import { html } from 'lit';
2021-05-27 21:00:43 +00:00
import { customElement, property, query, state } from 'lit/decorators.js';
2021-09-29 12:40:26 +00:00
import { classMap } from 'lit/directives/class-map.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { live } from 'lit/directives/live.js';
import { defaultValue } from '../../internal/default-value';
2022-03-24 12:01:09 +00:00
import { FormSubmitController } from '../../internal/form';
2022-08-17 15:37:37 +00:00
import ShoelaceElement from '../../internal/shoelace-element';
2022-03-24 12:01:09 +00:00
import { HasSlotController } from '../../internal/slot';
import { watch } from '../../internal/watch';
2021-07-10 00:45:44 +00:00
import styles from './textarea.styles';
import type { ShoelaceFormControl } from '../../internal/shoelace-element';
import type { CSSResultGroup } from 'lit';
2021-02-26 14:09:13 +00:00
/**
Enrich components `@summary` with description from docs (#962) * keep header styles with repositioned description text * `animated-image` move description to component * code style * `avatar` add summary from docs * `badge` add summary from docs * `breadcrumb` add summary from docs * `button` add summary from docs * lead sentence is now part of the header * `button-group` add summary from docs * `card` add summary from docs * `checkbox` add summary from docs * `color-picker` add summary from docs * `details` add summary from docs * `dialog` add summary from docs * `divider` add summary from docs * `drawer` add summary from docs * `dropdown` add summary from docs * `format-bytes` add summary from docs * `format-date` add summary from docs * `format-number` add summary from docs * `icon` add summary from docs * `icon-button` add summary from docs * `image-comparer` add summary from docs * `include` add summary from docs * `input` add summary from docs * `menu` add summary from docs * `menu-item` add summary from docs * `menu-label` add summary from docs * `popup` add summary from docs * `progressbar` add summary from docs * `progress-ring` add summary from docs * `radio` add summary from docs * `radio-button` add summary from docs * `range` add summary from docs * `rating` add summary from docs * `relative-time` add summary from docs * `select` add summary from docs * `skeleton` add summary from docs * `spinner` add summary from docs * `split-panel` add summary from docs * `switch` add summary from docs * `tab-group` add summary from docs * `tag` add summary from docs * `textarea` add summary from docs * `tooltip` add summary from docs * `visually-hidden` add summary from docs * `animation` add summary from docs * `breadcrumb-item` add summary from docs * `mutation-observer` add summary from docs * `radio-group` add summary from docs * `resize-observer` add summary from docs * `tab` add summary from docs * `tab-panel` add summary from docs * `tree` add summary from docs * `tree-item` add summary from docs * remove `title` for further usage of `Sl` classnames in docs * revert: use markdown parser for component summary
2022-10-21 13:56:35 +00:00
* @summary Textareas collect data from the user and allow multiple lines of text.
*
2021-02-26 14:09:13 +00:00
* @since 2.0
* @status stable
*
2022-08-03 15:06:52 +00:00
* @slot label - The textarea's label. Alternatively, you can use the `label` attribute.
2022-12-06 16:18:14 +00:00
* @slot help-text - Text that describes how to use the input. Alternatively, you can use the `help-text` attribute.
2021-02-26 14:09:13 +00:00
*
2022-12-07 22:40:46 +00:00
* @event sl-blur - Emitted when the control loses focus.
2022-02-12 18:46:27 +00:00
* @event sl-change - Emitted when an alteration to the control's value is committed by the user.
2021-06-25 20:25:46 +00:00
* @event sl-focus - Emitted when the control gains focus.
2022-12-07 22:40:46 +00:00
* @event sl-input - Emitted when the control receives input.
*
2022-12-06 16:18:14 +00:00
* @csspart form-control - The form control that wraps the label, input, and help text.
2022-03-18 21:33:23 +00:00
* @csspart form-control-label - The label's wrapper.
* @csspart form-control-input - The input's wrapper.
* @csspart form-control-help-text - The help text's wrapper.
2022-12-06 16:18:14 +00:00
* @csspart base - The component's base wrapper.
* @csspart textarea - The internal `<textarea>` control.
2021-02-26 14:09:13 +00:00
*/
2021-03-18 13:04:23 +00:00
@customElement('sl-textarea')
export default class SlTextarea extends ShoelaceElement implements ShoelaceFormControl {
static styles: CSSResultGroup = styles;
2021-03-06 17:01:39 +00:00
@query('.textarea__control') input: HTMLTextAreaElement;
// @ts-expect-error -- Controller is currently unused
private readonly formSubmitController = new FormSubmitController(this);
private readonly hasSlotController = new HasSlotController(this, 'help-text', 'label');
2021-02-26 14:09:13 +00:00
private resizeObserver: ResizeObserver;
@state() private hasFocus = false;
@state() invalid = false;
2022-11-30 20:45:21 +00:00
@property() title = ''; // make reactive to pass through
2021-03-06 17:01:39 +00:00
2022-12-06 16:18:14 +00:00
/** The name of the textarea, submitted as a name/value pair with form data. */
@property() name = '';
2021-02-26 14:09:13 +00:00
2022-12-06 16:18:14 +00:00
/** The current value of the textarea, submitted as a name/value pair with form data. */
2021-07-01 00:04:46 +00:00
@property() value = '';
2021-02-26 14:09:13 +00:00
2022-12-06 16:18:14 +00:00
/** The textarea's size. */
@property({ reflect: true }) size: 'small' | 'medium' | 'large' = 'medium';
2021-09-25 02:28:14 +00:00
/** Draws a filled textarea. */
@property({ type: Boolean, reflect: true }) filled = false;
2022-12-06 16:18:14 +00:00
/** The textarea's label. If you need to display HTML, use the `label` slot instead. */
@property() label = '';
2021-02-26 14:09:13 +00:00
2022-12-06 16:18:14 +00:00
/** The textarea's help text. If you need to display HTML, use the `help-text` slot instead. */
2021-07-01 00:04:46 +00:00
@property({ attribute: 'help-text' }) helpText = '';
2021-02-26 14:09:13 +00:00
2022-12-06 16:18:14 +00:00
/** Placeholder text to show as a hint when the input is empty. */
@property() placeholder = '';
2021-02-26 14:09:13 +00:00
/** The number of rows to display by default. */
2021-07-01 00:04:46 +00:00
@property({ type: Number }) rows = 4;
2021-02-26 14:09:13 +00:00
/** Controls how the textarea can be resized. */
2021-03-06 17:01:39 +00:00
@property() resize: 'none' | 'vertical' | 'auto' = 'vertical';
2021-02-26 14:09:13 +00:00
/** Disables the textarea. */
2021-07-01 00:04:46 +00:00
@property({ type: Boolean, reflect: true }) disabled = false;
2021-02-26 14:09:13 +00:00
/** Makes the textarea readonly. */
2021-07-01 00:04:46 +00:00
@property({ type: Boolean, reflect: true }) readonly = false;
2021-02-26 14:09:13 +00:00
/** The minimum length of input that will be considered valid. */
2021-03-06 17:01:39 +00:00
@property({ type: Number }) minlength: number;
2021-02-26 14:09:13 +00:00
/** The maximum length of input that will be considered valid. */
2021-03-06 17:01:39 +00:00
@property({ type: Number }) maxlength: number;
2021-02-26 14:09:13 +00:00
/** Makes the textarea a required field. */
2021-07-01 00:04:46 +00:00
@property({ type: Boolean, reflect: true }) required = false;
2021-02-26 14:09:13 +00:00
2022-12-06 16:18:14 +00:00
/** Controls whether and how text input is automatically capitalized as it is entered by the user. */
2021-11-17 14:22:41 +00:00
@property() autocapitalize: 'off' | 'none' | 'on' | 'sentences' | 'words' | 'characters';
2021-02-26 14:09:13 +00:00
2022-12-06 16:18:14 +00:00
/** Indicates whether the browser's autocorrect feature is on or off. */
2021-03-06 17:01:39 +00:00
@property() autocorrect: string;
2021-02-26 14:09:13 +00:00
2022-12-06 16:18:14 +00:00
/**
* Specifies what permission the browser has to provide assistance in filling out form field values. Refer to
* [this page on MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete) for available values.
*/
2021-03-06 17:01:39 +00:00
@property() autocomplete: string;
2021-02-26 14:09:13 +00:00
2022-12-06 16:18:14 +00:00
/** Indicates that the input should receive focus on page load. */
2021-03-06 17:01:39 +00:00
@property({ type: Boolean }) autofocus: boolean;
2021-02-26 14:09:13 +00:00
2022-12-06 16:18:14 +00:00
/** Used to customize the label or icon of the Enter key on virtual keyboards. */
2022-04-04 13:47:44 +00:00
@property() enterkeyhint: 'enter' | 'done' | 'go' | 'next' | 'previous' | 'search' | 'send';
2021-02-26 14:09:13 +00:00
/** Enables spell checking on the textarea. */
2022-12-08 19:42:04 +00:00
@property({
type: Boolean,
converter: {
// Allow "true|false" attribute values but keep the property boolean
fromAttribute: value => (!value || value === 'false' ? false : true),
toAttribute: value => (value ? 'true' : 'false')
}
})
spellcheck = true;
2021-02-26 14:09:13 +00:00
2022-12-06 16:18:14 +00:00
/**
* Tells the browser what type of data will be entered by the user, allowing it to display the appropriate virtual
* keyboard on supportive devices.
*/
2021-03-06 17:01:39 +00:00
@property() inputmode: 'none' | 'text' | 'decimal' | 'numeric' | 'tel' | 'search' | 'email' | 'url';
2022-12-06 16:18:14 +00:00
/** The default value of the form control. Primarily used for resetting the form control. */
@defaultValue() defaultValue = '';
2021-03-06 17:01:39 +00:00
connectedCallback() {
super.connectedCallback();
this.resizeObserver = new ResizeObserver(() => this.setTextareaHeight());
2021-02-26 14:09:13 +00:00
this.updateComplete.then(() => {
2021-06-02 12:47:55 +00:00
this.setTextareaHeight();
this.resizeObserver.observe(this.input);
});
2021-02-26 14:09:13 +00:00
}
2021-06-16 12:42:02 +00:00
firstUpdated() {
this.invalid = !this.input.checkValidity();
}
2021-03-06 17:01:39 +00:00
disconnectedCallback() {
super.disconnectedCallback();
2021-02-26 14:09:13 +00:00
this.resizeObserver.unobserve(this.input);
}
/** Sets focus on the textarea. */
focus(options?: FocusOptions) {
2021-02-26 14:09:13 +00:00
this.input.focus(options);
}
/** Removes focus from the textarea. */
blur() {
2021-02-26 14:09:13 +00:00
this.input.blur();
}
/** Selects all the text in the textarea. */
select() {
this.input.select();
2021-02-26 14:09:13 +00:00
}
2021-05-29 14:55:56 +00:00
/** Gets or sets the textarea's scroll position. */
scrollPosition(position?: { top?: number; left?: number }): { top: number; left: number } | undefined {
2022-01-19 14:37:07 +00:00
if (position) {
if (typeof position.top === 'number') this.input.scrollTop = position.top;
if (typeof position.left === 'number') this.input.scrollLeft = position.left;
2022-08-17 15:37:37 +00:00
return undefined;
2021-05-29 14:55:56 +00:00
}
return {
top: this.input.scrollTop,
left: this.input.scrollTop
};
}
2021-02-26 14:09:13 +00:00
/** Sets the start and end positions of the text selection (0-based). */
setSelectionRange(
selectionStart: number,
selectionEnd: number,
selectionDirection: 'forward' | 'backward' | 'none' = 'none'
) {
this.input.setSelectionRange(selectionStart, selectionEnd, selectionDirection);
2021-02-26 14:09:13 +00:00
}
/** Replaces a range of text with a new string. */
setRangeText(
replacement: string,
2022-12-07 22:40:46 +00:00
start?: number,
end?: number,
selectMode?: 'select' | 'start' | 'end' | 'preserve'
2021-02-26 14:09:13 +00:00
) {
2022-12-07 22:40:46 +00:00
// @ts-expect-error - start, end, and selectMode are optional
2021-02-26 14:09:13 +00:00
this.input.setRangeText(replacement, start, end, selectMode);
if (this.value !== this.input.value) {
this.value = this.input.value;
}
if (this.value !== this.input.value) {
this.value = this.input.value;
this.setTextareaHeight();
}
}
/** Checks for validity but does not show the browser's validation message. */
checkValidity() {
return this.input.checkValidity();
}
2021-02-26 14:09:13 +00:00
/** Checks for validity and shows the browser's validation message if the control is invalid. */
reportValidity() {
return this.input.reportValidity();
}
/** Sets a custom validation message. If `message` is not empty, the field will be considered invalid. */
setCustomValidity(message: string) {
this.input.setCustomValidity(message);
this.invalid = !this.input.checkValidity();
}
2021-06-25 23:22:05 +00:00
handleBlur() {
this.hasFocus = false;
2022-09-16 20:21:40 +00:00
this.emit('sl-blur');
2021-02-26 14:09:13 +00:00
}
2021-06-25 23:22:05 +00:00
handleChange() {
2021-02-26 14:09:13 +00:00
this.value = this.input.value;
this.setTextareaHeight();
2022-09-16 20:21:40 +00:00
this.emit('sl-change');
2021-02-26 14:09:13 +00:00
}
@watch('disabled', { waitUntilFirstUpdate: true })
2021-06-25 23:22:05 +00:00
handleDisabledChange() {
// Disabled form controls are always valid, so we need to recheck validity when the state changes
this.input.disabled = this.disabled;
this.invalid = !this.input.checkValidity();
2021-02-26 14:09:13 +00:00
}
handleFocus() {
this.hasFocus = true;
2022-09-16 20:21:40 +00:00
this.emit('sl-focus');
2021-02-26 14:09:13 +00:00
}
2021-06-25 23:22:05 +00:00
handleInput() {
this.value = this.input.value;
2022-09-16 20:21:40 +00:00
this.emit('sl-input');
2021-06-25 23:22:05 +00:00
}
@watch('rows', { waitUntilFirstUpdate: true })
2021-03-06 19:39:48 +00:00
handleRowsChange() {
this.setTextareaHeight();
2021-03-06 19:39:48 +00:00
}
@watch('value', { waitUntilFirstUpdate: true })
2021-03-06 19:39:48 +00:00
handleValueChange() {
this.input.value = this.value; // force a sync update
this.invalid = !this.input.checkValidity();
2022-09-16 19:11:02 +00:00
this.updateComplete.then(() => this.setTextareaHeight());
2021-03-06 19:39:48 +00:00
}
2021-02-26 14:09:13 +00:00
setTextareaHeight() {
if (this.resize === 'auto') {
this.input.style.height = 'auto';
this.input.style.height = `${this.input.scrollHeight}px`;
} else {
(this.input.style.height as string | undefined) = undefined;
2021-02-26 14:09:13 +00:00
}
}
render() {
const hasLabelSlot = this.hasSlotController.test('label');
const hasHelpTextSlot = this.hasSlotController.test('help-text');
2022-03-08 22:34:17 +00:00
const hasLabel = this.label ? true : !!hasLabelSlot;
const hasHelpText = this.helpText ? true : !!hasHelpTextSlot;
return html`
<div
part="form-control"
class=${classMap({
'form-control': true,
'form-control--small': this.size === 'small',
'form-control--medium': this.size === 'medium',
'form-control--large': this.size === 'large',
'form-control--has-label': hasLabel,
'form-control--has-help-text': hasHelpText
})}
>
2022-03-18 21:33:23 +00:00
<label
part="form-control-label"
class="form-control__label"
for="input"
aria-hidden=${hasLabel ? 'false' : 'true'}
>
2022-03-08 22:34:17 +00:00
<slot name="label">${this.label}</slot>
</label>
2022-03-18 21:33:23 +00:00
<div part="form-control-input" class="form-control-input">
2022-03-08 22:34:17 +00:00
<div
part="base"
class=${classMap({
textarea: true,
'textarea--small': this.size === 'small',
'textarea--medium': this.size === 'medium',
'textarea--large': this.size === 'large',
'textarea--standard': !this.filled,
'textarea--filled': this.filled,
'textarea--disabled': this.disabled,
'textarea--focused': this.hasFocus,
2022-05-11 14:16:37 +00:00
'textarea--empty': !this.value,
2022-03-08 22:34:17 +00:00
'textarea--invalid': this.invalid,
'textarea--resize-none': this.resize === 'none',
'textarea--resize-vertical': this.resize === 'vertical',
'textarea--resize-auto': this.resize === 'auto'
})}
>
<textarea
part="textarea"
id="input"
class="textarea__control"
title=${this.title /* An empty title prevents browser validation tooltips from appearing on hover */}
2022-03-08 22:34:17 +00:00
name=${ifDefined(this.name)}
.value=${live(this.value)}
?disabled=${this.disabled}
?readonly=${this.readonly}
?required=${this.required}
placeholder=${ifDefined(this.placeholder)}
rows=${ifDefined(this.rows)}
minlength=${ifDefined(this.minlength)}
maxlength=${ifDefined(this.maxlength)}
autocapitalize=${ifDefined(this.autocapitalize)}
autocorrect=${ifDefined(this.autocorrect)}
?autofocus=${this.autofocus}
spellcheck=${ifDefined(this.spellcheck)}
2022-04-04 13:47:44 +00:00
enterkeyhint=${ifDefined(this.enterkeyhint)}
2022-03-08 22:34:17 +00:00
inputmode=${ifDefined(this.inputmode)}
aria-describedby="help-text"
@change=${this.handleChange}
@input=${this.handleInput}
@focus=${this.handleFocus}
@blur=${this.handleBlur}
></textarea>
</div>
</div>
2022-12-02 22:03:59 +00:00
<slot
name="help-text"
2022-03-18 21:33:23 +00:00
part="form-control-help-text"
2022-03-08 22:34:17 +00:00
id="help-text"
class="form-control__help-text"
aria-hidden=${hasHelpText ? 'false' : 'true'}
2021-02-26 14:09:13 +00:00
>
2022-12-02 22:03:59 +00:00
${this.helpText}
</slot>
2022-03-08 22:34:17 +00:00
</div>
`;
2021-02-26 14:09:13 +00:00
}
}
2021-03-12 14:09:08 +00:00
declare global {
interface HTMLElementTagNameMap {
'sl-textarea': SlTextarea;
}
}