How to implement an ag-grid custom floating filter with material-ui withStyles HoC? - material-ui

Created an ag-grid custom floating filter with validation and need to style the filter when the validation fails with material-ui themed class using withStyles higher order component (HoC). However, when you wrap the custom floating filter with HoC onParentModelChanged doesn't get called at all.
Used hard-coded style to set the element style property but this is not allowed in the themed project using #material-ui/core v1.4.0.
Below is the custom floating filter that I created with validation and hard-coded style.
import { PropTypes } from 'prop-types';
import styles from './styles';
const DEFAULT_MIN_CHARS = 3;
const ENTER_KEY = 13;
export class CustomFloatingFilter extends Component {
constructor(props) {
super(props);
this.state = {
currentValue: '',
minChars: props.minChars ? props.minChars : DEFAULT_MIN_CHARS,
invalidFilter: false,
styles: styles()
};
this.keyPressed = this.keyPressed.bind(this);
this.valueChanged = this.valueChanged.bind(this);
this.onParentModelChanged = this.onParentModelChanged.bind(this);
this.onFloatingFilterChanged = change => {
const { minChars } = this.state;
if(change && change.model && (!change.model.filter || change.model.filter.length >= minChars)) {
return props.onFloatingFilterChanged(change);
}
return false;
};
}
keyPressed(event) {
this.setState(
{ enterPressed: event.which === ENTER_KEY },
() => {
const { enterPressed } = this.state;
if(enterPressed) { //update filter only when enter. valueChanged will handle all other cases
this.onFloatingFilterChanged(this.buildChanged());
}
}
);
}
valueChanged(event) {
const { minChars } = this.state;
this.setState(
{
currentValue: event.target.value,
invalidFilter: !!event.target.value && event.target.value.length < minChars
},
() => {
this.onFloatingFilterChanged(this.buildChanged());
}
);
}
onParentModelChanged(parentModel) {
this.setState({ currentValue: parentModel ? parentModel.filter : '' });
}
buildChanged() {
const { currentValue, enterPressed, invalidFilter } = this.state;
return {
model: {
filterType: 'text',
type: 'equals',
filter: currentValue
},
apply: !invalidFilter && (enterPressed || currentValue === '') //for applyButton:true case
};
}
render() {
const { currentValue, invalidFilter, styles } = this.state;
return (
<div style={invalidFilter ? styles.invalid : {} //eslint-disable-line
//withStyles HoC doesn't work with ag-grid floating filter component
}
>
<input className='ag-floating-filter-input' onKeyPress={this.keyPressed} onChange={this.valueChanged} value={currentValue} />
</div>
);
}
}
CustomFloatingFilter.propTypes = {
minChars: PropTypes.number,
onFloatingFilterChanged: PropTypes.func
};
export default CustomFloatingFilter;

Related

AgGrid - How can i have radio button filter instead of checkbox?

I have a custom filter values such as:
filterParams: {
values: ['Admin', 'Proje Yƶneticisi', 'Muhasebe'],
defaultToNothingSelected: true,
suppressSelectAll: true
},
However, I can choose multiple values like this. But I don't want to do that, I want to choose only one value instead of multiple choices.
Is there a way to convert this checkbox filter into a radio filter?
Thanks.
You can make a custom filter and there is a video on it: https://www.youtube.com/watch?v=yO3_nTyDv6o
Create a component like this, i am dynamically looking up the options to be displayed based on the extra column parameters supplied in the column def (e.g. thats where props.meta comes in)
import { Button, Radio, RadioGroup, Stack } from "#chakra-ui/react";
import { IFilterParams } from "ag-grid-community";
import React from "react";
import { IRegistryDataColumn } from "../../../../models/RegistryDataColumn";
interface IProps extends IFilterParams {
meta?: IRegistryDataColumn;
}
interface IOption {
value: string;
label: string;
}
export const FilterRadio = React.forwardRef((props: IProps, ref) => {
const [radioOptions, setRadioOptions] = React.useState<IOption[]>([]);
const [filterState, setFilterState] = React.useState<string>();
const handleClear = () => {
setFilterState(undefined);
};
// expose AG Grid Filter Lifecycle callbacks
React.useImperativeHandle(ref, () => {
return {
isFilterActive() {
return filterState !== undefined;
},
doesFilterPass(params) {
const isPass =
params.data[props.colDef.field as string] === filterState;
return isPass;
},
getModel() {},
setModel() {},
};
});
React.useEffect(() => {
props.filterChangedCallback();
}, [filterState]);
React.useEffect(() => {
const radioOptionsUpdate: IOption[] = [];
if (props.meta?.radio_options) {
Object.entries(props.meta.radio_options).forEach(([key, value]) => {
radioOptionsUpdate.push({ value: value.value, label: value.label });
});
}
setRadioOptions(radioOptionsUpdate);
}, [props.meta?.radio_options]);
return (
<Stack p={4} spacing={6} style={{ display: "inline-block" }}>
<Button size="sm" onClick={handleClear}>
Clear filter
</Button>
<RadioGroup onChange={setFilterState} value={filterState}>
<Stack spacing={4}>
{radioOptions.map((option) => (
<Radio key={option.value} value={option.value}>
{option.label}
</Radio>
))}
</Stack>
</RadioGroup>
</Stack>
);
});
And then include it in the column definition:
newCol.filter = FilterRadio;

Material Ui KeyboardDatepicker - The month shows invalid value

I am trying to implement KeyboardDatepicker inside ag grid's cell editor. When I select a date from the datepicker popup, the month value is shown incorrectly. The date I have selected is 30-04-2020 and the date it is showing is 30-30-2020. I tried using formatDate attribute to format the date as well. I am passing the selected value in proper format but the date is showing incorrectly. I am using date-io/moment version 1.3.13 and date-io/date-fns version 0.0.2. Anybody faced this issue before? I am sure this is a trivial issue and I am missing something. Any pointers would be much appreciated. Thanks in advance. Cheers!
Update:
Datepicker_component_grid.js
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import { KeyboardDatePicker, MuiPickersUtilsProvider } from '#material-ui/pickers';
import DateFnsUtils from '#date-io/date-fns'
import moment from 'moment'
import format from 'date-fns/format'
import Grid from '#material-ui/core/Grid'
import { SampleDatePickerWithUtils } from '../Sample_datepicker_with_utils';
export class DateEditor extends Component {
constructor(props) {
super(props)
this.onDateChange = this.onDateChange.bind(this)
this.state = {
value: null
}
}
componentDidMount() {
}
componentWillUnmount() {
}
componentDidUpdate() {
this.focus()
}
focus() {
window.setTimeout(() => {
let dateContainer = ReactDOM.findDOMNode(this.refs.dateContainer)
if (dateContainer) {
dateContainer.focus()
}
})
}
getValue() {
return this.state.value
}
isPopup() {
return false
}
onDateChange(date) {
this.setState({
value: date
},
() => this.props.api.stopEditing()
)
}
render() {
let storeValue = this.props.value
return (
<span
ref='dateContainer'
tabIndex={1}>
<SampleDatePickerWithUtils labelName={' '} schemaLocation='rowDate' isDisabled={false}
displayFormat='yyyy-mm-dd'
disableFuture={false}
onDateChange={this.onDateChange}
disablePast={false}
storeVal={storeValue}
gridSize={{ sm: 2, md: 1, lg: 1 }}></SampleDatePickerWithUtils>
</span>
)
}
}
SampleDatePickerWithUtils.js
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '#material-ui/core/styles'
import { updateFieldState, onTabOut, updateFocus } from 'actions/ticket_actions';
import { bindActionCreators } from 'redux';
import { getGridSizing } from 'styles/Sample_core_theme';
import { DatePicker, KeyboardDatePicker, MuiPickersUtilsProvider } from '#material-ui/pickers';
import { formatToYMD } from 'core/schema_translators/utils';
import EventIcon from '#material-ui/icons/Event';
import DateFnsUtils from '#date-io/date-fns'
import { SampleFieldComponent } from './base_components';
import { registerComponent } from 'actions/Sample_core_actions';
import { connect } from 'react-redux';
const moment = require('moment');
class MyDateFnsUtils extends DateFnsUtils {
startOfMonth(date) {
let dat = moment(date).startOf('month').toDate()
return dat
}
}
class _SampleDatePickerWithUtils extends SampleFieldComponent {
constructor(props) {
super(props);
let formattedDate = props.storeVal ? formatToYMD(props.storeVal) : null
this.state = {
value: formattedDate,
errorMsg: '',
isError: false,
}
this.styleProps = { disableUnderline: true }
this.inputLabelProps = { shrink: true }
this.onChangeCallback = this.onChangeCallback.bind(this)
// this.onBlurCallback = this.onBlurCallback.bind(this)
props.registerComponent(props.schemaLocation)
}
componentWillMount() {
this.props.registerComponent(this.props.schemaLocation)
if (this.props.manageValueManually) {
let dateValue = this.props.overriddenValue ? formatToYMD(this.props.overriddenValue) : null
this.props.updateFieldState(this.props.schemaLocation, dateValue)
}
}
componentDidMount() {
if (this.props.focusField) { this.focusDomElement() }
}
componentWillReceiveProps(nextProps) {
if (this.props.manageValueManually) {
if (nextProps.overriddenValue !== this.props.overriddenValue) {
let dateValue = nextProps.overriddenValue ? formatToYMD(nextProps.overriddenValue) : null
this.props.updateFieldState(this.props.schemaLocation, dateValue)
this.props.onTabOut(this.props.schemaLocation)
}
}
}
onChangeCallback(date) {
let formattedDate = date ? formatToYMD(date) : null
if (!this.props.manageValueManually) {
this.props.updateFieldState(this.props.schemaLocation, formattedDate)
this.props.onTabOut(this.props.schemaLocation) //this is required because the value is selected in a date picker
}
this.props.onDateChange(formattedDate)
}
render() {
const gridSizing = getGridSizing(this.props)
const { classes } = this.props
return (
<MuiPickersUtilsProvider utils={MyDateFnsUtils}>
<KeyboardDatePicker
keyboard={(!this.props.isDisabled).toString()}
keyboardIcon={<EventIcon style={{ fontSize: '22px', color: 'red' }} />}
clearable
disabled={this.props.isDisabled}
error={this.state.isError}
helperText={this.state.errorMsg}
InputProps={{ className: classes.inputProps }}
label={this.props.labelName === '' ? this.props.schemaLocation : this.props.labelName}
value='2020-04-30'
onChange={this.onChangeCallback}
// format={this.props.displayFormat}
format='yyyy-mm-dd'
onBlur={this.onBlurCallback}
InputLabelProps={this.inputLabelProps}
disableFuture={this.props.disableFuture}
disablePast={this.props.disablePast}
/>
</MuiPickersUtilsProvider>
);
}
}
const styles = (theme) => ({
inputProps: {
marginTop: '0px !important',
// fontSize: '14px',
border: 0,
'& input': {
fontSize: '14px',
'&:focus': {
boxSizing: 'content-box'
}
}
}
})
const SampleDatePickerWithUtils = withStyles(styles)(_SampleDatePickerWithUtils)
export { SampleDatePickerWithUtils }
Using KeyboardDatePicker with moment the format I use is
format = {moment.localeData().longDateFormat('L')} // In my case dd/mm/yyyy
If you want to use a different locale you can require it first and use it
require("moment/locale/en-us");
moment().locale("en-us");
format = {moment().locale(locale).localeData().longDateFormat('L')}
For the value I use moment date when the date has a value and null otherwise
value={date ? moment(date) : null}
and for the onChange I'm using universal format as I don't want to store it in locale format
{(date: any) => handleChange(path, date?.format('YYYY-MM-DD'))}

Does React-data-grid have a mechanism to handle pagination?

I didn't see anything in the docs for pagination. Is there a built-in mechanism for this, or would I have to implement it myself?
Here is an example of pagination (Infinite scrolling) in react data grid. I am using the scrollHeight,scrollTop and clientHeight properties to check whether to load next page.You need to modify your API's to support this type of pagination.
let columns = [
{
key: 'field1',
name: 'Field1 ',
},
{
key: 'field2',
name: 'Field2 ',
},
{
key: 'field3',
name: 'Field3',
},
]
export default class DataGrid extends React.Component {
constructor(props) {
super(props)
this.state = {height: window.innerHeight - 180 > 300 ? window.innerHeight - 180 : 300,page:1}
this.rowGetter = this.rowGetter.bind(this)
this.scrollListener = () => {
if (
(this.canvas.clientHeight +
this.canvas.scrollTop) >= this.canvas.scrollHeight) {
if (this.props.data.next !== null) {
let query = {}
let newpage = this.state.page +1
query['page'] = newpage
this.setState({'page':newpage})
this.props.dispatch(fetchData(query)).then(
(res) => {
// make handling
},
(err) => {
// make handleing
}
)
}
}
};
this.canvas = null;
}
componentDidMount() {
this.props.dispatch(fetchData({'page':this.state.page}))
this.canvas = findDOMNode(this).querySelector('.react-grid-Canvas');
this.canvas.addEventListener('scroll', this.scrollListener);
this._mounted = true
}
componentWillUnmount() {
if(this.canvas) {
this.canvas.removeEventListener('scroll', this.scrollListener);
}
}
getRows() {
return this.props.data.rows;
}
getSize() {
return this.getRows().length;
}
rowGetter(rowIndex) {
let rows = this.getRows();
let _row = rows[rowIndex]
return _row
}
render() {
return (
<ReactDataGrid columns={columns}
rowGetter={this.rowGetter}
rowsCount={this.getSize()}
headerRowHeight={40}
minHeight={this.state.height}
rowHeight={40}
/>
)
}
}
Note : Assumed data are taken from redux store

React Leaflet: setting a GeoJSON's style dynamically

I'm trying to change a GeoJSON component's style dynamically based on whether its ID matches a selector.
The author of the plugin refers to the Leaflet documentation, which says that the style should be passed as a function. Which I'm doing, but no dice.
My component:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions';
import { Marker, Popup, GeoJSON } from 'react-leaflet';
import { centroid } from '#turf/turf';
const position = geoJSON => {
return centroid(geoJSON).geometry.coordinates.reverse();
};
export class PlotMarker extends Component {
render() {
const {
id,
name,
geoJSON,
zoomLevel,
selectedPlot,
plotBeingEdited
} = this.props;
const markerPosition = position(geoJSON);
let style = () => {
color: 'blue';
};
if (selectedPlot === id) {
style = () => {
color: 'red';
};
}
if (zoomLevel > 14) {
return (
<GeoJSON
id={id}
data={geoJSON}
style={style}
onClick={() => {
this.props.selectPlot(id);
}}
/>
);
}
return (
<Marker
id={id}
className="marker"
position={markerPosition}
onClick={() => {
this.props.selectPlot(id);
}}>
<Popup>
<span>{name}</span>
</Popup>
</Marker>
);
}
}
function mapStateToProps(state) {
return {
selectedPlot: state.plots.selectedPlot,
plotBeingEdited: state.plots.plotBeingEdited,
zoomLevel: state.plots.zoomLevel
};
}
export default connect(mapStateToProps, actions)(PlotMarker);
OK, got it. It had to do with the way I was defining the style function. This doesn't work:
let style = () => {
color: 'blue';
};
if (selectedPlot === id) {
style = () => {
color: 'red';
};
}
if (zoomLevel > 14) {
return (
<GeoJSON
id={id}
data={geoJSON}
style={style}
onClick={() => {
this.props.selectPlot(id);
}}
/>
);
}
This works:
let style = () => {
return {
color: 'blue'
};
};
if (selectedPlot === id) {
style = () => {
return {
color: 'red'
};
};
}
if (zoomLevel > 14) {
return (
<GeoJSON
id={id}
data={geoJSON}
style={style}
onClick={() => {
this.props.selectPlot(id);
}}
/>
);
}

Angular 2 Reactive form + directive validation

I'm trying to wrap my head around the following problem:
I have a 'google-place-autocomplete' directive that adds the autocomplete functionality to an input field.
Now I also wanted it to be able to force a google place selection and only be 'valid' if the user has selected a place.
E.g:
#Directive({
selector: '[googlePlace][formControlName], [googlePlace][ngModel]',
providers: [{provide: NG_VALIDATORS, useExisting: GooglePlaceDirective, multi: true}]
})
export class GooglePlaceDirective implements Validator, OnChanges {
valid = false;
#Output() googlePlaceAddressChange: any = new EventEmitter();
#Input() googlePlaceAddress: any;
#Output() ngModelChange: any = new EventEmitter();
private autocomplete: any;
constructor(private googleMapService: GoogleMapsService,
private element: ElementRef,
private zone: NgZone) {
}
ngOnInit() {
let self = this;
this.googleMapService
.load()
.subscribe(
() => {
this.autocomplete = new google.maps.places.Autocomplete(this.element.nativeElement);
this.autocomplete.addListener('place_changed', function () {
self.placeChanged(this.getPlace());
});
}
);
}
private placeChanged(place) {
this.zone.run(() => {
this.googlePlaceAddress = {
address: this.element.nativeElement.value,
formattedAddress: place.formatted_address,
latitude: place.geometry.location.lat(),
longitude: place.geometry.location.lng()
};
this.valid = true;
this.googlePlaceAddressChange.emit(this.googlePlaceAddress);
this.ngModelChange.emit(this.element.nativeElement.value);
});
}
ngOnChanges(changes): void {
let googlePlaceDefined = typeof (changes.googlePlaceAddress) !== 'undefined';
let modelDefined = typeof (changes.ngModel) !== 'undefined';
if(modelDefined && !googlePlaceDefined) {
this.valid = false;
} else if(googlePlaceDefined && !modelDefined) {
this.valid = true;
}
}
validate(control: AbstractControl) {
return this.valid === false ? {'googlePlaceAddress': true} : null;
}
}
If I use this directive in an template driven form:
...
<input name="addr" type="text" [(ngModel)]="textValue" [(googlePlaceAddress)]="googleAddress" required>
<p *ngIf="addr.errors.googlePlaceAddress">Please select a proposed address</p>
...
it works fine.
Now I need to use this in an Reactive Form using FormGroup
let groups = [
new FormControl('', [Validators.required])
];
/** HTML **/
...
<input [id]="addr"
[formControlName]="address"
class="form-control"
type="text"
googlePlace
[placeholder]="question.label"
[(googlePlaceAddress)]="googleAddress">
...
However in this case the validation from the directive is never triggered.
I suppose angular2 expects it to be given through, when using Reactive Forms:
new FormControl('', [Validators.required, ???])
I must have taken a wrong path somewhere.
For future reference:
I solved my problem creating a component out of it together with a Value accessor:
#Component({
selector: 'app-google-place',
templateUrl: './google-place.component.html',
styleUrls: ['./google-place.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => GooglePlaceComponent),
multi: true
}
]
})
export class GooglePlaceComponent implements OnInit, ControlValueAccessor {
#ViewChild('inputElement') inputElement: ElementRef;
#Input() public placeholder: string = "Address";
#Input() public textValue: string = "";
private autocomplete: any;
private _place = null;
constructor(
private googleMapService: GoogleMapsService,
private zone: NgZone
) {
}
ngOnInit() {
this.googleMapService
.load()
.subscribe(
() => {
this.autocomplete = new google.maps.places.Autocomplete(this.inputElement.nativeElement);
this.autocomplete.addListener('place_changed', () => this.placeChanged());
}
);
}
placeChanged() {
this.zone.run(() => {
let place = this.autocomplete.getPlace();
this._place = {
address: this.inputElement.nativeElement.value,
formattedAddress: place.formatted_address,
latitude: place.geometry.location.lat(),
longitude: place.geometry.location.lng()
};
this.propagateChange(this._place);
});
}
onNgModelChange($event) {
if(this._place !== null) {
if(this._place.address !== $event) {
this._place = null;
this.propagateChange(this._place);
}
}
}
onBlur() {
this.propagateTouched();
}
writeValue(obj: any): void {
if(obj !== undefined) {
this._place = obj;
}
}
propagateChange = (_: any) => {};
registerOnChange(fn) {
this.propagateChange = fn;
}
propagateTouched = () => {};
registerOnTouched(fn: any): void {
this.propagateTouched = fn;
}
}
Using this I can use it in a FormGroup with the Validators.required and it will only be valid if a user has selected a google place.
EDIT
The html:
<input type="text"
(blur)="onBlur()"
#inputElement
class="form-control"
[(ngModel)]="textValue"
(ngModelChange)="onNgModelChange($event)">
The service:
import {Injectable} from '#angular/core';
import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
#Injectable()
export class GoogleMapsService {
private key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
private loaded = false;
private currentRequest = null;
constructor() {
}
load() {
if (this.loaded) {
return Observable.create((observer) => {
observer.next();
observer.complete();
});
}
if (this.currentRequest === null) {
//http://reactivex.io/rxjs/manual/overview.html#multicasted-observables
const source = Observable.create((observer) => {
this.loadMaps(observer);
});
const subject = new Subject();
this.currentRequest = source.multicast(subject);
this.currentRequest.connect();
}
return this.currentRequest;
}
private loadMaps(observer: any) {
const script: any = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?key=' + this.key + '&libraries=places';
if (script.readyState) { // IE, incl. IE9
script.onreadystatechange = () => {
if (script.readyState == 'loaded' || script.readyState == 'complete') {
script.onreadystatechange = null;
this.loaded = true;
observer.next();
observer.complete();
this.currentRequest = null;
}
};
} else {
script.onload = () => { // Other browsers
this.loaded = true;
observer.next();
observer.complete();
this.currentRequest = null;
};
}
script.onerror = () => {
observer.error('Unable to load');
this.currentRequest = null;
};
document.getElementsByTagName('head')[0].appendChild(script);
}
}
The 'usage':
With template ngModel
<app-google-place ([ngModel)]="place"></app-google-place>