| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835 |
- import * as moment from 'moment'
- import { attrsToStr, htmlEscape } from '../util/html'
- import { dayIDs } from '../util/date'
- import momentExt from '../moment-ext'
- import { formatRange } from '../date-formatting'
- import Component from './Component'
- import { eventRangeToEventFootprint } from '../models/event/util'
- import EventFootprint from '../models/event/EventFootprint'
- export default abstract class DateComponent extends Component {
- static guid: number = 0 // TODO: better system for this?
- eventRendererClass: any
- helperRendererClass: any
- businessHourRendererClass: any
- fillRendererClass: any
- uid: any
- childrenByUid: any
- isRTL: boolean = false // frequently accessed options
- nextDayThreshold: any // "
- dateProfile: any // hack
- eventRenderer: any
- helperRenderer: any
- businessHourRenderer: any
- fillRenderer: any
- hitsNeededDepth: number = 0 // necessary because multiple callers might need the same hits
- hasAllDayBusinessHours: boolean = false // TODO: unify with largeUnit and isTimeScale?
- isDatesRendered: boolean = false
- constructor(_view?, _options?) {
- super()
- // hack to set options prior to the this.opt calls
- if (_view) {
- this['view'] = _view
- }
- if (_options) {
- this['options'] = _options
- }
- this.uid = String(DateComponent.guid++)
- this.childrenByUid = {}
- this.nextDayThreshold = moment.duration(this.opt('nextDayThreshold'))
- this.isRTL = this.opt('isRTL')
- if (this.fillRendererClass) {
- this.fillRenderer = new this.fillRendererClass(this)
- }
- if (this.eventRendererClass) { // fillRenderer is optional -----v
- this.eventRenderer = new this.eventRendererClass(this, this.fillRenderer)
- }
- if (this.helperRendererClass && this.eventRenderer) {
- this.helperRenderer = new this.helperRendererClass(this, this.eventRenderer)
- }
- if (this.businessHourRendererClass && this.fillRenderer) {
- this.businessHourRenderer = new this.businessHourRendererClass(this, this.fillRenderer)
- }
- }
- addChild(child) {
- if (!this.childrenByUid[child.uid]) {
- this.childrenByUid[child.uid] = child
- return true
- }
- return false
- }
- removeChild(child) {
- if (this.childrenByUid[child.uid]) {
- delete this.childrenByUid[child.uid]
- return true
- }
- return false
- }
- // TODO: only do if isInDom?
- // TODO: make part of Component, along with children/batch-render system?
- updateSize(totalHeight, isAuto, isResize) {
- this.callChildren('updateSize', arguments)
- }
- // Options
- // -----------------------------------------------------------------------------------------------------------------
- opt(name) {
- return this._getView().opt(name) // default implementation
- }
- publiclyTrigger(...args) {
- let calendar = this._getCalendar()
- return calendar.publiclyTrigger.apply(calendar, args)
- }
- hasPublicHandlers(...args) {
- let calendar = this._getCalendar()
- return calendar.hasPublicHandlers.apply(calendar, args)
- }
- // Date
- // -----------------------------------------------------------------------------------------------------------------
- executeDateRender(dateProfile) {
- this.dateProfile = dateProfile // for rendering
- this.renderDates(dateProfile)
- this.isDatesRendered = true
- this.callChildren('executeDateRender', arguments)
- }
- executeDateUnrender() { // wrapper
- this.callChildren('executeDateUnrender', arguments)
- this.dateProfile = null
- this.unrenderDates()
- this.isDatesRendered = false
- }
- // date-cell content only
- renderDates(dateProfile) {
- // subclasses should implement
- }
- // date-cell content only
- unrenderDates() {
- // subclasses should override
- }
- // Now-Indicator
- // -----------------------------------------------------------------------------------------------------------------
- // Returns a string unit, like 'second' or 'minute' that defined how often the current time indicator
- // should be refreshed. If something falsy is returned, no time indicator is rendered at all.
- getNowIndicatorUnit() {
- // subclasses should implement
- }
- // Renders a current time indicator at the given datetime
- renderNowIndicator(date) {
- this.callChildren('renderNowIndicator', arguments)
- }
- // Undoes the rendering actions from renderNowIndicator
- unrenderNowIndicator() {
- this.callChildren('unrenderNowIndicator', arguments)
- }
- // Business Hours
- // ---------------------------------------------------------------------------------------------------------------
- renderBusinessHours(businessHourGenerator) {
- if (this.businessHourRenderer) {
- this.businessHourRenderer.render(businessHourGenerator)
- }
- this.callChildren('renderBusinessHours', arguments)
- }
- // Unrenders previously-rendered business-hours
- unrenderBusinessHours() {
- this.callChildren('unrenderBusinessHours', arguments)
- if (this.businessHourRenderer) {
- this.businessHourRenderer.unrender()
- }
- }
- // Event Displaying
- // -----------------------------------------------------------------------------------------------------------------
- executeEventRender(eventsPayload) {
- if (this.eventRenderer) {
- this.eventRenderer.rangeUpdated() // poorly named now
- this.eventRenderer.render(eventsPayload)
- } else if (this['renderEvents']) { // legacy
- this['renderEvents'](convertEventsPayloadToLegacyArray(eventsPayload))
- }
- this.callChildren('executeEventRender', arguments)
- }
- executeEventUnrender() {
- this.callChildren('executeEventUnrender', arguments)
- if (this.eventRenderer) {
- this.eventRenderer.unrender()
- } else if (this['destroyEvents']) { // legacy
- this['destroyEvents']()
- }
- }
- getBusinessHourSegs() { // recursive
- let segs = this.getOwnBusinessHourSegs()
- this.iterChildren(function(child) {
- segs.push.apply(segs, child.getBusinessHourSegs())
- })
- return segs
- }
- getOwnBusinessHourSegs() {
- if (this.businessHourRenderer) {
- return this.businessHourRenderer.getSegs()
- }
- return []
- }
- getEventSegs() { // recursive
- let segs = this.getOwnEventSegs()
- this.iterChildren(function(child) {
- segs.push.apply(segs, child.getEventSegs())
- })
- return segs
- }
- getOwnEventSegs() { // just for itself
- if (this.eventRenderer) {
- return this.eventRenderer.getSegs()
- }
- return []
- }
- // Event Rendering Triggering
- // -----------------------------------------------------------------------------------------------------------------
- triggerAfterEventsRendered() {
- this.triggerAfterEventSegsRendered(
- this.getEventSegs()
- )
- this.publiclyTrigger('eventAfterAllRender', {
- context: this,
- args: [ this ]
- })
- }
- triggerAfterEventSegsRendered(segs) {
- // an optimization, because getEventLegacy is expensive
- if (this.hasPublicHandlers('eventAfterRender')) {
- segs.forEach((seg) => {
- let legacy
- if (seg.el) { // necessary?
- legacy = seg.footprint.getEventLegacy()
- this.publiclyTrigger('eventAfterRender', {
- context: legacy,
- args: [ legacy, seg.el, this ]
- })
- }
- })
- }
- }
- triggerBeforeEventsDestroyed() {
- this.triggerBeforeEventSegsDestroyed(
- this.getEventSegs()
- )
- }
- triggerBeforeEventSegsDestroyed(segs) {
- if (this.hasPublicHandlers('eventDestroy')) {
- segs.forEach((seg) => {
- let legacy
- if (seg.el) { // necessary?
- legacy = seg.footprint.getEventLegacy()
- this.publiclyTrigger('eventDestroy', {
- context: legacy,
- args: [ legacy, seg.el, this ]
- })
- }
- })
- }
- }
- // Event Rendering Utils
- // -----------------------------------------------------------------------------------------------------------------
- // Hides all rendered event segments linked to the given event
- // RECURSIVE with subcomponents
- showEventsWithId(eventDefId) {
- this.getEventSegs().forEach(function(seg) {
- if (
- seg.footprint.eventDef.id === eventDefId &&
- seg.el // necessary?
- ) {
- seg.el.style.visibility = ''
- }
- })
- this.callChildren('showEventsWithId', arguments)
- }
- // Shows all rendered event segments linked to the given event
- // RECURSIVE with subcomponents
- hideEventsWithId(eventDefId) {
- this.getEventSegs().forEach(function(seg) {
- if (
- seg.footprint.eventDef.id === eventDefId &&
- seg.el // necessary?
- ) {
- seg.el.style.visibility = 'hidden'
- }
- })
- this.callChildren('hideEventsWithId', arguments)
- }
- // Drag-n-Drop Rendering (for both events and external elements)
- // ---------------------------------------------------------------------------------------------------------------
- // Renders a visual indication of a event or external-element drag over the given drop zone.
- // If an external-element, seg will be `null`.
- // Must return elements used for any mock events.
- renderDrag(eventFootprints, seg?, isTouch = false) {
- let renderedHelper = false
- this.iterChildren(function(child) {
- if (child.renderDrag(eventFootprints, seg, isTouch)) {
- renderedHelper = true
- }
- })
- return renderedHelper
- }
- // Unrenders a visual indication of an event or external-element being dragged.
- unrenderDrag() {
- this.callChildren('unrenderDrag', arguments)
- }
- // EXTERNAL Drag-n-Drop
- // ---------------------------------------------------------------------------------------------------------------
- // Doesn't need to implement a response, but must pass to children
- handlExternalDragStart(ev, el, skipBinding) {
- this.callChildren('handlExternalDragStart', arguments)
- }
- handleExternalDragMove(ev) {
- this.callChildren('handleExternalDragMove', arguments)
- }
- handleExternalDragStop(ev) {
- this.callChildren('handleExternalDragStop', arguments)
- }
- // Event Resizing
- // ---------------------------------------------------------------------------------------------------------------
- // Renders a visual indication of an event being resized.
- renderEventResize(eventFootprints, seg, isTouch) {
- this.callChildren('renderEventResize', arguments)
- }
- // Unrenders a visual indication of an event being resized.
- unrenderEventResize() {
- this.callChildren('unrenderEventResize', arguments)
- }
- // Selection
- // ---------------------------------------------------------------------------------------------------------------
- // Renders a visual indication of the selection
- // TODO: rename to `renderSelection` after legacy is gone
- renderSelectionFootprint(componentFootprint) {
- this.renderHighlight(componentFootprint)
- this.callChildren('renderSelectionFootprint', arguments)
- }
- // Unrenders a visual indication of selection
- unrenderSelection() {
- this.unrenderHighlight()
- this.callChildren('unrenderSelection', arguments)
- }
- // Highlight
- // ---------------------------------------------------------------------------------------------------------------
- // Renders an emphasis on the given date range. Given a span (unzoned start/end and other misc data)
- renderHighlight(componentFootprint) {
- if (this.fillRenderer) {
- this.fillRenderer.renderFootprint(
- 'highlight',
- componentFootprint,
- {
- getClasses() {
- return [ 'fc-highlight' ]
- }
- }
- )
- }
- this.callChildren('renderHighlight', arguments)
- }
- // Unrenders the emphasis on a date range
- unrenderHighlight() {
- if (this.fillRenderer) {
- this.fillRenderer.unrender('highlight')
- }
- this.callChildren('unrenderHighlight', arguments)
- }
- // Hit Areas
- // ---------------------------------------------------------------------------------------------------------------
- // just because all DateComponents support this interface
- // doesn't mean they need to have their own internal coord system. they can defer to sub-components.
- hitsNeeded() {
- if (!(this.hitsNeededDepth++)) {
- this.prepareHits()
- }
- this.callChildren('hitsNeeded', arguments)
- }
- hitsNotNeeded() {
- if (this.hitsNeededDepth && !(--this.hitsNeededDepth)) {
- this.releaseHits()
- }
- this.callChildren('hitsNotNeeded', arguments)
- }
- prepareHits() {
- // subclasses can implement
- }
- releaseHits() {
- // subclasses can implement
- }
- // Given coordinates from the topleft of the document, return data about the date-related area underneath.
- // Can return an object with arbitrary properties (although top/right/left/bottom are encouraged).
- // Must have a `grid` property, a reference to this current grid. TODO: avoid this
- // The returned object will be processed by getHitFootprint and getHitEl.
- queryHit(leftOffset, topOffset) {
- let childrenByUid = this.childrenByUid
- let uid
- let hit
- for (uid in childrenByUid) {
- hit = childrenByUid[uid].queryHit(leftOffset, topOffset)
- if (hit) {
- break
- }
- }
- return hit
- }
- getSafeHitFootprint(hit) {
- let footprint = this.getHitFootprint(hit)
- if (!this.dateProfile.activeUnzonedRange.containsRange(footprint.unzonedRange)) {
- return null
- }
- return footprint
- }
- getHitFootprint(hit): any {
- // what about being abstract!?
- }
- // Given position-level information about a date-related area within the grid,
- // should return an element that best represents it. passed to dayClick callback.
- getHitEl(hit): HTMLElement | null {
- return null
- }
- /* Converting eventRange -> eventFootprint
- ------------------------------------------------------------------------------------------------------------------*/
- eventRangesToEventFootprints(eventRanges) {
- let eventFootprints = []
- let i
- for (i = 0; i < eventRanges.length; i++) {
- eventFootprints.push.apply( // append
- eventFootprints,
- this.eventRangeToEventFootprints(eventRanges[i])
- )
- }
- return eventFootprints
- }
- eventRangeToEventFootprints(eventRange): EventFootprint[] {
- return [ eventRangeToEventFootprint(eventRange) ]
- }
- /* Converting componentFootprint/eventFootprint -> segs
- ------------------------------------------------------------------------------------------------------------------*/
- eventFootprintsToSegs(eventFootprints) {
- let segs = []
- let i
- for (i = 0; i < eventFootprints.length; i++) {
- segs.push.apply(segs,
- this.eventFootprintToSegs(eventFootprints[i])
- )
- }
- return segs
- }
- // Given an event's span (unzoned start/end and other misc data), and the event itself,
- // slices into segments and attaches event-derived properties to them.
- // eventSpan - { start, end, isStart, isEnd, otherthings... }
- eventFootprintToSegs(eventFootprint) {
- let unzonedRange = eventFootprint.componentFootprint.unzonedRange
- let segs
- let i
- let seg
- segs = this.componentFootprintToSegs(eventFootprint.componentFootprint)
- for (i = 0; i < segs.length; i++) {
- seg = segs[i]
- if (!unzonedRange.isStart) {
- seg.isStart = false
- }
- if (!unzonedRange.isEnd) {
- seg.isEnd = false
- }
- seg.footprint = eventFootprint
- // TODO: rename to seg.eventFootprint
- }
- return segs
- }
- componentFootprintToSegs(componentFootprint) {
- return []
- }
- // Utils
- // ---------------------------------------------------------------------------------------------------------------
- callChildren(methodName, args) {
- this.iterChildren(function(child) {
- child[methodName].apply(child, args)
- })
- }
- iterChildren(func) {
- let childrenByUid = this.childrenByUid
- let uid
- for (uid in childrenByUid) {
- func(childrenByUid[uid])
- }
- }
- _getCalendar() { // TODO: strip out. move to generic parent.
- let t = (this as any)
- return t.calendar || t.view.calendar
- }
- _getView() { // TODO: strip out. move to generic parent.
- return (this as any).view
- }
- _getDateProfile() {
- return this._getView().get('dateProfile')
- }
- // Generates HTML for an anchor to another view into the calendar.
- // Will either generate an <a> tag or a non-clickable <span> tag, depending on enabled settings.
- // `gotoOptions` can either be a moment input, or an object with the form:
- // { date, type, forceOff }
- // `type` is a view-type like "day" or "week". default value is "day".
- // `attrs` and `innerHtml` are use to generate the rest of the HTML tag.
- buildGotoAnchorHtml(gotoOptions, attrs, innerHtml) {
- let date
- let type
- let forceOff
- let finalOptions
- if (moment.isMoment(gotoOptions) || typeof gotoOptions !== 'object') {
- date = gotoOptions // a single moment input
- } else {
- date = gotoOptions.date
- type = gotoOptions.type
- forceOff = gotoOptions.forceOff
- }
- date = momentExt(date) // if a string, parse it
- finalOptions = { // for serialization into the link
- date: date.format('YYYY-MM-DD'),
- type: type || 'day'
- }
- if (typeof attrs === 'string') {
- innerHtml = attrs
- attrs = null
- }
- attrs = attrs ? ' ' + attrsToStr(attrs) : '' // will have a leading space
- innerHtml = innerHtml || ''
- if (!forceOff && this.opt('navLinks')) {
- return '<a' + attrs +
- ' data-goto="' + htmlEscape(JSON.stringify(finalOptions)) + '">' +
- innerHtml +
- '</a>'
- } else {
- return '<span' + attrs + '>' +
- innerHtml +
- '</span>'
- }
- }
- getAllDayHtml() {
- return this.opt('allDayHtml') || htmlEscape(this.opt('allDayText'))
- }
- // Computes HTML classNames for a single-day element
- getDayClasses(date, noThemeHighlight?) {
- let view = this._getView()
- let classes = []
- let today
- if (!this.dateProfile.activeUnzonedRange.containsDate(date)) {
- classes.push('fc-disabled-day') // TODO: jQuery UI theme?
- } else {
- classes.push('fc-' + dayIDs[date.day()])
- if (view.isDateInOtherMonth(date, this.dateProfile)) { // TODO: use DateComponent subclass somehow
- classes.push('fc-other-month')
- }
- today = view.calendar.getNow()
- if (date.isSame(today, 'day')) {
- classes.push('fc-today')
- if (noThemeHighlight !== true) {
- classes.push(view.calendar.theme.getClass('today'))
- }
- } else if (date < today) {
- classes.push('fc-past')
- } else {
- classes.push('fc-future')
- }
- }
- return classes
- }
- // Utility for formatting a range. Accepts a range object, formatting string, and optional separator.
- // Displays all-day ranges naturally, with an inclusive end. Takes the current isRTL into account.
- // The timezones of the dates within `range` will be respected.
- formatRange(range, isAllDay, formatStr, separator) {
- let end = range.end
- if (isAllDay) {
- end = end.clone().subtract(1) // convert to inclusive. last ms of previous day
- }
- return formatRange(range.start, end, formatStr, separator, this.isRTL)
- }
- // Compute the number of the give units in the "current" range.
- // Will return a floating-point number. Won't round.
- currentRangeAs(unit) {
- return this._getDateProfile().currentUnzonedRange.as(unit)
- }
- // Returns the date range of the full days the given range visually appears to occupy.
- // Returns a plain object with start/end, NOT an UnzonedRange!
- computeDayRange(unzonedRange) {
- let calendar = this._getCalendar()
- let startDay = calendar.msToUtcMoment(unzonedRange.startMs, true) // the beginning of the day the range starts
- let end = calendar.msToUtcMoment(unzonedRange.endMs)
- let endTimeMS = +end.time() // # of milliseconds into `endDay`
- let endDay = end.clone().stripTime() // the beginning of the day the range exclusively ends
- // If the end time is actually inclusively part of the next day and is equal to or
- // beyond the next day threshold, adjust the end to be the exclusive end of `endDay`.
- // Otherwise, leaving it as inclusive will cause it to exclude `endDay`.
- if (endTimeMS && endTimeMS >= this.nextDayThreshold) {
- endDay.add(1, 'days')
- }
- // If end is within `startDay` but not past nextDayThreshold, assign the default duration of one day.
- if (endDay <= startDay) {
- endDay = startDay.clone().add(1, 'days')
- }
- return { start: startDay, end: endDay }
- }
- // Does the given range visually appear to occupy more than one day?
- isMultiDayRange(unzonedRange) {
- let dayRange = this.computeDayRange(unzonedRange)
- return dayRange.end.diff(dayRange.start, 'days') > 1
- }
- }
- // legacy
- function convertEventsPayloadToLegacyArray(eventsPayload) {
- let eventDefId
- let eventInstances
- let legacyEvents = []
- let i
- for (eventDefId in eventsPayload) {
- eventInstances = eventsPayload[eventDefId].eventInstances
- for (i = 0; i < eventInstances.length; i++) {
- legacyEvents.push(
- eventInstances[i].toLegacy()
- )
- }
- }
- return legacyEvents
- }
|