How to Form Tables Correctly When HTML Template Components are Separated? - lit

When building tables in Lit, sometimes I need to generate different parts of a table in different parts of the code. But when I put everything together, the table does not look the same as if it were declared all in one place.
See this playground for an example of the same table that's assembled two different ways. Is there any way I can make the "two halves" table look the same as the first, while still creating the elements in separate html`` blocks?
I tried creating a table in two different ways (see playground), I expected it to be the same resulting table in both instances. What actually happened is that they looked different, and I want to know why/how to correct this.

Lit does not do string concatenation and each html tag function results in a cached Template element which can be efficiently rendered. This means that each of your html tags get implicitly closed by the browser's HTML parser.
E.g.: html`<table>...` is parsed by the browser into: html`<table>...</table>`. From lit.dev documentation on "Well-formed HTML": https://lit.dev/docs/templates/expressions/#well-formed-html
Lit templates must be well-formed HTML. The templates are parsed by the browser's built-in HTML parser before any values are interpolated. Follow these rules for well-formed templates:
Templates should not contain unclosed elements—they will be closed by the HTML parser.
Therefore instead of the following structure:
// Does not work correctly - do not copy this. For demonstration purposes.
const start = html`<table>`;
const content = html`content`;
const end = html`</table>`;
const result = [start, content, end];
return html`${result}`;
// This would render as: <table></table>content<table></table>
Consider the following structure instead where each html tag function is well formed HTML:
const tableFrame = (content) => html`<table>${content}</table>`;
const content = html`content`;
// Pass the content template result into the table frame.
return tableFrame(content);
The following is your code from the playground example restructured in this way:
<script type="module">
import {LitElement, html, css} from "https://cdn.jsdelivr.net/gh/lit/dist#2/core/lit-core.min.js";
class TableExample extends LitElement {
static styles = css`table, th, td { border: 1px solid black; }`;
generateTables() {
const tables = [];
const tableRow1 = html`
<tr>
<td rowspan=2>0</td>
<td>1</td>
</tr>`;
const tableRow2 = html`
</tr>
<td>2</td>
</tr>`;
const table1 = html`
<table>
<tr>
<td rowspan=2>0</td>
<td>1</td>
</tr>
</tr>
<td>2</td>
</tr>
</table>
`;
const tableFrame = (content) => html`<table>${content}</table>`;
// Full table
tables.push(table1);
tables.push(html`<br />`);
// Use tableFrame with custom content.
tables.push(tableFrame(html`<tr><td>Custom Content</td></tr>`));
tables.push(html`<br />`);
// Use tableFrame with the two rows defined earlier.
tables.push(tableFrame([tableRow1, tableRow2]));
return tables;
}
render() {
return this.generateTables();
}
}
customElements.define('table-example', TableExample)
</script>
<table-example></table-example>
As an additional reference the documentation on Templates: https://lit.dev/docs/templates/expressions/#templates

Related

How to bind string properties from object in repeat.for

I have a list of arrays in a table displayed using repeat.for. I need to display tr row in blue color when "receiving.supplier === Scrap Separated" and blue color row when the result is "receiving.supplier === Scrap Sorted". Is there any way I can do it with if.bind but for String that I got in network tab. Here is my network and code.
I think this is purely a CSS question. You can have CSS rules based on [data-supplier] and assign a different background color based on the value of the supplier property.
The example CSS rules can be as follows.
tr[data-supplier="Scrap Separated"] {
background-color: blue;
}
tr[data-supplier="Scrap Sorted"] {
background-color: green;
}
And then bind the data-supplier property in the markup.
<tr data-supplier="${recieving.supplier}">
...
</tr>
Note that you cannot possibly nest div directly under tbody as that will be evicted by browser being non-conformed element as per the expected schema.

html2pdf: overflow:hidden does not seem to work

I have text to output into cells, text might be too long, in this case I'd like the overflow to be simply hidden.
The version tested is html2pdf v. 5.2.2 .
I can't find doc about which CSS is recognised and which is not.
Instead I found in /src/Parsing/Css.php code that seems to imply that "overflow" is recognised at least for values "visible" and "hidden":
case 'overflow':
if (!in_array($val, array('visible', 'hidden'))) {
$val = 'visible';
}
$this->value['overflow'] = $val;
break;
So I tried following test case:
<?php
require __DIR__.'/vendor/autoload.php';
use Spipu\Html2Pdf\Html2Pdf;
$html = <<<EOT
<body>
<style>
.red {
color:red;
width:30px;max-width:30px;
overflow:hidden;
}
.blue {
color:blue;
}
</style>
<table>
<tr>
<td class="red" >totototototototototototototototo</td>
<td class="blue">titi</td>
</tr>
</table>
</body>
</html>
EOT;
$toPdf=false;
if($toPdf) {
$html2pdf = new Html2Pdf();
$html2pdf->writeHTML($html);
$html2pdf->output();
}
else { echo $html; }
I'd like the expected output, as rendered in an html browser.
But html2pdf's output simply ignores the css overflow directive (see captures).
Is there something I'm doing wrong?
Is there a way at all?
I'd like a CSS solution/turnaround if possible, no solution based on a substring truncation (because such solutions will have disastrous results with strings like "WWWMMWMWWM" vs "iiilliilli" for instance, 10 characters each, quite a different width).
I'd be grateful to any solution or any hint towards a solution.
Thanks in advance.
Here under the html output in a browser, and the PDF output made by html2pdf.
overflow:hidden finally seems to work with DIV elements.
But neither display:inline-blocknor float:left do, which would allow side by side DIVs...
A few more tests, and I found my turnaround: a DIV with overflow:hidden in each TD...

binding event listeners to ES6 objects [duplicate]

Do getElementsByClassName (and similar functions like getElementsByTagName and querySelectorAll) work the same as getElementById or do they return an array of elements?
The reason I ask is because I am trying to change the style of all elements using getElementsByClassName. See below.
//doesn't work
document.getElementsByClassName('myElement').style.size = '100px';
//works
document.getElementById('myIdElement').style.size = '100px';
Your getElementById code works since IDs have to be unique and thus the function always returns exactly one element (or null if none was found).
However, the methods
getElementsByClassName,
getElementsByName,
getElementsByTagName, and
getElementsByTagNameNS
return an iterable collection of elements.
The method names provide the hint: getElement implies singular, whereas getElements implies plural.
The method querySelector also returns a single element, and querySelectorAll returns an iterable collection.
The iterable collection can either be a NodeList or an HTMLCollection.
getElementsByName and querySelectorAll are both specified to return a NodeList; the other getElementsBy* methods are specified to return an HTMLCollection, but please note that some browser versions implement this differently.
Both of these collection types don’t offer the same properties that Elements, Nodes, or similar types offer; that’s why reading style off of document.getElements…(…) fails.
In other words: a NodeList or an HTMLCollection doesn’t have a style; only an Element has a style.
These “array-like” collections are lists that contain zero or more elements, which you need to iterate over, in order to access them.
While you can iterate over them similarly to an array, note that they are different from Arrays.
In modern browsers, you can convert these iterables to a proper Array with Array.from; then you can use forEach and other Array methods, e.g. iteration methods:
Array.from(document.getElementsByClassName("myElement"))
.forEach((element) => element.style.size = "100px");
In old browsers that don’t support Array.from or the iteration methods, you can still use Array.prototype.slice.call.
Then you can iterate over it like you would with a real array:
var elements = Array.prototype.slice
.call(document.getElementsByClassName("myElement"));
for(var i = 0; i < elements.length; ++i){
elements[i].style.size = "100px";
}
You can also iterate over the NodeList or HTMLCollection itself, but be aware that in most circumstances, these collections are live (MDN docs, DOM spec), i.e. they are updated as the DOM changes.
So if you insert or remove elements as you loop, make sure to not accidentally skip over some elements or create an infinite loop.
MDN documentation should always note if a method returns a live collection or a static one.
For example, a NodeList offers some iteration methods such as forEach in modern browsers:
document.querySelectorAll(".myElement")
.forEach((element) => element.style.size = "100px");
A simple for loop can also be used:
var elements = document.getElementsByClassName("myElement");
for(var i = 0; i < elements.length; ++i){
elements[i].style.size = "100px";
}
Aside: .childNodes yields a live NodeList and .children yields a live HTMLCollection, so these two getters also need to be handled carefully.
There are some libraries like jQuery which make DOM querying a bit shorter and create a layer of abstraction over “one element” and “a collection of elements”:
$(".myElement").css("size", "100px");
You are using a array as an object, the difference between getElementbyId and
getElementsByClassName is that:
getElementbyId will return an Element object or null if no element with the ID is found
getElementsByClassName will return a live HTMLCollection, possibly of length 0 if no matching elements are found
getElementsByClassName
The getElementsByClassName(classNames) method takes a string that
contains an unordered set of unique space-separated tokens
representing classes. When called, the method must return a live
NodeList object containing all the elements in the document that
have all the classes specified in that argument, having obtained the
classes by splitting a string on spaces. If there are no tokens
specified in the argument, then the method must return an empty
NodeList.
https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#getelementsbyclassname
getElementById
The getElementById() method accesses the first element with the specified id.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
in your code the lines:
1- document.getElementsByClassName('myElement').style.size = '100px';
will NOT work as expected, because the getElementByClassName will return an array, and the array will NOT have the style property, you can access each element by iterating through them.
That's why the function getElementById worked for you, this function will return the direct object. Therefore you will be able to access the style property.
ES6 provides Array.from() method, which creates a new Array instance from an array-like or iterable object.
let boxes = document.getElementsByClassName('box');
setTimeout(() => {
Array.from(boxes).forEach(v => v.style.background = 'green');
console.log(Array.from(boxes));
}, 500);
.box {
width: 50px;
height: 50px;
margin: 5px;
background: blue;
display: inline-block;
}
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>
As you can see inside the code snippet, after using Array.from() function you are then able to manipulate over each element.
The same solution using **`jQuery`**.
$('.box').css({'background':'green'});
.box {
width: 50px;
height: 50px;
margin: 5px;
background: blue;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>
The following description is taken from this page:
The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object.
The NodeList object represents a collection of nodes. The nodes can be
accessed by index numbers. The index starts at 0.
Tip: You can use the length property of the NodeList object to determine the number of elements with a specified class name, then you can loop through all elements and extract the info you want.
So, as a parameter getElementsByClassName would accept a class name.
If this is your HTML body:
<div id="first" class="menuItem"></div>
<div id="second" class="menuItem"></div>
<div id="third" class="menuItem"></div>
<div id="footer"></div>
then var menuItems = document.getElementsByClassName('menuItem') would return a collection (not an array) of the 3 upper <div>s, as they match the given class name.
You can then iterate over this nodes (<div>s in this case) collection with:
for (var menuItemIndex = 0 ; menuItemIndex < menuItems.length ; menuItemIndex ++) {
var currentMenuItem = menuItems[menuItemIndex];
// do stuff with currentMenuItem as a node.
}
Please refer to this post for more on differences between elements and nodes.
In Other Words
document.querySelector() selects only the first one element of the specified selector. So it doesn't spit out an array, it's a single value. Similar to document.getElementById() which fetches ID-elements only, since IDs have to be unique.
document.querySelectorAll() selects all elements with the specified selector and returns them in an array. Similar to document.getElementsByClassName() for classes and document.getElementsByTagName() tags only.
Why use querySelector?
It's used merely for the sole purpose of ease and brevity.
Why use getElement/sBy?*
Faster performance.
Why this performance difference?
Both ways of selection has the purpose of creating a NodeList for further use.
querySelectors generates a static NodeList with the selectors thus it must be first created from scratch.
getElement/sBy* immediately adapts the existing live NodeList of the current DOM.
So, when to use which method it's up to you/your project/your device.
Infos
Demo of all methods
NodeList Documentation
Performance Test
You could get a single element by running
document.querySelector('.myElement').style.size = '100px';
but it's going to work for the first element with class .myElement.
If you would like apply this for all elements with the class I suggest you to use
document.querySelectorAll('.myElement').forEach(function(element) {
element.style.size = '100px';
});
It returns Array-like list.
You make that an Array as example
var el = getElementsByClassName("elem");
el = Array.prototype.slice.call(el); //this line
el[0].appendChild(otherElem);
/*
* To hide all elements with the same class,
* use looping to reach each element with that class.
* In this case, looping is done recursively
*/
const hideAll = (className, i=0) => {
if(!document.getElementsByClassName(className)[i]){ //exits the loop when element of that id does not exist
return;
}
document.getElementsByClassName(className)[i].style.visibility = 'hidden'; //hide element
return hideAll(className, i+1) //loop for the next element
}
hideAll('appBanner') //the function call requires the class name
With any browser supporting ES5+ (any browser basically above IE8) you can use the Array.prototype.forEach method.
Array.prototype.forEach.call(document.getElementsByClassName('answer'), function(el) {
el.style.color= 'red';
});
caniuse source
So I was told that this is a duplicate from my question and I should delete mine, which I will do so I can keep the forum clean and keep the right to make questions.
As I think mine and this question are really different I will point out the answer to mine, so I will complete the knowledge in this page and the information will not be lost.
Question
I have a code in the snippet that has a document.getElementsByClassName("close")[0], what the [0] is doing?
I never seen a square brackets being used in getElementsByClassName for what purpose is it used for?
Also, how can I convert it to jQuery?
Answer
The code in the snippet has a [0] it is actually being used as a array and as it is a 0 it is referring to the first time the appointed class is being used.
Same thing above.
I couldn't really do it and no one answered it. In the part of the code that is refering to event. target I can not use $("#myModal") instead of document.getElementById("myModal"), I think they should equivalent, but in this case the jQuery form substituting the standard one will not result in the desired effect.
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
var modal = document.getElementById("myModal");
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
body {font-family: Arial, Helvetica, sans-serif;}
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<h2>Modal </h2>
<button id="myBtn">Open Modal</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
update
It seems I can't really delete mine question and people are unsatisfied with it, I really don't know what I should do.
Super old school solution:
[].forEach.call(document.getElementsByClassName('myClass'), function (el) {
el.style.size = '100px';
});
An answer for Drenzii's specific case...
You could make a function that will work for any of the word elements and pass in the number of the one you want to transform, like:
// Binds `wordButtons` to an (array-like) HTMLCollection of buttons
const wordButtons = document.getElementsByClassName("word");
// Applies the `slantWord` function to the first word button
slantWord(1);
// Defines the `slantWord` function
function slantWord(wordNumber) {
const index = wordNumber - 1; // Collection index is zero-based
wordButtons[index].style.transform = "rotate(7deg)"; // Transforms the specified button
}
<div class="wordGameContainer">
<button class="word word1">WORD 1</button>
<button class="word word2">WORD 2</button>
<button class="word word3">WORD 3</button>
<button class="word word4">WORD 4</button>
</div>
<div>
<button onclick="moveWord()" class="playButton">PLAY</button>
</div>

Is there a way/workaround to have the slot principle in hyperHTML without using Shadow DOM?

I like the simplicity of hyperHtml and lit-html that use 'Tagged Template Literals' to only update the 'variable parts' of the template. Simple javascript and no need for virtual DOM code and the recommended immutable state.
I would like to try using custom elements with hyperHtml as simple as possible
with support of the <slot/> principle in the templates, but without Shadow DOM. If I understand it right, slots are only possible with Shadow DOM?
Is there a way or workaround to have the <slot/> principle in hyperHTML without using Shadow DOM?
<my-popup>
<h1>Title</h1>
<my-button>Close<my-button>
</my-popup>
Although there are benefits, some reasons I prefer not to use Shadow DOM:
I want to see if I can convert my existing SPA: all required CSS styling lives now in SASS files and is compiled to 1 CSS file. Using global CSS inside Shadow DOM components is not easily possible and I prefer not to unravel the SASS (now)
Shadow DOM has some performance cost
I don't want the large Shadow DOM polyfill to have slots (webcomponents-lite.js: 84KB - unminified)
Let me start describing what are slots and what problem these solve.
Just Parked Data
Having slots in your layout is the HTML attempt to let you park some data within the layout, and address it later on through JavaScript.
You don't even need Shadow DOM to use slots, you just need a template with named slots that will put values in place.
<user-data>
<img src="..." slot="avatar">
<span slot="nick-name">...</span>
<span slot="full-name">...</span>
</user-data>
Can you spot the difference between that component and the following JavaScript ?
const userData = {
avatar: '...',
nickName: '...',
fullName: '...'
};
In other words, with a function like the following one we can already convert slots into useful data addressed by properties.
function slotsAsData(parent) {
const data = {};
parent.querySelectorAll('[slot]').forEach(el => {
// convert 'nick-name' into 'nickName' for easy JS access
// set the *DOM node* as data property value
data[el.getAttribute('slot').replace(
/-(\w)/g,
($0, $1) => $1.toUpperCase())
] = el; // <- this is a DOM node, not a string ;-)
});
return data;
}
Slots as hyperHTML interpolations
Now that we have a way to address slots, all we need is a way to place these inside our layout.
Theoretically, we don't need Custom Elements to make it possible.
document.querySelectorAll('user-data').forEach(el => {
// retrieve slots as data
const data = slotsAsData(el);
// place data within a more complex template
hyperHTML.bind(el)`
<div class="user">
<div class="avatar">
${data.avatar}
</div>
${data.nickName}
${data.fullName}
</div>`;
});
However, if we'd like to use Shadow DOM to keep styles and node safe from undesired page / 3rd parts pollution, we can do it as shown in this Code Pen example based on Custom Elements.
As you can see, the only needed API is the attachShadow one and there is a super lightweight polyfill for just that that weights 1.6K min-zipped.
Last, but not least, you could use slots inside hyperHTML template literals and let the browser do the transformation, but that would need heavier polyfills and I would not recommend it in production, specially when there are better and lighter alternatives as shown in here.
I hope this answer helped you.
I have a similar approach, i created a base element (from HyperElement) that check the children elements inside a custom element in the constructor, if the element doesn't have a slot attribute im just sending them to default slot
import hyperHTML from 'hyperhtml/esm';
class HbsBase extends HyperElement {
constructor(self) {
self = super(self);
self._checkSlots();
}
_checkSlots() {
const slots = this.children;
this.slots = {
default: []
};
if (slots.length > 0) {
[...slots].map((slot) => {
const to = slot.getAttribute ? slot.getAttribute('slot') : null;
if (!to) {
this.slots.default.push(slot);
} else {
this.slots[to] = slot;
}
})
}
}
}
custom element, im using a custom rollup plugin to load the templates
import template from './customElement.hyper.html';
class CustomElement extends HbsBase {
render() {
template(this.html, this, hyperHTML);
}
}
Then on the template customElement.hyper.html
<div>
${model.slots.body}
</div>
Using the element
<custom-element>
<div slot="body">
<div class="row">
<div class="col-sm-6">
<label for="" class="">Name</label>
<p>
${model.firstName} ${model.middleInitial} ${model.lastName}
</p>
</div>
</div>
...
</div>
</custom-element>
Slots without shadow dom are supported by multiple utilities and frameworks.
Stencil enables using without shadow DOM enabled. slotted-element gives support without framework.

Datatables with Meteor using Collections Join

I want to display the data in a tabular fashion, Data will be fetched using the joins of collection from Mongo DB , I have some experience in Datatables that I have used in my previous projects
I have been trying with lots of Meteor stuff to accomplish this.
What I tried and What is the result:
I am using loftsteinn:datatables-bootstrap3 (https://github.com/oskarszoon/meteor-datatables-bootstrap3/) I am trying to display the data using joining of two collections, for Joining of collections I am using : https://atmospherejs.com/reywood/publish-composite.
The Issue : as the data gets fetched and the page gets rendered with the table it shows 0 records, but after a few seconds rows get populated and datatable gets filled but still shows 0 records.
To Counter this issue I have to set timeout for few seconds and then it shows correctly.
Is there any better way, as I feel that in case the data gets increased, I may face issues again.
Possible Solutions with Other Packages?
Is anybody has expirience in Joining of Collections and displaying correctly in the tabular format with Pagination, Sorting and Search?
I would Appriciate any help in this.
CODE:
TEMPLATE
<template name="testdatatable">
{{#if Template.subscriptionsReady}}
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="myTable">
<thead>
<tr>
<th>Todos Name</th>
<th>List Name</th>
</tr>
</thead>
<tbody>
{{#each todos}}
<tr>
<td>{{name}}</td>
<td>{{lists.name}}</td>
</tr>
{{/each}}
</tbody>
</table>
{{else}}
<div class="loading">{{>spinner}}</div>
{{/if}}
</template>
TEMPLATE HELPER
Template.testdatatable.helpers({
todos: function() {
console.log(Todos.find());
return Todos.find();
},
lists: function() {
return Lists.findOne(this.listId);
}
});
PUBLISH COMPOSITE using ( reywood:publish-composite )
Meteor.publishComposite('tabular_Todos', {
find: function () {
return Todos.find();
},
children: [
{
find: function(todos) {
return Lists.find({_id: todos.listId });
}
}
]
});
ROUTING USING (iron Router)
Router.route('/testdatatable', {
name: 'testdatatable',
template: 'testdatatable',
onAfterAction: function(){
calltestdatatable();
},
subscriptions: function(){
return Meteor.subscribe('tabular_Todos');
}
});
OTHER FUNCTIONS
ON RENDERED
Template.testdatatable.onRendered(function(){
setTimeout(calldatatable, 2000);
});
SETTING A TIMEOUT TO DELAY THE DATATABLE
function calltestdatatable(){
setTimeout(calldatatable, 2000);
}
DATATABLE INITIALISATION
function calldatatable(){
$('#myTable').DataTable();
}
DATABASE
todos Collection
lists Collection
Thanks and Best Regards,
Manu
here is my route that fixes the problem :
Router.route('testdatatable', {
path: '/testdatatable',
name: 'testdatatable',
template: 'testdatatable',
waitOn: function() {
return [
Meteor.subscribe('tabular_Todos')
];
},
subscriptions: function(){
return Meteor.subscribe('tabular_Todos');
}
});
and template
Template.testdatatable.onRendered(function(){
$('#myTable').dataTable();
});
(as I used the --example todos, I had to change {{name}} as {{text}} to display the todo text)
Search, pagination, sorting works fine with meteor add lc3t35:datatables-bootstrap3 !
Answer to your first question.
your data needs to come into minimongo first, then client side will be able to render those data. As a workaround you can use loading animation. a quick solution would be using sacha:spin package. and your Blaze code will be something similar to this.
{{#if Template.subscriptionsReady}}
// load your view
{{else}}
<div class="loading">{{>spinner}}</div>
{{/if}}
your second problem is that ,db gets filled but table shows nothing except row skeleton. It's most probably because you have either problems with helper function or in the Blaze view. As you've not posted any code, it's hard to identify problem.
And to other questions: there are quite good numbers of packages for pagination and search. checkout atmosphere. you'll find some popular packages like pages and easy-search. you need to decide which suits for your project.