ScheduleRendererBase.java 21.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
package org.richfaces.renderkit;

import org.ajax4jsf.javascript.JSFunction;
import org.ajax4jsf.javascript.JSFunctionDefinition;
import org.ajax4jsf.javascript.JSObject;
import org.ajax4jsf.javascript.JSReference;
import org.ajax4jsf.renderkit.AjaxComponentRendererBase;
import org.ajax4jsf.renderkit.AjaxRendererUtils;
import org.richfaces.component.ScheduleCommonViewAttributes;
import org.richfaces.component.UISchedule;
import org.richfaces.component.UIScheduleAgendaDayView;
import org.richfaces.component.UIScheduleAgendaWeekView;
import org.richfaces.component.UIScheduleBasicDayView;
import org.richfaces.component.UIScheduleBasicWeekView;
import org.richfaces.component.UIScheduleMonthView;
import org.richfaces.component.event.ScheduleDateRangeChangeEvent;
import org.richfaces.component.event.ScheduleDateRangeSelectEvent;
import org.richfaces.component.event.ScheduleDateSelectEvent;
import org.richfaces.component.event.ScheduleItemMoveEvent;
import org.richfaces.component.event.ScheduleItemResizeEvent;
import org.richfaces.component.event.ScheduleItemSelectEvent;
import org.richfaces.component.event.ScheduleViewChangeEvent;

import javax.faces.FacesException;
import javax.faces.component.NamingContainer;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public abstract class ScheduleRendererBase extends AjaxComponentRendererBase {
// ------------------------------ FIELDS ------------------------------

    public static final String DATE_RANGE_CHANGE_EVENT = "dateRangeChange";

    public static final String DATE_RANGE_SELECT_EVENT = "dateRangeSelect";

    public static final String DATE_SELECT_EVENT = "dateSelect";

    public static final String ITEM_MOVE_EVENT = "itemMove";

    public static final String ITEM_RESIZE_EVENT = "itemResize";

    public static final String ITEM_SELECT_EVENT = "itemSelect";

    public static final String VIEW_CHANGE_EVENT = "viewChange";

    private static final String ALL_DAY_PARAM = "allDay";

    private static final String CALLBACK = "callback";

    private static final String DAY_DELTA_PARAM = "dayDelta";

    private static final Map<String, Object> DEFAULTS;

    private static final String END_DATE_PARAM = "endDate";

    private static final String EVENT_TYPE_PARAM = "eventType";

    private static final String ITEM_ID_PARAM = "itemId";

    private static final String MINUTE_DELTA_PARAM = "minuteDelta";

    private static final String START_DATE_PARAM = "startDate";

    private static final String VIEW_PARAM = "view";

// -------------------------- STATIC METHODS --------------------------

    /**
     * Following defaults are be used by addOptionIfSetAndNotDefault
     */
    static {
        Map<String, Object> defaults = new HashMap<String, Object>();
        defaults.put("styleClass", "");
        defaults.put("defaultView", UISchedule.DEFAULT_VIEW);
        defaults.put("firstDay", UISchedule.DEFAULT_FIRST_DAY - 1);
        defaults.put("isRTL", UISchedule.DEFAULT_RTL);
        defaults.put("weekends", UISchedule.DEFAULT_SHOW_WEEKENDS);
        defaults.put("weekMode", UISchedule.DEFAULT_WEEK_MODE);
        defaults.put("aspectRatio", UISchedule.DEFAULT_ASPECT_RATIO);
        defaults.put("allDaySlot", UISchedule.DEFAULT_ALL_DAY_SLOT);
        defaults.put("axisFormat", UISchedule.DEFAULT_AXIS_FORMAT);
        defaults.put("slotMinutes", UISchedule.DEFAULT_SLOT_MINUTES);
        defaults.put("defaultEventMinutes", UISchedule.DEFAULT_EVENT_MINUTES);
        defaults.put("firstHour", UISchedule.DEFAULT_FIRST_HOUR);
        defaults.put("minTime", UISchedule.DEFAULT_MIN_TIME);
        defaults.put("maxTime", UISchedule.DEFAULT_MAX_TIME);
        defaults.put("editable", UISchedule.DEFAULT_EDITABLE);
        defaults.put("selectable", UISchedule.DEFAULT_SELECTABLE);
        defaults.put("selectHelper", UISchedule.DEFAULT_SELECT_HELPER);
        defaults.put("unselectAuto", UISchedule.DEFAULT_UNSELECT_AUTO);
        defaults.put("unselectCancel", UISchedule.DEFAULT_UNSELECT_CANCEL);
        defaults.put("disableDragging", UISchedule.DEFAULT_DISABLE_DRAGGING);
        defaults.put("disableResizing", UISchedule.DEFAULT_DISABLE_RESIZING);
        defaults.put("dragRevertDuration", UISchedule.DEFAULT_DRAG_REVERT_DURATION);
        defaults.put("allDayDefault", UISchedule.DEFAULT_ALL_DAY_DEFAULT);
        defaults.put("onbeforeitemselect", "");
        defaults.put("onitemselect", "");
        defaults.put("onbeforeitemdrop", "");
        defaults.put("onitemdrop", "");
        defaults.put("onbeforeitemresize", "");
        defaults.put("onitemresize", "");
        defaults.put("onitemresizestart", "");
        defaults.put("onitemresizestop", "");
        defaults.put("onitemdragstart", "");
        defaults.put("onitemdragstop", "");
        defaults.put("onitemmouseover", "");
        defaults.put("onitemmouseout", "");
        defaults.put("onviewchange", "");
        defaults.put("onbeforedateselect", "");
        defaults.put("ondateselect", "");
        defaults.put("onbeforedaterangeselect", "");
        defaults.put("ondaterangeselect", "");
        defaults.put("ondaterangechange", "");
        DEFAULTS = Collections.unmodifiableMap(defaults);
    }

    private static void copyAttribute(String attribute, String suffix, UIComponent source, UIComponent target) {
        Object value = source.getAttributes().get(attribute);
        if (value != null) {
            target.getAttributes().put(attribute + suffix, value);
        }
    }

// -------------------------- OTHER METHODS --------------------------

    @Override
    public void decode(FacesContext context, UIComponent component) {
        if (!component.isRendered()) {
            return;
        }
        Map<String, String> requestParameterMap = context.getExternalContext().getRequestParameterMap();
        if (requestParameterMap.get(component.getClientId(context)) != null) {
            String startDateParam = requestParameterMap.get(getFieldId(context, (UISchedule) component,
                START_DATE_PARAM));
            String endDateParam = requestParameterMap.get(getFieldId(context, (UISchedule) component,
                END_DATE_PARAM));
            String itemIdParam = requestParameterMap.get(getFieldId(context, (UISchedule) component,
                ITEM_ID_PARAM));
            String dayDeltaParam = requestParameterMap.get(getFieldId(context, (UISchedule) component,
                DAY_DELTA_PARAM));
            String minuteDeltaParam = requestParameterMap.get(getFieldId(context, (UISchedule) component,
                MINUTE_DELTA_PARAM));
            String allDayParam = requestParameterMap.get(getFieldId(context, (UISchedule) component,
                ALL_DAY_PARAM));
            String eventTypeParam = requestParameterMap.get(getFieldId(context, (UISchedule) component,
                EVENT_TYPE_PARAM));
            String viewParam = requestParameterMap.get(getFieldId(context, (UISchedule) component,
                VIEW_PARAM));

            try {
                if (DATE_RANGE_CHANGE_EVENT.equals(eventTypeParam)) {
                    Date startDate = new Date(Long.parseLong(startDateParam) * 1000);
                    Date endDate = new Date(Long.parseLong(endDateParam) * 1000);
                    new ScheduleDateRangeChangeEvent(component, startDate, endDate).queue();
                } else if (ITEM_MOVE_EVENT.equals(eventTypeParam)) {
                    int dayDelta = Integer.parseInt(dayDeltaParam);
                    int minuteDelta = Integer.parseInt(minuteDeltaParam);
                    boolean allDay = Boolean.parseBoolean(allDayParam);
                    new ScheduleItemMoveEvent(component, itemIdParam, dayDelta, minuteDelta, allDay).queue();
                } else if (ITEM_RESIZE_EVENT.equals(eventTypeParam)) {
                    int dayDelta = Integer.parseInt(dayDeltaParam);
                    int minuteDelta = Integer.parseInt(minuteDeltaParam);
                    new ScheduleItemResizeEvent(component, itemIdParam, dayDelta, minuteDelta).queue();
                } else if (ITEM_SELECT_EVENT.equals(eventTypeParam)) {
                    new ScheduleItemSelectEvent(component, itemIdParam).queue();
                } else if (VIEW_CHANGE_EVENT.equals(eventTypeParam)) {
                    new ScheduleViewChangeEvent(component, viewParam).queue();
                } else if (DATE_SELECT_EVENT.equals(eventTypeParam)) {
                    Date startDate = new Date(Long.parseLong(startDateParam) * 1000);
                    boolean allDay = Boolean.parseBoolean(allDayParam);
                    new ScheduleDateSelectEvent(component, startDate, allDay).queue();
                } else if (DATE_RANGE_SELECT_EVENT.equals(eventTypeParam)) {
                    Date startDate = new Date(Long.parseLong(startDateParam) * 1000);
                    Date endDate = new Date(Long.parseLong(endDateParam) * 1000);
                    boolean allDay = Boolean.parseBoolean(allDayParam);
                    new ScheduleDateRangeSelectEvent(component, startDate, endDate, allDay).queue();
                }
            } catch (NumberFormatException ex) {
                throw new FacesException("Cannot convert request parmeters", ex);
            }
        }
    }

    public void writeInitFunction(FacesContext context, UISchedule component) throws IOException {
        ResponseWriter writer = context.getResponseWriter();
        String clientId = component.getClientId(context);
        Locale locale = context.getViewRoot().getLocale();
        String widgetVar = component.getWidgetVar();
        if (widgetVar != null) {
            writer.writeText("var " + widgetVar + " = ", null);
        }
        writer.writeText(new JSObject("RichFaces.Schedule", clientId, locale.toString(),
            getOptions(component),
            DATE_RANGE_CHANGE_EVENT,
            ITEM_SELECT_EVENT,
            ITEM_MOVE_EVENT,
            ITEM_RESIZE_EVENT,
            VIEW_CHANGE_EVENT,
            DATE_SELECT_EVENT,
            DATE_RANGE_SELECT_EVENT,
            createSubmitEventFunction(context, component)).toScript(),
            null);
    }

    private void addOptionHash(String attribute, UIComponent source, Map<String, Object> options) {
        Map<String, Object> hash = new HashMap<String, Object>(3);
        Map<String, Object> attributes = source.getAttributes();
        addOptionIfSetAndNotDefault("month", attributes.get(attribute + "Month"), hash);
        addOptionIfSetAndNotDefault("basicWeek", attributes.get(attribute + "BasicWeek"), hash);
        addOptionIfSetAndNotDefault("agendaWeek", attributes.get(attribute + "AgendaWeek"), hash);
        addOptionIfSetAndNotDefault("basicDay", attributes.get(attribute + "BasicDay"), hash);
        addOptionIfSetAndNotDefault("agendaDay", attributes.get(attribute + "AgendaDay"), hash);
        addOptionIfSetAndNotDefault("", attributes.get(attribute), hash);
        if (hash.size() > 0) {
            options.put(attribute, hash);
        }
    }

    protected void addOptionIfSetAndNotDefault(String optionName, Object value, Map<String, Object> options) {
        if (value != null && !"".equals(value) && !value.equals(DEFAULTS.get(optionName))) {
            options.put(optionName, value);
        }
    }

    protected Object createSubmitEventFunction(FacesContext context, UISchedule component) {
        JSFunction jsFunction;
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(getFieldId(context, component, START_DATE_PARAM), new JSReference(START_DATE_PARAM));
        params.put(getFieldId(context, component, END_DATE_PARAM), new JSReference(END_DATE_PARAM));
        params.put(getFieldId(context, component, ITEM_ID_PARAM), new JSReference(ITEM_ID_PARAM));
        params.put(getFieldId(context, component, DAY_DELTA_PARAM), new JSReference(DAY_DELTA_PARAM));
        params.put(getFieldId(context, component, MINUTE_DELTA_PARAM), new JSReference(MINUTE_DELTA_PARAM));
        params.put(getFieldId(context, component, ALL_DAY_PARAM), new JSReference(ALL_DAY_PARAM));
        params.put(getFieldId(context, component, EVENT_TYPE_PARAM), new JSReference(EVENT_TYPE_PARAM));
        params.put(getFieldId(context, component, VIEW_PARAM), new JSReference(VIEW_PARAM));
        String clientId = component.getClientId(context);
        params.put(clientId, clientId);
        if (isAjaxMode(component)) {
            jsFunction = AjaxRendererUtils.buildAjaxFunction(component, context);
            Map<String, Object> eventOptions = AjaxRendererUtils.buildEventOptions(context, component, params);
            eventOptions.put("oncomplete", new JSReference(CALLBACK));
            jsFunction.addParameter(eventOptions);
        } else if (UISchedule.SWITCH_TYPE_SERVER.equals(component.getSwitchType())) {
            jsFunction = new JSFunction("Richfaces.jsFormSubmit",
                component.getClientId(context),
                getUtils().getNestingForm(context, component).getClientId(context),
                null,
                params);
        } else {
            return null;
        }
        return new JSFunctionDefinition("event", VIEW_PARAM, EVENT_TYPE_PARAM, ITEM_ID_PARAM, START_DATE_PARAM,
            END_DATE_PARAM, DAY_DELTA_PARAM, MINUTE_DELTA_PARAM, ALL_DAY_PARAM, CALLBACK).addToBody(jsFunction);
    }

    protected String getFieldId(FacesContext context, UISchedule component, String attribute) {
        return getUtils().clientId(context, component) + NamingContainer.SEPARATOR_CHAR + attribute;
    }

    protected Map<String, Object> getOptions(UISchedule schedule) throws IOException {
        /**
         * Copy attributes from child view components
         */
        for (UIComponent child : schedule.getChildren()) {
            if (!child.isRendered()) {
                continue;
            }
            String suffix = "";
            if (child instanceof UIScheduleMonthView) {
                copyAttribute("weekMode", "", child, schedule);
                suffix = "Month";
            } else if (child instanceof UIScheduleAgendaDayView) {
                suffix = "AgendaDay";
            } else if (child instanceof UIScheduleAgendaWeekView) {
                suffix = "AgendaWeek";
            } else if (child instanceof UIScheduleBasicDayView) {
                suffix = "BasicDay";
            } else if (child instanceof UIScheduleBasicWeekView) {
                suffix = "BasicWeek";
            }
            if (child instanceof ScheduleCommonViewAttributes) {
                copyAttribute("timeFormat", suffix, child, schedule);
                copyAttribute("columnFormat", suffix, child, schedule);
                copyAttribute("titleFormat", suffix, child, schedule);
                copyAttribute("dragOpacity", suffix, child, schedule);
            }
        }
        /**
         * Include only attributes that are actually set.
         */
        Map<String, Object> options = new HashMap<String, Object>();
        addOptionIfSetAndNotDefault("defaultView", schedule.getView(), options);
        /**
         * firstDayOfWeek numeration in Calendar (sunday=1,monday=2,etc.) and in widget(sunday=0,monday=1,etc.)
         */
        Integer firstDay = schedule.getFirstDay();
        if (firstDay != null) {
            addOptionIfSetAndNotDefault("firstDay", firstDay - 1, options);
        }
        addOptionIfSetAndNotDefault("isRTL", schedule.getIsRTL(), options);
        addOptionIfSetAndNotDefault("weekends", schedule.getShowWeekends(), options);
        addOptionIfSetAndNotDefault("weekMode", schedule.getWeekMode(), options);
        addOptionIfSetAndNotDefault("height", schedule.getHeight(), options);
        addOptionIfSetAndNotDefault("contentHeight", schedule.getContentHeight(), options);
        addOptionIfSetAndNotDefault("aspectRatio", schedule.getAspectRatio(), options);
        addOptionIfSetAndNotDefault("allDaySlot", schedule.getAllDaySlot(), options);
        addOptionIfSetAndNotDefault("allDayText", schedule.getAllDayText(), options);
        addOptionIfSetAndNotDefault("axisFormat", schedule.getAxisFormat(), options);
        addOptionIfSetAndNotDefault("slotMinutes", schedule.getSlotMinutes(), options);
        addOptionIfSetAndNotDefault("defaultEventMinutes", schedule.getDefaultEventMinutes(), options);
        addOptionIfSetAndNotDefault("firstHour", schedule.getFirstHour(), options);
        addOptionIfSetAndNotDefault("minTime", schedule.getMinTime(), options);
        addOptionIfSetAndNotDefault("maxTime", schedule.getMaxTime(), options);
        addOptionIfSetAndNotDefault("editable", schedule.getEditable(), options);
        addOptionIfSetAndNotDefault("selectable", schedule.getSelectable(), options);
        addOptionIfSetAndNotDefault("selectHelper", schedule.getSelectHelper(), options);
        addOptionIfSetAndNotDefault("unselectAuto", schedule.getUnselectAuto(), options);
        addOptionIfSetAndNotDefault("unselectCancel", schedule.getUnselectCancel(), options);
        addOptionIfSetAndNotDefault("disableDragging", schedule.getDisableDragging(), options);
        addOptionIfSetAndNotDefault("disableResizing", schedule.getDisableResizing(), options);
        addOptionIfSetAndNotDefault("dragRevertDuration", schedule.getDragRevertDuration(), options);
        addOptionHash("dragOpacity", schedule, options);
        addOptionHash("titleFormat", schedule, options);
        addOptionHash("timeFormat", schedule, options);
        addOptionHash("columnFormat", schedule, options);
        Map<String, Object> headerOptions = new HashMap<String, Object>(3);
        addOptionIfSetAndNotDefault("left", schedule.getHeaderLeft(), headerOptions);
        addOptionIfSetAndNotDefault("center", schedule.getHeaderCenter(), headerOptions);
        addOptionIfSetAndNotDefault("right", schedule.getHeaderRight(), headerOptions);
        if (headerOptions.size() > 0) {
            options.put("header", headerOptions);
        }
        addOptionIfSetAndNotDefault("allDayDefault", schedule.getAllDayByDefault(), options);

        addOptionIfSetAndNotDefault("onbeforeitemselect", schedule.getOnbeforeitemselect(), options);
        addOptionIfSetAndNotDefault("onitemselect", schedule.getOnitemselect(), options);
        addOptionIfSetAndNotDefault("onbeforeitemdrop", schedule.getOnbeforeitemdrop(), options);
        addOptionIfSetAndNotDefault("onitemdrop", schedule.getOnitemdrop(), options);
        addOptionIfSetAndNotDefault("onbeforeitemresize", schedule.getOnbeforeitemresize(), options);
        addOptionIfSetAndNotDefault("onitemresize", schedule.getOnitemresize(), options);
        addOptionIfSetAndNotDefault("onitemresizestart", schedule.getOnitemresizestart(), options);
        addOptionIfSetAndNotDefault("onitemresizestop", schedule.getOnitemresizestop(), options);
        addOptionIfSetAndNotDefault("onitemdragstart", schedule.getOnitemdragstart(), options);
        addOptionIfSetAndNotDefault("onitemdragstop", schedule.getOnitemdragstop(), options);
        addOptionIfSetAndNotDefault("onitemmouseover", schedule.getOnitemmouseover(), options);
        addOptionIfSetAndNotDefault("onitemmouseout", schedule.getOnitemmouseout(), options);
        addOptionIfSetAndNotDefault("onviewchange", schedule.getOnviewchange(), options);
        addOptionIfSetAndNotDefault("onbeforedateselect", schedule.getOnbeforedateselect(), options);
        addOptionIfSetAndNotDefault("ondateselect", schedule.getOndateselect(), options);
        addOptionIfSetAndNotDefault("onbeforedaterangeselect", schedule.getOnbeforedaterangeselect(), options);
        addOptionIfSetAndNotDefault("ondaterangeselect", schedule.getOndaterangeselect(), options);
        addOptionIfSetAndNotDefault("ondaterangechange", schedule.getOndaterangechange(), options);
        addOptionIfSetAndNotDefault("onviewdisplay", schedule.getOnviewdisplay(), options);
        if (schedule.getDate() != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(schedule.getDate());
            options.put("year", calendar.get(Calendar.YEAR));
            options.put("month", calendar.get(Calendar.MONTH));
            options.put("date", calendar.get(Calendar.DATE));
        }
        if (!isClientMode(schedule)) {
            Map<String, Object> initialItems = new HashMap<String, Object>();
            Date startDate = UISchedule.getFirstDisplayedDay(schedule);
            Date endDate = UISchedule.getLastDisplayedDate(schedule);
            initialItems.put("items", schedule.getScheduleData(startDate, endDate));
            Map<String, Object> date = new HashMap<String, Object>();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            date.put("year", calendar.get(Calendar.YEAR));
            date.put("month", calendar.get(Calendar.MONTH));
            date.put("date", calendar.get(Calendar.DATE));
            initialItems.put("startDate", date);
            date = new HashMap<String, Object>();
            calendar.setTime(endDate);
            date.put("year", calendar.get(Calendar.YEAR));
            date.put("month", calendar.get(Calendar.MONTH));
            date.put("date", calendar.get(Calendar.DATE));
            initialItems.put("endDate", date);
            options.put("initialItems", initialItems);
        } else {
            options.put("events", schedule.getScheduleData(null, null));
        }
        return options;
    }

    protected boolean isAjaxMode(UISchedule component) {
        String mode = component.getSwitchType();
        return UISchedule.SWITCH_TYPE_AJAX.equals(mode) || "".equals(mode) || null == mode;
    }

    protected boolean isClientMode(UISchedule component) {
        String mode = component.getSwitchType();
        return UISchedule.SWITCH_TYPE_CLIENT.equals(mode);
    }
}