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

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