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 org.codehaus.jackson.map.ObjectMapper;
030
031import com.sun.faces.renderkit.html_basic.ListboxRenderer;
032
033/**
034 * @since 6.0
035 */
036public class NxListboxRenderer extends ListboxRenderer {
037
038    public static final String RENDERER_TYPE = "org.nuxeo.NxListboxRenderer";
039
040    public static final String DISABLE_SELECT2_PROPERTY = "disableSelect2";
041
042    @Override
043    public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
044
045        super.encodeEnd(context, component);
046
047        final boolean disableSelect2 = Boolean.parseBoolean((String) component.getAttributes().get("disableSelect2"));
048
049        if (!disableSelect2) {
050            ResponseWriter writer = context.getResponseWriter();
051            writer.startElement("script", component);
052            Map<String, String> params = new HashMap<String, String>();
053            final String placeholder = (String) component.getAttributes().get("placeholder");
054            final String width = (String) component.getAttributes().get("width");
055            if (placeholder != null) {
056                params.put("placeholder", placeholder);
057            }
058            if (width != null) {
059                params.put("width", width);
060            }
061            writer.write("jQuery(document).ready(function(){nuxeo.utils.select2ifySelect('" + component.getClientId()
062                    + "', " + new ObjectMapper().writeValueAsString(params) + ")});");
063            writer.endElement("script");
064        }
065    }
066
067}