PageRenderTime 149ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/addons/TemplatePanel.py

http://pyjamas.googlecode.com/
Python | 330 lines | 291 code | 23 blank | 16 comment | 16 complexity | d45348eba7b55a81df85c6c6f3d9fff3 MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0
  1. from __pyjamas__ import unescape
  2. from RichTextEditor import RichTextEditor
  3. import Window
  4. from __pyjamas__ import encodeURIComponent
  5. from EventDelegate import EventDelegate
  6. from ui import Label
  7. from pyjslib import List
  8. from ui import ComplexPanel
  9. from __pyjamas__ import console
  10. from HTTPRequest import HTTPRequest
  11. from ui import HTML, SimplePanel
  12. import DOM
  13. class TemplateLoader:
  14. def __init__(self, panel, url):
  15. self.panel = panel
  16. def onCompletion(self, text):
  17. self.panel.setTemplateText(text)
  18. def onError(self, text, code):
  19. self.panel.onError(text, code)
  20. def onTimeout(self, text):
  21. self.panel.onTimeout(text)
  22. class ContentSaveHandler:
  23. def __init__(self, templatePanel):
  24. self.templatePanel = templatePanel
  25. def onCompletion(self):
  26. self.templatePanel.onSaveComplete()
  27. def onError(self, error):
  28. Window.alert("Save failed: "+error)
  29. class PendingAttachOrInsert:
  30. def __init__(self, name, widget):
  31. self.name = name
  32. self.widget = widget
  33. class TemplatePanel(ComplexPanel):
  34. """
  35. Panel which allows you to attach or insert widgets into
  36. a pre-defined template.
  37. We don't do any caching of our own, since the browser will
  38. do caching for us, and probably more efficiently.
  39. """
  40. templateRoot = ""
  41. """Set staticRoot to change the base path of all the templates that are loaded; templateRoot should have a trailing slash"""
  42. def __init__(self, templateName, allowEdit=False):
  43. ComplexPanel.__init__(self)
  44. self.loaded = False # Set after widgets are attached
  45. self.widgetsAttached = False
  46. self.id = None
  47. self.templateName = None
  48. self.title = None
  49. self.elementsById = {}
  50. self.metaTags = {}
  51. self.body = None
  52. self.links = []
  53. self.forms = []
  54. self.metaTagList = []
  55. self.loadListeners = []
  56. self.toAttach = []
  57. self.toInsert = []
  58. self.setElement(DOM.createDiv())
  59. self.editor = None
  60. self.allowEdit = allowEdit
  61. if templateName:
  62. self.loadTemplate(templateName)
  63. def getTemplatePath(self, templateName):
  64. return self.templateRoot+'tpl/'+templateName+'.html'
  65. def loadTemplate(self, templateName):
  66. self.templateName = templateName
  67. self.id = templateName + str(hash(self))
  68. self.httpReq = HTTPRequest()
  69. self.httpReq.asyncGet(self.getTemplatePath(templateName), TemplateLoader(self))
  70. def getCurrentTemplate(self):
  71. """Return the template that is currently loaded, or is loading"""
  72. return self.templateName
  73. def isLoaded(self):
  74. """Return True if the template is finished loading"""
  75. return self.loaded
  76. def areWidgetsAttached(self):
  77. """Return True if the template is loaded and attachWidgets() has been called"""
  78. return self.widgetsAttached
  79. def setTemplateText(self, text):
  80. """
  81. Set the template text; if the template is not HTML, a subclass could override this
  82. to pre-process the text into HTML before passing it to the default implementation.
  83. """
  84. if self.allowEdit:
  85. self.originalText = text
  86. # If we have children, remove them all first since we are trashing their DOM
  87. for child in List(self.children):
  88. self.remove(child)
  89. DOM.setInnerHTML(self.getElement(), text)
  90. self.elementsById = {}
  91. self.links = []
  92. self.metaTags = {}
  93. self.forms = []
  94. self.metaTagList = []
  95. # Make the ids unique and store a pointer to each named element
  96. for node in DOM.walkChildren(self.getElement()):
  97. #console.log("Passing node with name %s", node.nodeName)
  98. if node.nodeName == "META":
  99. name = node.getAttribute("name")
  100. content = node.getAttribute("content")
  101. console.log("Found meta %o name %s content %s", node, name, content)
  102. self.metaTags[name] = content
  103. self.metaTagList.append(node)
  104. elif node.nodeName == "BODY":
  105. self.body = node
  106. elif node.nodeName == "TITLE":
  107. self.title = DOM.getInnerText(node)
  108. elif node.nodeName == "FORM":
  109. self.forms.append(node)
  110. nodeId = DOM.getAttribute(node, "id")
  111. if nodeId:
  112. self.elementsById[nodeId] = node
  113. DOM.setAttribute(node, "id", self.id+":"+node.id)
  114. nodeHref = DOM.getAttribute(node, "href")
  115. if nodeHref:
  116. self.links.append(node)
  117. self.loaded = True
  118. if self.attached:
  119. self.attachWidgets()
  120. self.widgetsAttached = True
  121. if self.allowEdit:
  122. self.editor = None
  123. self.editButton = Label("edit "+unescape(self.templateName))
  124. self.editButton.addStyleName("link")
  125. self.editButton.addStyleName("ContentPanelEditLink")
  126. self.editButton.addClickListener(EventDelegate("onClick", self, self.onEditContentClick))
  127. ComplexPanel.insert(self, self.editButton, self.getElement(), len(self.children))
  128. self.notifyLoadListeners()
  129. def onError(self, html, statusCode):
  130. if statusCode == 404 and self.allowEdit:
  131. self.editor = None
  132. self.originalText = ""
  133. DOM.setInnerHTML(self.getElement(), '')
  134. self.editButton = Label("create "+unescape(self.templateName))
  135. self.editButton.addStyleName("link")
  136. self.editButton.addStyleName("ContentPanelEditLink")
  137. self.editButton.addClickListener(EventDelegate("onClick", self, self.onEditContentClick))
  138. ComplexPanel.insert(self, self.editButton, self.getElement(), len(self.children))
  139. return
  140. # Show the page we got in an iframe, which will hopefully show the error better than we can.
  141. # DOM.setInnerHTML(self.getElement(), '<iframe src="'+self.getTemplatePath(self.templateName)+'"/>')
  142. def onTimeout(self, text):
  143. self.onError("Page loading timed out: "+text)
  144. def getElementsById(self):
  145. """Return a dict mapping an id to an element with that id inside the template; useful for post-processing"""
  146. return self.elementsById
  147. def getLinks(self):
  148. """Return a list of all the A HREF= elements found in the template."""
  149. return self.links
  150. def getForms(self):
  151. """Return a list of all the FORM elements found in the template."""
  152. return self.forms
  153. def onAttach(self):
  154. if not self.attached:
  155. SimplePanel.onAttach(self)
  156. if self.loaded and not self.widgetsAttached:
  157. self.attachWidgets()
  158. self.widgetsAttached = True
  159. def attachWidgets(self):
  160. """
  161. Attach and insert widgets into the DOM now that it has been loaded. If any
  162. widgets were attached before loading, they will have been queued and the
  163. default implementation will attach them.
  164. Override this in subclasses to attach your own widgets after loading.
  165. """
  166. for attach in self.toAttach:
  167. self.attach(attach.name, attach.widget)
  168. for insert in self.toInsert:
  169. self.insert(insert.name, insert.widget)
  170. def getElementById(self, id):
  171. return self.elementsById[id]
  172. def insert(self, id, widget):
  173. """
  174. Insert a widget into the element with the given id, at the end
  175. of its children.
  176. """
  177. if not self.loaded:
  178. self.toInsert.append(PendingAttachOrInsert(id, widget))
  179. else:
  180. element = self.getElementById(id)
  181. if element:
  182. self.adopt(widget, element)
  183. self.children.append(widget)
  184. else:
  185. console.error("Page error: No such element "+id)
  186. return widget
  187. def attachToElement(self, element, widget):
  188. events = DOM.getEventsSunk(widget.getElement())
  189. widget.unsinkEvents(events)
  190. widget.setElement(element)
  191. widget.sinkEvents(events)
  192. self.adopt(widget, None)
  193. self.children.append(widget)
  194. def replaceElement(self, element, widget):
  195. """
  196. Replace an existing element with the given widget
  197. """
  198. DOM.getParent(element).replaceChild(widget.getElement(), element)
  199. self.adopt(widget, None)
  200. self.children.append(widget)
  201. def attach(self, id, widget):
  202. """
  203. Attach a widget onto the element with the given id; the element
  204. currently associated with the widget is discarded.
  205. """
  206. if not self.loaded:
  207. self.toAttach.append(PendingAttachOrInsert(id, widget))
  208. else:
  209. element = self.getElementById(id)
  210. if element:
  211. self.attachToElement(element, widget)
  212. else:
  213. console.error("Page error: No such element "+id)
  214. return widget
  215. def getMeta(self, name):
  216. """
  217. Get the value of a meta-variable found in the template, or None if
  218. no meta tags were found with the given name.
  219. """
  220. return self.metaTags.get(name)
  221. def getTitle(self):
  222. """
  223. Return a user-friendly title for the page
  224. """
  225. if self.title: return self.title
  226. else: return self.templateName
  227. def addLoadListener(self, listener):
  228. """
  229. The listener should be a function or an object implementing onTemplateLoaded.
  230. It will be called this TemplatePanel instance after the template has been
  231. loaded and after attachWidgets() is called.
  232. """
  233. self.loadListeners.append(listener)
  234. def removeLoadListener(self, listener):
  235. self.loadListeners.remove(listener)
  236. def notifyLoadListeners(self):
  237. for listener in self.loadListeners:
  238. if listener.onTemplateLoaded: listener.onTemplateLoaded(self)
  239. else: listener(self)
  240. def onEditContentClick(self, sender):
  241. if self.editor:
  242. editor = self.editor
  243. self.editor = None
  244. ComplexPanel.remove(self, editor)
  245. self.editButton.setText("edit "+unescape(self.templateName))
  246. else:
  247. self.editor = RichTextEditor(self.originalText)
  248. self.editor.addSaveListener(self)
  249. ComplexPanel.insert(self, self.editor, self.getElement(), len(self.children))
  250. self.editButton.setText("close editor")
  251. def getTemplateSaveUrl(self, templateName):
  252. """
  253. Get the URL to post a template to when it is saved in the editor.
  254. """
  255. return self.getTemplatePath(templateName)
  256. def saveTemplateText(self, html):
  257. """
  258. Save the text. This method can be overridden to use a different
  259. save method. The default is to POST to the template save URL, passing
  260. a single parameter "content" with the html string.
  261. To change the target of the POST, override getTemplateSaveUrl().
  262. To preprocess the html, override this method in a subclass and perform
  263. processing there.
  264. """
  265. HTTPRequest().asyncPost(self.getTemplateSaveUrl(self.templateName),
  266. "content="+encodeURIComponent(html),
  267. ContentSaveHandler(self))
  268. def onSave(self, sender):
  269. """
  270. Called when the user clicks save in the content editor.
  271. """
  272. html = self.editor.getHTML()
  273. self.saveTemplateText(html)
  274. def onSaveComplete(self):
  275. """
  276. Called when the template was successfully POSTed to the server; it reloads the template.
  277. Subclasses which don't use the default method of saving may want to call this after
  278. they successfully save the template.
  279. """
  280. self.loadTemplate(self.templateName)