001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.wicket; 018 019import java.io.Serializable; 020import java.util.LinkedHashMap; 021import java.util.Map; 022import java.util.regex.Pattern; 023 024import org.apache.wicket.behavior.AttributeAppender; 025import org.apache.wicket.util.string.Strings; 026 027/** 028 * An AttributeModifier specialized in managing the <em>CSS style</em> 029 * attribute 030 */ 031public abstract class StyleAttributeModifier extends AttributeAppender 032{ 033 private static final Pattern STYLES_SPLITTER = Pattern.compile("\\s*;\\s*"); 034 private static final Pattern KEY_VALUE_SPLITTER = Pattern.compile("\\s*:\\s*"); 035 036 /** 037 * Constructor. 038 */ 039 public StyleAttributeModifier() 040 { 041 super("style", null, ";"); 042 } 043 044 @Override 045 protected Serializable newValue(String currentValue, String appendValue) 046 { 047 String[] styles; 048 if (Strings.isEmpty(currentValue)) 049 { 050 styles = new String[0]; 051 } 052 else 053 { 054 styles = STYLES_SPLITTER.split(currentValue.trim()); 055 } 056 Map<String, String> oldStyles = new LinkedHashMap<>(); 057 for (String style : styles) 058 { 059 String[] keyValue = KEY_VALUE_SPLITTER.split(style, 2); 060 oldStyles.put(keyValue[0], keyValue[1]); 061 } 062 063 Map<String, String> newStyles = update(oldStyles); 064 065 String separator = getSeparator(); 066 StringBuilder result = new StringBuilder(); 067 for (Map.Entry<String, String> entry : newStyles.entrySet()) 068 { 069 result 070 .append(entry.getKey()) 071 .append(':') 072 .append(entry.getValue()) 073 .append(separator); 074 } 075 return result.length() > 0 ? result.toString() : VALUELESS_ATTRIBUTE_REMOVE; 076 } 077 078 /** 079 * Callback to update the CSS class values for a tag. 080 * 081 * @param oldStyles 082 * A map with the old style key/values 083 * @return A map with the new style key/values 084 */ 085 protected abstract Map<String, String> update(Map<String, String> oldStyles); 086}