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 71KB

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