You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

VAbstractCalendarPanel.java 72KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224
  1. /*
  2. * Copyright 2000-2018 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client.ui;
  17. import static com.vaadin.client.DateTimeService.asTwoDigits;
  18. import java.util.Date;
  19. import java.util.HashMap;
  20. import java.util.List;
  21. import java.util.Map;
  22. import java.util.function.Predicate;
  23. import java.util.logging.Logger;
  24. import java.util.stream.Collectors;
  25. import java.util.stream.Stream;
  26. import com.google.gwt.aria.client.Id;
  27. import com.google.gwt.aria.client.Roles;
  28. import com.google.gwt.aria.client.SelectedValue;
  29. import com.google.gwt.dom.client.Element;
  30. import com.google.gwt.dom.client.NativeEvent;
  31. import com.google.gwt.event.dom.client.BlurEvent;
  32. import com.google.gwt.event.dom.client.BlurHandler;
  33. import com.google.gwt.event.dom.client.ClickHandler;
  34. import com.google.gwt.event.dom.client.DomEvent;
  35. import com.google.gwt.event.dom.client.FocusEvent;
  36. import com.google.gwt.event.dom.client.FocusHandler;
  37. import com.google.gwt.event.dom.client.KeyCodes;
  38. import com.google.gwt.event.dom.client.KeyDownEvent;
  39. import com.google.gwt.event.dom.client.KeyDownHandler;
  40. import com.google.gwt.event.dom.client.KeyPressEvent;
  41. import com.google.gwt.event.dom.client.KeyPressHandler;
  42. import com.google.gwt.event.dom.client.MouseDownEvent;
  43. import com.google.gwt.event.dom.client.MouseDownHandler;
  44. import com.google.gwt.event.dom.client.MouseOutEvent;
  45. import com.google.gwt.event.dom.client.MouseOutHandler;
  46. import com.google.gwt.event.dom.client.MouseUpEvent;
  47. import com.google.gwt.event.dom.client.MouseUpHandler;
  48. import com.google.gwt.i18n.client.DateTimeFormat;
  49. import com.google.gwt.user.client.DOM;
  50. import com.google.gwt.user.client.Event;
  51. import com.google.gwt.user.client.Timer;
  52. import com.google.gwt.user.client.ui.Button;
  53. import com.google.gwt.user.client.ui.FlexTable;
  54. import com.google.gwt.user.client.ui.InlineHTML;
  55. import com.google.gwt.user.client.ui.Widget;
  56. import com.vaadin.client.DateTimeService;
  57. import com.vaadin.client.WidgetUtil;
  58. import com.vaadin.client.ui.aria.AriaHelper;
  59. import com.vaadin.shared.util.SharedUtil;
  60. /**
  61. * Abstract calendar panel to show and select a date using a resolution. The
  62. * class is parameterized by the date resolution enumeration type.
  63. *
  64. * @author Vaadin Ltd
  65. *
  66. * @param <R>
  67. * the resolution type which this field is based on (day, month, ...)
  68. * @since 8.0
  69. */
  70. @SuppressWarnings("deprecation")
  71. public abstract class VAbstractCalendarPanel<R extends Enum<R>>
  72. extends FocusableFlexTable implements KeyDownHandler, KeyPressHandler,
  73. MouseOutHandler, MouseDownHandler, MouseUpHandler, BlurHandler,
  74. FocusHandler, SubPartAware {
  75. public interface SubmitListener {
  76. /**
  77. * Called when calendar user triggers a submitting operation in calendar
  78. * panel. E.g. clicking on day or hitting enter.
  79. */
  80. void onSubmit();
  81. /**
  82. * On e.g. ESC key.
  83. */
  84. void onCancel();
  85. }
  86. /**
  87. * Blur listener that listens to blur event from the panel.
  88. */
  89. public interface FocusOutListener {
  90. /**
  91. * @return true if the calendar panel is not used after focus moves out
  92. */
  93. boolean onFocusOut(DomEvent<?> event);
  94. }
  95. /**
  96. * FocusChangeListener is notified when the panel changes its _focused_
  97. * value.
  98. */
  99. public interface FocusChangeListener {
  100. void focusChanged(Date focusedDate);
  101. }
  102. /**
  103. * Represents a Date button in the calendar
  104. */
  105. private class VEventButton extends Button {
  106. public VEventButton() {
  107. addMouseDownHandler(VAbstractCalendarPanel.this);
  108. addMouseOutHandler(VAbstractCalendarPanel.this);
  109. addMouseUpHandler(VAbstractCalendarPanel.this);
  110. }
  111. }
  112. private static final String CN_FOCUSED = "focused";
  113. private static final String CN_TODAY = "today";
  114. private static final String CN_SELECTED = "selected";
  115. private static final String CN_OFFMONTH = "offmonth";
  116. private static final String CN_OUTSIDE_RANGE = "outside-range";
  117. private VEventButton prevYear;
  118. private VEventButton nextYear;
  119. private VEventButton prevMonth;
  120. private VEventButton nextMonth;
  121. private FlexTable days = new FlexTable();
  122. private R resolution;
  123. private Timer mouseTimer;
  124. private Date value;
  125. private DateTimeService dateTimeService;
  126. private boolean showISOWeekNumbers;
  127. private FocusedDate displayedMonth;
  128. private FocusedDate focusedDate;
  129. private Day selectedDay;
  130. private Day focusedDay;
  131. private FocusOutListener focusOutListener;
  132. private SubmitListener submitListener;
  133. private FocusChangeListener focusChangeListener;
  134. private boolean hasFocus = false;
  135. private VDateField<R> parent;
  136. private boolean initialRenderDone = false;
  137. private String prevMonthAssistiveLabel;
  138. private String nextMonthAssistiveLabel;
  139. private String prevYearAssistiveLabel;
  140. private String nextYearAssistiveLabel;
  141. /**
  142. * Represents a click handler for when a user selects a value by using the
  143. * mouse
  144. */
  145. private ClickHandler dayClickHandler = event -> {
  146. if (!isEnabled() || isReadonly()) {
  147. return;
  148. }
  149. Date newDate = ((Day) event.getSource()).getDate();
  150. if (!isDateInsideRange(newDate,
  151. getResolution(VAbstractCalendarPanel.this::isDay))) {
  152. return;
  153. }
  154. if (newDate.getMonth() != displayedMonth.getMonth()
  155. || newDate.getYear() != displayedMonth.getYear()) {
  156. // If an off-month date was clicked, we must change the
  157. // displayed month and re-render the calendar (#8931)
  158. displayedMonth.setMonth(newDate.getMonth());
  159. displayedMonth.setYear(newDate.getYear());
  160. renderCalendar();
  161. }
  162. focusDay(newDate);
  163. selectFocused();
  164. onSubmit();
  165. };
  166. private Map<String, String> dateStyles = new HashMap<String, String>();
  167. private DateTimeFormat df = DateTimeFormat.getFormat("yyyy-MM-dd");
  168. public VAbstractCalendarPanel() {
  169. getElement().setId(DOM.createUniqueId());
  170. setStyleName(VDateField.CLASSNAME + "-calendarpanel");
  171. Roles.getGridRole().set(getElement());
  172. addKeyDownHandler(this);
  173. addFocusHandler(this);
  174. addBlurHandler(this);
  175. }
  176. public void setParentField(VDateField<R> parent) {
  177. this.parent = parent;
  178. }
  179. /**
  180. * Sets the focus to given date in the current view. Used when moving in the
  181. * calendar with the keyboard.
  182. *
  183. * @param date
  184. * A Date representing the day of month to be focused. Must be
  185. * one of the days currently visible.
  186. */
  187. private void focusDay(Date date) {
  188. // Only used when calendar body is present
  189. if (acceptDayFocus()) {
  190. if (focusedDay != null) {
  191. focusedDay.removeStyleDependentName(CN_FOCUSED);
  192. }
  193. if (date != null && focusedDate != null) {
  194. focusedDate.setTime(date.getTime());
  195. int rowCount = days.getRowCount();
  196. for (int i = 0; i < rowCount; i++) {
  197. int cellCount = days.getCellCount(i);
  198. for (int j = 0; j < cellCount; j++) {
  199. Widget widget = days.getWidget(i, j);
  200. if (widget instanceof VAbstractCalendarPanel.Day) {
  201. Day curday = (Day) widget;
  202. if (curday.getDate().equals(date)) {
  203. curday.addStyleDependentName(CN_FOCUSED);
  204. focusedDay = curday;
  205. // Reference focused day from calendar panel
  206. Roles.getGridRole()
  207. .setAriaActivedescendantProperty(
  208. getElement(),
  209. Id.of(curday.getElement()));
  210. return;
  211. }
  212. }
  213. }
  214. }
  215. }
  216. }
  217. }
  218. /**
  219. * Returns {@code true} if current resolution assumes handling focus event
  220. * for day UI component.
  221. *
  222. * @return {@code true} if day focus events should be handled, {@code false}
  223. * otherwise
  224. */
  225. protected abstract boolean acceptDayFocus();
  226. /**
  227. * Returns {@code true} if the provided {@code resolution} represents a day.
  228. *
  229. * @param resolution
  230. * the given resolution
  231. * @return {@code true} if the {@code resolution} represents a day
  232. */
  233. protected abstract boolean isDay(R resolution);
  234. /**
  235. * Returns {@code true} if the provided {@code resolution} represents a
  236. * month.
  237. *
  238. * @param resolution
  239. * the given resolution
  240. * @return {@code true} if the {@code resolution} represents a month
  241. */
  242. protected abstract boolean isMonth(R resolution);
  243. /**
  244. * Returns {@code true} if the provided {@code resolution} represents an
  245. * year.
  246. *
  247. * @param resolution
  248. * the given resolution
  249. * @return {@code true} if the {@code resolution} represents a year
  250. */
  251. protected boolean isYear(R resolution) {
  252. return parent.isYear(resolution);
  253. }
  254. /**
  255. * Returns {@code true} if the {@code resolution} representation is strictly
  256. * below month (day, hour, etc..).
  257. *
  258. * @param resolution
  259. * the given resolution
  260. * @return whether the {@code resolution} is below the month resolution
  261. */
  262. protected abstract boolean isBelowMonth(R resolution);
  263. /**
  264. * Returns all available resolutions for the widget.
  265. *
  266. * @return all available resolutions
  267. */
  268. protected Stream<R> getResolutions() {
  269. return parent.getResolutions();
  270. }
  271. /**
  272. * Finds the resolution by the {@code filter}.
  273. *
  274. * @param filter
  275. * predicate to filter resolutions
  276. * @return the resolution accepted by the {@code filter}
  277. */
  278. protected R getResolution(Predicate<R> filter) {
  279. List<R> resolutions = getResolutions().filter(filter)
  280. .collect(Collectors.toList());
  281. assert resolutions
  282. .size() == 1 : "The result of filtering by the predicate "
  283. + "contains unexpected number of resolution items :"
  284. + resolutions.size();
  285. return resolutions.get(0);
  286. }
  287. /**
  288. * Sets the selection highlight to a given day in the current view
  289. *
  290. * @param date
  291. * A Date representing the day of month to be selected. Must be
  292. * one of the days currently visible.
  293. *
  294. */
  295. private void selectDate(Date date) {
  296. if (selectedDay != null) {
  297. selectedDay.removeStyleDependentName(CN_SELECTED);
  298. Roles.getGridcellRole()
  299. .removeAriaSelectedState(selectedDay.getElement());
  300. }
  301. int rowCount = days.getRowCount();
  302. for (int i = 0; i < rowCount; i++) {
  303. int cellCount = days.getCellCount(i);
  304. for (int j = 0; j < cellCount; j++) {
  305. Widget widget = days.getWidget(i, j);
  306. if (widget instanceof VAbstractCalendarPanel.Day) {
  307. Day curday = (Day) widget;
  308. if (curday.getDate().equals(date)) {
  309. curday.addStyleDependentName(CN_SELECTED);
  310. selectedDay = curday;
  311. Roles.getGridcellRole().setAriaSelectedState(
  312. selectedDay.getElement(), SelectedValue.TRUE);
  313. return;
  314. }
  315. }
  316. }
  317. }
  318. }
  319. /**
  320. * Updates year, month, day from focusedDate to value
  321. */
  322. private void selectFocused() {
  323. if (focusedDate != null
  324. && isDateInsideRange(focusedDate, getResolution())) {
  325. if (value == null) {
  326. // No previously selected value (set to null on server side).
  327. // Create a new date using current date and time
  328. value = new Date();
  329. }
  330. /*
  331. * #5594 set Date (day) to 1 in order to prevent any kind of
  332. * wrapping of months when later setting the month. (e.g. 31 ->
  333. * month with 30 days -> wraps to the 1st of the following month,
  334. * e.g. 31st of May -> 31st of April = 1st of May)
  335. */
  336. value.setDate(1);
  337. if (value.getYear() != focusedDate.getYear()) {
  338. value.setYear(focusedDate.getYear());
  339. }
  340. if (value.getMonth() != focusedDate.getMonth()) {
  341. value.setMonth(focusedDate.getMonth());
  342. }
  343. if (value.getDate() != focusedDate.getDate()) {
  344. }
  345. // We always need to set the date, even if it hasn't changed, since
  346. // it was forced to 1 above.
  347. value.setDate(focusedDate.getDate());
  348. selectDate(focusedDate);
  349. } else {
  350. getLogger()
  351. .info("Trying to select the focused date which is NULL!");
  352. }
  353. }
  354. protected boolean onValueChange() {
  355. return false;
  356. }
  357. public R getResolution() {
  358. return resolution;
  359. }
  360. public void setResolution(R resolution) {
  361. this.resolution = resolution;
  362. }
  363. /**
  364. * Checks whether the widget is not editable (read-only).
  365. *
  366. * @return {@code true} if the widget is read-only
  367. */
  368. protected boolean isReadonly() {
  369. return parent.isReadonly();
  370. }
  371. /**
  372. * Checks whether the widget is enabled.
  373. *
  374. * @return {@code true} is the widget is enabled
  375. */
  376. protected boolean isEnabled() {
  377. return parent.isEnabled();
  378. }
  379. @Override
  380. public void setStyleName(String style) {
  381. super.setStyleName(style);
  382. if (initialRenderDone) {
  383. // Dynamic updates to the stylename needs to render the calendar to
  384. // update the inner element stylenames
  385. renderCalendar();
  386. }
  387. }
  388. @Override
  389. public void setStylePrimaryName(String style) {
  390. super.setStylePrimaryName(style);
  391. if (initialRenderDone) {
  392. // Dynamic updates to the stylename needs to render the calendar to
  393. // update the inner element stylenames
  394. renderCalendar();
  395. }
  396. }
  397. /**
  398. * Sets the style names for dates.
  399. *
  400. * @param dateStyles
  401. * the map of date string to style name
  402. *
  403. * @since 8.3
  404. */
  405. public void setDateStyles(Map<String, String> dateStyles) {
  406. this.dateStyles.clear();
  407. if (dateStyles != null) {
  408. this.dateStyles.putAll(dateStyles);
  409. }
  410. }
  411. private void clearCalendarBody(boolean remove) {
  412. if (!remove) {
  413. // Leave the cells in place but clear their contents
  414. // This has the side effect of ensuring that the calendar always
  415. // contain 7 rows.
  416. for (int row = 1; row < 7; row++) {
  417. for (int col = 0; col < 8; col++) {
  418. days.setHTML(row, col, "&nbsp;");
  419. }
  420. }
  421. } else if (getRowCount() > 1) {
  422. removeRow(1);
  423. days.clear();
  424. }
  425. }
  426. /**
  427. * Builds the top buttons and current month and year header.
  428. *
  429. * @param needsMonth
  430. * Should the month buttons be visible?
  431. * @param needsBody
  432. * indicates whether the calendar body is drawn
  433. */
  434. private void buildCalendarHeader(boolean needsMonth, boolean needsBody) {
  435. getRowFormatter().addStyleName(0,
  436. parent.getStylePrimaryName() + "-calendarpanel-header");
  437. if (prevMonth == null && needsMonth) {
  438. prevMonth = new VEventButton();
  439. prevMonth.setHTML("&lsaquo;");
  440. prevMonth.setStyleName("v-button-prevmonth");
  441. nextMonth = new VEventButton();
  442. nextMonth.setHTML("&rsaquo;");
  443. nextMonth.setStyleName("v-button-nextmonth");
  444. setWidget(0, 3, nextMonth);
  445. setWidget(0, 1, prevMonth);
  446. Roles.getButtonRole().set(prevMonth.getElement());
  447. Roles.getButtonRole()
  448. .setTabindexExtraAttribute(prevMonth.getElement(), -1);
  449. Roles.getButtonRole().set(nextMonth.getElement());
  450. Roles.getButtonRole()
  451. .setTabindexExtraAttribute(nextMonth.getElement(), -1);
  452. } else if (prevMonth != null && !needsMonth) {
  453. // Remove month traverse buttons
  454. remove(prevMonth);
  455. remove(nextMonth);
  456. prevMonth = null;
  457. nextMonth = null;
  458. }
  459. if (prevYear == null) {
  460. prevYear = new VEventButton();
  461. prevYear.setHTML("&laquo;");
  462. prevYear.setStyleName("v-button-prevyear");
  463. nextYear = new VEventButton();
  464. nextYear.setHTML("&raquo;");
  465. nextYear.setStyleName("v-button-nextyear");
  466. setWidget(0, 0, prevYear);
  467. setWidget(0, 4, nextYear);
  468. Roles.getButtonRole().set(prevYear.getElement());
  469. Roles.getButtonRole()
  470. .setTabindexExtraAttribute(prevYear.getElement(), -1);
  471. Roles.getButtonRole().set(nextYear.getElement());
  472. Roles.getButtonRole()
  473. .setTabindexExtraAttribute(nextYear.getElement(), -1);
  474. }
  475. updateControlButtonRangeStyles(needsMonth);
  476. updateAssistiveLabels();
  477. final String monthName = needsMonth
  478. ? getDateTimeService().getMonth(displayedMonth.getMonth())
  479. : "";
  480. final int year = displayedMonth.getYear() + 1900;
  481. getFlexCellFormatter().setStyleName(0, 2,
  482. parent.getStylePrimaryName() + "-calendarpanel-month");
  483. getFlexCellFormatter().setStyleName(0, 0,
  484. parent.getStylePrimaryName() + "-calendarpanel-prevyear");
  485. getFlexCellFormatter().setStyleName(0, 4,
  486. parent.getStylePrimaryName() + "-calendarpanel-nextyear");
  487. getFlexCellFormatter().setStyleName(0, 3,
  488. parent.getStylePrimaryName() + "-calendarpanel-nextmonth");
  489. getFlexCellFormatter().setStyleName(0, 1,
  490. parent.getStylePrimaryName() + "-calendarpanel-prevmonth");
  491. // Set ID to be referenced from focused date or calendar panel
  492. Element monthYearElement = getFlexCellFormatter().getElement(0, 2);
  493. AriaHelper.ensureHasId(monthYearElement);
  494. Event.sinkEvents(monthYearElement, Event.ONCLICK);
  495. Event.setEventListener(monthYearElement, event -> {
  496. // Don't handle header clicks if resolution in below month
  497. if (!isEnabled() || isReadonly() || isBelowMonth(getResolution())) {
  498. return;
  499. }
  500. selectFocused();
  501. onSubmit();
  502. });
  503. if (!needsBody) {
  504. Roles.getGridRole().setAriaLabelledbyProperty(getElement(),
  505. Id.of(monthYearElement));
  506. } else {
  507. Roles.getGridRole().removeAriaLabelledbyProperty(getElement());
  508. }
  509. setHTML(0, 2,
  510. "<span class=\"" + parent.getStylePrimaryName()
  511. + "-calendarpanel-month\">" + monthName + " " + year
  512. + "</span>");
  513. if (!isBelowMonth(getResolution())) {
  514. monthYearElement.addClassName("header-month-year");
  515. }
  516. }
  517. private void updateControlButtonRangeStyles(boolean needsMonth) {
  518. if (focusedDate == null) {
  519. return;
  520. }
  521. if (needsMonth) {
  522. Date prevMonthDate = (Date) focusedDate.clone();
  523. removeOneMonth(prevMonthDate);
  524. R month = getResolution(VAbstractCalendarPanel.this::isMonth);
  525. if (!isDateInsideRange(prevMonthDate, month)) {
  526. prevMonth.addStyleName(CN_OUTSIDE_RANGE);
  527. } else {
  528. prevMonth.removeStyleName(CN_OUTSIDE_RANGE);
  529. }
  530. Date nextMonthDate = (Date) focusedDate.clone();
  531. addOneMonth(nextMonthDate);
  532. if (!isDateInsideRange(nextMonthDate, month)) {
  533. nextMonth.addStyleName(CN_OUTSIDE_RANGE);
  534. } else {
  535. nextMonth.removeStyleName(CN_OUTSIDE_RANGE);
  536. }
  537. }
  538. Date prevYearDate = (Date) focusedDate.clone();
  539. prevYearDate.setYear(prevYearDate.getYear() - 1);
  540. R year = getResolution(VAbstractCalendarPanel.this::isYear);
  541. if (!isDateInsideRange(prevYearDate, year)) {
  542. prevYear.addStyleName(CN_OUTSIDE_RANGE);
  543. } else {
  544. prevYear.removeStyleName(CN_OUTSIDE_RANGE);
  545. }
  546. Date nextYearDate = (Date) focusedDate.clone();
  547. nextYearDate.setYear(nextYearDate.getYear() + 1);
  548. if (!isDateInsideRange(nextYearDate, year)) {
  549. nextYear.addStyleName(CN_OUTSIDE_RANGE);
  550. } else {
  551. nextYear.removeStyleName(CN_OUTSIDE_RANGE);
  552. }
  553. }
  554. /**
  555. * Returns date time service for the widget.
  556. *
  557. * @see #setDateTimeService(DateTimeService)
  558. *
  559. * @return date time service
  560. */
  561. protected DateTimeService getDateTimeService() {
  562. return dateTimeService;
  563. }
  564. /**
  565. * Returns the date field which this panel is attached to.
  566. *
  567. * @return the "parent" date field
  568. */
  569. protected VDateField<R> getDateField() {
  570. return parent;
  571. }
  572. public void setDateTimeService(DateTimeService dateTimeService) {
  573. this.dateTimeService = dateTimeService;
  574. }
  575. /**
  576. * Returns whether ISO 8601 week numbers should be shown in the value
  577. * selector or not. ISO 8601 defines that a week always starts with a Monday
  578. * so the week numbers are only shown if this is the case.
  579. *
  580. * @return true if week number should be shown, false otherwise
  581. */
  582. public boolean isShowISOWeekNumbers() {
  583. return showISOWeekNumbers;
  584. }
  585. public void setShowISOWeekNumbers(boolean showISOWeekNumbers) {
  586. this.showISOWeekNumbers = showISOWeekNumbers;
  587. if (initialRenderDone && isBelowMonth(resolution)) {
  588. clearCalendarBody(false);
  589. buildCalendarBody();
  590. }
  591. }
  592. /**
  593. * Checks inclusively whether a date is inside a range of dates or not.
  594. *
  595. * @param date
  596. * @return
  597. */
  598. private boolean isDateInsideRange(Date date, R minResolution) {
  599. assert (date != null);
  600. return isAcceptedByRangeEnd(date, minResolution)
  601. && isAcceptedByRangeStart(date, minResolution);
  602. }
  603. /**
  604. * Accepts dates greater than or equal to rangeStart, depending on the
  605. * resolution. If the resolution is set to DAY, the range will compare on a
  606. * day-basis. If the resolution is set to YEAR, only years are compared. So
  607. * even if the range is set to one millisecond in next year, also next year
  608. * will be included.
  609. *
  610. * @param date
  611. * @param minResolution
  612. * @return
  613. */
  614. private boolean isAcceptedByRangeStart(Date date, R minResolution) {
  615. assert (date != null);
  616. // rangeStart == null means that we accept all values below rangeEnd
  617. if (rangeStart == null) {
  618. return true;
  619. }
  620. String dateStrResolution = dateStrResolution(date, minResolution);
  621. return rangeStart.substring(0, dateStrResolution.length())
  622. .compareTo(dateStrResolution) <= 0;
  623. }
  624. private String dateStrResolution(Date date, R minResolution) {
  625. String dateStrResolution = (1900 + date.getYear()) + "";
  626. while (dateStrResolution.length() < 4) {
  627. dateStrResolution = "0" + dateStrResolution;
  628. }
  629. if (!isYear(minResolution)) {
  630. dateStrResolution += "-" + asTwoDigits(1 + date.getMonth());
  631. if (!isMonth(minResolution)) {
  632. dateStrResolution += "-" + asTwoDigits(date.getDate());
  633. }
  634. }
  635. return dateStrResolution;
  636. }
  637. /**
  638. * Accepts dates earlier than or equal to rangeStart, depending on the
  639. * resolution. If the resolution is set to DAY, the range will compare on a
  640. * day-basis. If the resolution is set to YEAR, only years are compared. So
  641. * even if the range is set to one millisecond in next year, also next year
  642. * will be included.
  643. *
  644. * @param date
  645. * @param minResolution
  646. * @return
  647. */
  648. private boolean isAcceptedByRangeEnd(Date date, R minResolution) {
  649. assert (date != null);
  650. // rangeEnd == null means that we accept all values above rangeStart
  651. if (rangeEnd == null) {
  652. return true;
  653. }
  654. // If dateStrResolution has more year digits than rangeEnd, we need
  655. // to pad it in order to be lexicographically compatible
  656. String dateStrResolution = dateStrResolution(date, minResolution);
  657. String paddedEnd = rangeEnd.substring(0);
  658. int yearDigits = dateStrResolution.indexOf("-");
  659. if (yearDigits == -1) {
  660. yearDigits = dateStrResolution.length();
  661. }
  662. while (paddedEnd.indexOf("-") < yearDigits) {
  663. paddedEnd = "0" + paddedEnd;
  664. }
  665. return paddedEnd.substring(0, dateStrResolution.length())
  666. .compareTo(dateStrResolution) >= 0;
  667. }
  668. private static Date clearDateBelowMonth(Date date) {
  669. date.setDate(1);
  670. return clearDateBelowDay(date);
  671. }
  672. private static Date clearDateBelowDay(Date date) {
  673. date.setHours(0);
  674. date.setMinutes(0);
  675. date.setSeconds(0);
  676. // Clearing milliseconds
  677. long time = date.getTime() / 1000;
  678. date = new Date(time * 1000);
  679. return date;
  680. }
  681. /**
  682. * Builds the day and time selectors of the calendar.
  683. */
  684. private void buildCalendarBody() {
  685. final int weekColumn = 0;
  686. final int firstWeekdayColumn = 1;
  687. final int headerRow = 0;
  688. setWidget(1, 0, days);
  689. setCellPadding(0);
  690. setCellSpacing(0);
  691. getFlexCellFormatter().setColSpan(1, 0, 5);
  692. getFlexCellFormatter().setStyleName(1, 0,
  693. getDateField().getStylePrimaryName() + "-calendarpanel-body");
  694. days.getFlexCellFormatter().setStyleName(headerRow, weekColumn,
  695. "v-week");
  696. days.setHTML(headerRow, weekColumn, "<strong></strong>");
  697. // Hide the week column if week numbers are not to be displayed.
  698. days.getFlexCellFormatter().setVisible(headerRow, weekColumn,
  699. isShowISOWeekNumbers());
  700. days.getRowFormatter().setStyleName(headerRow,
  701. getDateField().getStylePrimaryName()
  702. + "-calendarpanel-weekdays");
  703. if (isShowISOWeekNumbers()) {
  704. days.getFlexCellFormatter().setStyleName(headerRow, weekColumn,
  705. "v-first");
  706. days.getFlexCellFormatter().setStyleName(headerRow,
  707. firstWeekdayColumn, "");
  708. days.getRowFormatter().addStyleName(headerRow,
  709. getDateField().getStylePrimaryName()
  710. + "-calendarpanel-weeknumbers");
  711. } else {
  712. days.getFlexCellFormatter().setStyleName(headerRow, weekColumn, "");
  713. days.getFlexCellFormatter().setStyleName(headerRow,
  714. firstWeekdayColumn, "v-first");
  715. }
  716. days.getFlexCellFormatter().setStyleName(headerRow,
  717. firstWeekdayColumn + 6, "v-last");
  718. // Print weekday names
  719. final int firstDay = getDateTimeService().getFirstDayOfWeek();
  720. for (int i = 0; i < 7; i++) {
  721. int day = (i + firstDay) % 7;
  722. if (isBelowMonth(getResolution())) {
  723. days.setHTML(headerRow, firstWeekdayColumn + i, "<strong>"
  724. + getDateTimeService().getShortDay(day) + "</strong>");
  725. } else {
  726. days.setHTML(headerRow, firstWeekdayColumn + i, "");
  727. }
  728. Roles.getColumnheaderRole().set(days.getCellFormatter()
  729. .getElement(headerRow, firstWeekdayColumn + i));
  730. }
  731. // Zero out hours, minutes, seconds, and milliseconds to compare dates
  732. // without time part
  733. final Date tmp = new Date();
  734. final Date today = new Date(tmp.getYear(), tmp.getMonth(),
  735. tmp.getDate());
  736. final Date selectedDate = value == null ? null
  737. : new Date(value.getYear(), value.getMonth(), value.getDate());
  738. final int startWeekDay = getDateTimeService()
  739. .getStartWeekDay(displayedMonth);
  740. final Date curr = (Date) displayedMonth.clone();
  741. // Start from the first day of the week that at least partially belongs
  742. // to the current month
  743. curr.setDate(1 - startWeekDay);
  744. // No month has more than 6 weeks so 6 is a safe maximum for rows.
  745. for (int weekOfMonth = 1; weekOfMonth < 7; weekOfMonth++) {
  746. for (int dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) {
  747. // Actually write the day of month
  748. Date dayDate = (Date) curr.clone();
  749. Day day = new Day(dayDate);
  750. // Set ID with prefix of the calendar panel's ID
  751. day.getElement().setId(getElement().getId() + "-" + weekOfMonth
  752. + "-" + dayOfWeek);
  753. // Set assistive label to read focused date and month/year
  754. Roles.getButtonRole().set(day.getElement());
  755. Roles.getButtonRole().setAriaLabelledbyProperty(
  756. day.getElement(), Id.of(day.getElement()),
  757. Id.of(getFlexCellFormatter().getElement(0, 2)));
  758. day.setStyleName(getDateField().getStylePrimaryName()
  759. + "-calendarpanel-day");
  760. if (!isDateInsideRange(dayDate, getResolution(this::isDay))) {
  761. day.addStyleDependentName(CN_OUTSIDE_RANGE);
  762. }
  763. if (curr.equals(selectedDate)) {
  764. day.addStyleDependentName(CN_SELECTED);
  765. Roles.getGridcellRole().setAriaSelectedState(
  766. day.getElement(), SelectedValue.TRUE);
  767. selectedDay = day;
  768. }
  769. if (curr.equals(today)) {
  770. day.addStyleDependentName(CN_TODAY);
  771. }
  772. if (curr.equals(focusedDate)) {
  773. focusedDay = day;
  774. if (hasFocus) {
  775. day.addStyleDependentName(CN_FOCUSED);
  776. // Reference focused day from calendar panel
  777. Roles.getGridRole().setAriaActivedescendantProperty(
  778. getElement(), Id.of(day.getElement()));
  779. }
  780. }
  781. if (curr.getMonth() != displayedMonth.getMonth()) {
  782. day.addStyleDependentName(CN_OFFMONTH);
  783. }
  784. String dayDateString = df.format(dayDate);
  785. if (dateStyles.containsKey(dayDateString)) {
  786. day.addStyleName(dateStyles.get(dayDateString));
  787. }
  788. days.setWidget(weekOfMonth, firstWeekdayColumn + dayOfWeek,
  789. day);
  790. Roles.getGridcellRole().set(days.getCellFormatter().getElement(
  791. weekOfMonth, firstWeekdayColumn + dayOfWeek));
  792. // ISO week numbers if requested
  793. days.getCellFormatter().setVisible(weekOfMonth, weekColumn,
  794. isShowISOWeekNumbers());
  795. if (isShowISOWeekNumbers()) {
  796. final String baseCssClass = getDateField()
  797. .getStylePrimaryName()
  798. + "-calendarpanel-weeknumber";
  799. String weekCssClass = baseCssClass;
  800. int weekNumber = DateTimeService.getISOWeekNumber(curr);
  801. days.setHTML(weekOfMonth, 0, "<span class=\"" + weekCssClass
  802. + "\"" + ">" + weekNumber + "</span>");
  803. }
  804. curr.setDate(curr.getDate() + 1);
  805. }
  806. }
  807. }
  808. /**
  809. * Updates the calendar and text field with the selected dates.
  810. */
  811. public void renderCalendar() {
  812. renderCalendar(true);
  813. }
  814. /**
  815. * Returns the value of initialRenderDone
  816. *
  817. * @since 8.7
  818. */
  819. public boolean isInitialRenderDone() {
  820. return initialRenderDone;
  821. }
  822. /**
  823. * For internal use only. May be removed or replaced in the future.
  824. *
  825. * Updates the calendar and text field with the selected dates.
  826. *
  827. * @param updateDate
  828. * The value false prevents setting the selected date of the
  829. * calendar based on focusedDate. That can be used when only the
  830. * resolution of the calendar is changed and no date has been
  831. * selected.
  832. */
  833. @SuppressWarnings("rawtypes")
  834. public void renderCalendar(boolean updateDate) {
  835. if (parent instanceof VAbstractPopupCalendar
  836. && !((VAbstractPopupCalendar) parent).popup.isShowing()) {
  837. // a popup that isn't open cannot possibly need a focus change event
  838. updateDate = false;
  839. }
  840. doRenderCalendar(updateDate);
  841. initialRenderDone = true;
  842. }
  843. /**
  844. * Performs the rendering required by the {@link #renderCalendar(boolean)}.
  845. * Subclasses may override this method to provide a custom implementation
  846. * avoiding {@link #renderCalendar(boolean)} override. The latter method
  847. * contains a common logic which should not be overridden.
  848. *
  849. * @param updateDate
  850. * The value false prevents setting the selected date of the
  851. * calendar based on focusedDate. That can be used when only the
  852. * resolution of the calendar is changed and no date has been
  853. * selected.
  854. */
  855. protected void doRenderCalendar(boolean updateDate) {
  856. super.setStylePrimaryName(
  857. getDateField().getStylePrimaryName() + "-calendarpanel");
  858. if (focusedDate == null) {
  859. Date date = getDate();
  860. if (date == null) {
  861. date = new Date();
  862. }
  863. // focusedDate must have zero hours, mins, secs, millisecs
  864. focusedDate = new FocusedDate(date.getYear(), date.getMonth(),
  865. date.getDate());
  866. displayedMonth = new FocusedDate(date.getYear(), date.getMonth(),
  867. 1);
  868. }
  869. if (updateDate && !isDay(getResolution())
  870. && focusChangeListener != null) {
  871. focusChangeListener.focusChanged(new Date(focusedDate.getTime()));
  872. }
  873. final boolean needsMonth = !isYear(getResolution());
  874. boolean needsBody = isBelowMonth(resolution);
  875. buildCalendarHeader(needsMonth, needsBody);
  876. clearCalendarBody(!needsBody);
  877. if (needsBody) {
  878. buildCalendarBody();
  879. }
  880. }
  881. /**
  882. * Moves the focus forward the given number of days.
  883. */
  884. private void focusNextDay(int days) {
  885. if (focusedDate == null) {
  886. return;
  887. }
  888. Date focusCopy = ((Date) focusedDate.clone());
  889. focusCopy.setDate(focusedDate.getDate() + days);
  890. if (!isDateInsideRange(focusCopy, getResolution())) {
  891. // If not inside allowed range, then do not move anything
  892. return;
  893. }
  894. int oldMonth = focusedDate.getMonth();
  895. int oldYear = focusedDate.getYear();
  896. focusedDate.setDate(focusedDate.getDate() + days);
  897. if (focusedDate.getMonth() == oldMonth
  898. && focusedDate.getYear() == oldYear) {
  899. // Month did not change, only move the selection
  900. focusDay(focusedDate);
  901. } else {
  902. // If the month changed we need to re-render the calendar
  903. displayedMonth.setMonth(focusedDate.getMonth());
  904. displayedMonth.setYear(focusedDate.getYear());
  905. renderCalendar();
  906. }
  907. }
  908. /**
  909. * Moves the focus backward the given number of days.
  910. */
  911. private void focusPreviousDay(int days) {
  912. focusNextDay(-days);
  913. }
  914. /**
  915. * Selects the next month
  916. */
  917. private void focusNextMonth() {
  918. if (focusedDate == null) {
  919. return;
  920. }
  921. // Trying to request next month
  922. Date requestedNextMonthDate = (Date) focusedDate.clone();
  923. addOneMonth(requestedNextMonthDate);
  924. if (!isDateInsideRange(requestedNextMonthDate,
  925. getResolution(this::isMonth))) {
  926. return;
  927. }
  928. // Now also checking whether the day is inside the range or not. If not
  929. // inside,
  930. // correct it
  931. if (!isDateInsideRange(requestedNextMonthDate,
  932. getResolution(this::isDay))) {
  933. requestedNextMonthDate = adjustDateToFitInsideRange(
  934. requestedNextMonthDate);
  935. }
  936. focusedDate.setTime(requestedNextMonthDate.getTime());
  937. displayedMonth.setMonth(displayedMonth.getMonth() + 1);
  938. renderCalendar();
  939. }
  940. private static void addOneMonth(Date date) {
  941. int currentMonth = date.getMonth();
  942. int requestedMonth = (currentMonth + 1) % 12;
  943. date.setMonth(date.getMonth() + 1);
  944. /*
  945. * If the selected value was e.g. 31.3 the new value would be 31.4 but
  946. * this value is invalid so the new value will be 1.5. This is taken
  947. * care of by decreasing the value until we have the correct month.
  948. */
  949. while (date.getMonth() != requestedMonth) {
  950. date.setDate(date.getDate() - 1);
  951. }
  952. }
  953. private static void removeOneMonth(Date date) {
  954. int currentMonth = date.getMonth();
  955. date.setMonth(date.getMonth() - 1);
  956. /*
  957. * If the selected value was e.g. 31.12 the new value would be 31.11 but
  958. * this value is invalid so the new value will be 1.12. This is taken
  959. * care of by decreasing the value until we have the correct month.
  960. */
  961. while (date.getMonth() == currentMonth) {
  962. date.setDate(date.getDate() - 1);
  963. }
  964. }
  965. /**
  966. * Selects the previous month
  967. */
  968. private void focusPreviousMonth() {
  969. if (focusedDate == null) {
  970. return;
  971. }
  972. Date requestedPreviousMonthDate = (Date) focusedDate.clone();
  973. removeOneMonth(requestedPreviousMonthDate);
  974. if (!isDateInsideRange(requestedPreviousMonthDate,
  975. getResolution(this::isMonth))) {
  976. return;
  977. }
  978. if (!isDateInsideRange(requestedPreviousMonthDate,
  979. getResolution(this::isDay))) {
  980. requestedPreviousMonthDate = adjustDateToFitInsideRange(
  981. requestedPreviousMonthDate);
  982. }
  983. focusedDate.setTime(requestedPreviousMonthDate.getTime());
  984. displayedMonth.setMonth(displayedMonth.getMonth() - 1);
  985. renderCalendar();
  986. }
  987. /**
  988. * Selects the previous year
  989. */
  990. private void focusPreviousYear(int years) {
  991. if (focusedDate == null) {
  992. return;
  993. }
  994. Date previousYearDate = (Date) focusedDate.clone();
  995. previousYearDate.setYear(previousYearDate.getYear() - years);
  996. // Do not focus if not inside range
  997. if (!isDateInsideRange(previousYearDate, getResolution(this::isYear))) {
  998. return;
  999. }
  1000. // If we remove one year, but have to roll back a bit, fit it
  1001. // into the calendar. Also the months have to be changed
  1002. if (!isDateInsideRange(previousYearDate, getResolution(this::isDay))) {
  1003. previousYearDate = adjustDateToFitInsideRange(previousYearDate);
  1004. focusedDate.setYear(previousYearDate.getYear());
  1005. focusedDate.setMonth(previousYearDate.getMonth());
  1006. focusedDate.setDate(previousYearDate.getDate());
  1007. displayedMonth.setYear(previousYearDate.getYear());
  1008. displayedMonth.setMonth(previousYearDate.getMonth());
  1009. } else {
  1010. int currentMonth = focusedDate.getMonth();
  1011. focusedDate.setYear(focusedDate.getYear() - years);
  1012. displayedMonth.setYear(displayedMonth.getYear() - years);
  1013. /*
  1014. * If the focused date was a leap day (Feb 29), the new date becomes
  1015. * Mar 1 if the new year is not also a leap year. Set it to Feb 28
  1016. * instead.
  1017. */
  1018. if (focusedDate.getMonth() != currentMonth) {
  1019. focusedDate.setDate(0);
  1020. }
  1021. }
  1022. renderCalendar();
  1023. }
  1024. /**
  1025. * Selects the next year
  1026. */
  1027. private void focusNextYear(int years) {
  1028. if (focusedDate == null) {
  1029. return;
  1030. }
  1031. Date nextYearDate = (Date) focusedDate.clone();
  1032. nextYearDate.setYear(nextYearDate.getYear() + years);
  1033. // Do not focus if not inside range
  1034. if (!isDateInsideRange(nextYearDate, getResolution(this::isYear))) {
  1035. return;
  1036. }
  1037. // If we add one year, but have to roll back a bit, fit it
  1038. // into the calendar. Also the months have to be changed
  1039. if (!isDateInsideRange(nextYearDate, getResolution(this::isDay))) {
  1040. nextYearDate = adjustDateToFitInsideRange(nextYearDate);
  1041. focusedDate.setYear(nextYearDate.getYear());
  1042. focusedDate.setMonth(nextYearDate.getMonth());
  1043. focusedDate.setDate(nextYearDate.getDate());
  1044. displayedMonth.setYear(nextYearDate.getYear());
  1045. displayedMonth.setMonth(nextYearDate.getMonth());
  1046. } else {
  1047. int currentMonth = focusedDate.getMonth();
  1048. focusedDate.setYear(focusedDate.getYear() + years);
  1049. displayedMonth.setYear(displayedMonth.getYear() + years);
  1050. /*
  1051. * If the focused date was a leap day (Feb 29), the new date becomes
  1052. * Mar 1 if the new year is not also a leap year. Set it to Feb 28
  1053. * instead.
  1054. */
  1055. if (focusedDate.getMonth() != currentMonth) {
  1056. focusedDate.setDate(0);
  1057. }
  1058. }
  1059. renderCalendar();
  1060. }
  1061. /**
  1062. * Handles a user click on the component
  1063. *
  1064. * @param sender
  1065. * The component that was clicked
  1066. */
  1067. private void processClickEvent(Widget sender) {
  1068. if (!isEnabled() || isReadonly()) {
  1069. return;
  1070. }
  1071. if (sender == prevYear) {
  1072. focusPreviousYear(1);
  1073. } else if (sender == nextYear) {
  1074. focusNextYear(1);
  1075. } else if (sender == prevMonth) {
  1076. focusPreviousMonth();
  1077. } else if (sender == nextMonth) {
  1078. focusNextMonth();
  1079. }
  1080. }
  1081. /*
  1082. * (non-Javadoc)
  1083. *
  1084. * @see
  1085. * com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt
  1086. * .event.dom.client.KeyDownEvent)
  1087. */
  1088. @Override
  1089. public void onKeyDown(KeyDownEvent event) {
  1090. handleKeyPress(event);
  1091. }
  1092. /*
  1093. * (non-Javadoc)
  1094. *
  1095. * @see
  1096. * com.google.gwt.event.dom.client.KeyPressHandler#onKeyPress(com.google
  1097. * .gwt.event.dom.client.KeyPressEvent)
  1098. */
  1099. @Override
  1100. public void onKeyPress(KeyPressEvent event) {
  1101. handleKeyPress(event);
  1102. }
  1103. /**
  1104. * Handles the keypress from both the onKeyPress event and the onKeyDown
  1105. * event
  1106. *
  1107. * @param event
  1108. * The keydown/keypress event
  1109. */
  1110. private void handleKeyPress(DomEvent<?> event) {
  1111. // Check tabs
  1112. int keycode = event.getNativeEvent().getKeyCode();
  1113. if (keycode == KeyCodes.KEY_TAB
  1114. && event.getNativeEvent().getShiftKey()) {
  1115. if (onTabOut(event)) {
  1116. return;
  1117. }
  1118. }
  1119. // Handle the navigation
  1120. if (handleNavigation(keycode,
  1121. event.getNativeEvent().getCtrlKey()
  1122. || event.getNativeEvent().getMetaKey(),
  1123. event.getNativeEvent().getShiftKey())) {
  1124. event.preventDefault();
  1125. }
  1126. }
  1127. /**
  1128. * Notifies submit-listeners of a submit event
  1129. */
  1130. private void onSubmit() {
  1131. if (getSubmitListener() != null) {
  1132. getSubmitListener().onSubmit();
  1133. }
  1134. }
  1135. /**
  1136. * Notifies submit-listeners of a cancel event
  1137. */
  1138. private void onCancel() {
  1139. if (getSubmitListener() != null) {
  1140. getSubmitListener().onCancel();
  1141. }
  1142. }
  1143. /**
  1144. * Handles the keyboard navigation when the resolution is set to years.
  1145. *
  1146. * @param keycode
  1147. * The keycode to process
  1148. * @param ctrl
  1149. * Is ctrl pressed?
  1150. * @param shift
  1151. * is shift pressed
  1152. * @return Returns true if the keycode was processed, else false
  1153. */
  1154. protected boolean handleNavigationYearMode(int keycode, boolean ctrl,
  1155. boolean shift) {
  1156. // Ctrl and Shift selection not supported
  1157. if (ctrl || shift) {
  1158. return false;
  1159. } else if (keycode == getPreviousKey()) {
  1160. focusNextYear(10); // Add 10 years
  1161. return true;
  1162. } else if (keycode == getForwardKey()) {
  1163. focusNextYear(1); // Add 1 year
  1164. return true;
  1165. } else if (keycode == getNextKey()) {
  1166. focusPreviousYear(10); // Subtract 10 years
  1167. return true;
  1168. } else if (keycode == getBackwardKey()) {
  1169. focusPreviousYear(1); // Subtract 1 year
  1170. return true;
  1171. } else if (keycode == getSelectKey()) {
  1172. value = (Date) focusedDate.clone();
  1173. onSubmit();
  1174. return true;
  1175. } else if (keycode == getResetKey()) {
  1176. // Restore showing value the selected value
  1177. focusedDate.setTime(value.getTime());
  1178. renderCalendar();
  1179. return true;
  1180. } else if (keycode == getCloseKey()) {
  1181. // TODO fire listener, on users responsibility??
  1182. onCancel();
  1183. return true;
  1184. }
  1185. return false;
  1186. }
  1187. /**
  1188. * Handle the keyboard navigation when the resolution is set to MONTH.
  1189. *
  1190. * @param keycode
  1191. * The keycode to handle
  1192. * @param ctrl
  1193. * Was the ctrl key pressed?
  1194. * @param shift
  1195. * Was the shift key pressed?
  1196. * @return
  1197. */
  1198. protected boolean handleNavigationMonthMode(int keycode, boolean ctrl,
  1199. boolean shift) {
  1200. // Ctrl selection not supported
  1201. if (ctrl) {
  1202. return false;
  1203. } else if (keycode == getPreviousKey()) {
  1204. focusNextYear(1); // Add 1 year
  1205. return true;
  1206. } else if (keycode == getForwardKey()) {
  1207. focusNextMonth(); // Add 1 month
  1208. return true;
  1209. } else if (keycode == getNextKey()) {
  1210. focusPreviousYear(1); // Subtract 1 year
  1211. return true;
  1212. } else if (keycode == getBackwardKey()) {
  1213. focusPreviousMonth(); // Subtract 1 month
  1214. return true;
  1215. } else if (keycode == getSelectKey()) {
  1216. value = (Date) focusedDate.clone();
  1217. onSubmit();
  1218. return true;
  1219. } else if (keycode == getResetKey()) {
  1220. // Restore showing value the selected value
  1221. focusedDate.setTime(value.getTime());
  1222. renderCalendar();
  1223. return true;
  1224. } else if (keycode == getCloseKey()) {
  1225. onCancel();
  1226. // TODO fire close event
  1227. return true;
  1228. }
  1229. return false;
  1230. }
  1231. /**
  1232. * Handle keyboard navigation what the resolution is set to DAY.
  1233. *
  1234. * @param keycode
  1235. * The keycode to handle
  1236. * @param ctrl
  1237. * Was the ctrl key pressed?
  1238. * @param shift
  1239. * Was the shift key pressed?
  1240. * @return Return true if the key press was handled by the method, else
  1241. * return false.
  1242. */
  1243. protected boolean handleNavigationDayMode(int keycode, boolean ctrl,
  1244. boolean shift) {
  1245. // Ctrl key is not in use
  1246. if (ctrl) {
  1247. return false;
  1248. }
  1249. /*
  1250. * Jumps to the next day.
  1251. */
  1252. if (keycode == getForwardKey() && !shift) {
  1253. focusNextDay(1);
  1254. return true;
  1255. /*
  1256. * Jumps to the previous day
  1257. */
  1258. } else if (keycode == getBackwardKey() && !shift) {
  1259. focusPreviousDay(1);
  1260. return true;
  1261. /*
  1262. * Jumps one week forward in the calendar
  1263. */
  1264. } else if (keycode == getNextKey() && !shift) {
  1265. focusNextDay(7);
  1266. return true;
  1267. /*
  1268. * Jumps one week back in the calendar
  1269. */
  1270. } else if (keycode == getPreviousKey() && !shift) {
  1271. focusPreviousDay(7);
  1272. return true;
  1273. /*
  1274. * Selects the value that is chosen
  1275. */
  1276. } else if (keycode == getSelectKey() && !shift) {
  1277. selectFocused();
  1278. onSubmit(); // submit
  1279. return true;
  1280. } else if (keycode == getCloseKey()) {
  1281. onCancel();
  1282. // TODO close event
  1283. return true;
  1284. /*
  1285. * Jumps to the next month
  1286. */
  1287. } else if (shift && keycode == getForwardKey()) {
  1288. focusNextMonth();
  1289. return true;
  1290. /*
  1291. * Jumps to the previous month
  1292. */
  1293. } else if (shift && keycode == getBackwardKey()) {
  1294. focusPreviousMonth();
  1295. return true;
  1296. /*
  1297. * Jumps to the next year
  1298. */
  1299. } else if (shift && keycode == getPreviousKey()) {
  1300. focusNextYear(1);
  1301. return true;
  1302. /*
  1303. * Jumps to the previous year
  1304. */
  1305. } else if (shift && keycode == getNextKey()) {
  1306. focusPreviousYear(1);
  1307. return true;
  1308. /*
  1309. * Resets the selection
  1310. */
  1311. } else if (keycode == getResetKey() && !shift) {
  1312. // Restore showing value the selected value
  1313. focusedDate = new FocusedDate(value.getYear(), value.getMonth(),
  1314. value.getDate());
  1315. displayedMonth = new FocusedDate(value.getYear(), value.getMonth(),
  1316. 1);
  1317. renderCalendar();
  1318. return true;
  1319. }
  1320. return false;
  1321. }
  1322. /**
  1323. * Handles the keyboard navigation.
  1324. *
  1325. * @param keycode
  1326. * The key code that was pressed
  1327. * @param ctrl
  1328. * Was the ctrl key pressed
  1329. * @param shift
  1330. * Was the shift key pressed
  1331. * @return Return true if key press was handled by the component, else
  1332. * return false
  1333. */
  1334. protected boolean handleNavigation(int keycode, boolean ctrl,
  1335. boolean shift) {
  1336. if (!isEnabled() || isReadonly()) {
  1337. return false;
  1338. } else if (isYear(getResolution())) {
  1339. return handleNavigationYearMode(keycode, ctrl, shift);
  1340. } else if (isMonth(getResolution())) {
  1341. return handleNavigationMonthMode(keycode, ctrl, shift);
  1342. } else if (isDay(getResolution())) {
  1343. return handleNavigationDayMode(keycode, ctrl, shift);
  1344. } else {
  1345. return handleNavigationDayMode(keycode, ctrl, shift);
  1346. }
  1347. }
  1348. /**
  1349. * Returns the reset key which will reset the calendar to the previous
  1350. * selection. By default this is backspace but it can be overridden to
  1351. * change the key to whatever you want.
  1352. *
  1353. * @return
  1354. */
  1355. protected int getResetKey() {
  1356. return KeyCodes.KEY_BACKSPACE;
  1357. }
  1358. /**
  1359. * Returns the select key which selects the value. By default this is the
  1360. * enter key but it can be changed to whatever you like by overriding this
  1361. * method.
  1362. *
  1363. * @return
  1364. */
  1365. protected int getSelectKey() {
  1366. return KeyCodes.KEY_ENTER;
  1367. }
  1368. /**
  1369. * Returns the key that closes the popup window if this is a VPopopCalendar.
  1370. * Else this does nothing. By default this is the Escape key but you can
  1371. * change the key to whatever you want by overriding this method.
  1372. *
  1373. * @return
  1374. */
  1375. protected int getCloseKey() {
  1376. return KeyCodes.KEY_ESCAPE;
  1377. }
  1378. /**
  1379. * The key that selects the next day in the calendar. By default this is the
  1380. * right arrow key but by overriding this method it can be changed to
  1381. * whatever you like.
  1382. *
  1383. * @return
  1384. */
  1385. protected int getForwardKey() {
  1386. return KeyCodes.KEY_RIGHT;
  1387. }
  1388. /**
  1389. * The key that selects the previous day in the calendar. By default this is
  1390. * the left arrow key but by overriding this method it can be changed to
  1391. * whatever you like.
  1392. *
  1393. * @return
  1394. */
  1395. protected int getBackwardKey() {
  1396. return KeyCodes.KEY_LEFT;
  1397. }
  1398. /**
  1399. * The key that selects the next week in the calendar. By default this is
  1400. * the down arrow key but by overriding this method it can be changed to
  1401. * whatever you like.
  1402. *
  1403. * @return
  1404. */
  1405. protected int getNextKey() {
  1406. return KeyCodes.KEY_DOWN;
  1407. }
  1408. /**
  1409. * The key that selects the previous week in the calendar. By default this
  1410. * is the up arrow key but by overriding this method it can be changed to
  1411. * whatever you like.
  1412. *
  1413. * @return
  1414. */
  1415. protected int getPreviousKey() {
  1416. return KeyCodes.KEY_UP;
  1417. }
  1418. /*
  1419. * (non-Javadoc)
  1420. *
  1421. * @see
  1422. * com.google.gwt.event.dom.client.MouseOutHandler#onMouseOut(com.google
  1423. * .gwt.event.dom.client.MouseOutEvent)
  1424. */
  1425. @Override
  1426. public void onMouseOut(MouseOutEvent event) {
  1427. if (mouseTimer != null) {
  1428. mouseTimer.cancel();
  1429. }
  1430. }
  1431. /*
  1432. * (non-Javadoc)
  1433. *
  1434. * @see
  1435. * com.google.gwt.event.dom.client.MouseDownHandler#onMouseDown(com.google
  1436. * .gwt.event.dom.client.MouseDownEvent)
  1437. */
  1438. @Override
  1439. public void onMouseDown(MouseDownEvent event) {
  1440. // Click-n-hold the left mouse button for fast-forward or fast-rewind.
  1441. // Timer is first used for a 500ms delay after mousedown. After that has
  1442. // elapsed, another timer is triggered to go off every 150ms. Both
  1443. // timers are cancelled on mouseup or mouseout.
  1444. if (event.getNativeButton() == NativeEvent.BUTTON_LEFT && event
  1445. .getSource() instanceof VAbstractCalendarPanel.VEventButton) {
  1446. final VEventButton sender = (VEventButton) event.getSource();
  1447. processClickEvent(sender);
  1448. mouseTimer = new Timer() {
  1449. @Override
  1450. public void run() {
  1451. mouseTimer = new Timer() {
  1452. @Override
  1453. public void run() {
  1454. processClickEvent(sender);
  1455. }
  1456. };
  1457. mouseTimer.scheduleRepeating(150);
  1458. }
  1459. };
  1460. mouseTimer.schedule(500);
  1461. }
  1462. }
  1463. /*
  1464. * (non-Javadoc)
  1465. *
  1466. * @see
  1467. * com.google.gwt.event.dom.client.MouseUpHandler#onMouseUp(com.google.gwt
  1468. * .event.dom.client.MouseUpEvent)
  1469. */
  1470. @Override
  1471. public void onMouseUp(MouseUpEvent event) {
  1472. if (mouseTimer != null) {
  1473. mouseTimer.cancel();
  1474. }
  1475. }
  1476. /**
  1477. * Adjusts a date to fit inside the range, only if outside
  1478. *
  1479. * @param date
  1480. */
  1481. private Date adjustDateToFitInsideRange(Date date) {
  1482. if (!isAcceptedByRangeStart(date, resolution)) {
  1483. date = parseRangeString(rangeStart);
  1484. } else if (!isAcceptedByRangeEnd(date, resolution)) {
  1485. date = parseRangeString(rangeEnd);
  1486. }
  1487. return date;
  1488. }
  1489. private Date parseRangeString(String dateStr) {
  1490. if (dateStr == null || "".equals(dateStr))
  1491. return null;
  1492. int year = Integer.parseInt(dateStr.substring(0, 4)) - 1900;
  1493. int month = parsePart(dateStr, 5, 2, 1) - 1;
  1494. int day = parsePart(dateStr, 8, 2, 1);
  1495. int hrs = parsePart(dateStr, 11, 2, 0);
  1496. int min = parsePart(dateStr, 14, 2, 0);
  1497. int sec = parsePart(dateStr, 17, 2, 0);
  1498. return new Date(year, month, day, hrs, min, sec);
  1499. }
  1500. private int parsePart(String dateStr, int beginIndex, int length,
  1501. int defValue) {
  1502. if (dateStr.length() < beginIndex + length)
  1503. return defValue;
  1504. return Integer
  1505. .parseInt(dateStr.substring(beginIndex, beginIndex + length));
  1506. }
  1507. /**
  1508. * Sets the data of the Panel.
  1509. *
  1510. * @param currentDate
  1511. * The date to set
  1512. */
  1513. public void setDate(Date currentDate) {
  1514. doSetDate(currentDate, false, () -> {
  1515. });
  1516. }
  1517. /**
  1518. * The actual implementation of the logic which sets the data of the Panel.
  1519. * The method {@link #setDate(Date)} just delegate a call to this method
  1520. * providing additional config parameters.
  1521. *
  1522. * @param currentDate
  1523. * currentDate The date to set
  1524. * @param needRerender
  1525. * if {@code true} then calendar will be rerendered regardless of
  1526. * internal logic, otherwise the decision will be made on the
  1527. * internal state inside the method
  1528. * @param focusAction
  1529. * an additional action which will be executed in case
  1530. * rerendering is not required
  1531. */
  1532. protected void doSetDate(Date currentDate, boolean needRerender,
  1533. Runnable focusAction) {
  1534. // Check that we are not re-rendering an already active date
  1535. if (currentDate == value && currentDate != null) {
  1536. return;
  1537. }
  1538. boolean currentDateWasAdjusted = false;
  1539. // Check that selected date is inside the allowed range
  1540. if (currentDate != null
  1541. && !isDateInsideRange(currentDate, getResolution())) {
  1542. currentDate = adjustDateToFitInsideRange(currentDate);
  1543. currentDateWasAdjusted = true;
  1544. }
  1545. Date oldDisplayedMonth = displayedMonth;
  1546. value = currentDate;
  1547. // If current date was adjusted, we will not select any date,
  1548. // since that will look like a date is selected. Instead we
  1549. // only focus on the adjusted value
  1550. if (value == null || currentDateWasAdjusted) {
  1551. // If ranges enabled, we may need to focus on a different view to
  1552. // potentially not get stuck
  1553. if (rangeStart != null || rangeEnd != null) {
  1554. Date dateThatFitsInsideRange = adjustDateToFitInsideRange(
  1555. new Date());
  1556. focusedDate = new FocusedDate(dateThatFitsInsideRange.getYear(),
  1557. dateThatFitsInsideRange.getMonth(),
  1558. dateThatFitsInsideRange.getDate());
  1559. displayedMonth = new FocusedDate(
  1560. dateThatFitsInsideRange.getYear(),
  1561. dateThatFitsInsideRange.getMonth(), 1);
  1562. // value was adjusted. Set selected to null to not cause
  1563. // confusion, but this is only needed (and allowed) when we have
  1564. // a day
  1565. // resolution
  1566. if (isDay(getResolution())) {
  1567. value = null;
  1568. }
  1569. } else {
  1570. focusedDate = displayedMonth = null;
  1571. }
  1572. } else {
  1573. focusedDate = new FocusedDate(value.getYear(), value.getMonth(),
  1574. value.getDate());
  1575. displayedMonth = new FocusedDate(value.getYear(), value.getMonth(),
  1576. 1);
  1577. }
  1578. // Re-render calendar if the displayed month is changed.
  1579. if (needRerender || oldDisplayedMonth == null || value == null
  1580. || oldDisplayedMonth.getYear() != value.getYear()
  1581. || oldDisplayedMonth.getMonth() != value.getMonth()) {
  1582. renderCalendar();
  1583. } else {
  1584. focusDay(focusedDate);
  1585. selectFocused();
  1586. focusAction.run();
  1587. }
  1588. if (!hasFocus) {
  1589. focusDay(null);
  1590. }
  1591. }
  1592. /**
  1593. * A widget representing a single day in the calendar panel.
  1594. */
  1595. private class Day extends InlineHTML {
  1596. private final Date date;
  1597. Day(Date date) {
  1598. super("" + date.getDate());
  1599. this.date = date;
  1600. addClickHandler(dayClickHandler);
  1601. }
  1602. public Date getDate() {
  1603. return date;
  1604. }
  1605. }
  1606. public Date getDate() {
  1607. return value;
  1608. }
  1609. /**
  1610. * If true should be returned if the panel will not be used after this
  1611. * event.
  1612. *
  1613. * @param event
  1614. * @return
  1615. */
  1616. protected boolean onTabOut(DomEvent<?> event) {
  1617. if (focusOutListener != null) {
  1618. return focusOutListener.onFocusOut(event);
  1619. }
  1620. return false;
  1621. }
  1622. /**
  1623. * A focus out listener is triggered when the panel loosed focus. This can
  1624. * happen either after a user clicks outside the panel or tabs out.
  1625. *
  1626. * @param listener
  1627. * The listener to trigger
  1628. */
  1629. public void setFocusOutListener(FocusOutListener listener) {
  1630. focusOutListener = listener;
  1631. }
  1632. /**
  1633. * The submit listener is called when the user selects a value from the
  1634. * calendar either by clicking the day or selects it by keyboard.
  1635. *
  1636. * @param submitListener
  1637. * The listener to trigger
  1638. */
  1639. public void setSubmitListener(SubmitListener submitListener) {
  1640. this.submitListener = submitListener;
  1641. }
  1642. /**
  1643. * The given FocusChangeListener is notified when the focused date changes
  1644. * by user either clicking on a new date or by using the keyboard.
  1645. *
  1646. * @param listener
  1647. * The FocusChangeListener to be notified
  1648. */
  1649. public void setFocusChangeListener(FocusChangeListener listener) {
  1650. focusChangeListener = listener;
  1651. }
  1652. /**
  1653. * Returns the submit listener that listens to selection made from the
  1654. * panel.
  1655. *
  1656. * @return The listener or NULL if no listener has been set
  1657. */
  1658. public SubmitListener getSubmitListener() {
  1659. return submitListener;
  1660. }
  1661. /*
  1662. * (non-Javadoc)
  1663. *
  1664. * @see
  1665. * com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event
  1666. * .dom.client.BlurEvent)
  1667. */
  1668. @Override
  1669. public void onBlur(final BlurEvent event) {
  1670. if (event.getSource() instanceof VAbstractCalendarPanel) {
  1671. hasFocus = false;
  1672. focusDay(null);
  1673. }
  1674. }
  1675. /*
  1676. * (non-Javadoc)
  1677. *
  1678. * @see
  1679. * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
  1680. * .dom.client.FocusEvent)
  1681. */
  1682. @Override
  1683. public void onFocus(FocusEvent event) {
  1684. if (event.getSource() instanceof VAbstractCalendarPanel) {
  1685. hasFocus = true;
  1686. // Focuses the current day if the calendar shows the days
  1687. if (focusedDay != null) {
  1688. focusDay(focusedDate);
  1689. }
  1690. }
  1691. }
  1692. private static final String SUBPART_NEXT_MONTH = "nextmon";
  1693. private static final String SUBPART_PREV_MONTH = "prevmon";
  1694. private static final String SUBPART_NEXT_YEAR = "nexty";
  1695. private static final String SUBPART_PREV_YEAR = "prevy";
  1696. private static final String SUBPART_HOUR_SELECT = "h";
  1697. private static final String SUBPART_MINUTE_SELECT = "m";
  1698. private static final String SUBPART_SECS_SELECT = "s";
  1699. private static final String SUBPART_AMPM_SELECT = "ampm";
  1700. private static final String SUBPART_DAY = "day";
  1701. private static final String SUBPART_MONTH_YEAR_HEADER = "header";
  1702. private String rangeStart;
  1703. private String rangeEnd;
  1704. @Override
  1705. public String getSubPartName(
  1706. com.google.gwt.user.client.Element subElement) {
  1707. if (contains(nextMonth, subElement)) {
  1708. return SUBPART_NEXT_MONTH;
  1709. } else if (contains(prevMonth, subElement)) {
  1710. return SUBPART_PREV_MONTH;
  1711. } else if (contains(nextYear, subElement)) {
  1712. return SUBPART_NEXT_YEAR;
  1713. } else if (contains(prevYear, subElement)) {
  1714. return SUBPART_PREV_YEAR;
  1715. } else if (contains(days, subElement)) {
  1716. // Day, find out which dayOfMonth and use that as the identifier
  1717. Day day = WidgetUtil.findWidget(subElement, Day.class);
  1718. if (day != null) {
  1719. Date date = day.getDate();
  1720. int id = date.getDate();
  1721. // Zero or negative ids map to days of the preceding month,
  1722. // past-the-end-of-month ids to days of the following month
  1723. if (date.getMonth() < displayedMonth.getMonth()) {
  1724. id -= DateTimeService.getNumberOfDaysInMonth(date);
  1725. } else if (date.getMonth() > displayedMonth.getMonth()) {
  1726. id += DateTimeService
  1727. .getNumberOfDaysInMonth(displayedMonth);
  1728. }
  1729. return SUBPART_DAY + id;
  1730. }
  1731. } else if (getCellFormatter().getElement(0, 2)
  1732. .isOrHasChild(subElement)) {
  1733. return SUBPART_MONTH_YEAR_HEADER;
  1734. }
  1735. return null;
  1736. }
  1737. /**
  1738. * Checks if subElement is inside the widget DOM hierarchy.
  1739. *
  1740. * @param w
  1741. * @param subElement
  1742. * @return true if {@code w} is a parent of subElement, false otherwise.
  1743. */
  1744. protected boolean contains(Widget w, Element subElement) {
  1745. if (w == null || w.getElement() == null) {
  1746. return false;
  1747. }
  1748. return w.getElement().isOrHasChild(subElement);
  1749. }
  1750. @Override
  1751. public com.google.gwt.user.client.Element getSubPartElement(
  1752. String subPart) {
  1753. if (SUBPART_NEXT_MONTH.equals(subPart)) {
  1754. return nextMonth.getElement();
  1755. }
  1756. if (SUBPART_PREV_MONTH.equals(subPart)) {
  1757. return prevMonth.getElement();
  1758. }
  1759. if (SUBPART_NEXT_YEAR.equals(subPart)) {
  1760. return nextYear.getElement();
  1761. }
  1762. if (SUBPART_PREV_YEAR.equals(subPart)) {
  1763. return prevYear.getElement();
  1764. }
  1765. if (subPart.startsWith(SUBPART_DAY)) {
  1766. // Zero or negative ids map to days in the preceding month,
  1767. // past-the-end-of-month ids to days in the following month
  1768. int dayOfMonth = Integer
  1769. .parseInt(subPart.substring(SUBPART_DAY.length()));
  1770. Date date = new Date(displayedMonth.getYear(),
  1771. displayedMonth.getMonth(), dayOfMonth);
  1772. for (Widget w : days) {
  1773. if (w instanceof VAbstractCalendarPanel.Day) {
  1774. Day day = (Day) w;
  1775. if (day.getDate().equals(date)) {
  1776. return day.getElement();
  1777. }
  1778. }
  1779. }
  1780. }
  1781. if (SUBPART_MONTH_YEAR_HEADER.equals(subPart)) {
  1782. return DOM.asOld(
  1783. (Element) getCellFormatter().getElement(0, 2).getChild(0));
  1784. }
  1785. return null;
  1786. }
  1787. @Override
  1788. protected void onDetach() {
  1789. super.onDetach();
  1790. if (mouseTimer != null) {
  1791. mouseTimer.cancel();
  1792. }
  1793. }
  1794. /**
  1795. * Helper class to inform the screen reader that the user changed the
  1796. * selected date. It sets the value of a field that is outside the view, and
  1797. * is defined as a live area. That way the screen reader recognizes the
  1798. * change and reads it to the user.
  1799. */
  1800. public class FocusedDate extends Date {
  1801. public FocusedDate(int year, int month, int date) {
  1802. super(year, month, date);
  1803. }
  1804. @Override
  1805. public void setTime(long time) {
  1806. super.setTime(time);
  1807. setLabel();
  1808. }
  1809. @Override
  1810. @Deprecated
  1811. public void setDate(int date) {
  1812. super.setDate(date);
  1813. setLabel();
  1814. }
  1815. @Override
  1816. @Deprecated
  1817. public void setMonth(int month) {
  1818. super.setMonth(month);
  1819. setLabel();
  1820. }
  1821. @Override
  1822. @Deprecated
  1823. public void setYear(int year) {
  1824. super.setYear(year);
  1825. setLabel();
  1826. }
  1827. private void setLabel() {
  1828. if (getDateField() instanceof VAbstractPopupCalendar) {
  1829. ((VAbstractPopupCalendar<?, ?>) getDateField())
  1830. .setFocusedDate(this);
  1831. }
  1832. }
  1833. }
  1834. /**
  1835. * Sets the start range for this component. The start range is inclusive,
  1836. * and it depends on the current resolution, what is considered inside the
  1837. * range.
  1838. *
  1839. * @param newRangeStart
  1840. * - the allowed range's start date
  1841. */
  1842. public void setRangeStart(String newRangeStart) {
  1843. if (!SharedUtil.equals(rangeStart, newRangeStart)) {
  1844. rangeStart = newRangeStart;
  1845. if (initialRenderDone) {
  1846. // Dynamic updates to the range needs to render the calendar to
  1847. // update the element stylenames
  1848. renderCalendar();
  1849. }
  1850. }
  1851. }
  1852. /**
  1853. * Sets the end range for this component. The end range is inclusive, and it
  1854. * depends on the current resolution, what is considered inside the range.
  1855. *
  1856. * @param newRangeEnd
  1857. * - the allowed range's end date
  1858. */
  1859. public void setRangeEnd(String newRangeEnd) {
  1860. if (!SharedUtil.equals(rangeEnd, newRangeEnd)) {
  1861. // Dates with year 10000 or more has + prefix, which is not compatible
  1862. // with format returned by dateStrResolution method
  1863. if (newRangeEnd.startsWith("+")) {
  1864. rangeEnd = newRangeEnd.substring(1);
  1865. } else {
  1866. rangeEnd = newRangeEnd;
  1867. }
  1868. if (initialRenderDone) {
  1869. // Dynamic updates to the range needs to render the calendar to
  1870. // update the element stylenames
  1871. renderCalendar();
  1872. }
  1873. }
  1874. }
  1875. /**
  1876. * Set assistive label for the previous year element.
  1877. *
  1878. * @param label
  1879. * the label to set
  1880. * @since 8.4
  1881. */
  1882. public void setAssistiveLabelPreviousYear(String label) {
  1883. prevYearAssistiveLabel = label;
  1884. }
  1885. /**
  1886. * Set assistive label for the next year element.
  1887. *
  1888. * @param label
  1889. * the label to set
  1890. * @since 8.4
  1891. */
  1892. public void setAssistiveLabelNextYear(String label) {
  1893. nextYearAssistiveLabel = label;
  1894. }
  1895. /**
  1896. * Set assistive label for the previous month element.
  1897. *
  1898. * @param label
  1899. * the label to set
  1900. * @since 8.4
  1901. */
  1902. public void setAssistiveLabelPreviousMonth(String label) {
  1903. prevMonthAssistiveLabel = label;
  1904. }
  1905. /**
  1906. * Set assistive label for the next month element.
  1907. *
  1908. * @param label
  1909. * the label to set
  1910. * @since 8.4
  1911. */
  1912. public void setAssistiveLabelNextMonth(String label) {
  1913. nextMonthAssistiveLabel = label;
  1914. }
  1915. /**
  1916. * Updates assistive labels of the navigation elements.
  1917. *
  1918. * @since 8.4
  1919. */
  1920. public void updateAssistiveLabels() {
  1921. if (prevMonth != null) {
  1922. Roles.getButtonRole().setAriaLabelProperty(prevMonth.getElement(),
  1923. prevMonthAssistiveLabel);
  1924. }
  1925. if (nextMonth != null) {
  1926. Roles.getButtonRole().setAriaLabelProperty(nextMonth.getElement(),
  1927. nextMonthAssistiveLabel);
  1928. }
  1929. if (prevYear != null) {
  1930. Roles.getButtonRole().setAriaLabelProperty(prevYear.getElement(),
  1931. prevYearAssistiveLabel);
  1932. }
  1933. if (nextYear != null) {
  1934. Roles.getButtonRole().setAriaLabelProperty(nextYear.getElement(),
  1935. nextYearAssistiveLabel);
  1936. }
  1937. }
  1938. private static Logger getLogger() {
  1939. return Logger.getLogger(VAbstractCalendarPanel.class.getName());
  1940. }
  1941. }