How to hook data-grid events in parent lit-element component? - vaadin

I want to react on events started by elements placed in the data-grid rows.
Vaading data-grid prevents events from bubbling up to the parent component containing the grid. Having buttons placed in the grid column rendered for each row I cannot catch the click or any other event from the component that hosts the grid.
The examples from https://vaadin.com/components/vaadin-grid/html-examples are relying on js hooks being attached in the html file. I am working with Lit-element and trying to do the same at firstUpdated() callback. The problem is that apparently at this point the table is not available.
<vaadin-grid id="test" .items=${this.data} theme="compact">
<vaadin-grid-column width="40px" flex-grow="0">
<template class="header">#</template>
<template>
<vaadin-button style="font-size:10px;" theme="icon" focus-target #click="${(e) => { console.log(e) }}">
<iron-icon icon="icons:create"></iron-icon>
</vaadin-button>
</template>
</vaadin-grid-column>
</vaadin-grid>
I expected to have the log and nothing happens as the grid component prevents event from bubbling up to my component.
The code that tries to implement renderer property for vaadin-grid-column:
import { LitElement, html, css } from 'lit-element'
import {render} from 'lit-html';
import '#vaadin/vaadin-grid/vaadin-grid.js'
import '#vaadin/vaadin-grid/vaadin-grid-filter-column.js'
import '#vaadin/vaadin-grid/vaadin-grid-sort-column.js';
import '#vaadin/vaadin-grid/vaadin-grid-filter.js';
import '#vaadin/vaadin-grid/vaadin-grid-sorter.js'
export default class MyClass extends LitElement {
static get properties () {
return {
data: {
type: Array,
hasChanged: () => true
},
}
}
get grid() {
return this.shadowRoot.querySelector('vaadin-grid');
}
constructor () {
super()
this.data = []//is being assigned from super as a property to a custom element
}
render () {
return html`
<vaadin-grid id="test" .items=${this.data}>
<vaadin-grid-column .renderer=${this.columnRenderer} header="some header text"></vaadin-grid-column>
</vaadin-grid>
`
}
columnRenderer(root, column, rowData) {
render(html`test string`, root);
}
}
window.customElements.define('my-elem', MyClass)

When using vaadin-grid inside LitElement-based components you should use renderers
Here's how your code would look using renderers
import {LitElement, html} from 'lit-element';
// you need lit-html's render function
import {render} from 'lit-html';
class MyElement extends LitElement {
// we'll just assume the data array is defined to keep the sample short
render() {
return html`
<vaadin-grid id="test" .items=${this.data} theme="compact">
<vaadin-grid-column width="40px" flex-grow="0" .renderer=${this.columnRenderer} .headerRenderer=${this.columnHeaderRenderer}></vaadin-grid-column>
<vaadin-grid>
`;
}
columnHeaderRenderer(root) {
render(html`#`, root);
// you could also just do this
// root.textContent = '#'
// or actually just use the column's header property would be easier tbh
}
columnRenderer(root, column, rowData) {
render(
html`
<vaadin-button style="font-size: 10px;" theme="icon" focus-target #click="${(e) => { console.log(e) }}">
<iron-icon icon="icons:create"></iron-icon>
</vaadin-button>
`, root);
}
}
You can see this and more of vaadin-grid's features in action in LitElement in this Glitch created by one of the vaadin team members

Related

How to write unittest for table row selection using Antd Library in React

I have a react application and I'm using #testing-library/jest-dom for unit testing and antd 3.x library for UI design. In one of my UI screen there is a table and a button where the button only enables when one of the row in table is checked. So I wanted to do a unittest for this. So below is my src code,
import {Modal, Button, Form, Input, DatePicker, Table, Card, Tooltip} from 'antd';
...
...
return (
<>
<Form>
...
<Card>
<Table
data-testid={'lift-hold-grid'}
className="holdListResultsTable"
rowSelection={rowSelection}
columns={columns}
dataSource={dataSourcee}
components={{
body: {
row: showRestorationTooltip
}
}}
/>
</Card>
...
<div style = {...}>
<Button data-testid={'lift-hold-button'} disabled={...} onClick={...}>
Lift Hold
</Button>
</div>
<Form>
</>
)
and below is the unittest
import { render } from "#testing-library/react";
import { Provider } from "react-redux";
import thunk from "redux-thunk";
function renderWithReduxAndThunk(ui, initialState) {
const createdStore = createStore(rootReducer, initialState, applyMiddleware(thunk));
return {
...render(<Provider store={createdStore}>{ui}</Provider>),
createdStore,
}
}
const changedState = {
...
}
it('should enable the lift hold button after checkbox selection and note input', () => {
const { container, getByTestId } = renderWithReduxAndThunk(<LegalHoldLiftScreen />, changedState);
const checkBox = container.querySelector('.ant-checkbox-input');
fireEvent.click(checkBox);
const downloadButton = getByTestId('lift-hold-button');
expect(downloadButton).toBeTruthy();
expect(downloadButton).not.toBeDisabled();
});
but this fails with below message
● should enable the lift hold button after checkbox selection and note input
Unable to fire a "click" event - please provide a DOM element.
what am I missing here??

Reactjs with Rails, remove duplicated createMuiTheme

the code below is one of my component.
i am creating this with Ruby on Rails framework, with react_rails gem and webpacker, experimenting on Material UI.
as you can see, i am changing the Material UI default font theme with my own choice of font. below code is a success.
my question is, do i have to repeat this step for all my component?
importing createMuiTheme, stating the theme const, and wrapping <MuiThemeProvider /> in every render?
is there a single way to do this universally, without repeating in all component?
thanks for the advice.
import React from 'react';
import PropTypes from 'prop-types';
import Card from '#material-ui/core/Card';
import CardActions from '#material-ui/core/CardActions';
import CardContent from '#material-ui/core/CardContent';
import Button from '#material-ui/core/Button';
import Popover from '#material-ui/core/Popover';
import Typography from '#material-ui/core/Typography';
import List from '#material-ui/core/List';
import ListItem from '#material-ui/core/ListItem';
import ListItemText from '#material-ui/core/ListItemText';
import Avatar from '#material-ui/core/Avatar';
import EmailIcon from '#material-ui/icons/Email';
import HomeIcon from '#material-ui/icons/Home';
import PersonIcon from '#material-ui/icons/Person';
import { MuiThemeProvider, createMuiTheme, withStyles } from '#material-ui/core/styles';
const theme = createMuiTheme({
typography: {
fontFamily: 'Bebas',
},
});
export class SimpleCard extends React.Component {
render () {
return (
<div >
<MuiThemeProvider theme={theme}>
<Card raised="true">
<CardContent >
<List>
<ListItem>
<Avatar>
<EmailIcon />
</Avatar>
<ListItemText primary="Email" secondary={this.props.order.order_mail} />
</ListItem>
</List>
</CardContent>
</Card>
</MuiThemeProvider>
</div>
);
}
}
export default withStyles(styles)(SimpleCard);
Did you try wrapping the MuiThemeProvider around the entire site/app? This is what I do in React.js. I set up my theme in the root file and wrap it around the entire component
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
// Components
import Navbar from "./components/layout/Navbar";
import Footer from "./components/layout/Footer";
import Login from "./components/auth/Login";
import Dashboard from "./components/dashboard/Dashboard";
// Styles
import "./stylesheets/App.css";
import {
MuiThemeProvider,
createMuiTheme,
withTheme
} from "#material-ui/core/styles";
import { grey } from "#material-ui/core/colors";
import { withStyles } from "#material-ui/core";
const theme = createMuiTheme({
overrides: {
MuiGrid: {
container: {
width: "100%",
margin: "0"
}
}
},
palette: {
primary: {
light: "#c146b1",
main: "#8e0081",
dark: "#5c0054",
contrastText: "#ffffff"
},
secondary: {
light: "#6bffff",
main: "#00eae3",
dark: "#00b7b1",
contrastText: "#000000"
}
}
});
const drawerWidth = 240;
const styles = theme => ({
app: {
backgroundColor: grey[200]
},
drawerOpen: {
marginLeft: 0
},
drawerClosed: {
marginLeft: -drawerWidth
}
});
class App extends Component {
constructor() {
super();
this.state = {
navOpen: false
};
}
toggleDrawer = () => {
this.setState({
navOpen: !this.state.navOpen
});
};
render() {
const { classes } = this.props;
return (
<MuiThemeProvider theme={theme}>
<div className={classes.app}>
<Navbar
toggleDrawer={this.toggleDrawer}
navOpen={this.state.navOpen}
/>
<Route exact path="/" component={Dashboard} />
<Route exact path="/register" component={PatientRegister} />
<Route exact path="/login" component={Login} />
<Footer />
</div>
</Router>
</MuiThemeProvider>
);
}
}
export default withTheme(theme)(withStyles(styles)(App));
This is an example of my component that will be rendered in the root div (aka the entire application). Notice how wraps the entire app? I stripped a lot out to make it simpler to understand, but if you are using Redux (which is awesome) then I would recommend having that as your outer wrapper, and the rest inside of that. In other words:
<Provider store={store}>
<MuiThemeProvider theme={theme}>
<div class="App">
// Your App Here
</div>
</MuiThemeProvider>
</Provider>

Programmatically open an N level self nested mat-menu component with matMenuTrigger openMenu

I am trying to make a self nested component that uses Angular Material mat-menu. I have a flyoutcomponent that is a wrapper for flyout-menu-item component, that will have a button as a matMenuTrigger for the nested component that will appear as many levels as the FeatureInput.FeatureChoices dictates. FeatureInput is an object that has FeatureChoices that may or may not contain other featurechoices etc N levels deep. Below code does not compile but it should demonstrate what I am doing. Basically I have flyout menu component as a input to a form and I am trying to load a stored answer on a form rather than select new, which I can do easily using the nested component. The desired behavior is that if the user clicks top matMenuTrigger button to open the top menu that it would expand all child menus to the menu item that matches with the FeatureInput.FeatureValue and sets the menu item _highlighted to true. I am using the menuOpen input parameter and ngChanges successfully to find the match(with I a setTimeout which cannot be right). Basically when I console.log this.trigger it is undefined. Ideally in the ngOnChange to the openMenu I would go through all menus and call openMenu on all the triggers but I cannot get access to the matMenuTrigger with ViewChild as the docs say. I get undefined. *-( All help welcome please and thanks.
Here is flyout template component.
<div>
<buttonmat-button [matMenuTriggerFor]="menu.childMenu"
(onMenuOpen)="onMenuOpen()"
(onMenuClose)="onMenuClose()">
<span [innerHTML]="featureInput.Text"></span>
</button>
<app-flyout-menu-item #menu
[featureChoicesObject]="featureInput.FeatureChoices"></app-flyout-menu-item>
</div>
And here is its .ts
import { Component, OnInit, Input, ViewChild } from '#angular/core';
import { MatMenuTrigger } from '#angular/material';
#Component({
selector: 'app-flyout',
templateUrl: './flyout.component.html',
styleUrls: ['./flyout.component.scss']
})
export class FlyoutComponent implements OnInit {
#Input() featureInput: FeatureInput
constructor() { }
ngOnInit() {
}
onMenuOpen() {
this.menuOpen = true;
}
onMenuClose() {
this.menuOpen = false;
}
}
And here is flyout-menu-item template
<mat-menu #childMenu="matMenu" [overlapTrigger]="false">
<span *ngFor="let featureChoice of featureChoices">
<span>
<button mat-menu-item [matMenuTriggerFor]="menu.childMenu">
<span [innerHTML]="featureChoice.Text"></span>
</button>
<app-flyout-menu-item #menu
[menuOpen]="menuOpen"
[featureInput]="featureInput"
[featureChoicesObject]="featureChoice.FeatureChoices"
(onOptionSelected)="someService.SomeMethod($event)"></app-flyout-menu-item>
</span>
<span *ngIf="!featureChoice.FeatureChoices">
<button mat-menu-item (click)="selectOption(featureChoice.ID)" [innerHTML]="featureChoice.Text" value="{{featureChoice.ID}}"></button>
</span>
</span>
</mat-menu>
And here is its .ts
import { Component, OnInit, Input, Output, ViewChild, EventEmitter, OnChanges, SimpleChanges } from '#angular/core';
import { MatMenuTrigger } from '#angular/material';
import { FeatureChoice } from 'app/model/feature-choice';
import { FeatureInput } from 'app/model/feature-input';
#Component({
selector: 'app-flyout-menu-item',
templateUrl: './flyout-menu-item.component.html',
styleUrls: ['./flyout-menu-item.component.scss']
})
export class FlyoutMenuItemComponent implements OnInit{
#ViewChild('menu') public menu;
#ViewChild('childMenu') public childMenu;
#ViewChild(MatMenuTrigger) public trigger: MatMenuTrigger;
#Input() featureInput: FeatureInput;
#Input() featureChoicesObject: FeatureChoice;
#Output() onOptionSelected: EventEmitter<FeatureInput> = new EventEmitter<FeatureInput>();
constructor(public solutionDataService: SolutionDataService) { }
ngOnInit() {
console.log(this.trigger);
}
ngOnChanges(simpleChanges: SimpleChanges) {
if (simpleChanges.menuOpen && simpleChanges.menuOpen.currentValue) {
setTimeout(() => {
// console.log(this.menu);
const itemsArray = this.childMenu.items.toArray();
for (let x = 0; x < itemsArray.length; x++) {
const menuItem = itemsArray[x];
if (this.featureInput.FeatureValue !== '' && menuItem._elementRef.nativeElement.value === this.featureInput.FeatureValue) {
menuItem._highlighted = true;
}
}
}, 1);
}
}
}
this.menuOpen = true;
Perhaps add menuOpen: boolean = false as an attribute at the top of your FlyoutComponent. I don't know where the value of menuOpen is saved.
the menuOpen property relates to the matMenuTrigger.
here's an example:
<button [ngClass]="{'active-icon': trigger.menuOpen}" type="button" mat-
icon-button #trigger="matMenuTrigger" [matMenuTriggerFor]="help">
<mat-icon></mat-icon>
</button>
<mat-menu #help="matMenu">
<div> textId </div>
</mat-menu>

How to remove a child component with a delete button in the child itself

I have an email component (email-tag.html) that consist of a label, a select and a delete button element.
The email-tag.html component is hosted in its parent email-view-tag.html. email-view-tag contains an add-email-button that adds the email-tag element to the DOM each time it is clicked.
I need help in removing an added email-tag component when its delete-button is clicked. It is the compnoent that contains the delete-button that should be removed.
The two components are shown below:
email-tag.html
<!DOCTYPE html>
<polymer-element name='email-tag'>
<template>
<style>
.main-flex-container
{
display:flex;
flex-flow:row wrap;
align-content:flex-start;
}
.col
{
display:flex;
flex-flow:column;
align-content:flex-start;
flex-grow:1;
}
</style>
<div id='email' class='main-flex-container'>
<section id='col1' class='col'>
<input id=emailTxt
type='text'
list='_emails'
value='{{webContact.homeEmail}}'>
<datalist id='_emails'>
<template repeat='{{email in emails}}'>
<option value='{{email}}'>{{email}}</option>
</template>
</datalist>
</section>
<section id='col2' class='col'>
<button id='delete-email-btn' type='button' on-click='{{deletePhone}}'>Delete</button>
</section>
</div>
</template>
<script type="application/dart">
import 'package:polymer/polymer.dart' show CustomTag, PolymerElement;
import 'dart:html' show Event, Node;
#CustomTag( 'email-tag' )
class EmailElement extends PolymerElement
{
//#observable
EmailElement.created() : super.created();
List<String> emails = [ '', 'Home', 'Personal', 'Private', 'Work', ];
void deletePhone( Event e, var detail, Node target)
{
//shadowRoot.querySelector('#new-phone' ).remove();
//print( 'Current row deleted' );
}
}
</script>
</polymer-element>
email-view-tag.html
<!DOCTYPE html>
<link rel="import" href="email-tag.html">
<polymer-element name='email-view-tag'>
<template>
<style>
.main-flex-container
{
display:flex;
flex-flow:row wrap;
align-content:flex-start;
}
.col
{
display:flex;
flex-flow:column;
align-content:flex-start;
flex-grow:1;
}
</style>
<div id='email-view' class='main-flex-container'>
<section id='row0' >
<button id='add-email-btn' type='button' on-click='{{addPhone}}'>Add Phone</button>
</section >
<section id='rows' class='col'>
<!-- <epimss-phone-header-tag id='col1' class='col'></epimss-phone-header-tag> -->
</section>
</div>
</template>
<script type="application/dart">
import 'package:polymer/polymer.dart' show CustomTag, PolymerElement;
import 'dart:html' show Event, Node, Element;
#CustomTag( 'email-view-tag' )
class EmailViewElement extends PolymerElement
{
//#observable
EmailViewElement.created() : super.created();
void addPhone( Event e, var detail, Node target )
{
$[ 'rows' ].children.add( new Element.tag( 'email-tag' ) );
}
#override
void attached() {
super.attached();
$[ 'add-email-btn' ].click();
}
}
</script>
</polymer-element>
The application does execute normally and clicking the add button does add the email component. The delete button does not work - it is here I am asking for help.
Thanks
The child component, <email-tag> should not be in the business of deleting itself. Instead, it should delegate that responsibility to the the parent component, email-view-tag, by dispatching a custom event.
Here is the code for dispatching a custom event from deletePhone:
void deletePhone( Event e, var detail, Node target){
dispatchEvent(new CustomEvent('notneeded'));
}
Then, in the parent, <custom-view>, change your code for adding <email-tag>s like so:
void addPhone( Event e, var detail, Node target ) {
$['rows'].children.add( new Element.tag('email-tag'));
$['rows'].on["notneeded"].listen((Event e) {
(e.target as Element).remove();
});
}
Also, I would change the name of deletePhone, since the method no longer deletes the record but merely informs the parent that it is not needed. Call it 'notNeeded' or something similar.
EDIT
#ShailenTuli is right about encapsulation should not be broken.
But also JS Polymer elements access the parent in their layout elements because it's still convenient in some scenarios.
This works now in PolymerDart too.
(this.parentNode as ShadowRoot).host
ORIGINAL
You can fire an event and make the email-view-tag listen to this tag and the event handler can remove the event target from it's childs.
I had a similar question a while ago:
How to access parent model from polymer component
This was actually the question I wanted refer to
How can I access the host of a custom element
but the first one may be of some use too.
PolymerJS FAQ - When is the best time to access an element’s parent node?
attached() currently still named enteredView() in Dart, but will be renamed probably soon.

How do I fire a custom event from Polymer Dart?

I want to fire/send/emit a custom event from inside a Polymer element. For example, I want to convert a normal DOM event like "changed" to a more semantic event like "todoupdated".
This is the HTML that I have:
<polymer-element name="todo-item" extends="li" attributes="item">
<template>
<style>
label.done {
color: gray;
text-decoration: line-through;
}
</style>
<label class="checkbox {{item.doneClass}}">
<input type="checkbox" checked="{{item.done}}">
{{item.text}}
</label>
</template>
<script type="application/dart" src="todo_item.dart"></script>
</polymer-element>
I want the change events on checkbox to bubble out of the custom element as something more... useful. :)
Step 1
Capture the change events on the <input>. Notice the on-change below.
<!-- from inside todo_item.html -->
<input type="checkbox" checked="{{item.done}}" on-change="{{change}}">
Step 2
Handle the change event in the custom element code that contains the checkbox.
import 'package:polymer/polymer.dart';
import 'dart:html';
import 'models.dart';
#CustomTag('todo-item')
class TodoItemElement extends PolymerElement with ObservableMixin {
#observable Item item;
bool get applyAuthorStyles => true;
void change(Event e, var details, Node target) {
// do stuff here
}
}
Notice the change event handler. That method is run any time the checkbox state changes.
Step 3
Dispatch a custom event.
void change(Event e, var details, Node target) {
dispatchEvent(new CustomEvent('todochange'));
}
NOTE: the custom event name must not contain dashes.
Step 4
Listen for the custom event in a parent custom element.
<template repeat="{{item in items}}" >
<li is="todo-item" class="{{item.doneClass}}" item="{{item}}" on-todochange="todoChanged"></li>
</template>
Notice the use of on-todochange.
Enjoy!
Polymer has a helper method that simplifies firing events
// dispatch a custom event
this.fire('polymer-select', detail: {'item': item, 'isSelected': isSelected});
Additional info:
To make the event available to subscriber that want to add a listener programmatically
// getter
async.Stream<dom.CustomEvent> get onPolymerSelect =>
PolymerSelection._onPolymerSelect.forTarget(this);
// private EventStreamProvider
static const dom.EventStreamProvider<dom.CustomEvent> _onPolymerSelect =
const dom.EventStreamProvider<dom.CustomEvent>('polymer-select');
subscribe to the event programmatically instead of declaratively:
($['#ps'] as PolymerSelect) // get the children and cast it to its actual type
.onPolymerSelect.listen((e) => print(e['isSelected'])); // subscribe
I managed this using <core-signals> and the polymer helper method fire. This way you are able to listen to events fired from elements that are not children. source.
todochange.html
<!doctype html>
<polymer-element name="todo-item" extends="li">
<template>
<style>
label.done {
color: gray;
text-decoration: line-through;
}
</style>
<label class="checkbox {{item.doneClass}}">
<input type="checkbox" checked="{{item.done}}">
{{item.text}}
</label>
</template>
<script type="application/dart" src="todo_item.dart"></script>
</polymer-element>
todochange.dart
import 'package:polymer/polymer.dart';
import 'dart:html';
#CustomTag('todo-item')
class TodoItemElement extends PolymerElement {
#observable Item item;
void change(Event e, var details, Node target) {
// the name is the name of your custom event
this.fire( "core-signal", detail: { "name": "todochange" } );
}
}
Then any subscriber just has to do this
subscriber.html
...
<link rel="import" href="packages/core_elements/core_signals.html>
...
<template>
<core-signals on-core-signal-todochange="{{handleToDoChange}}"></core-signals>
...
</template>
subscriber.dart
#CustomTag( "subscriber" )
class Sub extends PolymerElement {
...
void handleToDoChange( Event e, var detail, Node target ) {
print( "Got event from <todo-item>" );
}
...
}

Resources