001package gwt.material.design.client.base.mixin;
002
003/*
004 * #%L
005 * GwtMaterial
006 * %%
007 * Copyright (C) 2015 GwtMaterialDesign
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 gwt.material.design.client.base.HasColors;
024
025import com.google.gwt.user.client.ui.UIObject;
026
027/**
028 * @author Ben Dol
029 */
030public class ColorsMixin<T extends UIObject & HasColors> extends AbstractMixin<T> implements HasColors {
031
032    private String bgColor = "";
033    private String textColor = "";
034
035    public ColorsMixin(final T widget) {
036        super(widget);
037    }
038
039    @Override
040    public void setBackgroundColor(String bgColor) {
041        if(this.bgColor != null && !this.bgColor.isEmpty()) {
042            uiObject.removeStyleName(this.bgColor);
043        }
044        this.bgColor = bgColor;
045
046        if(bgColor != null && !bgColor.isEmpty()) {
047            uiObject.addStyleName(bgColor);
048        }
049    }
050
051    @Override
052    public String getBackgroundColor() {
053        return bgColor;
054    }
055
056    @Override
057    public void setTextColor(String textColor) {
058        if(this.textColor != null && !this.textColor.isEmpty()) {
059            uiObject.removeStyleName(this.textColor);
060        }
061        this.textColor = ensureTextColorFormat(textColor);
062
063        if(this.textColor != null && !this.textColor.isEmpty()) {
064            uiObject.addStyleName(this.textColor);
065        }
066    }
067
068    @Override
069    public String getTextColor() {
070        return textColor;
071    }
072
073    /**
074     * Allow for the use of text shading and auto formatting.
075     */
076    protected String ensureTextColorFormat(String textColor) {
077        String formatted = "";
078        boolean mainColor = true;
079        for(String style : textColor.split(" ")) {
080            if(mainColor) {
081                // the main color
082                if(!style.endsWith("-text")) {
083                    style += "-text";
084                }
085                mainColor = false;
086            } else {
087                // the shading type
088                if(!style.startsWith("text-")) {
089                    style = " text-" + style;
090                }
091            }
092            formatted += style;
093        }
094        return formatted;
095    }
096}