summaryrefslogtreecommitdiffstats
path: root/src/collective/contact/widget/widgets.py
blob: a58842c5badc7ef7f54b31a258804effd3e568e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
from z3c.form.interfaces import IFieldWidget
from z3c.form.widget import FieldWidget
from zope.component import getUtility
from zope.i18n import translate
from zope.interface import implementer, implements, Interface
from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile
from five import grok
from Products.CMFPlone.utils import base_hasattr

from plone.app.layout.viewlets.interfaces import IBelowContent
from plone.app.layout.viewlets.interfaces import IHtmlHeadLinks
from plone.formwidget.autocomplete.widget import (
    AutocompleteMultiSelectionWidget,
    AutocompleteSelectionWidget)
from plone.formwidget.autocomplete.widget import AutocompleteSearch as BaseAutocompleteSearch

from . import _
from .interfaces import (
    IContactAutocompleteWidget,
    IContactAutocompleteSelectionWidget,
    IContactAutocompleteMultiSelectionWidget,
    IContactContent,
    IContactWidgetSettings,
    )

class PatchLoadInsideOverlay(grok.Viewlet):
    grok.context(Interface)
    grok.viewletmanager(IHtmlHeadLinks)

    def render(self):
        return """<script type="text/javascript">
var ccw = {};
$(document).ready(function() {
  $(document).bind('formOverlayLoadSuccess', function(e, req, myform, api, pb, ajax_parent) {
    ajax_parent.find('div').slice(0, 1).prepend(ajax_parent.find('.portalMessage').detach());
  });
  $(document).bind('loadInsideOverlay', function(e, el, responseText, errorText, api) {
    var el = $(el);
    var o = el.closest('.overlay-ajax');
    var pbo = o.data('pbo');
    var overlay_counter = parseInt(pbo.nt.substring(3, pbo.nt.length));
    o.css({zIndex: 9998+overlay_counter});
  });
  ccw.fill_autocomplete = function (el, pbo, noform) {
    var objpath = el.find('input[name=objpath]');
    if (objpath.length) {
        data = objpath.val().split('|');
        var input_box = pbo.source.siblings('div').find('.querySelectSearch input');
        formwidget_autocomplete_new_value(input_box, data[0], data[1]);
        input_box.flushCache();
        // trigger change event on newly added input element
        var input = input_box.parents('.querySelectSearch').parent('div').siblings('.autocompleteInputWidget').find('input').last();
        var url = data[3];
        ccw.add_contact_preview(input, url);
        input.trigger('change');
    }
    return noform;
  };

  var pendingCall = {timeStamp: null, procID: null};
  ccw.add_contact_preview = function (input, url) {
    if (url) {
        input.siblings('.label')
            .wrapInner('<a href="'+url+'" target="_new" class="link-tooltip">');
    }
  };

  $(document).delegate('.link-tooltip', 'mouseleave', function() {
    if (pendingCall.procID) {
      clearTimeout(pendingCall.procID);
      pendingCall.procID = null;
    }
  });
  $(document).delegate('.link-tooltip', 'mouseenter', function() {
    var trigger = $(this);
    // don't open tooltip in tooltip
    if (trigger.closest('.tooltip').length) {
        return;
    }
    if (!trigger.data('tooltip')) {
      if (pendingCall.procID) {
        clearTimeout(pendingCall.procID);
      }
      var timeStamp = new Date();
      var tooltipCall = function() {
          var tip = $('<div class="tooltip pb-ajax" style="display:none">%s</div>')
                .insertAfter(trigger);
          trigger.tooltip({relative: true, position: "center right"});
          var tooltip = trigger.tooltip();
          tooltip.show();
          var url = trigger.attr('href');
          $.get(url, {ajax_load: new Date().getTime()}, function(data) {
            tooltip.hide();
            tooltip.getTip().html($('<div />').append(
                    data.replace(/<script(.|\s)*?\/script>/gi, ""))
                .find(common_content_filter));
            if (pendingCall.timeStamp == timeStamp) {
                tooltip.show();
            }
            pendingCall.procID = null;
          });
      }
      pendingCall = {timeStamp: timeStamp,
                     procID: setTimeout(tooltipCall, 500)};
    }
  });
});
</script>
<style type="text/css">
.tooltip {
  overflow: hidden;
}
.tooltip, #calroot {
  z-index: 99999;
}
</style>
""" % translate(_(u"please wait"), context=self.request)


class TermViewlet(grok.Viewlet):
    grok.name('term-contact')
    grok.context(IContactContent)
    grok.viewletmanager(IBelowContent)

    @property
    def token(self):
        return '/'.join(self.context.getPhysicalPath())

    @property
    def title(self):
        if base_hasattr(self.context, 'get_full_title'):
            title = self.context.get_full_title()
        else:
            title = self.context.Title()
        title = title.decode('utf-8')
        return title

    @property
    def portal_type(self):
        return self.context.portal_type

    @property
    def url(self):
        return self.context.absolute_url()

    def render(self):
        return u"""<input type="hidden" name="objpath" value="%s" />""" % (
                    '|'.join([self.token, self.title, self.portal_type, self.url]))

OVERLAY_TEMPLATE = """
$('#%(id)s-autocomplete').find('.%(klass)s'
    ).prepOverlay({
  subtype: 'ajax',
  filter: common_content_filter+',#viewlet-below-content>*',
  formselector: '%(formselector)s',
  closeselector: '%(closeselector)s',
  noform: function(el, pbo) {return ccw.fill_autocomplete(el, pbo, 'close');},
  config: {
      closeOnClick: %(closeOnClick)s,
      closeOnEsc: %(closeOnClick)s
  }
});
"""

class ContactBaseWidget(object):
    implements(IContactAutocompleteWidget)
    noValueLabel = _(u'(nothing)')
    autoFill = False
    close_on_click = True
    display_template = ViewPageTemplateFile('templates/contact_display.pt')
    input_template = ViewPageTemplateFile('templates/contact_input.pt')
    js_callback_template = """
function (event, data, formatted) {
    (function($) {
        var input_box = $(event.target);
        formwidget_autocomplete_new_value(input_box,data[0],data[1]);
        // trigger change event on newly added input element
        var input = input_box.parents('.querySelectSearch').parent('div').siblings('.autocompleteInputWidget').find('input').last();
        var url = data[3];
        ccw.add_contact_preview(input, url);
        input.trigger('change');
    }(jQuery));
}
"""

    def tokenToUrl(self, token):
        if token == "--NOVALUE--":
            return ""
        return self.bound_source.tokenToUrl(token)

    def render(self):
        settings = getUtility(IContactWidgetSettings)
        attributes = settings.add_contact_infos(self)
        for key, value in attributes.items():
            setattr(self, key, value)
        return super(ContactBaseWidget, self).render()

    def js_extra(self):
        content = ""
        include_default = False
        for action in self.actions:
            formselector = action.get('formselector', None)
            if formselector is None:
                include_default = True
            else:
                closeselector = action.get('closeselector',
                        '[name="form.buttons.cancel"]')
                content += OVERLAY_TEMPLATE % dict(
                        id=self.id,
                        klass=action['klass'],
                        formselector=formselector,
                        closeselector=closeselector,
                        closeOnClick=self.close_on_click and 'true' or 'false')

        if include_default:
            content += OVERLAY_TEMPLATE % dict(
                    id=self.id,
                    klass='addnew',
                    formselector='#form',
                    closeselector='[name="form.buttons.cancel"]',
                    closeOnClick=self.close_on_click and 'true' or 'false')

        return content

class ContactAutocompleteSelectionWidget(ContactBaseWidget, AutocompleteSelectionWidget):
    implements(IContactAutocompleteSelectionWidget)


class ContactAutocompleteMultiSelectionWidget(ContactBaseWidget, AutocompleteMultiSelectionWidget):
    implements(IContactAutocompleteMultiSelectionWidget)


@implementer(IFieldWidget)
def ContactAutocompleteFieldWidget(field, request):
    widget = ContactAutocompleteSelectionWidget(request)
    return FieldWidget(field, widget)


@implementer(IFieldWidget)
def ContactAutocompleteMultiFieldWidget(field, request):
    widget = ContactAutocompleteMultiSelectionWidget(request)
    return FieldWidget(field, widget)


class AutocompleteSearch(BaseAutocompleteSearch):
    def __call__(self):

        # We want to check that the user was indeed allowed to access the
        # form for this widget. We can only this now, since security isn't
        # applied yet during traversal.
        self.validate_access()

        query = self.request.get('q', None)
        path = self.request.get('path', None)
        if not query:
            if path is None:
                return ''
            else:
                query = ''

        # Update the widget before accessing the source.
        # The source was only bound without security applied
        # during traversal before.
        self.context.update()
        source = self.context.bound_source

        if path is not None:
            query = "path:%s %s" % (source.tokenToPath(path), query)

        if query:
            terms = set(source.search(query))
        else:
            terms = set()

        return u'\n'.join([u"|".join((t.token, t.title or t.token, t.portal_type, t.url, t.extra))
                            for t in sorted(terms, key=lambda t: t.title)])