src/pyams_utils/fanstatic.py
changeset 289 c8e21d7dd685
child 292 b338586588ad
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/pyams_utils/fanstatic.py	Wed Dec 05 12:45:56 2018 +0100
@@ -0,0 +1,107 @@
+#
+# Copyright (c) 2008-2015 Thierry Florac <tflorac AT ulthar.net>
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+
+__docformat__ = 'restructuredtext'
+
+from fanstatic import Resource
+from fanstatic.core import NeededResources, render_css, set_resource_file_existence_checking
+from pyramid.path import DottedNameResolver
+from zope.interface import Interface
+
+from pyams_utils.adapter import ContextRequestViewAdapter, adapter_config
+from pyams_utils.interfaces.tales import ITALESExtension
+
+
+def render_js(url, defer=False):
+    return '<script type="text/javascript" src="%s" %s></script>' % (url, 'defer' if defer else '')
+
+
+class ExternalResource(Resource):
+    """Fanstatic external resource"""
+
+    dependency_nr = 0
+
+    def __init__(self, library, path, defer=False, resource_type=None, **kwargs):
+        set_resource_file_existence_checking(False)
+        try:
+            if 'renderer' in kwargs:
+                del kwargs['renderer']
+            if 'bottom' not in kwargs:
+                kwargs['bottom'] = path.endswith('.js')
+            Resource.__init__(self, library, path, renderer=self.render, **kwargs)
+        finally:
+            set_resource_file_existence_checking(True)
+        self.defer = defer
+        if resource_type:
+            self.resource_type = resource_type
+        else:
+            self.resource_type = path.rsplit('.', 1)[1].lower()
+
+    def render(self, library_url):
+        if self.resource_type == 'css':
+            return render_css(self.relpath)
+        elif self.resource_type == 'js':
+            return render_js(self.relpath, self.defer)
+        else:
+            return ''
+
+
+def get_resource_path(resource, signature='--static--', versioning=True):
+    """Get path for given resource"""
+    res = NeededResources(publisher_signature=signature, versioning=versioning)
+    return '{0}/{1}'.format(res.library_url(resource.library), resource.relpath)
+
+
+@adapter_config(name='resource_path', context=(Interface, Interface, Interface), provides=ITALESExtension)
+class FanstaticTalesExtension(ContextRequestViewAdapter):
+    """tales:resource_path() TALES extension
+
+    This TALES extension generates an URL matching a given Fanstatic resource.
+    Resource is given as a string made of package name (in dotted form) followed by a colon and by the resource name.
+
+    For example::
+
+    .. code-block:: html
+
+        <div tal:attributes="data-ams-plugin-pyams_content-src extension:resource_path('pyams_content.zmi:pyams_content')" />
+    """
+
+    def render(self, resource):
+        library, resource_name = resource.split(':')
+        resolver = DottedNameResolver()
+        module = resolver.maybe_resolve(library)
+        resource = getattr(module, resource_name)
+        return get_resource_path(resource)
+
+
+@adapter_config(name='need_resource', context=(Interface, Interface, Interface), provides=ITALESExtension)
+class FanstaticNeededResourceTalesExtension(ContextRequestViewAdapter):
+    """tales:need_resource() TALES extension
+
+    This extension generates a call to Fanstatic resource.need() function to include given resource
+    into generated HTML code.
+    Resource is given as a string made of package name (in dotted form) followed by a colon and by the resource name.
+
+    For example::
+
+    .. code-block:: html
+
+        <tal:var define="tales:need_resource('pyams_content.zmi:pyams_content')" />
+    """
+
+    def render(self, resource):
+        library, resource_name = resource.split(':')
+        resolver = DottedNameResolver()
+        module = resolver.maybe_resolve(library)
+        resource = getattr(module, resource_name)
+        resource.need()
+        return ''