Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

VAbstractCalendarPanel.java 65KB

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