001// Copyright 2007, 2008 The Apache Software Foundation 002// 003// Licensed under the Apache License, Version 2.0 (the "License"); 004// you may not use this file except in compliance with the License. 005// You may obtain a copy of the License at 006// 007// http://www.apache.org/licenses/LICENSE-2.0 008// 009// Unless required by applicable law or agreed to in writing, software 010// distributed under the License is distributed on an "AS IS" BASIS, 011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 012// See the License for the specific language governing permissions and 013// limitations under the License. 014 015package org.apache.tapestry5.internal.util; 016 017import org.apache.tapestry5.*; 018 019import java.util.Map; 020 021public class SelectModelRenderer implements SelectModelVisitor 022{ 023 private final MarkupWriter writer; 024 025 private final ValueEncoder encoder; 026 027 public SelectModelRenderer(final MarkupWriter writer, ValueEncoder encoder) 028 { 029 this.writer = writer; 030 this.encoder = encoder; 031 } 032 033 public void beginOptionGroup(OptionGroupModel groupModel) 034 { 035 writer.element("optgroup", "label", groupModel.getLabel()); 036 037 writeDisabled(groupModel.isDisabled()); 038 writeAttributes(groupModel.getAttributes()); 039 } 040 041 public void endOptionGroup(OptionGroupModel groupModel) 042 { 043 writer.end(); // select 044 } 045 046 @SuppressWarnings("unchecked") 047 public void option(OptionModel optionModel) 048 { 049 Object optionValue = optionModel.getValue(); 050 051 String clientValue = encoder.toClient(optionValue); 052 053 writer.element("option", "value", clientValue); 054 055 if (isOptionSelected(optionModel, clientValue)) writer.attributes("selected", "selected"); 056 057 writeDisabled(optionModel.isDisabled()); 058 writeAttributes(optionModel.getAttributes()); 059 060 writer.write(optionModel.getLabel()); 061 062 writer.end(); 063 } 064 065 private void writeDisabled(boolean disabled) 066 { 067 if (disabled) writer.attributes("disabled", "disabled"); 068 } 069 070 private void writeAttributes(Map<String, String> attributes) 071 { 072 if (attributes == null) return; 073 074 for (Map.Entry<String, String> e : attributes.entrySet()) 075 writer.attributes(e.getKey(), e.getValue()); 076 } 077 078 /** 079 * If true, then the selected attribute will be written. This implementation always returns false. 080 */ 081 protected boolean isOptionSelected(OptionModel optionModel, String clientValue) 082 { 083 return false; 084 } 085 086}