001package org.gwtbootstrap3.client.ui.base.mixin;
002
003/*
004 * #%L
005 * GwtBootstrap3
006 * %%
007 * Copyright (C) 2013 GwtBootstrap3
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 * 
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 * 
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023import java.util.List;
024
025import org.gwtbootstrap3.client.ui.base.HasDataTarget;
026import org.gwtbootstrap3.client.ui.constants.Attributes;
027
028import com.google.gwt.dom.client.Document;
029import com.google.gwt.dom.client.Element;
030import com.google.gwt.user.client.ui.UIObject;
031import com.google.gwt.user.client.ui.Widget;
032
033/**
034 * @author Sven Jacobs
035 */
036public class DataTargetMixin<T extends UIObject & HasDataTarget> extends AbstractMixin implements HasDataTarget {
037
038    /**
039     * Ensures the given element has a non-empty id.
040     *
041     * @param element The element being examined.
042     * @see Document#createUniqueId()
043     */
044    private void ensureId(final Element element) {
045        final String id = element.getId();
046        if (id == null || id.isEmpty()) {
047            element.setId(Document.get().createUniqueId());
048        }
049    }
050
051    public DataTargetMixin(final T uiObject) {
052        super(uiObject);
053    }
054
055    @Override
056    public void setDataTargetWidget(final Widget widget) {
057        final Element element = widget.getElement();
058        ensureId(element);
059        this.setDataTarget("#" + element.getId());
060    }
061
062    @Override
063    public void setDataTargetWidgets(final List<Widget> widgets) {
064        final String styleName = Document.get().createUniqueId();
065        for (final Widget widget : widgets) {
066            widget.addStyleName(styleName);
067        }
068        this.setDataTarget("." + styleName);
069    }
070
071    @Override
072    public void setDataTarget(final String dataTarget) {
073        if (dataTarget != null) {
074            uiObject.getElement().setAttribute(Attributes.DATA_TARGET, dataTarget);
075        } else {
076            uiObject.getElement().removeAttribute(Attributes.DATA_TARGET);
077        }
078    }
079
080    @Override
081    public String getDataTarget() {
082        return uiObject.getElement().getAttribute(Attributes.DATA_TARGET);
083    }
084}