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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212
  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. String dateStrResolution = dateStrResolution(date, minResolution);
  655. return rangeEnd.substring(0, dateStrResolution.length())
  656. .compareTo(dateStrResolution) >= 0;
  657. }
  658. private static Date clearDateBelowMonth(Date date) {
  659. date.setDate(1);
  660. return clearDateBelowDay(date);
  661. }
  662. private static Date clearDateBelowDay(Date date) {
  663. date.setHours(0);
  664. date.setMinutes(0);
  665. date.setSeconds(0);
  666. // Clearing milliseconds
  667. long time = date.getTime() / 1000;
  668. date = new Date(time * 1000);
  669. return date;
  670. }
  671. /**
  672. * Builds the day and time selectors of the calendar.
  673. */
  674. private void buildCalendarBody() {
  675. final int weekColumn = 0;
  676. final int firstWeekdayColumn = 1;
  677. final int headerRow = 0;
  678. setWidget(1, 0, days);
  679. setCellPadding(0);
  680. setCellSpacing(0);
  681. getFlexCellFormatter().setColSpan(1, 0, 5);
  682. getFlexCellFormatter().setStyleName(1, 0,
  683. getDateField().getStylePrimaryName() + "-calendarpanel-body");
  684. days.getFlexCellFormatter().setStyleName(headerRow, weekColumn,
  685. "v-week");
  686. days.setHTML(headerRow, weekColumn, "<strong></strong>");
  687. // Hide the week column if week numbers are not to be displayed.
  688. days.getFlexCellFormatter().setVisible(headerRow, weekColumn,
  689. isShowISOWeekNumbers());
  690. days.getRowFormatter().setStyleName(headerRow,
  691. getDateField().getStylePrimaryName()
  692. + "-calendarpanel-weekdays");
  693. if (isShowISOWeekNumbers()) {
  694. days.getFlexCellFormatter().setStyleName(headerRow, weekColumn,
  695. "v-first");
  696. days.getFlexCellFormatter().setStyleName(headerRow,
  697. firstWeekdayColumn, "");
  698. days.getRowFormatter().addStyleName(headerRow,
  699. getDateField().getStylePrimaryName()
  700. + "-calendarpanel-weeknumbers");
  701. } else {
  702. days.getFlexCellFormatter().setStyleName(headerRow, weekColumn, "");
  703. days.getFlexCellFormatter().setStyleName(headerRow,
  704. firstWeekdayColumn, "v-first");
  705. }
  706. days.getFlexCellFormatter().setStyleName(headerRow,
  707. firstWeekdayColumn + 6, "v-last");
  708. // Print weekday names
  709. final int firstDay = getDateTimeService().getFirstDayOfWeek();
  710. for (int i = 0; i < 7; i++) {
  711. int day = (i + firstDay) % 7;
  712. if (isBelowMonth(getResolution())) {
  713. days.setHTML(headerRow, firstWeekdayColumn + i, "<strong>"
  714. + getDateTimeService().getShortDay(day) + "</strong>");
  715. } else {
  716. days.setHTML(headerRow, firstWeekdayColumn + i, "");
  717. }
  718. Roles.getColumnheaderRole().set(days.getCellFormatter()
  719. .getElement(headerRow, firstWeekdayColumn + i));
  720. }
  721. // Zero out hours, minutes, seconds, and milliseconds to compare dates
  722. // without time part
  723. final Date tmp = new Date();
  724. final Date today = new Date(tmp.getYear(), tmp.getMonth(),
  725. tmp.getDate());
  726. final Date selectedDate = value == null ? null
  727. : new Date(value.getYear(), value.getMonth(), value.getDate());
  728. final int startWeekDay = getDateTimeService()
  729. .getStartWeekDay(displayedMonth);
  730. final Date curr = (Date) displayedMonth.clone();
  731. // Start from the first day of the week that at least partially belongs
  732. // to the current month
  733. curr.setDate(1 - startWeekDay);
  734. // No month has more than 6 weeks so 6 is a safe maximum for rows.
  735. for (int weekOfMonth = 1; weekOfMonth < 7; weekOfMonth++) {
  736. for (int dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) {
  737. // Actually write the day of month
  738. Date dayDate = (Date) curr.clone();
  739. Day day = new Day(dayDate);
  740. // Set ID with prefix of the calendar panel's ID
  741. day.getElement().setId(getElement().getId() + "-" + weekOfMonth
  742. + "-" + dayOfWeek);
  743. // Set assistive label to read focused date and month/year
  744. Roles.getButtonRole().set(day.getElement());
  745. Roles.getButtonRole().setAriaLabelledbyProperty(
  746. day.getElement(), Id.of(day.getElement()),
  747. Id.of(getFlexCellFormatter().getElement(0, 2)));
  748. day.setStyleName(getDateField().getStylePrimaryName()
  749. + "-calendarpanel-day");
  750. if (!isDateInsideRange(dayDate, getResolution(this::isDay))) {
  751. day.addStyleDependentName(CN_OUTSIDE_RANGE);
  752. }
  753. if (curr.equals(selectedDate)) {
  754. day.addStyleDependentName(CN_SELECTED);
  755. Roles.getGridcellRole().setAriaSelectedState(
  756. day.getElement(), SelectedValue.TRUE);
  757. selectedDay = day;
  758. }
  759. if (curr.equals(today)) {
  760. day.addStyleDependentName(CN_TODAY);
  761. }
  762. if (curr.equals(focusedDate)) {
  763. focusedDay = day;
  764. if (hasFocus) {
  765. day.addStyleDependentName(CN_FOCUSED);
  766. // Reference focused day from calendar panel
  767. Roles.getGridRole().setAriaActivedescendantProperty(
  768. getElement(), Id.of(day.getElement()));
  769. }
  770. }
  771. if (curr.getMonth() != displayedMonth.getMonth()) {
  772. day.addStyleDependentName(CN_OFFMONTH);
  773. }
  774. String dayDateString = df.format(dayDate);
  775. if (dateStyles.containsKey(dayDateString)) {
  776. day.addStyleName(dateStyles.get(dayDateString));
  777. }
  778. days.setWidget(weekOfMonth, firstWeekdayColumn + dayOfWeek,
  779. day);
  780. Roles.getGridcellRole().set(days.getCellFormatter().getElement(
  781. weekOfMonth, firstWeekdayColumn + dayOfWeek));
  782. // ISO week numbers if requested
  783. days.getCellFormatter().setVisible(weekOfMonth, weekColumn,
  784. isShowISOWeekNumbers());
  785. if (isShowISOWeekNumbers()) {
  786. final String baseCssClass = getDateField()
  787. .getStylePrimaryName()
  788. + "-calendarpanel-weeknumber";
  789. String weekCssClass = baseCssClass;
  790. int weekNumber = DateTimeService.getISOWeekNumber(curr);
  791. days.setHTML(weekOfMonth, 0, "<span class=\"" + weekCssClass
  792. + "\"" + ">" + weekNumber + "</span>");
  793. }
  794. curr.setDate(curr.getDate() + 1);
  795. }
  796. }
  797. }
  798. /**
  799. * Updates the calendar and text field with the selected dates.
  800. */
  801. public void renderCalendar() {
  802. renderCalendar(true);
  803. }
  804. /**
  805. * Returns the value of initialRenderDone
  806. *
  807. * @since 8.7
  808. */
  809. public boolean isInitialRenderDone() {
  810. return initialRenderDone;
  811. }
  812. /**
  813. * For internal use only. May be removed or replaced in the future.
  814. *
  815. * Updates the calendar and text field with the selected dates.
  816. *
  817. * @param updateDate
  818. * The value false prevents setting the selected date of the
  819. * calendar based on focusedDate. That can be used when only the
  820. * resolution of the calendar is changed and no date has been
  821. * selected.
  822. */
  823. @SuppressWarnings("rawtypes")
  824. public void renderCalendar(boolean updateDate) {
  825. if (parent instanceof VAbstractPopupCalendar
  826. && !((VAbstractPopupCalendar) parent).popup.isShowing()) {
  827. if (getDate() == null) {
  828. // no date set, cannot pre-render yet
  829. return;
  830. }
  831. // a popup that isn't open cannot possibly need a focus change event
  832. updateDate = false;
  833. }
  834. doRenderCalendar(updateDate);
  835. initialRenderDone = true;
  836. }
  837. /**
  838. * Performs the rendering required by the {@link #renderCalendar(boolean)}.
  839. * Subclasses may override this method to provide a custom implementation
  840. * avoiding {@link #renderCalendar(boolean)} override. The latter method
  841. * contains a common logic which should not be overridden.
  842. *
  843. * @param updateDate
  844. * The value false prevents setting the selected date of the
  845. * calendar based on focusedDate. That can be used when only the
  846. * resolution of the calendar is changed and no date has been
  847. * selected.
  848. */
  849. protected void doRenderCalendar(boolean updateDate) {
  850. super.setStylePrimaryName(
  851. getDateField().getStylePrimaryName() + "-calendarpanel");
  852. if (focusedDate == null) {
  853. Date date = getDate();
  854. if (date == null) {
  855. date = new Date();
  856. }
  857. // focusedDate must have zero hours, mins, secs, millisecs
  858. focusedDate = new FocusedDate(date.getYear(), date.getMonth(),
  859. date.getDate());
  860. displayedMonth = new FocusedDate(date.getYear(), date.getMonth(),
  861. 1);
  862. }
  863. if (updateDate && !isDay(getResolution())
  864. && focusChangeListener != null) {
  865. focusChangeListener.focusChanged(new Date(focusedDate.getTime()));
  866. }
  867. final boolean needsMonth = !isYear(getResolution());
  868. boolean needsBody = isBelowMonth(resolution);
  869. buildCalendarHeader(needsMonth, needsBody);
  870. clearCalendarBody(!needsBody);
  871. if (needsBody) {
  872. buildCalendarBody();
  873. }
  874. }
  875. /**
  876. * Moves the focus forward the given number of days.
  877. */
  878. private void focusNextDay(int days) {
  879. if (focusedDate == null) {
  880. return;
  881. }
  882. Date focusCopy = ((Date) focusedDate.clone());
  883. focusCopy.setDate(focusedDate.getDate() + days);
  884. if (!isDateInsideRange(focusCopy, getResolution())) {
  885. // If not inside allowed range, then do not move anything
  886. return;
  887. }
  888. int oldMonth = focusedDate.getMonth();
  889. int oldYear = focusedDate.getYear();
  890. focusedDate.setDate(focusedDate.getDate() + days);
  891. if (focusedDate.getMonth() == oldMonth
  892. && focusedDate.getYear() == oldYear) {
  893. // Month did not change, only move the selection
  894. focusDay(focusedDate);
  895. } else {
  896. // If the month changed we need to re-render the calendar
  897. displayedMonth.setMonth(focusedDate.getMonth());
  898. displayedMonth.setYear(focusedDate.getYear());
  899. renderCalendar();
  900. }
  901. }
  902. /**
  903. * Moves the focus backward the given number of days.
  904. */
  905. private void focusPreviousDay(int days) {
  906. focusNextDay(-days);
  907. }
  908. /**
  909. * Selects the next month
  910. */
  911. private void focusNextMonth() {
  912. if (focusedDate == null) {
  913. return;
  914. }
  915. // Trying to request next month
  916. Date requestedNextMonthDate = (Date) focusedDate.clone();
  917. addOneMonth(requestedNextMonthDate);
  918. if (!isDateInsideRange(requestedNextMonthDate,
  919. getResolution(this::isMonth))) {
  920. return;
  921. }
  922. // Now also checking whether the day is inside the range or not. If not
  923. // inside,
  924. // correct it
  925. if (!isDateInsideRange(requestedNextMonthDate,
  926. getResolution(this::isDay))) {
  927. requestedNextMonthDate = adjustDateToFitInsideRange(
  928. requestedNextMonthDate);
  929. }
  930. focusedDate.setTime(requestedNextMonthDate.getTime());
  931. displayedMonth.setMonth(displayedMonth.getMonth() + 1);
  932. renderCalendar();
  933. }
  934. private static void addOneMonth(Date date) {
  935. int currentMonth = date.getMonth();
  936. int requestedMonth = (currentMonth + 1) % 12;
  937. date.setMonth(date.getMonth() + 1);
  938. /*
  939. * If the selected value was e.g. 31.3 the new value would be 31.4 but
  940. * this value is invalid so the new value will be 1.5. This is taken
  941. * care of by decreasing the value until we have the correct month.
  942. */
  943. while (date.getMonth() != requestedMonth) {
  944. date.setDate(date.getDate() - 1);
  945. }
  946. }
  947. private static void removeOneMonth(Date date) {
  948. int currentMonth = date.getMonth();
  949. date.setMonth(date.getMonth() - 1);
  950. /*
  951. * If the selected value was e.g. 31.12 the new value would be 31.11 but
  952. * this value is invalid so the new value will be 1.12. This is taken
  953. * care of by decreasing the value until we have the correct month.
  954. */
  955. while (date.getMonth() == currentMonth) {
  956. date.setDate(date.getDate() - 1);
  957. }
  958. }
  959. /**
  960. * Selects the previous month
  961. */
  962. private void focusPreviousMonth() {
  963. if (focusedDate == null) {
  964. return;
  965. }
  966. Date requestedPreviousMonthDate = (Date) focusedDate.clone();
  967. removeOneMonth(requestedPreviousMonthDate);
  968. if (!isDateInsideRange(requestedPreviousMonthDate,
  969. getResolution(this::isMonth))) {
  970. return;
  971. }
  972. if (!isDateInsideRange(requestedPreviousMonthDate,
  973. getResolution(this::isDay))) {
  974. requestedPreviousMonthDate = adjustDateToFitInsideRange(
  975. requestedPreviousMonthDate);
  976. }
  977. focusedDate.setTime(requestedPreviousMonthDate.getTime());
  978. displayedMonth.setMonth(displayedMonth.getMonth() - 1);
  979. renderCalendar();
  980. }
  981. /**
  982. * Selects the previous year
  983. */
  984. private void focusPreviousYear(int years) {
  985. if (focusedDate == null) {
  986. return;
  987. }
  988. Date previousYearDate = (Date) focusedDate.clone();
  989. previousYearDate.setYear(previousYearDate.getYear() - years);
  990. // Do not focus if not inside range
  991. if (!isDateInsideRange(previousYearDate, getResolution(this::isYear))) {
  992. return;
  993. }
  994. // If we remove one year, but have to roll back a bit, fit it
  995. // into the calendar. Also the months have to be changed
  996. if (!isDateInsideRange(previousYearDate, getResolution(this::isDay))) {
  997. previousYearDate = adjustDateToFitInsideRange(previousYearDate);
  998. focusedDate.setYear(previousYearDate.getYear());
  999. focusedDate.setMonth(previousYearDate.getMonth());
  1000. focusedDate.setDate(previousYearDate.getDate());
  1001. displayedMonth.setYear(previousYearDate.getYear());
  1002. displayedMonth.setMonth(previousYearDate.getMonth());
  1003. } else {
  1004. int currentMonth = focusedDate.getMonth();
  1005. focusedDate.setYear(focusedDate.getYear() - years);
  1006. displayedMonth.setYear(displayedMonth.getYear() - years);
  1007. /*
  1008. * If the focused date was a leap day (Feb 29), the new date becomes
  1009. * Mar 1 if the new year is not also a leap year. Set it to Feb 28
  1010. * instead.
  1011. */
  1012. if (focusedDate.getMonth() != currentMonth) {
  1013. focusedDate.setDate(0);
  1014. }
  1015. }
  1016. renderCalendar();
  1017. }
  1018. /**
  1019. * Selects the next year
  1020. */
  1021. private void focusNextYear(int years) {
  1022. if (focusedDate == null) {
  1023. return;
  1024. }
  1025. Date nextYearDate = (Date) focusedDate.clone();
  1026. nextYearDate.setYear(nextYearDate.getYear() + years);
  1027. // Do not focus if not inside range
  1028. if (!isDateInsideRange(nextYearDate, getResolution(this::isYear))) {
  1029. return;
  1030. }
  1031. // If we add one year, but have to roll back a bit, fit it
  1032. // into the calendar. Also the months have to be changed
  1033. if (!isDateInsideRange(nextYearDate, getResolution(this::isDay))) {
  1034. nextYearDate = adjustDateToFitInsideRange(nextYearDate);
  1035. focusedDate.setYear(nextYearDate.getYear());
  1036. focusedDate.setMonth(nextYearDate.getMonth());
  1037. focusedDate.setDate(nextYearDate.getDate());
  1038. displayedMonth.setYear(nextYearDate.getYear());
  1039. displayedMonth.setMonth(nextYearDate.getMonth());
  1040. } else {
  1041. int currentMonth = focusedDate.getMonth();
  1042. focusedDate.setYear(focusedDate.getYear() + years);
  1043. displayedMonth.setYear(displayedMonth.getYear() + years);
  1044. /*
  1045. * If the focused date was a leap day (Feb 29), the new date becomes
  1046. * Mar 1 if the new year is not also a leap year. Set it to Feb 28
  1047. * instead.
  1048. */
  1049. if (focusedDate.getMonth() != currentMonth) {
  1050. focusedDate.setDate(0);
  1051. }
  1052. }
  1053. renderCalendar();
  1054. }
  1055. /**
  1056. * Handles a user click on the component
  1057. *
  1058. * @param sender
  1059. * The component that was clicked
  1060. */
  1061. private void processClickEvent(Widget sender) {
  1062. if (!isEnabled() || isReadonly()) {
  1063. return;
  1064. }
  1065. if (sender == prevYear) {
  1066. focusPreviousYear(1);
  1067. } else if (sender == nextYear) {
  1068. focusNextYear(1);
  1069. } else if (sender == prevMonth) {
  1070. focusPreviousMonth();
  1071. } else if (sender == nextMonth) {
  1072. focusNextMonth();
  1073. }
  1074. }
  1075. /*
  1076. * (non-Javadoc)
  1077. *
  1078. * @see
  1079. * com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt
  1080. * .event.dom.client.KeyDownEvent)
  1081. */
  1082. @Override
  1083. public void onKeyDown(KeyDownEvent event) {
  1084. handleKeyPress(event);
  1085. }
  1086. /*
  1087. * (non-Javadoc)
  1088. *
  1089. * @see
  1090. * com.google.gwt.event.dom.client.KeyPressHandler#onKeyPress(com.google
  1091. * .gwt.event.dom.client.KeyPressEvent)
  1092. */
  1093. @Override
  1094. public void onKeyPress(KeyPressEvent event) {
  1095. handleKeyPress(event);
  1096. }
  1097. /**
  1098. * Handles the keypress from both the onKeyPress event and the onKeyDown
  1099. * event
  1100. *
  1101. * @param event
  1102. * The keydown/keypress event
  1103. */
  1104. private void handleKeyPress(DomEvent<?> event) {
  1105. // Check tabs
  1106. int keycode = event.getNativeEvent().getKeyCode();
  1107. if (keycode == KeyCodes.KEY_TAB
  1108. && event.getNativeEvent().getShiftKey()) {
  1109. if (onTabOut(event)) {
  1110. return;
  1111. }
  1112. }
  1113. // Handle the navigation
  1114. if (handleNavigation(keycode,
  1115. event.getNativeEvent().getCtrlKey()
  1116. || event.getNativeEvent().getMetaKey(),
  1117. event.getNativeEvent().getShiftKey())) {
  1118. event.preventDefault();
  1119. }
  1120. }
  1121. /**
  1122. * Notifies submit-listeners of a submit event
  1123. */
  1124. private void onSubmit() {
  1125. if (getSubmitListener() != null) {
  1126. getSubmitListener().onSubmit();
  1127. }
  1128. }
  1129. /**
  1130. * Notifies submit-listeners of a cancel event
  1131. */
  1132. private void onCancel() {
  1133. if (getSubmitListener() != null) {
  1134. getSubmitListener().onCancel();
  1135. }
  1136. }
  1137. /**
  1138. * Handles the keyboard navigation when the resolution is set to years.
  1139. *
  1140. * @param keycode
  1141. * The keycode to process
  1142. * @param ctrl
  1143. * Is ctrl pressed?
  1144. * @param shift
  1145. * is shift pressed
  1146. * @return Returns true if the keycode was processed, else false
  1147. */
  1148. protected boolean handleNavigationYearMode(int keycode, boolean ctrl,
  1149. boolean shift) {
  1150. // Ctrl and Shift selection not supported
  1151. if (ctrl || shift) {
  1152. return false;
  1153. } else if (keycode == getPreviousKey()) {
  1154. focusNextYear(10); // Add 10 years
  1155. return true;
  1156. } else if (keycode == getForwardKey()) {
  1157. focusNextYear(1); // Add 1 year
  1158. return true;
  1159. } else if (keycode == getNextKey()) {
  1160. focusPreviousYear(10); // Subtract 10 years
  1161. return true;
  1162. } else if (keycode == getBackwardKey()) {
  1163. focusPreviousYear(1); // Subtract 1 year
  1164. return true;
  1165. } else if (keycode == getSelectKey()) {
  1166. value = (Date) focusedDate.clone();
  1167. onSubmit();
  1168. return true;
  1169. } else if (keycode == getResetKey()) {
  1170. // Restore showing value the selected value
  1171. focusedDate.setTime(value.getTime());
  1172. renderCalendar();
  1173. return true;
  1174. } else if (keycode == getCloseKey()) {
  1175. // TODO fire listener, on users responsibility??
  1176. onCancel();
  1177. return true;
  1178. }
  1179. return false;
  1180. }
  1181. /**
  1182. * Handle the keyboard navigation when the resolution is set to MONTH.
  1183. *
  1184. * @param keycode
  1185. * The keycode to handle
  1186. * @param ctrl
  1187. * Was the ctrl key pressed?
  1188. * @param shift
  1189. * Was the shift key pressed?
  1190. * @return
  1191. */
  1192. protected boolean handleNavigationMonthMode(int keycode, boolean ctrl,
  1193. boolean shift) {
  1194. // Ctrl selection not supported
  1195. if (ctrl) {
  1196. return false;
  1197. } else if (keycode == getPreviousKey()) {
  1198. focusNextYear(1); // Add 1 year
  1199. return true;
  1200. } else if (keycode == getForwardKey()) {
  1201. focusNextMonth(); // Add 1 month
  1202. return true;
  1203. } else if (keycode == getNextKey()) {
  1204. focusPreviousYear(1); // Subtract 1 year
  1205. return true;
  1206. } else if (keycode == getBackwardKey()) {
  1207. focusPreviousMonth(); // Subtract 1 month
  1208. return true;
  1209. } else if (keycode == getSelectKey()) {
  1210. value = (Date) focusedDate.clone();
  1211. onSubmit();
  1212. return true;
  1213. } else if (keycode == getResetKey()) {
  1214. // Restore showing value the selected value
  1215. focusedDate.setTime(value.getTime());
  1216. renderCalendar();
  1217. return true;
  1218. } else if (keycode == getCloseKey()) {
  1219. onCancel();
  1220. // TODO fire close event
  1221. return true;
  1222. }
  1223. return false;
  1224. }
  1225. /**
  1226. * Handle keyboard navigation what the resolution is set to DAY.
  1227. *
  1228. * @param keycode
  1229. * The keycode to handle
  1230. * @param ctrl
  1231. * Was the ctrl key pressed?
  1232. * @param shift
  1233. * Was the shift key pressed?
  1234. * @return Return true if the key press was handled by the method, else
  1235. * return false.
  1236. */
  1237. protected boolean handleNavigationDayMode(int keycode, boolean ctrl,
  1238. boolean shift) {
  1239. // Ctrl key is not in use
  1240. if (ctrl) {
  1241. return false;
  1242. }
  1243. /*
  1244. * Jumps to the next day.
  1245. */
  1246. if (keycode == getForwardKey() && !shift) {
  1247. focusNextDay(1);
  1248. return true;
  1249. /*
  1250. * Jumps to the previous day
  1251. */
  1252. } else if (keycode == getBackwardKey() && !shift) {
  1253. focusPreviousDay(1);
  1254. return true;
  1255. /*
  1256. * Jumps one week forward in the calendar
  1257. */
  1258. } else if (keycode == getNextKey() && !shift) {
  1259. focusNextDay(7);
  1260. return true;
  1261. /*
  1262. * Jumps one week back in the calendar
  1263. */
  1264. } else if (keycode == getPreviousKey() && !shift) {
  1265. focusPreviousDay(7);
  1266. return true;
  1267. /*
  1268. * Selects the value that is chosen
  1269. */
  1270. } else if (keycode == getSelectKey() && !shift) {
  1271. selectFocused();
  1272. onSubmit(); // submit
  1273. return true;
  1274. } else if (keycode == getCloseKey()) {
  1275. onCancel();
  1276. // TODO close event
  1277. return true;
  1278. /*
  1279. * Jumps to the next month
  1280. */
  1281. } else if (shift && keycode == getForwardKey()) {
  1282. focusNextMonth();
  1283. return true;
  1284. /*
  1285. * Jumps to the previous month
  1286. */
  1287. } else if (shift && keycode == getBackwardKey()) {
  1288. focusPreviousMonth();
  1289. return true;
  1290. /*
  1291. * Jumps to the next year
  1292. */
  1293. } else if (shift && keycode == getPreviousKey()) {
  1294. focusNextYear(1);
  1295. return true;
  1296. /*
  1297. * Jumps to the previous year
  1298. */
  1299. } else if (shift && keycode == getNextKey()) {
  1300. focusPreviousYear(1);
  1301. return true;
  1302. /*
  1303. * Resets the selection
  1304. */
  1305. } else if (keycode == getResetKey() && !shift) {
  1306. // Restore showing value the selected value
  1307. focusedDate = new FocusedDate(value.getYear(), value.getMonth(),
  1308. value.getDate());
  1309. displayedMonth = new FocusedDate(value.getYear(), value.getMonth(),
  1310. 1);
  1311. renderCalendar();
  1312. return true;
  1313. }
  1314. return false;
  1315. }
  1316. /**
  1317. * Handles the keyboard navigation.
  1318. *
  1319. * @param keycode
  1320. * The key code that was pressed
  1321. * @param ctrl
  1322. * Was the ctrl key pressed
  1323. * @param shift
  1324. * Was the shift key pressed
  1325. * @return Return true if key press was handled by the component, else
  1326. * return false
  1327. */
  1328. protected boolean handleNavigation(int keycode, boolean ctrl,
  1329. boolean shift) {
  1330. if (!isEnabled() || isReadonly()) {
  1331. return false;
  1332. } else if (isYear(getResolution())) {
  1333. return handleNavigationYearMode(keycode, ctrl, shift);
  1334. } else if (isMonth(getResolution())) {
  1335. return handleNavigationMonthMode(keycode, ctrl, shift);
  1336. } else if (isDay(getResolution())) {
  1337. return handleNavigationDayMode(keycode, ctrl, shift);
  1338. } else {
  1339. return handleNavigationDayMode(keycode, ctrl, shift);
  1340. }
  1341. }
  1342. /**
  1343. * Returns the reset key which will reset the calendar to the previous
  1344. * selection. By default this is backspace but it can be overridden to
  1345. * change the key to whatever you want.
  1346. *
  1347. * @return
  1348. */
  1349. protected int getResetKey() {
  1350. return KeyCodes.KEY_BACKSPACE;
  1351. }
  1352. /**
  1353. * Returns the select key which selects the value. By default this is the
  1354. * enter key but it can be changed to whatever you like by overriding this
  1355. * method.
  1356. *
  1357. * @return
  1358. */
  1359. protected int getSelectKey() {
  1360. return KeyCodes.KEY_ENTER;
  1361. }
  1362. /**
  1363. * Returns the key that closes the popup window if this is a VPopopCalendar.
  1364. * Else this does nothing. By default this is the Escape key but you can
  1365. * change the key to whatever you want by overriding this method.
  1366. *
  1367. * @return
  1368. */
  1369. protected int getCloseKey() {
  1370. return KeyCodes.KEY_ESCAPE;
  1371. }
  1372. /**
  1373. * The key that selects the next day in the calendar. By default this is the
  1374. * right arrow key but by overriding this method it can be changed to
  1375. * whatever you like.
  1376. *
  1377. * @return
  1378. */
  1379. protected int getForwardKey() {
  1380. return KeyCodes.KEY_RIGHT;
  1381. }
  1382. /**
  1383. * The key that selects the previous day in the calendar. By default this is
  1384. * the left arrow key but by overriding this method it can be changed to
  1385. * whatever you like.
  1386. *
  1387. * @return
  1388. */
  1389. protected int getBackwardKey() {
  1390. return KeyCodes.KEY_LEFT;
  1391. }
  1392. /**
  1393. * The key that selects the next week in the calendar. By default this is
  1394. * the down arrow key but by overriding this method it can be changed to
  1395. * whatever you like.
  1396. *
  1397. * @return
  1398. */
  1399. protected int getNextKey() {
  1400. return KeyCodes.KEY_DOWN;
  1401. }
  1402. /**
  1403. * The key that selects the previous week in the calendar. By default this
  1404. * is the up arrow key but by overriding this method it can be changed to
  1405. * whatever you like.
  1406. *
  1407. * @return
  1408. */
  1409. protected int getPreviousKey() {
  1410. return KeyCodes.KEY_UP;
  1411. }
  1412. /*
  1413. * (non-Javadoc)
  1414. *
  1415. * @see
  1416. * com.google.gwt.event.dom.client.MouseOutHandler#onMouseOut(com.google
  1417. * .gwt.event.dom.client.MouseOutEvent)
  1418. */
  1419. @Override
  1420. public void onMouseOut(MouseOutEvent event) {
  1421. if (mouseTimer != null) {
  1422. mouseTimer.cancel();
  1423. }
  1424. }
  1425. /*
  1426. * (non-Javadoc)
  1427. *
  1428. * @see
  1429. * com.google.gwt.event.dom.client.MouseDownHandler#onMouseDown(com.google
  1430. * .gwt.event.dom.client.MouseDownEvent)
  1431. */
  1432. @Override
  1433. public void onMouseDown(MouseDownEvent event) {
  1434. // Click-n-hold the left mouse button for fast-forward or fast-rewind.
  1435. // Timer is first used for a 500ms delay after mousedown. After that has
  1436. // elapsed, another timer is triggered to go off every 150ms. Both
  1437. // timers are cancelled on mouseup or mouseout.
  1438. if (event.getNativeButton() == NativeEvent.BUTTON_LEFT && event
  1439. .getSource() instanceof VAbstractCalendarPanel.VEventButton) {
  1440. final VEventButton sender = (VEventButton) event.getSource();
  1441. processClickEvent(sender);
  1442. mouseTimer = new Timer() {
  1443. @Override
  1444. public void run() {
  1445. mouseTimer = new Timer() {
  1446. @Override
  1447. public void run() {
  1448. processClickEvent(sender);
  1449. }
  1450. };
  1451. mouseTimer.scheduleRepeating(150);
  1452. }
  1453. };
  1454. mouseTimer.schedule(500);
  1455. }
  1456. }
  1457. /*
  1458. * (non-Javadoc)
  1459. *
  1460. * @see
  1461. * com.google.gwt.event.dom.client.MouseUpHandler#onMouseUp(com.google.gwt
  1462. * .event.dom.client.MouseUpEvent)
  1463. */
  1464. @Override
  1465. public void onMouseUp(MouseUpEvent event) {
  1466. if (mouseTimer != null) {
  1467. mouseTimer.cancel();
  1468. }
  1469. }
  1470. /**
  1471. * Adjusts a date to fit inside the range, only if outside
  1472. *
  1473. * @param date
  1474. */
  1475. private Date adjustDateToFitInsideRange(Date date) {
  1476. if (!isAcceptedByRangeStart(date, resolution)) {
  1477. date = parseRangeString(rangeStart);
  1478. } else if (!isAcceptedByRangeEnd(date, resolution)) {
  1479. date = parseRangeString(rangeEnd);
  1480. }
  1481. return date;
  1482. }
  1483. private Date parseRangeString(String dateStr) {
  1484. if (dateStr == null || "".equals(dateStr))
  1485. return null;
  1486. int year = Integer.parseInt(dateStr.substring(0, 4)) - 1900;
  1487. int month = parsePart(dateStr, 5, 2, 1) - 1;
  1488. int day = parsePart(dateStr, 8, 2, 1);
  1489. int hrs = parsePart(dateStr, 11, 2, 0);
  1490. int min = parsePart(dateStr, 14, 2, 0);
  1491. int sec = parsePart(dateStr, 17, 2, 0);
  1492. return new Date(year, month, day, hrs, min, sec);
  1493. }
  1494. private int parsePart(String dateStr, int beginIndex, int length,
  1495. int defValue) {
  1496. if (dateStr.length() < beginIndex + length)
  1497. return defValue;
  1498. return Integer
  1499. .parseInt(dateStr.substring(beginIndex, beginIndex + length));
  1500. }
  1501. /**
  1502. * Sets the data of the Panel.
  1503. *
  1504. * @param currentDate
  1505. * The date to set
  1506. */
  1507. public void setDate(Date currentDate) {
  1508. doSetDate(currentDate, false, () -> {
  1509. });
  1510. }
  1511. /**
  1512. * The actual implementation of the logic which sets the data of the Panel.
  1513. * The method {@link #setDate(Date)} just delegate a call to this method
  1514. * providing additional config parameters.
  1515. *
  1516. * @param currentDate
  1517. * currentDate The date to set
  1518. * @param needRerender
  1519. * if {@code true} then calendar will be rerendered regardless of
  1520. * internal logic, otherwise the decision will be made on the
  1521. * internal state inside the method
  1522. * @param focusAction
  1523. * an additional action which will be executed in case
  1524. * rerendering is not required
  1525. */
  1526. protected void doSetDate(Date currentDate, boolean needRerender,
  1527. Runnable focusAction) {
  1528. // Check that we are not re-rendering an already active date
  1529. if (currentDate == value && currentDate != null) {
  1530. return;
  1531. }
  1532. boolean currentDateWasAdjusted = false;
  1533. // Check that selected date is inside the allowed range
  1534. if (currentDate != null
  1535. && !isDateInsideRange(currentDate, getResolution())) {
  1536. currentDate = adjustDateToFitInsideRange(currentDate);
  1537. currentDateWasAdjusted = true;
  1538. }
  1539. Date oldDisplayedMonth = displayedMonth;
  1540. value = currentDate;
  1541. // If current date was adjusted, we will not select any date,
  1542. // since that will look like a date is selected. Instead we
  1543. // only focus on the adjusted value
  1544. if (value == null || currentDateWasAdjusted) {
  1545. // If ranges enabled, we may need to focus on a different view to
  1546. // potentially not get stuck
  1547. if (rangeStart != null || rangeEnd != null) {
  1548. Date dateThatFitsInsideRange = adjustDateToFitInsideRange(
  1549. new Date());
  1550. focusedDate = new FocusedDate(dateThatFitsInsideRange.getYear(),
  1551. dateThatFitsInsideRange.getMonth(),
  1552. dateThatFitsInsideRange.getDate());
  1553. displayedMonth = new FocusedDate(
  1554. dateThatFitsInsideRange.getYear(),
  1555. dateThatFitsInsideRange.getMonth(), 1);
  1556. // value was adjusted. Set selected to null to not cause
  1557. // confusion, but this is only needed (and allowed) when we have
  1558. // a day
  1559. // resolution
  1560. if (isDay(getResolution())) {
  1561. value = null;
  1562. }
  1563. } else {
  1564. focusedDate = displayedMonth = null;
  1565. }
  1566. } else {
  1567. focusedDate = new FocusedDate(value.getYear(), value.getMonth(),
  1568. value.getDate());
  1569. displayedMonth = new FocusedDate(value.getYear(), value.getMonth(),
  1570. 1);
  1571. }
  1572. // Re-render calendar if the displayed month is changed.
  1573. if (needRerender || oldDisplayedMonth == null || value == null
  1574. || oldDisplayedMonth.getYear() != value.getYear()
  1575. || oldDisplayedMonth.getMonth() != value.getMonth()) {
  1576. renderCalendar();
  1577. } else {
  1578. focusDay(focusedDate);
  1579. selectFocused();
  1580. focusAction.run();
  1581. }
  1582. if (!hasFocus) {
  1583. focusDay(null);
  1584. }
  1585. }
  1586. /**
  1587. * A widget representing a single day in the calendar panel.
  1588. */
  1589. private class Day extends InlineHTML {
  1590. private final Date date;
  1591. Day(Date date) {
  1592. super("" + date.getDate());
  1593. this.date = date;
  1594. addClickHandler(dayClickHandler);
  1595. }
  1596. public Date getDate() {
  1597. return date;
  1598. }
  1599. }
  1600. public Date getDate() {
  1601. return value;
  1602. }
  1603. /**
  1604. * If true should be returned if the panel will not be used after this
  1605. * event.
  1606. *
  1607. * @param event
  1608. * @return
  1609. */
  1610. protected boolean onTabOut(DomEvent<?> event) {
  1611. if (focusOutListener != null) {
  1612. return focusOutListener.onFocusOut(event);
  1613. }
  1614. return false;
  1615. }
  1616. /**
  1617. * A focus out listener is triggered when the panel loosed focus. This can
  1618. * happen either after a user clicks outside the panel or tabs out.
  1619. *
  1620. * @param listener
  1621. * The listener to trigger
  1622. */
  1623. public void setFocusOutListener(FocusOutListener listener) {
  1624. focusOutListener = listener;
  1625. }
  1626. /**
  1627. * The submit listener is called when the user selects a value from the
  1628. * calendar either by clicking the day or selects it by keyboard.
  1629. *
  1630. * @param submitListener
  1631. * The listener to trigger
  1632. */
  1633. public void setSubmitListener(SubmitListener submitListener) {
  1634. this.submitListener = submitListener;
  1635. }
  1636. /**
  1637. * The given FocusChangeListener is notified when the focused date changes
  1638. * by user either clicking on a new date or by using the keyboard.
  1639. *
  1640. * @param listener
  1641. * The FocusChangeListener to be notified
  1642. */
  1643. public void setFocusChangeListener(FocusChangeListener listener) {
  1644. focusChangeListener = listener;
  1645. }
  1646. /**
  1647. * Returns the submit listener that listens to selection made from the
  1648. * panel.
  1649. *
  1650. * @return The listener or NULL if no listener has been set
  1651. */
  1652. public SubmitListener getSubmitListener() {
  1653. return submitListener;
  1654. }
  1655. /*
  1656. * (non-Javadoc)
  1657. *
  1658. * @see
  1659. * com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event
  1660. * .dom.client.BlurEvent)
  1661. */
  1662. @Override
  1663. public void onBlur(final BlurEvent event) {
  1664. if (event.getSource() instanceof VAbstractCalendarPanel) {
  1665. hasFocus = false;
  1666. focusDay(null);
  1667. }
  1668. }
  1669. /*
  1670. * (non-Javadoc)
  1671. *
  1672. * @see
  1673. * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
  1674. * .dom.client.FocusEvent)
  1675. */
  1676. @Override
  1677. public void onFocus(FocusEvent event) {
  1678. if (event.getSource() instanceof VAbstractCalendarPanel) {
  1679. hasFocus = true;
  1680. // Focuses the current day if the calendar shows the days
  1681. if (focusedDay != null) {
  1682. focusDay(focusedDate);
  1683. }
  1684. }
  1685. }
  1686. private static final String SUBPART_NEXT_MONTH = "nextmon";
  1687. private static final String SUBPART_PREV_MONTH = "prevmon";
  1688. private static final String SUBPART_NEXT_YEAR = "nexty";
  1689. private static final String SUBPART_PREV_YEAR = "prevy";
  1690. private static final String SUBPART_HOUR_SELECT = "h";
  1691. private static final String SUBPART_MINUTE_SELECT = "m";
  1692. private static final String SUBPART_SECS_SELECT = "s";
  1693. private static final String SUBPART_AMPM_SELECT = "ampm";
  1694. private static final String SUBPART_DAY = "day";
  1695. private static final String SUBPART_MONTH_YEAR_HEADER = "header";
  1696. private String rangeStart;
  1697. private String rangeEnd;
  1698. @Override
  1699. public String getSubPartName(
  1700. com.google.gwt.user.client.Element subElement) {
  1701. if (contains(nextMonth, subElement)) {
  1702. return SUBPART_NEXT_MONTH;
  1703. } else if (contains(prevMonth, subElement)) {
  1704. return SUBPART_PREV_MONTH;
  1705. } else if (contains(nextYear, subElement)) {
  1706. return SUBPART_NEXT_YEAR;
  1707. } else if (contains(prevYear, subElement)) {
  1708. return SUBPART_PREV_YEAR;
  1709. } else if (contains(days, subElement)) {
  1710. // Day, find out which dayOfMonth and use that as the identifier
  1711. Day day = WidgetUtil.findWidget(subElement, Day.class);
  1712. if (day != null) {
  1713. Date date = day.getDate();
  1714. int id = date.getDate();
  1715. // Zero or negative ids map to days of the preceding month,
  1716. // past-the-end-of-month ids to days of the following month
  1717. if (date.getMonth() < displayedMonth.getMonth()) {
  1718. id -= DateTimeService.getNumberOfDaysInMonth(date);
  1719. } else if (date.getMonth() > displayedMonth.getMonth()) {
  1720. id += DateTimeService
  1721. .getNumberOfDaysInMonth(displayedMonth);
  1722. }
  1723. return SUBPART_DAY + id;
  1724. }
  1725. } else if (getCellFormatter().getElement(0, 2)
  1726. .isOrHasChild(subElement)) {
  1727. return SUBPART_MONTH_YEAR_HEADER;
  1728. }
  1729. return null;
  1730. }
  1731. /**
  1732. * Checks if subElement is inside the widget DOM hierarchy.
  1733. *
  1734. * @param w
  1735. * @param subElement
  1736. * @return true if {@code w} is a parent of subElement, false otherwise.
  1737. */
  1738. protected boolean contains(Widget w, Element subElement) {
  1739. if (w == null || w.getElement() == null) {
  1740. return false;
  1741. }
  1742. return w.getElement().isOrHasChild(subElement);
  1743. }
  1744. @Override
  1745. public com.google.gwt.user.client.Element getSubPartElement(
  1746. String subPart) {
  1747. if (SUBPART_NEXT_MONTH.equals(subPart)) {
  1748. return nextMonth.getElement();
  1749. }
  1750. if (SUBPART_PREV_MONTH.equals(subPart)) {
  1751. return prevMonth.getElement();
  1752. }
  1753. if (SUBPART_NEXT_YEAR.equals(subPart)) {
  1754. return nextYear.getElement();
  1755. }
  1756. if (SUBPART_PREV_YEAR.equals(subPart)) {
  1757. return prevYear.getElement();
  1758. }
  1759. if (subPart.startsWith(SUBPART_DAY)) {
  1760. // Zero or negative ids map to days in the preceding month,
  1761. // past-the-end-of-month ids to days in the following month
  1762. int dayOfMonth = Integer
  1763. .parseInt(subPart.substring(SUBPART_DAY.length()));
  1764. Date date = new Date(displayedMonth.getYear(),
  1765. displayedMonth.getMonth(), dayOfMonth);
  1766. for (Widget w : days) {
  1767. if (w instanceof VAbstractCalendarPanel.Day) {
  1768. Day day = (Day) w;
  1769. if (day.getDate().equals(date)) {
  1770. return day.getElement();
  1771. }
  1772. }
  1773. }
  1774. }
  1775. if (SUBPART_MONTH_YEAR_HEADER.equals(subPart)) {
  1776. return DOM.asOld(
  1777. (Element) getCellFormatter().getElement(0, 2).getChild(0));
  1778. }
  1779. return null;
  1780. }
  1781. @Override
  1782. protected void onDetach() {
  1783. super.onDetach();
  1784. if (mouseTimer != null) {
  1785. mouseTimer.cancel();
  1786. }
  1787. }
  1788. /**
  1789. * Helper class to inform the screen reader that the user changed the
  1790. * selected date. It sets the value of a field that is outside the view, and
  1791. * is defined as a live area. That way the screen reader recognizes the
  1792. * change and reads it to the user.
  1793. */
  1794. public class FocusedDate extends Date {
  1795. public FocusedDate(int year, int month, int date) {
  1796. super(year, month, date);
  1797. }
  1798. @Override
  1799. public void setTime(long time) {
  1800. super.setTime(time);
  1801. setLabel();
  1802. }
  1803. @Override
  1804. @Deprecated
  1805. public void setDate(int date) {
  1806. super.setDate(date);
  1807. setLabel();
  1808. }
  1809. @Override
  1810. @Deprecated
  1811. public void setMonth(int month) {
  1812. super.setMonth(month);
  1813. setLabel();
  1814. }
  1815. @Override
  1816. @Deprecated
  1817. public void setYear(int year) {
  1818. super.setYear(year);
  1819. setLabel();
  1820. }
  1821. private void setLabel() {
  1822. if (getDateField() instanceof VAbstractPopupCalendar) {
  1823. ((VAbstractPopupCalendar<?, ?>) getDateField())
  1824. .setFocusedDate(this);
  1825. }
  1826. }
  1827. }
  1828. /**
  1829. * Sets the start range for this component. The start range is inclusive,
  1830. * and it depends on the current resolution, what is considered inside the
  1831. * range.
  1832. *
  1833. * @param newRangeStart
  1834. * - the allowed range's start date
  1835. */
  1836. public void setRangeStart(String newRangeStart) {
  1837. if (!SharedUtil.equals(rangeStart, newRangeStart)) {
  1838. rangeStart = newRangeStart;
  1839. if (initialRenderDone) {
  1840. // Dynamic updates to the range needs to render the calendar to
  1841. // update the element stylenames
  1842. renderCalendar();
  1843. }
  1844. }
  1845. }
  1846. /**
  1847. * Sets the end range for this component. The end range is inclusive, and it
  1848. * depends on the current resolution, what is considered inside the range.
  1849. *
  1850. * @param newRangeEnd
  1851. * - the allowed range's end date
  1852. */
  1853. public void setRangeEnd(String newRangeEnd) {
  1854. if (!SharedUtil.equals(rangeEnd, newRangeEnd)) {
  1855. rangeEnd = newRangeEnd;
  1856. if (initialRenderDone) {
  1857. // Dynamic updates to the range needs to render the calendar to
  1858. // update the element stylenames
  1859. renderCalendar();
  1860. }
  1861. }
  1862. }
  1863. /**
  1864. * Set assistive label for the previous year element.
  1865. *
  1866. * @param label
  1867. * the label to set
  1868. * @since 8.4
  1869. */
  1870. public void setAssistiveLabelPreviousYear(String label) {
  1871. prevYearAssistiveLabel = label;
  1872. }
  1873. /**
  1874. * Set assistive label for the next year element.
  1875. *
  1876. * @param label
  1877. * the label to set
  1878. * @since 8.4
  1879. */
  1880. public void setAssistiveLabelNextYear(String label) {
  1881. nextYearAssistiveLabel = label;
  1882. }
  1883. /**
  1884. * Set assistive label for the previous month element.
  1885. *
  1886. * @param label
  1887. * the label to set
  1888. * @since 8.4
  1889. */
  1890. public void setAssistiveLabelPreviousMonth(String label) {
  1891. prevMonthAssistiveLabel = label;
  1892. }
  1893. /**
  1894. * Set assistive label for the next month element.
  1895. *
  1896. * @param label
  1897. * the label to set
  1898. * @since 8.4
  1899. */
  1900. public void setAssistiveLabelNextMonth(String label) {
  1901. nextMonthAssistiveLabel = label;
  1902. }
  1903. /**
  1904. * Updates assistive labels of the navigation elements.
  1905. *
  1906. * @since 8.4
  1907. */
  1908. public void updateAssistiveLabels() {
  1909. if (prevMonth != null) {
  1910. Roles.getButtonRole().setAriaLabelProperty(prevMonth.getElement(),
  1911. prevMonthAssistiveLabel);
  1912. }
  1913. if (nextMonth != null) {
  1914. Roles.getButtonRole().setAriaLabelProperty(nextMonth.getElement(),
  1915. nextMonthAssistiveLabel);
  1916. }
  1917. if (prevYear != null) {
  1918. Roles.getButtonRole().setAriaLabelProperty(prevYear.getElement(),
  1919. prevYearAssistiveLabel);
  1920. }
  1921. if (nextYear != null) {
  1922. Roles.getButtonRole().setAriaLabelProperty(nextYear.getElement(),
  1923. nextYearAssistiveLabel);
  1924. }
  1925. }
  1926. private static Logger getLogger() {
  1927. return Logger.getLogger(VAbstractCalendarPanel.class.getName());
  1928. }
  1929. }