1# vi:ft=python 2from nevow import tags as T, rend, loaders, athena, url 3from formless import annotate, webform 4from twisted.python import util 5 6animals = {u'elf' : u'Pointy ears. Bad attitude regarding trees.', 7 u'chipmunk': u'Cute. Fuzzy. Sings horribly.', 8 u'chupacabra': u'It sucks goats.', 9 u'ninja': u'Stealthy and invisible, and technically an animal.', 10 } 11 12 13class TypeAheadPage(athena.LivePage): 14 _tmpl = util.sibpath(__file__, "typeahead.html") 15 docFactory = loaders.xmlfile(_tmpl) 16 def render_typehereField(self, ctx, data): 17 frag = TypeAheadFieldFragment() 18 frag.page = self 19 return frag 20 21class TypeAheadFieldFragment(athena.LiveFragment): 22 docFactory = loaders.stan( 23 T.span(render=T.directive('liveFragment'))[ '\n', 24 T.input(type="text", _class="typehere"), '\n', 25 T.h3(_class="description"), 26 ]) 27 28 def loadDescription(self, typed): 29 if typed == u'': 30 return None, u'--' 31 matches = [] 32 for key in animals: 33 if key.startswith(typed): 34 matches.append(key) 35 if len(matches) == 1: 36 return matches[0], animals[matches[0]] 37 elif len(matches) > 1: 38 return None, u"(Multiple found)" 39 else: 40 return None, u'--' 41 athena.expose(loadDescription) 42 43class DataEntry(rend.Page): 44 """Add Animal""" 45 addSlash = 1 46 47 docFactory = loaders.stan( 48 T.html[T.body[T.h1[ 49 "First, a Setup Form."], 50 T.h2["Enter some animals as data. Click 'Done' to test looking up these animals."], 51 T.h3["The neat stuff happens when you hit 'Done'."], 52 webform.renderForms(), 53 T.ol(data=T.directive("animals"), render=rend.sequence)[ 54 T.li(pattern="item", render=T.directive("string")), 55 ], 56 T.h1[T.a(href=url.here.child('typeahead'))["Done"]], 57 ] 58 ] 59 ) 60 def bind_animals(self, ctx, ): 61 """Add Animal""" 62 return annotate.MethodBinding( 63 'animals', 64 annotate.Method(arguments= 65 [annotate.Argument('animal', annotate.String()), 66 annotate.Argument('description', annotate.Text())]), 67 action="Add Animal", 68 ) 69 70 def animals(self, animal, description): 71 """Add Animal""" 72 if not (animal and description): 73 return 74 animals[animal.decode('utf-8')] = description.decode('utf-8') 75 return url.here 76 77 def data_animals(self, ctx, data): 78 return animals.keys() 79 80 def child_typeahead(self, ctx): 81 return TypeAheadPage(None, None) 82 83