Notes app :)
at main 93 lines 2.5 kB view raw
1 2// Credit: https://css-tricks.com/auto-growing-inputs-textareas/#comment-1787000 3// Please use theirs, not mine. I have modified it for my own purposes. 4const autoWidthTemplate = document.createElement('template'); 5autoWidthTemplate.innerHTML = ` 6 <style> 7 :host { 8 display: inline-block; 9 vertical-align: top; 10 align-items: center; 11 position: relative; 12 } 13 :host::after { 14 width: auto; 15 min-width: 1em; 16 content: attr(data-value) ' '; 17 visibility: hidden; 18 white-space: pre-wrap; 19 font: inherit; 20 pointer-events: none; 21 overflow-wrap: anywhere; 22 touch-action: none; /* these two rules are just in case*/ 23 z-index: -99; /* prevents inputs */ 24 } 25 input { 26 font: inherit; 27 width: 100%; 28 min-width: 6ch; 29 position: absolute; 30 border: 0; 31 padding: 0; /* for iOS */ 32 background: none; 33 } 34 </style> 35 <input size='1'></input> 36`; 37class AutoWidthInput extends HTMLElement { 38 static get formAssociated() { 39 return true; 40 } 41 42 constructor() { 43 super(); 44 this.internals = this.attachInternals(); 45 46 this._shadowRoot = this.attachShadow({ mode: 'open' }); 47 this._shadowRoot.appendChild(autoWidthTemplate.content.cloneNode(true)); 48 this._input = this._shadowRoot.querySelector('input'); 49 50 this.value_ = this._input.value; 51 52 } 53 _manageValidity() { 54 const value = this._input.value; 55 const required = this._input.hasAttribute("required"); 56 57 if (value === '' && required) { 58 this.internals.setValidity({ 59 valueMissing: true 60 }, 'This field is required', this._input); 61 } else { 62 this.internals.setValidity({}); 63 } 64 } 65 66 connectedCallback() { 67 this.value = this._input.value; 68 69 this._input.addEventListener('input', (e) => { 70 this.value = this._input.value; 71 }); 72 } 73 74 formResetCallback() { 75 this.value = ""; 76 } 77 get value() { 78 return this._input.value; 79 } 80 set value(v) { 81 this._input.value = v; 82 this.dataset.value = v; 83 this.internals.setFormValue(v); 84 this._manageValidity(); 85 } 86 static get observedAttributes() { 87 return ['placeholder', 'name', 'required']; 88 } 89 attributeChangedCallback(name, oldVal, newVal) { 90 this._input.setAttribute(name, newVal); 91 } 92} 93window.customElements.define('autowidth-input', AutoWidthInput);