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