|
| 1 | +import { JsxChildren } from 'dom-renderer'; |
| 2 | +import { observable } from 'mobx'; |
| 3 | +import { |
| 4 | + attribute, |
| 5 | + component, |
| 6 | + formField, |
| 7 | + observer, |
| 8 | + WebCellProps, |
| 9 | + WebField |
| 10 | +} from 'web-cell'; |
| 11 | + |
| 12 | +export interface RangeInputProps extends WebCellProps<HTMLInputElement> { |
| 13 | + icon?: JsxChildren | ((itemValue: number) => JsxChildren); |
| 14 | +} |
| 15 | + |
| 16 | +export interface RangeInput extends WebField<RangeInputProps> {} |
| 17 | + |
| 18 | +@component({ tagName: 'range-input', mode: 'open' }) |
| 19 | +@formField |
| 20 | +@observer |
| 21 | +export class RangeInput |
| 22 | + extends HTMLElement |
| 23 | + implements WebField<RangeInputProps> |
| 24 | +{ |
| 25 | + @attribute |
| 26 | + @observable |
| 27 | + accessor type = 'range'; |
| 28 | + |
| 29 | + @attribute |
| 30 | + @observable |
| 31 | + accessor min: number | undefined; |
| 32 | + |
| 33 | + @attribute |
| 34 | + @observable |
| 35 | + accessor max: number | undefined; |
| 36 | + |
| 37 | + @attribute |
| 38 | + @observable |
| 39 | + accessor step = 1; |
| 40 | + |
| 41 | + @observable |
| 42 | + accessor icon: RangeInputProps['icon'] | undefined; |
| 43 | + |
| 44 | + connectedCallback() { |
| 45 | + this.classList.add('d-inline-block', 'position-relative'); |
| 46 | + } |
| 47 | + |
| 48 | + handleChange = ({ currentTarget }: Event) => { |
| 49 | + this.value = (currentTarget as HTMLInputElement).value; |
| 50 | + |
| 51 | + this.emit('change'); |
| 52 | + }; |
| 53 | + |
| 54 | + renderItem(index: number) { |
| 55 | + const { icon, step, value } = this; |
| 56 | + const fullValue = step * index; |
| 57 | + const itemValue = Math.max(Math.min(+value - fullValue, step), 0); |
| 58 | + |
| 59 | + return ( |
| 60 | + <li key={index} className="text-center"> |
| 61 | + {typeof icon === 'function' ? icon(itemValue) : icon} |
| 62 | + </li> |
| 63 | + ); |
| 64 | + } |
| 65 | + |
| 66 | + render() { |
| 67 | + const { icon, min, max = icon ? 5 : 100, value = min || 0 } = this; |
| 68 | + |
| 69 | + return ( |
| 70 | + <> |
| 71 | + <link |
| 72 | + rel="stylesheet" |
| 73 | + href="https://unpkg.com/bootstrap@5.3.3/dist/css/bootstrap.min.css" |
| 74 | + /> |
| 75 | + <input |
| 76 | + className={icon ? 'opacity-0' : ''} |
| 77 | + style={{ margin: '0 -0.5rem', cursor: 'pointer' }} |
| 78 | + type="range" |
| 79 | + min={min?.toString()} |
| 80 | + max={max?.toString()} |
| 81 | + value={value?.toString()} |
| 82 | + onChange={this.handleChange} |
| 83 | + /> |
| 84 | + <ol className="list-unstyled user-select-none position-absolute start-0 top-0 w-100 h-100 pe-none d-flex justify-content-around"> |
| 85 | + {Array.from({ length: max }, (_, index) => |
| 86 | + this.renderItem(index) |
| 87 | + )} |
| 88 | + </ol> |
| 89 | + </> |
| 90 | + ); |
| 91 | + } |
| 92 | +} |
0 commit comments