-
Notifications
You must be signed in to change notification settings - Fork 5
/
Timespanpicker.jsx
273 lines (252 loc) · 12 KB
/
Timespanpicker.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/* (c) Andrii Ulianenko */
import React, { Component, PropTypes } from 'react';
import * as d3 from 'd3';
import moment from 'moment';
import './timespanpicker.css';
const config = {
labelsPAdding: 13,
segmentsColorsArray: ['#bbb', '#ddd'],
defaultInnerRadiusIndex: 1.4,
defaultChartPadding: 60
};
class CircularTimespanpicker extends Component {
constructor(props) {
super(props);
this.state = {};
}
static propTypes = {
outerRadius : React.PropTypes.number,
innerRadius : React.PropTypes.number,
showResults : React.PropTypes.bool,
onClick : React.PropTypes.func,
interval : (props, propName, componentName) => {
const interval = props[propName];
if ( !Number.isInteger(interval) || interval > 60 || 60 % interval) {
return new Error(
`Invalid prop ${propName} supplied to ${componentName}. Validation failed.
Expects integer equal or less than 60 and 60 is divisible by it`
);
}
},
boundaryHour : (props, propName, componentName) => {
const boundaryHour = props[propName];
if ( !Number.isInteger(boundaryHour) || boundaryHour > 24) {
return new Error(
`Invalid prop ${propName} supplied to ${componentName}. Validation failed.
Expects integer less than 24`
);
}
},
};
static defaultProps = {
outerRadius : 150,
interval : 30,
boundaryHour: 8,
showResults : true,
onClick : (value) => { console.log (value) }
};
componentWillMount() {
let { outerRadius, innerRadius, interval, boundaryHour, onClick, showResults } = this.props;
innerRadius = (innerRadius && innerRadius < outerRadius) ? innerRadius : outerRadius/config.defaultInnerRadiusIndex;
const width = outerRadius * 2 + config.defaultChartPadding;
const segmentsInHour = 60/interval;
const totalNumberOfSegments = 720/interval;
const boundaryIsPostMeridiem = boundaryHour > 12;
const pie = d3.pie().sort(null).value(d => 1);
const segmentsArray = pie(new Array(totalNumberOfSegments));
const hoursLabelsArray = pie(new Array(12));
const colorScale = d3.scaleOrdinal().domain([0, 1, 2]).range(config.segmentsColorsArray);
const segmentsArcFn = d3.arc()
.outerRadius(outerRadius)
.innerRadius(innerRadius);
const minutesArcFn = d3.arc()
.outerRadius(outerRadius + config.labelsPAdding)
.innerRadius(outerRadius + config.labelsPAdding)
.startAngle(d => d.startAngle + Math.PI / totalNumberOfSegments)
.endAngle(d => d.endAngle + Math.PI / totalNumberOfSegments);
const hoursArcFn = d3.arc()
.outerRadius(outerRadius + config.labelsPAdding)
.innerRadius(outerRadius + config.labelsPAdding)
.startAngle(d => d.startAngle - 0.26)
.endAngle(d => d.endAngle - 0.26);
const initialObject = {
interval, boundaryHour, width, segmentsInHour, boundaryIsPostMeridiem,
segmentsArcFn, minutesArcFn, hoursArcFn, segmentsArray, showResults, onClick,
hoursLabelsArray, colorScale, innerRadius, outerRadius, totalNumberOfSegments
};
this.setState({ initialObject })
}
/* On click on segment convert simple segment's value [startValue, endValue] in moment.js object and save it in a state as "chosen" */
handleClick(clickedValue, isEntered) {
/* skip handling if click anf hover were started out of segments*/
if (isEntered && !this.state.initialObject.mouseIsClickedDown) return;
const clickedStartValue = clickedValue[0];
const clickedFinishValue = clickedValue[1];
const { initialObject: { boundaryHour, onClick }, ...segments } = this.state;
const segmentPreviousValue = segments[clickedFinishValue];
const segmentCurrentValue = {
[String(clickedFinishValue)]: segmentPreviousValue
? null
: [
moment().set('hour', boundaryHour).set('minute', 0).minute(clickedStartValue),
moment().set('hour', boundaryHour).set('minute', 0).minute(clickedFinishValue)
]
};
this.setState(segmentCurrentValue);
onClick({ ...segments, ...segmentCurrentValue})
}
/* Define an hours labels. "showSingleBoundaryHour" set displaying of doubled boundary hours (e.g. '8|20', '16|4') */
getHoursLabels(boundary, index, showSingleBoundaryHour) {
const hour24 = index + 12,
hour12 = showSingleBoundaryHour ? index: index || "00",
isInBottomQuadrants = (index > 3 && index < 10);
if (boundary > 12) {
boundary = boundary - 12;
if (index === boundary) return showSingleBoundaryHour ? hour24 : isInBottomQuadrants ? `${hour24} | ${hour12}` : `${hour12} | ${hour24}`;
return index < boundary ? hour12: hour24;
} else {
if (index === boundary) return showSingleBoundaryHour ? hour12 : isInBottomQuadrants ? `${hour12} | ${hour24}`: `${hour24} | ${hour12}`;
return index < boundary ? hour24 : hour12;
}
}
/* combine the neighbour short time spans in one union (e.g. '5:20-5:30' and '5:30-5:40' will be combined in a '5:20-5:40') */
getReducedArray(state) {
const keysArr = Object.keys(state).filter(key => key !== 'initialObject' && state[key]);
if (keysArr.length) {
if(keysArr.length === 1) {
/* if is single, returns it - no needs to combine */
return [state[keysArr[0]]];
} else {
/* combine time spans */
let reducedArr = keysArr.reduce((prev, currentKey) => {
let tempArr = Array.isArray(prev) ? prev : [state[prev]],
lastElement = tempArr[tempArr.length-1],
currentElement = state[currentKey];
if (!currentElement[0].diff(lastElement[1], 'minutes')) {
/*if last element finished in the same time current started, combine them as ['start of the last', 'end of the current]*/
tempArr[tempArr.length-1] = [lastElement[0], currentElement[1]]
} else {
tempArr.push(currentElement);
}
return tempArr
});
return reducedArr;
}
}
/* if there is no chosen spans in the state, returns empty array */
return []
}
getBoundaryLinesRotationDegree() {
let { boundaryHour, boundaryIsPostMeridiem } = this.state.initialObject;
return 30 * (boundaryIsPostMeridiem ? boundaryHour - 12 : boundaryHour);
/* 1 hour = 360 / 12 = 30 degrees */
}
setSegmentsValue(index) {
const {interval, boundaryHour, totalNumberOfSegments, segmentsInHour, boundaryIsPostMeridiem } = this.state.initialObject;
index = boundaryIsPostMeridiem ? index + totalNumberOfSegments : index;
const boundaryIndex = boundaryHour * segmentsInHour;
const recalculatedIndex = index - boundaryIndex + (index < boundaryIndex ? totalNumberOfSegments : 0);
const startMinutes = recalculatedIndex * interval;
return [startMinutes, startMinutes + interval]
}
storeMouseIsClickedDown(mouseIsClickedDown) {
const { initialObject } = this.state;
this.setState({initialObject: { ...initialObject, mouseIsClickedDown }})
}
render() {
if (!this.state.initialObject) return null;
const {
interval, boundaryHour, width, segmentsInHour,
segmentsArcFn, minutesArcFn, hoursArcFn, segmentsArray,
hoursLabelsArray, colorScale, outerRadius, innerRadius, showResults
} = this.state.initialObject;
return (
<div className="timepickerwrapper"
onMouseDown={()=>{this.storeMouseIsClickedDown(true)}}
onMouseUp={()=>{this.storeMouseIsClickedDown(false)}}
onMouseLeave={()=>{this.storeMouseIsClickedDown(false)}}
>
<svg width={width} height={width}>
<g transform={`translate(${width/2},${width/2})`}>
{segmentsArray.map((item, index) =>(
<Segment
key={index}
index={index}
item={item}
segmentArcFn={segmentsArcFn}
minutesArcFn={minutesArcFn}
label={((index % segmentsInHour) + 1) * interval}
fill={colorScale((Math.floor(index/segmentsInHour)) % 2)}
value={this.setSegmentsValue(index)}
handleClick={this.handleClick.bind(this)}
isActive={this.state[this.setSegmentsValue(index)[1]]}
/>
))}
<g className="hoursLabelsGroup">
{hoursLabelsArray.map((item, index) => (
<text
key={index}
className={`hourLabel${index === boundaryHour ? " boundary": ""}`}
transform={`translate(${hoursArcFn.centroid(item)})`}
dy=".35em"
style={{'textAnchor':'middle'}}
>
{this.getHoursLabels(boundaryHour, index, true)}
</text>
))}
</g>
<g className="boundaryGroup">
<path
className="boundaryLine"
d={`M 0 -${innerRadius-20} V -${outerRadius+4}`}
transform={`rotate(${this.getBoundaryLinesRotationDegree()})`}
/>
</g>
</g>
</svg>
{showResults ? <TimeResults results={this.getReducedArray(this.state)} /> : null}
</div>
);
}
}
export default CircularTimespanpicker;
/* Stateless Components */
function TimeResults(props) {
const { results } = props;
return results.length ?
(<div className="results">
<h6>Selected Time</h6>
{results.map((segment, n)=>(
segment.length ? <p key={n}>{segment[0].format('H:mm')} - {segment[1].format('H:mm')}</p> : null
)
)}
</div>)
: null
}
function Segment(props) {
const {item, segmentArcFn, minutesArcFn, label, fill, value, handleClick, isActive } = props;
return (
<g className={`segment${isActive ? " active":""}`}
onClick={()=>{handleClick(value)}}
onMouseDown={()=>{handleClick(value, true)}}
>
<path
d={segmentArcFn(item)}
fill={fill}
onMouseLeave={()=>{handleClick(value, true)}}
onDragLeave={()=>{handleClick(value, true)}}
onMouseDown={()=>{handleClick(value, true)}}
/>
{
label === 60 ? null :
<text
className="minuteLabel"
transform={`translate(${minutesArcFn.centroid(item)})`}
dy=".35em"
>
{label}
</text>
}
</g>
)
}