01: // Copyright 2007 The Apache Software Foundation
02: //
03: // Licensed under the Apache License, Version 2.0 (the "License");
04: // you may not use this file except in compliance with the License.
05: // You may obtain a copy of the License at
06: //
07: // http://www.apache.org/licenses/LICENSE-2.0
08: //
09: // Unless required by applicable law or agreed to in writing, software
10: // distributed under the License is distributed on an "AS IS" BASIS,
11: // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12: // See the License for the specific language governing permissions and
13: // limitations under the License.
14:
15: package org.apache.tapestry.internal.services;
16:
17: import static org.apache.tapestry.ioc.internal.util.CollectionFactory.newList;
18:
19: import java.util.List;
20:
21: import org.apache.tapestry.dom.Document;
22: import org.apache.tapestry.dom.Element;
23: import org.apache.tapestry.ioc.internal.util.InternalUtils;
24:
25: public class DocumentScriptBuilderImpl implements DocumentScriptBuilder {
26: private final List<String> _scripts = newList();
27:
28: private final StringBuilder _scriptBlock = new StringBuilder();
29:
30: public void addScriptLink(String scriptURL) {
31: if (_scripts.contains(scriptURL))
32: return;
33:
34: _scripts.add(scriptURL);
35: }
36:
37: public void addScript(String script) {
38: if (InternalUtils.isBlank(script))
39: return;
40:
41: _scriptBlock.append(script);
42: _scriptBlock.append("\n");
43: }
44:
45: public void updateDocument(Document document) {
46: Element body = document.find("html/body");
47:
48: if (body == null)
49: return;
50:
51: for (int i = 0; i < _scripts.size(); i++) {
52: String scriptURL = _scripts.get(i);
53:
54: body.elementAt(i, "script", "src", scriptURL, "type",
55: "text/javascript");
56: }
57:
58: if (_scriptBlock.length() > 0) {
59: Element e = body.element("script", "type",
60: "text/javascript", "language", "javascript");
61: e.raw("\n<!--\n");
62:
63: // This assumes that Prototype is available.
64:
65: e.text("Event.observe(window, \"load\", function() {\n");
66:
67: e.text(_scriptBlock.toString());
68:
69: e.text("});\n");
70:
71: e.raw("// -->\n");
72: }
73:
74: }
75:
76: }
|