001/*
002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     <a href="mailto:grenard@nuxeo.com">Guillaume</a>
016 */
017package org.nuxeo.ecm.platform.ui.web.renderer;
018
019import java.io.IOException;
020import java.util.HashMap;
021import java.util.Map;
022
023import javax.faces.component.UIComponent;
024import javax.faces.context.FacesContext;
025import javax.faces.context.ResponseWriter;
026
027import org.codehaus.jackson.map.ObjectMapper;
028
029import com.sun.faces.renderkit.html_basic.ListboxRenderer;
030
031/**
032 * @since 6.0
033 */
034public class NxListboxRenderer extends ListboxRenderer {
035
036    public static final String RENDERER_TYPE = "org.nuxeo.NxListboxRenderer";
037
038    public static final String DISABLE_SELECT2_PROPERTY = "disableSelect2";
039
040    @Override
041    public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
042
043        super.encodeEnd(context, component);
044
045        final boolean disableSelect2 = Boolean.parseBoolean((String) component.getAttributes().get("disableSelect2"));
046
047        if (!disableSelect2) {
048            ResponseWriter writer = context.getResponseWriter();
049            writer.startElement("script", component);
050            Map<String, String> params = new HashMap<String, String>();
051            final String placeholder = (String) component.getAttributes().get("placeholder");
052            final String width = (String) component.getAttributes().get("width");
053            if (placeholder != null) {
054                params.put("placeholder", placeholder);
055            }
056            if (width != null) {
057                params.put("width", width);
058            }
059            writer.write("jQuery(document).ready(function(){nuxeo.utils.select2ifySelect('" + component.getClientId()
060                    + "', " + new ObjectMapper().writeValueAsString(params) + ")});");
061            writer.endElement("script");
062        }
063    }
064
065}