react-calendar-timeline pop up not working - react-calendar-timeline

I can't get an onclick popup to work for react-calendar-timeline
https://www.assuredlimited.co.uk/temp/react-calendar-timeline-demo/dist/index.asp is the link
itemRenderer: ({
item,
itemContext,
getItemProps,
getResizeProps
}) => {
const { left: leftResizeProps, right: rightResizeProps } = getResizeProps()
const Theetails = item.Address;
return ("<div {...getItemProps({style: {background, color, borderColor, boxShadow, borderStyle: 'solid', borderWidth: 1, borderRadius: 4, borderLeftWidth: itemContext.selected ? 3 : 1, borderRightWidth: itemContext.selected ? 3 : 1 } })} onMouseEnter={() =>{ this.setState({ showModal: true })}} onMouseLeave={() =>{this.setState({ showModal: false }) }} onClick={() =>{ this.setState({ showModal: false })}} > <div style={{ height: itemContext.dimensions.height,overflow: 'hidden',marginLeft: '10px',paddingLeft: 3,textOverflow: 'ellipsis',lineHeight: '20px',marginTop: '15px'}}>{itemContext.title}</div>{this.state.showModal && <div className='itemModal' style={{left: left,right: right}}><div className='itemModal'>" & TheDetails & "</div></div>}</div>")}
var props = {
groups: groups,
items: items,
fixedHeader: 'fixed',
canMove: false, // defaults
canResize: true,
itemsSorted: true,
itemTouchSendsClick: false,
stackItems: true,
itemHeightRatio: 0.75,
dragSnap: 1000 * 60 * 15,
itemRenderer: this.itemRenderer,
defaultTimeStart: new Date(TheMoment - (7 * OneDay)),
defaultTimeEnd: new Date(TheMoment + (7 * OneDay)),
minZoom: 60 * 60 * 1000, // 1 hour
maxZoom: 5 * 365.24 * 86400 * 1000, // 5 years
keys: {
groupIdKey: 'id',
groupTitleKey: 'title',
itemIdKey: 'id',
itemTitleKey: 'title',
itemGroupKey: 'group',
itemTimeStartKey: 'start',
itemTimeEndKey: 'end'
},
// this limits the timeline to -6 months ... +6 months
onTimeChange: function (visibleTimeStart, visibleTimeEnd) {
if (visibleTimeStart < minTime && visibleTimeEnd > maxTime) {
this.updateScrollCanvas(minTime, maxTime)
} else if (visibleTimeStart < minTime) {
this.updateScrollCanvas(minTime, minTime + (visibleTimeEnd - visibleTimeStart))
} else if (visibleTimeEnd > maxTime) {
this.updateScrollCanvas(maxTime - (visibleTimeEnd - visibleTimeStart), maxTime)
} else {
this.updateScrollCanvas(visibleTimeStart, visibleTimeEnd)
}
}
}
var filter = React.createElement("div", {}, "The filter");
/* jshint undef:false */
ReactDOM.render(React.createElement(ReactCalendarTimeline['default'], props, filter), document.getElementById('main'));
Is part of my code.nothing happesns when I click on a job title but I want the address to poup in a modal. Thanksenter code here

Related

How to detect click on chart js 3.7.1 axis label?

How to detect click on an axis label with chart.js
In the example bellow, I can only detect click on the graph itself
https://stackblitz.com/edit/ng2-charts-bar-template-qchyz6
You will need to implement a custom plugin that can listen to all the events of the canvas:
const findLabel = (labels, evt) => {
let found = false;
let res = null;
labels.forEach(l => {
l.labels.forEach((label, index) => {
if (evt.x > label.x && evt.x < label.x2 && evt.y > label.y && evt.y < label.y2) {
res = {
label: label.label,
index
};
found = true;
}
});
});
return [found, res];
};
const getLabelHitboxes = (scales) => (Object.values(scales).map((s) => ({
scaleId: s.id,
labels: s._labelItems.map((e, i) => ({
x: e.translation[0] - s._labelSizes.widths[i],
x2: e.translation[0] + s._labelSizes.widths[i] / 2,
y: e.translation[1] - s._labelSizes.heights[i] / 2,
y2: e.translation[1] + s._labelSizes.heights[i] / 2,
label: e.label,
index: i
}))
})));
const plugin = {
id: 'customHover',
afterEvent: (chart, event, opts) => {
const evt = event.event;
if (evt.type !== 'click') {
return;
}
const [found, labelInfo] = findLabel(getLabelHitboxes(chart.scales), evt);
if (found) {
console.log(labelInfo);
}
}
}
Chart.register(plugin);
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'orange'
}
]
},
options: {}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
</body>
Adpatation for Angular with ng2-charts (chart-js v3.7.1)
Just use Chart.register
i.e. put the following functiion into component ngOnInit()
RegisterPlugin() {
Chart.register(
{
id: 'yAxisCustomClick',
afterEvent: (chart: Chart<'bar'>, event: {
event: ChartEvent;
replay: boolean;
changed?: boolean | undefined;
cancelable: false;
inChartArea: boolean
}) => {
const evt = event.event;
if (evt.type === 'click' && evt.x! < Object.values(chart.scales).filter(s => s.id === 'x')[0].getBasePixel()) {
const labelIndex = Object.values(chart.scales).filter(s => s.id === 'y')[0].getValueForPixel(evt.y!);
const label = Object.values(chart.scales).filter(s => s.id === 'y')[0].getTicks()[labelIndex!]?.label;
if (label) {
console.log('Do the stuff for', label)
}
}
}
}
);
}
Example in stackblitz udpated
https://stackblitz.com/edit/ng2-charts-bar-template-qchyz6

Odd animation with multiple series

I was trying to adapt the spline animation for time series (https://www.highcharts.com/demo/dynamic-update) for multiple series.
I modified the example here https://jsfiddle.net/2wj3fquL/
Highcharts.chart('container', {
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series;
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.random();
series[0].addPoint([x, y], true, true);
y = Math.random();
series[1].addPoint([x, y], true, true);
}, 1000);
}
}
},
time: {
useUTC: false
},
title: {
text: 'Live random data'
},
accessibility: {
announceNewData: {
enabled: true,
minAnnounceInterval: 15000,
announcementFormatter: function (allSeries, newSeries, newPoint) {
if (newPoint) {
return 'New point added. Value: ' + newPoint.y;
}
return false;
}
}
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
headerFormat: '<b>{series.name}</b><br/>',
pointFormat: '{point.x:%Y-%m-%d %H:%M:%S}<br/>{point.y:.2f}'
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}, {
name: 'other data',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}]
});
Unfortunately the effect is odd since one series moves smooth while the other doesn't ...
How could I solve this problem?
Thanks
That is because the chart is redrawn twice. Disable redraw in the first addPoint method call.
events: {
load: function() {
...
setInterval(function() {
...
series[0].addPoint([x, y], false, true);
series[1].addPoint([x, y], true, true);
}, 1000);
}
}
Live demo: https://jsfiddle.net/BlackLabel/0n2yw57m/
API Reference: https://api.highcharts.com/class-reference/Highcharts.Series#addPoint

Is there a way to "simulate" pressing the refresh button to refresh a List?

Is there a way to "simulate" pressing the refresh button to refresh a List? I have a list that I want it to update every 10 seconds. Is there a way to "press" the refresh button every 10 seconds?
My list name is ActiveJobsList.
This is what I have at the moment:
export function autoRefresh() {
var counter = 10;
var id;
if(location.href.includes("activejobs")) {
id = setInterval(function() {
counter--;
if(counter < 0 && location.href.includes("activejobs")) {
// What should go here?
clearInterval(id);
}
}, 1000);
}
else if (!location.href.includes("activejobs"))
{
clearInterval(id);
}
}
Okay so I managed to figure it out.
I used
var x = document.getElementsByTagName('button');
console.log(x);
To figure out which button corresponded to the refresh button for admin-on-rest. In my case, it was the second button in the array.
Here is my updated code.
export function autoRefresh() {
var counter = 30;
var id;
if(location.href.includes("activejobs")) {
id = setInterval(function() {
counter--;
if(counter < 0 && location.href.includes("activejobs")) {
document.getElementsByTagName('button')[1].click();
counter = 30;
}
}, 1000);
}
else if (!location.href.includes("activejobs"))
{
counter = 30;
}
}
You could leverage React.Component.shouldComponentUpdate(), on your ActiveJobsList
https://facebook.github.io/react/docs/react-component.html#shouldcomponentupdate
I have created a component that provides a drop down menu for auto update setting. Here is the code and below it is an example of how to invoke it.
class AutoUpdt extends Component {
static propTypes = { setAutoUpdate : PropTypes.func
, interval : PropTypes.array
, iconColor : PropTypes.any
}
static defaultProps = { interval : [10,30,60,120,300,600,900,1800,3600]
, iconColor : '#00bcd4'
}
constructor(props) { super(props)
this.state = { open : false
, needrefresh : false
, intervaltime : false
}
}
handleTouchTap(event) { event.preventDefault()
this.setState({ open: true, anchorEl: event.currentTarget, })
}
handleRequestClose() { this.setState({ open: false, })
}
handleShow(event) { let intervaltime = event.currentTarget.innerText.toLowerCase().split(' (secs)')[0].trim()
let newintevaltime = (this.state.intervaltime === false) ? intervaltime : false
this.props.setAutoUpdate( newintevaltime )
this.setState({ open: false, needrefresh: true, intervaltime : newintevaltime})
}
render() {
return ( <div style={{ display: 'inline-block' }}>
<IconButton tooltip="Set Auto Update"
iconStyle={{ color: this.props.iconColor }}
onTouchTap={this.handleTouchTap.bind(this)} ><AutoIcon /></IconButton>
<Popover open={this.state.open}
anchorEl={this.state.anchorEl}
anchorOrigin={{ horizontal: 'left', vertical: 'bottom' }}
targetOrigin={{ horizontal: 'left', vertical: 'top' }}
onRequestClose={this.handleRequestClose.bind(this)} >
<Menu>
{this.props.interval.map( el =>
<ListItem style={( el.toString() !== this.state.intervaltime )
? { color:'#00bcd4' , margin: 0, padding : 2 }
: { color: '#f48fb1' , margin: 0, padding : 2 } }
data-key={ el.toString()}
key={el.toString()}
primaryText={ el.toString() + ' (secs)'}
onTouchTap={this.handleShow.bind(this)} /> )}
</Menu >
</Popover>
</div>)
}
}
// It is invoked by using these two functions in another component
checkMounted(){ this.props.checkMounted && this.props.checkMounted() && this.updateData()
}
setAutoUpdate = ( intervaltimer, checkMounted) => {
const this_ = this
this.state.intervaltimer && clearInterval(this.state.intervaltimer)
this.setState( intervaltimer ? { intervaltimer : setInterval( this_.checkMounted.bind(this_), +intervaltimer * 1000) } : { intervaltimer : false} )
}
// And using this line in the render function of the calling component
{ this.props.hasAuto && <AutoUpdt setAutoUpdate={this.setAutoUpdate} icon={<NavigationRefresh />} /> }

Calendar doesn't render any events after $scope.splice(0) and $scope.push(event)

Hi I have problem with angular ui-calendar(angular wrapper for arshaw's fullcalendar).
In the first state I load the events immediately through a $http call. The calendar renders as expected.
In the second step, I load unapproved or approved events according to result of showNeschvaleneTerminyFunction(). After this load however, calendar renders, but does not have any events. I verified that the object on scope has events and is being updated correctly by echoing the object on the screen. However the calendar does not ever show the events.
Could you please help me, how can I properly load and reload events with ajax from php driven storage?
Here is my code
$scope.events = [];
$scope.getTermins = function(){
if($scope.showNeschvaleneTerminy == true){
$http.get(plutanium.ajaxurl + '?action=terminy_read').success(function (data, status, headers, config) {
$scope.events.splice(0, $scope.events.length);
$className = '';
for (var i = 0; i < data.length; i++) {
if (data[i].status == 0) {
$className = 'b-danger';
} else {
$className = 'b-info';
}
$scope.events.push({
id: data[i].id,
title: data[i].jmeno,
start: moment(data[i].date).toDate(),
end: moment(data[i].date).add('hours', 1).toDate(),
allDay: false,
className: ['b-l b-2x ' + $className]
});
}
});
}else{
$http.get(plutanium.ajaxurl + '?action=terminy_approved').success(function (data, status, headers, config) {
$scope.events.splice(0, $scope.events.length);
$className = '';
for (var i = 0; i < data.length; i++) {
$scope.events.push({
id: data[i].id,
title: data[i].jmeno,
start: moment(data[i].date).toDate(),
end: moment(data[i].date).add('hours', 1).toDate(),
allDay: false,
className: ['b-l b-2x b-info']
});
}
});
}
}
$scope.getTermins();
$scope.showNeschvaleneTerminyFunction = function () {
if ($scope.showNeschvaleneTerminy == false) {
$scope.showNeschvaleneTerminy = true
} else {
$scope.showNeschvaleneTerminy = false
}
$scope.getTermins();
}
/* config object */
$scope.uiConfig = {
calendar1:{
defaultView: 'agendaDay',
height: $window.innerHeight-200,
firstDay: 1,
firstHour: 7,
slotMinutes: 60,
defaultEventMinutes: 120,
minTime: 7,
maxTime: 15,
editable: true,
header:{
left: '',
center: 'title',
right: ''
},
dayClick: $scope.AgendaOnDayClick,
eventClick: $scope.alertOnEventClick,
eventDrop: $scope.alertOnDrop,
//eventResize: $scope.alertOnResize,
//eventMouseover: $scope.alertOnMouseOver,
},
calendar2: {
editable: true,
header: {
left: 'prev',
center: 'title',
right: 'next'
},
height: $window.innerHeight - 200,
firstDay: 1,
minTime: 7,
maxTime: 15,
dayClick: $scope.MonthOnDayClick,
eventClick: $scope.alertOnEventClick,
eventDrop: $scope.alertOnDrop,
//eventResize: $scope.alertOnResize,
//eventMouseover: $scope.alertOnMouseOver,
dayRender: $scope.setDay
},
calendar3: {
defaultView: 'agendaDay',
editable: true,
header: {
left: '',
center: 'title',
right: ''
},
height: $window.innerHeight - 200,
firstDay: 1,
firstHour: 7,
slotMinutes: 60,
defaultEventMinutes: 120,
minTime: 7,
maxTime: 15,
dayClick: $scope.AgendaOnDayClick,
eventClick: $scope.alertOnEventClick,
eventDrop: $scope.alertOnDrop,
//eventResize: $scope.alertOnResize,
//eventMouseover: $scope.alertOnMouseOver,
}
};
$scope.eventSources = [$scope.events];
So I didn't find any solution to my problem, that's why I disabled ui-calendar wrapper and now I am calling fullcalendar refreshevents function manually after loading events to array. It works now like a charm.

No rows rendered by embertable but colums show up

I am using the newest ember and embertable. Tried to use example from the page and rewrite it for use in my MVC project. Problem is that rows will not show but the columns show.
Is this a problem with the new ember version?
Edit: Putting som more information here.
HTML
<script type="text/x-handlebars" data-template-name="application">
<div class='presentation-container'>
{{view Ember.Table.TablesContainer controllerBinding="tableController"}}
</div>
</script>
The output(No rows =/ )
Date Entry Low Open Volume High Close
EmployeetaskController
App.EmployeetasksController = Ember.Controller.extend({
tableController: Ember.computed(function () {
return Ember.get('App.EmployeetasksController.TableController').create();
}).property() });
App.EmployeetasksController.LazyDataSource = Ember.ArrayProxy.extend({
init: function () {
console.log('EmployeetasksController.LazyDataSource init');
enter code here this._super();
},
objectAt: function (idx) {
console.log("Lager rad");
var date, row;
row = this.get('content')[idx];
if (row) {
return row;
}
date = new Date();
date.setDate(date.getDate() + idx);
row = {
index: idx,
date: date,
open: Math.random() * 100 - 50,
high: Math.random() * 100 - 50,
low: Math.random() * 100 - 50,
close: Math.random() * 100 - 50,
volume: Math.random() * 1000000
};
this.get('content')[idx] = row;
return row;
}, });
App.EmployeetasksController.TableController = Ember.Table.TableController.extend({
init: function () {
console.log('EmployeetasksController.TableController init');
this._super();
},
hasHeader: true,
hasFooter: true,
numFixedColumns: 0,
numRows: 500000,
rowHeight: 30,
columns: Ember.computed(function () {
var columnNames, columns, dateColumn, entryColumn;
columnNames = ['open', 'high', 'low', 'close', 'volume'];
entryColumn = Ember.Table.ColumnDefinition.create({
columnWidth: 100,
headerCellName: 'Entry',
contentPath: 'index'
});
dateColumn = Ember.Table.ColumnDefinition.create({
columnWidth: 150,
headerCellName: 'Date',
getCellContent: function (row) {
return row['date'].toDateString();
}
});
columns = columnNames.map(function (key, index) {
var name;
name = key.charAt(0).toUpperCase() + key.slice(1);
return Ember.Table.ColumnDefinition.create({
columnWidth: 100,
headerCellName: name,
getCellContent: function (row) {
return row[key].toFixed(2);
}
});
});
columns.unshift(dateColumn);
columns.unshift(entryColumn);
return columns;
}).property(),
content: Ember.computed(function () {
console.log("Lager array");
return App.EmployeetasksController.LazyDataSource.create({
content: new Array(this.get('numRows'))
});
}).property('numRows') });
The view
App.EmployeetasksView = Ember.View.extend({
classNames: 'ember-app',
templateName: 'employeetasks'
});
Outdated ember and handlebars fixed it.

Resources