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.modules;
014
015import org.apache.tapestry5.BooleanHook;
016import org.apache.tapestry5.MarkupWriter;
017import org.apache.tapestry5.SymbolConstants;
018import org.apache.tapestry5.annotations.Path;
019import org.apache.tapestry5.internal.InternalConstants;
020import org.apache.tapestry5.internal.services.DocumentLinker;
021import org.apache.tapestry5.internal.services.ResourceStreamer;
022import org.apache.tapestry5.internal.services.ajax.JavaScriptSupportImpl;
023import org.apache.tapestry5.internal.services.assets.ResourceChangeTracker;
024import org.apache.tapestry5.internal.services.javascript.*;
025import org.apache.tapestry5.internal.util.MessageCatalogResource;
026import org.apache.tapestry5.ioc.*;
027import org.apache.tapestry5.ioc.annotations.Contribute;
028import org.apache.tapestry5.ioc.annotations.Primary;
029import org.apache.tapestry5.ioc.annotations.Symbol;
030import org.apache.tapestry5.ioc.services.FactoryDefaults;
031import org.apache.tapestry5.ioc.services.SymbolProvider;
032import org.apache.tapestry5.ioc.util.IdAllocator;
033import org.apache.tapestry5.json.JSONObject;
034import org.apache.tapestry5.services.*;
035import org.apache.tapestry5.services.compatibility.Compatibility;
036import org.apache.tapestry5.services.compatibility.Trait;
037import org.apache.tapestry5.services.javascript.*;
038import org.apache.tapestry5.services.messages.ComponentMessagesSource;
039
040import java.util.Locale;
041
042/**
043 * Defines the services related to JavaScript and {@link org.apache.tapestry5.services.javascript.JavaScriptStack}s.
044 *
045 * @since 5.4
046 */
047public class JavaScriptModule
048{
049    private final static String ROOT = "${tapestry.asset.root}";
050
051    private final Environment environment;
052
053    private final EnvironmentalShadowBuilder environmentalBuilder;
054
055    public JavaScriptModule(Environment environment, EnvironmentalShadowBuilder environmentalBuilder)
056    {
057        this.environment = environment;
058        this.environmentalBuilder = environmentalBuilder;
059    }
060
061    public static void bind(ServiceBinder binder)
062    {
063        binder.bind(ModuleManager.class, ModuleManagerImpl.class);
064        binder.bind(JavaScriptStackSource.class, JavaScriptStackSourceImpl.class);
065        binder.bind(JavaScriptStack.class, ExtensibleJavaScriptStack.class).withMarker(Core.class).withId("CoreJavaScriptStack");
066        binder.bind(JavaScriptStack.class, ExtensibleJavaScriptStack.class).withMarker(Internal.class).withId("InternalJavaScriptStack");
067    }
068
069    /**
070     * Contributes the "core" and "internal" {@link JavaScriptStack}s
071     *
072     * @since 5.2.0
073     */
074    @Contribute(JavaScriptStackSource.class)
075    public static void provideBuiltinJavaScriptStacks(MappedConfiguration<String, JavaScriptStack> configuration,
076                                                      @Core JavaScriptStack coreStack,
077                                                      @Internal JavaScriptStack internalStack)
078    {
079        configuration.add(InternalConstants.CORE_STACK_NAME, coreStack);
080        configuration.add("internal", internalStack);
081    }
082
083    // These are automatically bundles with the core JavaScript stack; some applications may want to add a few
084    // additional ones, such as t5/core/zone.
085    private static final String[] bundledModules = new String[]{
086            "alert", "ajax", "bootstrap", "console", "dom", "events", "exception-frame", "fields", "forms",
087            "pageinit", "messages", "utils", "validation"
088    };
089
090    /**
091     * The core JavaScriptStack has a number of entries:
092     * <dl>
093     * <dt>requirejs</dt> <dd>The RequireJS AMD JavaScript library</dd>
094     * <dt>scriptaculous.js, effects.js</dt> <dd>Optional JavaScript libraries in compatibility mode (see {@link Trait#SCRIPTACULOUS})</dd>
095     * <dt>t53-compatibility.js</dt> <dd>Optional JavaScript library (see {@link Trait#INITIALIZERS})</dd>
096     * <dt>underscore-library, underscore-module</dt>
097     * <dt>The Underscore JavaScript library, and the shim that allows underscore to be injected</dt>
098     * <dt>t5/core/init</dt> <dd>Optional module related to t53-compatibility.js</dd>
099     * <dt>jquery-library</dt> <dd>The jQuery library</dd>
100     * <dt>jquery-noconflict</dt> <dd>Switches jQuery to no-conflict mode (only present when the infrastructure is "prototype").</dd>
101     * <dt>jquery</dt> <dd>A module shim that allows jQuery to be injected (and also switches jQuery to no-conflict mode)</dd>
102     * <dt>bootstrap.css, tapestry.css, exception-frame.css, tapestry-console.css, tree.css</dt>
103     * <dd>CSS files</dd>
104     * <dt>t5/core/[...]</dt>
105     * <dd>Additional JavaScript modules</dd>
106     * <dt>jquery</dt>
107     * <dd>Added if the infrastructure provider is "jquery".</dd>
108     * </dl>
109     * <p/>
110     * User modules may replace or extend this list.
111     */
112    @Contribute(JavaScriptStack.class)
113    @Core
114    public static void setupCoreJavaScriptStack(OrderedConfiguration<StackExtension> configuration,
115                                                Compatibility compatibility,
116                                                @Symbol(SymbolConstants.JAVASCRIPT_INFRASTRUCTURE_PROVIDER)
117                                                String provider)
118    {
119        configuration.add("requirejs", StackExtension.library(ROOT + "/require.js"));
120        configuration.add("underscore-library", StackExtension.library(ROOT + "/underscore-1.5.2.js"));
121
122        if (provider.equals("prototype"))
123        {
124            final String SCRIPTY = "${tapestry.scriptaculous}";
125
126            add(configuration, StackExtensionType.LIBRARY, SCRIPTY + "/prototype.js");
127
128            if (compatibility.enabled(Trait.SCRIPTACULOUS))
129            {
130                add(configuration, StackExtensionType.LIBRARY,
131                        SCRIPTY + "/scriptaculous.js",
132                        SCRIPTY + "/effects.js");
133            }
134        }
135
136        if (compatibility.enabled(Trait.INITIALIZERS))
137        {
138            add(configuration, StackExtensionType.LIBRARY, ROOT + "/t53-compatibility.js");
139            configuration.add("t5/core/init", new StackExtension(StackExtensionType.MODULE, "t5/core/init"));
140        }
141
142        configuration.add("jquery-library", StackExtension.library(ROOT + "/jquery.js"));
143
144        if (provider.equals("prototype"))
145        {
146            configuration.add("jquery-noconflict", StackExtension.library(ROOT + "/jquery-noconflict.js"));
147        }
148
149        add(configuration, StackExtensionType.MODULE, "jquery");
150
151        addCoreStylesheets(configuration, "${" + SymbolConstants.BOOTSTRAP_ROOT + "}/css/bootstrap.css");
152
153        for (String name : bundledModules)
154        {
155            String full = "t5/core/" + name;
156            configuration.add(full, StackExtension.module(full));
157        }
158
159        configuration.add("underscore-module", StackExtension.module("underscore"));
160    }
161
162    @Contribute(JavaScriptStack.class)
163    @Internal
164    public static void setupInternalJavaScriptStack(OrderedConfiguration<StackExtension> configuration)
165    {
166
167        // For the internal stack, ignore the configuration and just use the Bootstrap CSS shipped with the
168        // framework. This is part of a hack to make internal pages (such as ExceptionReport and T5Dashboard)
169        // render correctly even when the Bootstrap CSS has been replaced by the application.
170
171        addCoreStylesheets(configuration, ROOT + "/bootstrap/css/bootstrap.css");
172    }
173
174    private static void addCoreStylesheets(OrderedConfiguration<StackExtension> configuration, String bootstrapPath)
175    {
176        add(configuration, StackExtensionType.STYLESHEET,
177                bootstrapPath,
178
179                ROOT + "/tapestry.css",
180
181                ROOT + "/exception-frame.css",
182
183                ROOT + "/tapestry-console.css",
184
185                ROOT + "/tree.css");
186    }
187
188    private static void add(OrderedConfiguration<StackExtension> configuration, StackExtensionType type, String... paths)
189    {
190        for (String path : paths)
191        {
192            int slashx = path.lastIndexOf('/');
193            String id = path.substring(slashx + 1);
194
195            configuration.add(id, new StackExtension(type, path));
196        }
197    }
198
199
200    /**
201     * Builds a proxy to the current {@link JavaScriptSupport} inside this thread's {@link org.apache.tapestry5.services.Environment}.
202     *
203     * @since 5.2.0
204     */
205    public JavaScriptSupport buildJavaScriptSupport()
206    {
207        return environmentalBuilder.build(JavaScriptSupport.class);
208    }
209
210    @Contribute(Dispatcher.class)
211    @Primary
212    public static void setupModuleDispatchers(OrderedConfiguration<Dispatcher> configuration,
213                                              ModuleManager moduleManager,
214                                              OperationTracker tracker,
215                                              ResourceStreamer resourceStreamer,
216                                              PathConstructor pathConstructor,
217                                              @Symbol(SymbolConstants.MODULE_PATH_PREFIX)
218                                              String modulePathPrefix)
219    {
220        configuration.add("Modules",
221                new ModuleDispatcher(moduleManager, resourceStreamer, tracker, pathConstructor, modulePathPrefix, false),
222                "after:Asset", "before:ComponentEvent");
223
224        configuration.add("ComnpressedModules",
225                new ModuleDispatcher(moduleManager, resourceStreamer, tracker, pathConstructor, modulePathPrefix, true),
226                "after:Modules", "before:ComponentEvent");
227    }
228
229    /**
230     * Adds page render filters, each of which provides an {@link org.apache.tapestry5.annotations.Environmental}
231     * service. Filters
232     * often provide {@link org.apache.tapestry5.annotations.Environmental} services needed by
233     * components as they render.
234     * <dl>
235     * <dt>JavascriptSupport</dt>
236     * <dd>Provides {@link JavaScriptSupport}</dd>
237     * </dl>
238     */
239    @Contribute(MarkupRenderer.class)
240    public void exposeJavaScriptSupportForFullPageRenders(OrderedConfiguration<MarkupRendererFilter> configuration,
241                                                          final JavaScriptStackSource javascriptStackSource,
242                                                          final JavaScriptStackPathConstructor javascriptStackPathConstructor,
243                                                          final Request request)
244    {
245
246        final BooleanHook suppressCoreStylesheetsHook = createSuppressCoreStylesheetHook(request);
247
248        MarkupRendererFilter javaScriptSupport = new MarkupRendererFilter()
249        {
250            public void renderMarkup(MarkupWriter writer, MarkupRenderer renderer)
251            {
252                DocumentLinker linker = environment.peekRequired(DocumentLinker.class);
253
254                JavaScriptSupportImpl support = new JavaScriptSupportImpl(linker, javascriptStackSource,
255                        javascriptStackPathConstructor, suppressCoreStylesheetsHook);
256
257                environment.push(JavaScriptSupport.class, support);
258
259                renderer.renderMarkup(writer);
260
261                environment.pop(JavaScriptSupport.class);
262
263                support.commit();
264            }
265        };
266
267        configuration.add("JavaScriptSupport", javaScriptSupport, "after:DocumentLinker");
268    }
269
270    /**
271     * Contributes {@link PartialMarkupRendererFilter}s used when rendering a
272     * partial Ajax response.
273     * <dl>
274     * <dt>JavaScriptSupport
275     * <dd>Provides {@link JavaScriptSupport}</dd>
276     * </dl>
277     */
278    @Contribute(PartialMarkupRenderer.class)
279    public void exposeJavaScriptSupportForPartialPageRender(OrderedConfiguration<PartialMarkupRendererFilter> configuration,
280                                                            final JavaScriptStackSource javascriptStackSource,
281
282                                                            final JavaScriptStackPathConstructor javascriptStackPathConstructor,
283
284                                                            final Request request)
285    {
286        final BooleanHook suppressCoreStylesheetsHook = createSuppressCoreStylesheetHook(request);
287
288        PartialMarkupRendererFilter javascriptSupport = new PartialMarkupRendererFilter()
289        {
290            public void renderMarkup(MarkupWriter writer, JSONObject reply, PartialMarkupRenderer renderer)
291            {
292                IdAllocator idAllocator;
293
294                if (request.getParameter(InternalConstants.SUPPRESS_NAMESPACED_IDS) == null)
295                {
296                    String uid = Long.toHexString(System.nanoTime());
297
298                    String namespace = "_" + uid;
299
300                    idAllocator = new IdAllocator(namespace);
301                } else
302                {
303                    // When suppressed, work just like normal rendering.
304                    idAllocator = new IdAllocator();
305                }
306
307                DocumentLinker linker = environment.peekRequired(DocumentLinker.class);
308
309                JavaScriptSupportImpl support = new JavaScriptSupportImpl(linker, javascriptStackSource,
310                        javascriptStackPathConstructor, idAllocator, true, suppressCoreStylesheetsHook);
311
312                environment.push(JavaScriptSupport.class, support);
313
314                renderer.renderMarkup(writer, reply);
315
316                environment.pop(JavaScriptSupport.class);
317
318                support.commit();
319            }
320        };
321
322        configuration.add("JavaScriptSupport", javascriptSupport, "after:DocumentLinker");
323    }
324
325    private BooleanHook createSuppressCoreStylesheetHook(final Request request)
326    {
327        return new BooleanHook()
328        {
329            @Override
330            public boolean checkHook()
331            {
332                return request.getAttribute(InternalConstants.SUPPRESS_CORE_STYLESHEETS) != null;
333            }
334        };
335    }
336
337
338    @Contribute(ModuleManager.class)
339    public static void setupBaseModules(MappedConfiguration<String, Object> configuration,
340                                        @Path("${tapestry.asset.root}/underscore-shim.js")
341                                        Resource underscoreShim,
342
343                                        @Path("${tapestry.asset.root}/jquery-shim.js")
344                                        Resource jqueryShim,
345
346                                        @Path("${tapestry.asset.root}/typeahead-0.9.3.js")
347                                        Resource typeahead,
348
349                                        @Path("${tapestry.asset.root}/moment-2.8.3.js")
350                                        Resource moment,
351
352                                        @Path("${" + SymbolConstants.BOOTSTRAP_ROOT + "}/js/transition.js")
353                                        Resource transition)
354    {
355        // The underscore shim module allows Underscore to be injected
356        configuration.add("underscore", new JavaScriptModuleConfiguration(underscoreShim));
357        configuration.add("jquery", new JavaScriptModuleConfiguration(jqueryShim));
358
359        configuration.add("bootstrap/transition", new JavaScriptModuleConfiguration(transition).dependsOn("jquery"));
360
361        for (String name : new String[]{"affix", "alert", "button", "carousel", "collapse", "dropdown", "modal",
362                "scrollspy", "tab", "tooltip"})
363        {
364            Resource lib = transition.forFile(name + ".js");
365
366            configuration.add("bootstrap/" + name, new JavaScriptModuleConfiguration(lib).dependsOn("bootstrap/transition"));
367        }
368
369        Resource popover = transition.forFile("popover.js");
370
371        configuration.add("bootstrap/popover", new JavaScriptModuleConfiguration(popover).dependsOn("bootstrap/tooltip"));
372
373        configuration.add("t5/core/typeahead", new JavaScriptModuleConfiguration(typeahead).dependsOn("jquery"));
374
375        configuration.add("moment", new JavaScriptModuleConfiguration(moment));
376
377    }
378
379    @Contribute(SymbolProvider.class)
380    @FactoryDefaults
381    public static void setupFactoryDefaults(MappedConfiguration<String, Object> configuration)
382    {
383        configuration.add(SymbolConstants.JAVASCRIPT_INFRASTRUCTURE_PROVIDER, "prototype");
384        configuration.add(SymbolConstants.MODULE_PATH_PREFIX, "modules");
385    }
386
387    @Contribute(ModuleManager.class)
388    public static void setupFoundationFramework(MappedConfiguration<String, Object> configuration,
389                                                @Symbol(SymbolConstants.JAVASCRIPT_INFRASTRUCTURE_PROVIDER)
390                                                String provider,
391                                                @Path("classpath:org/apache/tapestry5/t5-core-dom-prototype.js")
392                                                Resource domPrototype,
393                                                @Path("classpath:org/apache/tapestry5/t5-core-dom-jquery.js")
394                                                Resource domJQuery)
395    {
396        if (provider.equals("prototype"))
397        {
398            configuration.add("t5/core/dom", new JavaScriptModuleConfiguration(domPrototype));
399        }
400
401        if (provider.equals("jquery"))
402        {
403            configuration.add("t5/core/dom", new JavaScriptModuleConfiguration(domJQuery));
404        }
405
406        // If someone wants to support a different infrastructure, they should set the provider symbol to some other value
407        // and contribute their own version of the t5/core/dom module.
408    }
409
410    @Contribute(ModuleManager.class)
411    public static void setupApplicationCatalogModules(MappedConfiguration<String, Object> configuration,
412                                                      LocalizationSetter localizationSetter,
413                                                      ComponentMessagesSource messagesSource,
414                                                      ResourceChangeTracker resourceChangeTracker,
415                                                      @Symbol(SymbolConstants.COMPACT_JSON) boolean compactJSON)
416    {
417        for (Locale locale : localizationSetter.getSupportedLocales())
418        {
419            MessageCatalogResource resource = new MessageCatalogResource(locale, messagesSource, resourceChangeTracker, compactJSON);
420
421            configuration.add("t5/core/messages/" + locale.toString(), new JavaScriptModuleConfiguration(resource));
422        }
423    }
424
425    /**
426     * Contributes 'ConfigureHTMLElement', which writes the attributes into the HTML tag to describe locale, etc.
427     * Contributes 'AddBrowserCompatibilityStyles', which writes {@code <style/>} elements into the {@code <head/>}
428     * element that modifies the page loading mask to work on IE 8 and IE 9.
429     */
430    @Contribute(MarkupRenderer.class)
431    public static void prepareHTMLPageOnRender(OrderedConfiguration<MarkupRendererFilter> configuration)
432    {
433        configuration.addInstance("ConfigureHTMLElement", ConfigureHTMLElementFilter.class);
434        configuration.add("AddBrowserCompatibilityStyles", new AddBrowserCompatibilityStyles());
435    }
436
437}