Skip to content

Instantly share code, notes, and snippets.

@zzarcon
Last active January 4, 2017 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zzarcon/b5efa0d9377e0718736a326936f05da3 to your computer and use it in GitHub Desktop.
Save zzarcon/b5efa0d9377e0718736a326936f05da3 to your computer and use it in GitHub Desktop.
component: styles + allow deletion
/** @jsx h */
import 'skatejs-web-components';
import { Component, h, prop } from 'skatejs';
import styles from './styles';
class SKTags extends Component {
static props = {
delimiter: prop.string({attribute: true, default: ' '}),
tags: prop.array({attribute: true}),
deletion: prop.boolean({attribute: true}),
styles: prop.string({attribute: true})
}
renderCallback() {
const tags = this.tags;
const allowDeletion = this.deletion ? 'deletion' : '';
const tagElements = tags.map(t => {
const tagContent = allowDeletion ? <span class='deletion'>{t}</span> : t;
return <span class="tag" onclick={this.onTagClick} >{tagContent}</span>;
});
return <div>
<style>{styles}</style>
<div class='wrapper' onclick={this.onWrapperClick}>
<span class='tags'>{tagElements}</span>
<input type="text" oninput={this.onInput} onkeydown={this.onKeydown} autofocus="true" class= 'input'/>
</div>
</div>
}
onTagClick = e => {
if (e.target.classList.contains('deletion')) {
const childs = Array.from(e.currentTarget.parentElement.children);
const index = childs.indexOf(e.currentTarget);
this.removeTag(index);
this.focusInput();
}
}
onWrapperClick = e => {
this.focusInput();
}
focusInput() {
this.shadowRoot.querySelector('.input').focus();
}
onKeydown = e => {
const value = e.target.value;
const isDel = e.keyCode === 8;
if (isDel && value.length <= 0) {
this.removeTag();
}
}
onInput = e => {
const lastChar = e.target.value.substr(-1);
const value = e.target.value.slice(0, -1).trim();
const isDelimiter = lastChar === this.delimiter;
if (value && isDelimiter) {
this.addTag(value);
e.target.value = '';
}
this.adjustInputSize(e.target.value.length);
}
adjustInputSize(textLength) {
const input = this.shadowRoot.querySelector('.input');
const width = (textLength * 10) + 6;
input.style.width = `${width}px`;
}
addTag(value) {
this.tags = this.tags.concat(value);
}
removeTag(index = -1) {
const tags = this.tags.slice();
tags.splice(index, 1);
this.tags = tags;
}
}
customElements.define('sk-tags', SKTags);
@treshugart
Copy link

treshugart commented Jan 2, 2017

Same comments as in https://gist.github.com/zzarcon/cad6e94c103f0f6912e2d269647c38ce#file-index-jsx but wanted to add that deletion should probably be a prop.boolean({ attribute: true }). You'll have to import { prop } from 'skatejs', too.

@zzarcon
Copy link
Author

zzarcon commented Jan 3, 2017

@treshugart done ✅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment