HStack
Last updated
Last updated
๐ฐ CSS โฉ Layout โฉ System โฉ
ๅจๆ็ๆ๏ผๅฆๆ HStack ๅ ง้จๆๅๅ ไปถ้่ฆใๆฉซๅๆดๅฑใ๏ผๅฏไปฅไฝฟ็จ flex: 1ใ
// 0.0.5 + helpers
import {attr} from './helpers.mjs';
// HStack
export default class HStack extends HTMLElement {
// this.render()
render() {
const {spacing, alignment} = this;
const attrs = [spacing, alignment].filter(attr => !!attr); // remove empty attributes
// if no specific settings, use default values and return.
if (attrs.length === 0) return;
// style ID for this element
const styleID = `hstack-${attrs.join('_')}`;
// put HStack style ID in "data-xxx" attribute
this.dataset.style = styleID;
// if no such <style> with this ID, create it.
if (!document.getElementById(styleID)) {
// create <style>
let style = document.createElement('style');
style.id = styleID;
// concate css rules
const rules = [
// spacing between items
`${spacing ? `[data-style="${styleID}"] > * + :not(i-spacer) {margin-left: ${spacing};}` : ''}`,
// stack alignmentment
`${alignment ? `[data-style="${styleID}"] {align-items: ${alignment};}` : ''}`,
]
.filter(rule => rule !== '') // remove empty rules
.join('\n');
style.innerHTML = `${rules}`;
document.head.appendChild(style);
}
}
// -------------- getters/setters -----------------
// this.spacing (= '30px')
get spacing() { return attr(this, 'spacing') }
set spacing(val) { return attr(this, 'spacing', val) }
// this.alignment (= 'flex-start' | 'center' | 'flex-end')
get alignment() { return attr(this, 'alignment') }
set alignment(val) { return attr(this, 'alignment', val) }
// -------------- lifecycle callbacks ----------------
// โญ connected to document
connectedCallback() {
this.render();
}
// โญ observed attributes
static get observedAttributes() {
return ['spacing', 'alignment'];
}
// re-renders whenever one of attributes changes.
attributeChangedCallback() {
this.render();
}
}
// โญ๏ธ register <hstack->
customElements.get('hstack-') || customElements.define('hstack-', HStack);
/* 0.1.0 - align-items: center -> stretch */
/* hstack */
hstack- {
display: flex;
flex-direction: row;
align-items: stretch;
}
/* hstack ๅ
ง้ spacer ็้้ */
hstack- > * + :not(spacer-) {
margin-left: var(--spacing);
}
/*
ๅฆๆๅชๆๅฏไธไธๅ hstack๏ผๅฐฑ่ฎๅฎ็ๅฏฌๅบฆ็บ 100%๏ผ
้ๆจฃ่ฃก้ข็ spacer ๆ่ฝ็ผ็ไฝ็จใ
*/
hstack-:only-child {
width: 100%;
}
replit โฉ layout 0.1.0 - align-items: center โ stretch