calendarView = (dataset, feature, calendarType, setWidth, setCellSize, color = false) => {
const timeWeek = calendarType === "sunday" ? d3.utcSunday : d3.utcMonday
const countDay = calendarType === "sunday" ? d => d.getUTCDay() : d => (d.getUTCDay() + 6) % 7
if(color == false) {
color = d3.scaleSequential(d3.interpolatePiYG).domain(d3.extent(dataset, d => d[feature]))
}
function pathMonth(t) {
const n = calendarType === "weekday" ? 5 : 7;
const d = Math.max(0, Math.min(n, countDay(t)));
const w = timeWeek.count(d3.utcYear(t), t);
return `${d === 0 ? `M${w * setCellSize},0`
: d === n ? `M${(w + 1) * setCellSize},0`
: `M${(w + 1) * setCellSize},0V${d * setCellSize}H${w * setCellSize}`}V${n * setCellSize}`;
}
const height = setCellSize * (calendarType === "weekday" ? 7 : 9)
const years = d3.nest()
.key(d => d.date.getUTCFullYear())
.entries(dataset)
.reverse();
const svg = d3.select(DOM.svg(setWidth, height * years.length))
.style("font", "10px sans-serif")
.style("width", width)
.style("height", height * years.length);
const year = svg.selectAll("g")
.data(years)
.join("g")
.attr("transform", (d, i) => `translate(40,${height * i + cellSize * 1.5})`);
year.append("text")
.attr("x", -5)
.attr("y", -5)
.attr("font-weight", "bold")
.attr("text-anchor", "end")
.text(d => d.key);
year.append("g")
.attr("text-anchor", "end")
.selectAll("text")
.data((calendarType === "weekday" ? d3.range(2, 7) : d3.range(7)).map(i => new Date(1995, 0, i)))
.join("text")
.attr("x", -5)
.attr("y", d => (countDay(d) + 0.5) * cellSize)
.attr("dy", "0.31em")
.text(formatDay);
year.append("g")
.selectAll("rect")
.data(d => d.values)
.join("rect")
.attr("width", setCellSize - 1)
.attr("height", setCellSize - 1)
.attr("x", d => timeWeek.count(d3.utcYear(d.date), d.date) * setCellSize + 0.5)
.attr("y", d => countDay(d.date) * setCellSize + 0.5)
.attr("fill", d => color(d[feature]))
.append("title")
.text(d => `${formatDate(d.date)}: ${format(d[feature])}`);
const month = year.append("g")
.selectAll("g")
.data(d => d3.utcMonths(d3.utcMonth(d.values[0].date), d.values[d.values.length - 1].date))
.join("g");
month.filter((d, i) => i).append("path")
.attr("fill", "none")
.attr("stroke", "#fff")
.attr("stroke-width", 3)
.attr("d", pathMonth);
month.append("text")
.attr("x", d => timeWeek.count(d3.utcYear(d), timeWeek.ceil(d)) * setCellSize + 2)
.attr("y", -5)
.text(formatMonth);
return svg.node();
}