001/*
002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     <a href="mailto:grenard@nuxeo.com">Guillaume</a>
018 */
019package org.nuxeo.ecm.platform.ui.web.renderer;
020
021import java.io.IOException;
022import java.util.HashMap;
023import java.util.Map;
024
025import javax.faces.component.UIComponent;
026import javax.faces.context.FacesContext;
027import javax.faces.context.ResponseWriter;
028
029import com.fasterxml.jackson.databind.ObjectMapper;
030import com.sun.faces.renderkit.html_basic.ListboxRenderer;
031
032/**
033 * @since 6.0
034 */
035public class NxListboxRenderer extends ListboxRenderer {
036
037    public static final String RENDERER_TYPE = "org.nuxeo.NxListboxRenderer";
038
039    public static final String DISABLE_SELECT2_PROPERTY = "disableSelect2";
040
041    @Override
042    public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
043
044        super.encodeEnd(context, component);
045
046        final boolean disableSelect2 = Boolean.parseBoolean((String) component.getAttributes().get("disableSelect2"));
047
048        if (!disableSelect2) {
049            ResponseWriter writer = context.getResponseWriter();
050            writer.startElement("script", component);
051            Map<String, String> params = new HashMap<String, String>();
052            final String placeholder = (String) component.getAttributes().get("placeholder");
053            final String width = (String) component.getAttributes().get("width");
054            if (placeholder != null) {
055                params.put("placeholder", placeholder);
056            }
057            if (width != null) {
058                params.put("width", width);
059            }
060            writer.write("jQuery(document).ready(function(){nuxeo.utils.select2ifySelect('" + component.getClientId()
061                    + "', " + new ObjectMapper().writeValueAsString(params) + ")});");
062            writer.endElement("script");
063        }
064    }
065
066}