View.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. import { assignTo } from './util/object'
  2. import { parseFieldSpecs } from './util/misc'
  3. import Calendar from './Calendar'
  4. import { default as DateProfileGenerator, DateProfile } from './DateProfileGenerator'
  5. import DateComponent from './component/DateComponent'
  6. import { DateMarker, addDays, addMs, diffWholeDays } from './datelib/marker'
  7. import { createDuration } from './datelib/duration'
  8. import { createFormatter } from './datelib/formatting'
  9. import { default as EmitterMixin, EmitterInterface } from './common/EmitterMixin'
  10. import { OpenDateRange, parseRange, DateRange, rangesEqual } from './datelib/date-range'
  11. /* An abstract class from which other views inherit from
  12. ----------------------------------------------------------------------------------------------------------------------*/
  13. export default abstract class View extends DateComponent {
  14. on: EmitterInterface['on']
  15. one: EmitterInterface['one']
  16. off: EmitterInterface['off']
  17. trigger: EmitterInterface['trigger']
  18. triggerWith: EmitterInterface['triggerWith']
  19. hasHandlers: EmitterInterface['hasHandlers']
  20. type: string // subclass' view name (string)
  21. name: string // deprecated. use `type` instead
  22. title: string // the text that will be displayed in the header's title
  23. calendar: Calendar // owner Calendar object
  24. viewSpec: any
  25. options: any // hash containing all options. already merged with view-specific-options
  26. queuedScroll: any
  27. eventOrderSpecs: any // criteria for ordering events when they have same date/time
  28. // for date utils, computed from options
  29. isHiddenDayHash: boolean[]
  30. // now indicator
  31. isNowIndicatorRendered: boolean
  32. initialNowDate: DateMarker // result first getNow call
  33. initialNowQueriedMs: number // ms time the getNow was called
  34. nowIndicatorTimeoutID: any // for refresh timing of now indicator
  35. nowIndicatorIntervalID: any // "
  36. dateProfileGeneratorClass: any // initialized after class
  37. dateProfileGenerator: DateProfileGenerator
  38. // whether minTime/maxTime will affect the activeRange. Views must opt-in.
  39. // initialized after class
  40. usesMinMaxTime: boolean
  41. constructor(calendar, viewSpec) {
  42. super(null, viewSpec.options)
  43. this.calendar = calendar
  44. this.viewSpec = viewSpec
  45. // shortcuts
  46. this.type = viewSpec.type
  47. // .name is deprecated
  48. this.name = this.type
  49. this.initHiddenDays()
  50. this.dateProfileGenerator = new this.dateProfileGeneratorClass(this)
  51. this.eventOrderSpecs = parseFieldSpecs(this.opt('eventOrder'))
  52. this.initialize()
  53. }
  54. initialize() { // convenient for sublcasses
  55. }
  56. // Retrieves an option with the given name
  57. opt(name) {
  58. return this.options[name]
  59. }
  60. /* Title and Date Formatting
  61. ------------------------------------------------------------------------------------------------------------------*/
  62. // Computes what the title at the top of the calendar should be for this view
  63. computeTitle(dateProfile) {
  64. let dateEnv = this.getDateEnv()
  65. let range: DateRange
  66. // for views that span a large unit of time, show the proper interval, ignoring stray days before and after
  67. if (/^(year|month)$/.test(dateProfile.currentRangeUnit)) {
  68. range = dateProfile.currentRange
  69. } else { // for day units or smaller, use the actual day range
  70. range = dateProfile.activeRange
  71. }
  72. return dateEnv.formatRange(
  73. range.start,
  74. range.end,
  75. createFormatter(
  76. this.opt('titleFormat') || this.computeTitleFormat(dateProfile),
  77. this.opt('titleRangeSeparator')
  78. ),
  79. { isEndExclusive: dateProfile.isRangeAllDay }
  80. )
  81. }
  82. // Generates the format string that should be used to generate the title for the current date range.
  83. // Attempts to compute the most appropriate format if not explicitly specified with `titleFormat`.
  84. computeTitleFormat(dateProfile) {
  85. let currentRangeUnit = dateProfile.currentRangeUnit
  86. if (currentRangeUnit === 'year') {
  87. return { year: 'numeric' }
  88. } else if (currentRangeUnit === 'month') {
  89. return { year: 'numeric', month: 'long' } // like "September 2014"
  90. } else {
  91. let days = diffWholeDays(
  92. dateProfile.currentRange.start,
  93. dateProfile.currentRange.end
  94. )
  95. if (days !== null && days > 1) {
  96. // multi-day range. shorter, like "Sep 9 - 10 2014"
  97. return { year: 'numeric', month: 'short', day: 'numeric' }
  98. } else {
  99. // one day. longer, like "September 9 2014"
  100. return { year: 'numeric', month: 'long', day: 'numeric' }
  101. }
  102. }
  103. }
  104. // Date Setting/Unsetting
  105. // -----------------------------------------------------------------------------------------------------------------
  106. computeDateProfile(date: DateMarker): DateProfile {
  107. let dateProfile = this.dateProfileGenerator.build(date, undefined, true) // forceToValid=true
  108. if ( // reuse current reference if possible, for rendering optimization
  109. this.dateProfile &&
  110. rangesEqual(this.dateProfile.activeRange, dateProfile.activeRange)
  111. ) {
  112. return this.dateProfile
  113. }
  114. return dateProfile
  115. }
  116. get activeStart(): Date {
  117. return this.getDateEnv().toDate(this.dateProfile.activeRange.start)
  118. }
  119. get activeEnd(): Date {
  120. return this.getDateEnv().toDate(this.dateProfile.activeRange.end)
  121. }
  122. get currentStart(): Date {
  123. return this.getDateEnv().toDate(this.dateProfile.currentRange.start)
  124. }
  125. get currentEnd(): Date {
  126. return this.getDateEnv().toDate(this.dateProfile.currentRange.end)
  127. }
  128. // Skeleton Rendering
  129. // -----------------------------------------------------------------------------------------------------------------
  130. afterSkeletonRender() {
  131. this.publiclyTriggerAfterSizing('viewSkeletonRender', [
  132. {
  133. view: this,
  134. el: this.el
  135. }
  136. ])
  137. }
  138. beforeSkeletonUnrender() {
  139. this.publiclyTrigger('viewSkeletonDestroy', [
  140. {
  141. view: this,
  142. el: this.el
  143. }
  144. ])
  145. }
  146. // Date Rendering
  147. // -----------------------------------------------------------------------------------------------------------------
  148. afterDatesRender() {
  149. this.title = this.computeTitle(this.dateProfile)
  150. this.addScroll({ isDateInit: true })
  151. this.startNowIndicator() // shouldn't render yet because updateSize will be called soon
  152. this.publiclyTriggerAfterSizing('datesRender', [
  153. {
  154. view: this,
  155. el: this.el
  156. }
  157. ])
  158. }
  159. beforeDatesUnrender() {
  160. this.publiclyTrigger('datesDestroy', [
  161. {
  162. view: this,
  163. el: this.el
  164. }
  165. ])
  166. this.stopNowIndicator()
  167. }
  168. /* Now Indicator
  169. ------------------------------------------------------------------------------------------------------------------*/
  170. // Immediately render the current time indicator and begins re-rendering it at an interval,
  171. // which is defined by this.getNowIndicatorUnit().
  172. // TODO: somehow do this for the current whole day's background too
  173. startNowIndicator() {
  174. let dateEnv = this.getDateEnv()
  175. let unit
  176. let update
  177. let delay // ms wait value
  178. if (this.opt('nowIndicator')) {
  179. unit = this.getNowIndicatorUnit()
  180. if (unit) {
  181. update = this.updateNowIndicator.bind(this)
  182. this.initialNowDate = this.calendar.getNow()
  183. this.initialNowQueriedMs = new Date().valueOf()
  184. // wait until the beginning of the next interval
  185. delay = dateEnv.add(
  186. dateEnv.startOf(this.initialNowDate, unit),
  187. createDuration(1, unit)
  188. ).valueOf() - this.initialNowDate.valueOf()
  189. // TODO: maybe always use setTimeout, waiting until start of next unit
  190. this.nowIndicatorTimeoutID = setTimeout(() => {
  191. this.nowIndicatorTimeoutID = null
  192. update()
  193. if (unit === 'second') {
  194. delay = 1000 // every second
  195. } else {
  196. delay = 1000 * 60 // otherwise, every minute
  197. }
  198. this.nowIndicatorIntervalID = setInterval(update, delay) // update every interval
  199. }, delay)
  200. }
  201. // rendering will be initiated in updateSize
  202. }
  203. }
  204. // rerenders the now indicator, computing the new current time from the amount of time that has passed
  205. // since the initial getNow call.
  206. updateNowIndicator() {
  207. if (
  208. this.renderedFlags.dates &&
  209. this.initialNowDate // activated before?
  210. ) {
  211. this.unrenderNowIndicator() // won't unrender if unnecessary
  212. this.renderNowIndicator(
  213. addMs(this.initialNowDate, new Date().valueOf() - this.initialNowQueriedMs)
  214. )
  215. this.isNowIndicatorRendered = true
  216. }
  217. }
  218. // Immediately unrenders the view's current time indicator and stops any re-rendering timers.
  219. // Won't cause side effects if indicator isn't rendered.
  220. stopNowIndicator() {
  221. if (this.isNowIndicatorRendered) {
  222. if (this.nowIndicatorTimeoutID) {
  223. clearTimeout(this.nowIndicatorTimeoutID)
  224. this.nowIndicatorTimeoutID = null
  225. }
  226. if (this.nowIndicatorIntervalID) {
  227. clearInterval(this.nowIndicatorIntervalID)
  228. this.nowIndicatorIntervalID = null
  229. }
  230. this.unrenderNowIndicator()
  231. this.isNowIndicatorRendered = false
  232. }
  233. }
  234. /* Dimensions
  235. ------------------------------------------------------------------------------------------------------------------*/
  236. updateSize(totalHeight, isAuto, force) {
  237. super.updateSize(totalHeight, isAuto, force)
  238. this.updateNowIndicator()
  239. }
  240. /* Scroller
  241. ------------------------------------------------------------------------------------------------------------------*/
  242. addScroll(scroll) {
  243. let queuedScroll = this.queuedScroll || (this.queuedScroll = {})
  244. if (!queuedScroll.isLocked) {
  245. assignTo(queuedScroll, scroll)
  246. }
  247. }
  248. popScroll() {
  249. this.applyQueuedScroll()
  250. this.queuedScroll = null
  251. }
  252. applyQueuedScroll() {
  253. this.applyScroll(this.queuedScroll || {})
  254. }
  255. queryScroll() {
  256. let scroll = {} as any
  257. if (this.renderedFlags.dates) {
  258. assignTo(scroll, this.queryDateScroll())
  259. }
  260. return scroll
  261. }
  262. applyScroll(scroll) {
  263. if (scroll.isLocked) {
  264. delete scroll.isLocked
  265. }
  266. if (scroll.isDateInit) {
  267. delete scroll.isDateInit
  268. if (this.renderedFlags.dates) {
  269. assignTo(scroll, this.computeInitialDateScroll())
  270. }
  271. }
  272. if (this.renderedFlags.dates) {
  273. this.applyDateScroll(scroll)
  274. }
  275. }
  276. computeInitialDateScroll() {
  277. return {} // subclasses must implement
  278. }
  279. queryDateScroll() {
  280. return {} // subclasses must implement
  281. }
  282. applyDateScroll(scroll) {
  283. // subclasses must implement
  284. }
  285. /* Date Utils
  286. ------------------------------------------------------------------------------------------------------------------*/
  287. // For DateComponent::getDayClasses
  288. isDateInOtherMonth(date: DateMarker, dateProfile) {
  289. return false
  290. }
  291. // Arguments after name will be forwarded to a hypothetical function value
  292. // WARNING: passed-in arguments will be given to generator functions as-is and can cause side-effects.
  293. // Always clone your objects if you fear mutation.
  294. getRangeOption(name, ...otherArgs): OpenDateRange {
  295. let val = this.opt(name)
  296. if (typeof val === 'function') {
  297. val = val.apply(null, otherArgs)
  298. }
  299. if (val) {
  300. return parseRange(val, this.calendar.dateEnv)
  301. }
  302. }
  303. /* Hidden Days
  304. ------------------------------------------------------------------------------------------------------------------*/
  305. // Initializes internal variables related to calculating hidden days-of-week
  306. initHiddenDays() {
  307. let hiddenDays = this.opt('hiddenDays') || [] // array of day-of-week indices that are hidden
  308. let isHiddenDayHash = [] // is the day-of-week hidden? (hash with day-of-week-index -> bool)
  309. let dayCnt = 0
  310. let i
  311. if (this.opt('weekends') === false) {
  312. hiddenDays.push(0, 6) // 0=sunday, 6=saturday
  313. }
  314. for (i = 0; i < 7; i++) {
  315. if (
  316. !(isHiddenDayHash[i] = hiddenDays.indexOf(i) !== -1)
  317. ) {
  318. dayCnt++
  319. }
  320. }
  321. if (!dayCnt) {
  322. throw new Error('invalid hiddenDays') // all days were hidden? bad.
  323. }
  324. this.isHiddenDayHash = isHiddenDayHash
  325. }
  326. // Remove days from the beginning and end of the range that are computed as hidden.
  327. // If the whole range is trimmed off, returns null
  328. trimHiddenDays(range: DateRange): DateRange | null {
  329. let start = range.start
  330. let end = range.end
  331. if (start) {
  332. start = this.skipHiddenDays(start)
  333. }
  334. if (end) {
  335. end = this.skipHiddenDays(end, -1, true)
  336. }
  337. if (start == null || end == null || start < end) {
  338. return { start, end }
  339. }
  340. return null
  341. }
  342. // Is the current day hidden?
  343. // `day` is a day-of-week index (0-6), or a Date (used for UTC)
  344. isHiddenDay(day) {
  345. if (day instanceof Date) {
  346. day = day.getUTCDay()
  347. }
  348. return this.isHiddenDayHash[day]
  349. }
  350. // Incrementing the current day until it is no longer a hidden day, returning a copy.
  351. // DOES NOT CONSIDER validRange!
  352. // If the initial value of `date` is not a hidden day, don't do anything.
  353. // Pass `isExclusive` as `true` if you are dealing with an end date.
  354. // `inc` defaults to `1` (increment one day forward each time)
  355. skipHiddenDays(date: DateMarker, inc = 1, isExclusive = false) {
  356. while (
  357. this.isHiddenDayHash[(date.getUTCDay() + (isExclusive ? inc : 0) + 7) % 7]
  358. ) {
  359. date = addDays(date, inc)
  360. }
  361. return date
  362. }
  363. }
  364. EmitterMixin.mixInto(View)
  365. View.prototype.usesMinMaxTime = false
  366. View.prototype.dateProfileGeneratorClass = DateProfileGenerator