1 line
2.0 KiB
JavaScript
1 line
2.0 KiB
JavaScript
import{getDateRect,isSameDate,getMonthDateRect,isValidDate,getDate}from"../date";export default class TCalendar{constructor(e={}){this.type="single",Object.assign(this,e),this.minDate||(this.minDate=getDate()),this.maxDate||(this.maxDate=getDate(6))}getTrimValue(){const{value:e,type:t}=this,a=e=>e instanceof Date?e:"number"==typeof e?new Date(e):new Date;if("single"===t&&isValidDate(e))return a(e);if("multiple"===t||"range"===t){if(Array.isArray(e)){return e.every(e=>isValidDate(e))?e.map(e=>a(e)):[]}return[]}}getDays(e){const t=[];let a=this.firstDayOfWeek%7;for(;t.length<7;)t.push(e[a]),a=(a+1)%7;return t}getMonths(){const e=[],t=this.getTrimValue(),{minDate:a,maxDate:i,type:r,allowSameDay:s,format:n}=this,m=getDateRect(a);let{year:l,month:o}=m;const{time:D}=m,{year:h,month:u,time:y}=getDateRect(i),c=(e,a,i)=>{const n=new Date(e,a,i,23,59,59);if("single"===r&&t&&isSameDate({year:e,month:a,date:i},t))return"selected";if("multiple"===r&&t){if(t.some(t=>isSameDate({year:e,month:a,date:i},t)))return"selected"}if("range"===r&&t&&Array.isArray(t)){const[r,m]=t,l=r&&isSameDate({year:e,month:a,date:i},r),o=m&&isSameDate({year:e,month:a,date:i},m);if(l&&o&&s)return"start-end";if(l)return"start";if(o)return"end";if(r&&m&&n.getTime()>r.getTime()&&n.getTime()<m.getTime())return"centre"}const m=new Date(e,a,i,0,0,0);return n.getTime()<D||m.getTime()>y?"disabled":""};for(;l<h||l===h&&o<=u;){const t=getMonthDateRect(new Date(l,o,1)),a=[];for(let e=1;e<=31&&!(e>t.lastDate);e+=1){const t={date:new Date(l,o,e),day:e,type:c(l,o,e)};a.push(n?n(t):t)}e.push({year:l,month:o,months:a,weekdayOfFirstDay:t.weekdayOfFirstDay});const i=getDateRect(new Date(l,o+1,1));l=i.year,o=i.month}return e}select({cellType:e,year:t,month:a,date:i}){const{type:r}=this,s=this.getTrimValue();if("disabled"===e)return;const n=new Date(t,a,i);if(this.value=n,"range"===r&&Array.isArray(s))1===s.length&&n>=s[0]?this.value=[s[0],n]:this.value=[n];else if("multiple"===r&&Array.isArray(s)){const e=[...s],t=s.findIndex(e=>isSameDate(e,n));t>-1?e.splice(t,1):e.push(n),this.value=e}return this.value}} |