progressbar.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. """
  2. Progress Bar.
  3. pymdownx.progressbar
  4. Simple plugin to add support for progress bars
  5. ```
  6. /* No label */
  7. [==30%]
  8. /* Label */
  9. [==30% MyLabel]
  10. /* works with attr_list inline style */
  11. [==50/200 MyLabel]{: .additional-class }
  12. ```
  13. New line is not required before the progress bar but suggested unless in a table.
  14. Can take percentages and divisions.
  15. Floats are okay. Numbers must be positive. This is an experimental extension.
  16. Functionality is subject to change.
  17. Minimum Recommended Styling
  18. (but you could add gloss, candy striping, animation, or anything else):
  19. ```
  20. .progress {
  21. display: block;
  22. width: 300px;
  23. margin: 10px 0;
  24. height: 24px;
  25. border: 1px solid #ccc;
  26. -webkit-border-radius: 3px;
  27. -moz-border-radius: 3px;
  28. border-radius: 3px;
  29. background-color: #F8F8F8;
  30. position: relative;
  31. box-shadow: inset -1px 1px 3px rgba(0, 0, 0, .1);
  32. }
  33. .progress-label {
  34. position: absolute;
  35. text-align: center;
  36. font-weight: bold;
  37. width: 100%; margin: 0;
  38. line-height: 24px;
  39. color: #333;
  40. -webkit-font-smoothing: antialiased !important;
  41. white-space: nowrap;
  42. overflow: hidden;
  43. }
  44. .progress-bar {
  45. height: 24px;
  46. float: left;
  47. border-right: 1px solid #ccc;
  48. -webkit-border-radius: 3px;
  49. -moz-border-radius: 3px;
  50. border-radius: 3px;
  51. background-color: #34c2e3;
  52. box-shadow: inset 0 1px 0px rgba(255, 255, 255, .5);
  53. }
  54. For Level Colors
  55. .progress-100plus .progress-bar {
  56. background-color: #1ee038;
  57. }
  58. .progress-80plus .progress-bar {
  59. background-color: #86e01e;
  60. }
  61. .progress-60plus .progress-bar {
  62. background-color: #f2d31b;
  63. }
  64. .progress-40plus .progress-bar {
  65. background-color: #f2b01e;
  66. }
  67. .progress-20plus .progress-bar {
  68. background-color: #f27011;
  69. }
  70. .progress-0plus .progress-bar {
  71. background-color: #f63a0f;
  72. }
  73. ```
  74. MIT license.
  75. Copyright (c) 2014 - 2017 Isaac Muse <isaacmuse@gmail.com>
  76. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  77. documentation files (the "Software"), to deal in the Software without restriction, including without limitation
  78. the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
  79. and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  80. The above copyright notice and this permission notice shall be included in all copies or substantial portions
  81. of the Software.
  82. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  83. TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  84. THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  85. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  86. DEALINGS IN THE SOFTWARE.
  87. """
  88. from markdown import Extension
  89. from markdown.inlinepatterns import InlineProcessor, dequote
  90. import xml.etree.ElementTree as etree
  91. from markdown.extensions.attr_list import AttrListTreeprocessor
  92. from . import util
  93. RE_PROGRESS = r'''(?x)
  94. \[={1,}\s* # Opening
  95. (?:
  96. (?P<percent>100(?:.0+)?|[1-9]?[0-9](?:\.\d+)?)% | # Percent
  97. (?:(?P<frac_num>\d+(?:\.\d+)?)\s*/\s*(?P<frac_den>\d+(?:\.\d+)?)) # Fraction
  98. )
  99. (?P<title>\s+(?P<quote>['"]).*?(?P=quote))?\s* # Title
  100. \] # Closing
  101. (?P<attr_list>\{\:?([^\}]*)\})? # Optional attr list
  102. '''
  103. CLASS_LEVEL = "progress-%dplus"
  104. class ProgressBarTreeProcessor(AttrListTreeprocessor):
  105. """Used for AttrList compatibility."""
  106. def run(self, elem):
  107. """Inline check for attributes at start of tail."""
  108. if elem.tail:
  109. m = self.INLINE_RE.match(elem.tail)
  110. if m:
  111. self.assign_attrs(elem, m.group(1))
  112. elem.tail = elem.tail[m.end():]
  113. class ProgressBarPattern(InlineProcessor):
  114. """Pattern handler for the progress bars."""
  115. def __init__(self, pattern, md):
  116. """Initialize."""
  117. InlineProcessor.__init__(self, pattern, md)
  118. def create_tag(self, width, label, add_classes, alist):
  119. """Create the tag."""
  120. # Create list of all classes and remove duplicates
  121. classes = list(
  122. set(
  123. ["progress"] +
  124. self.config.get('add_classes', '').split() +
  125. add_classes
  126. )
  127. )
  128. classes.sort()
  129. el = etree.Element("div")
  130. el.set('class', ' '.join(classes))
  131. bar = etree.SubElement(el, 'div')
  132. bar.set('class', "progress-bar")
  133. bar.set('style', 'width:%s%%' % width)
  134. p = etree.SubElement(bar, 'p')
  135. p.set('class', 'progress-label')
  136. p.text = label
  137. if alist is not None:
  138. el.tail = alist
  139. if 'attr_list' in self.md.treeprocessors:
  140. ProgressBarTreeProcessor(self.md).run(el)
  141. return el
  142. def handleMatch(self, m, data):
  143. """Handle the match."""
  144. label = ""
  145. level_class = self.config.get('level_class', False)
  146. increment = self.config.get('progress_increment', 20)
  147. add_classes = []
  148. alist = None
  149. if m.group(5):
  150. label = dequote(self.unescape(m.group('title').strip()))
  151. if m.group('attr_list'):
  152. alist = m.group('attr_list')
  153. if m.group('percent'):
  154. value = float(m.group('percent'))
  155. else:
  156. try:
  157. num = float(m.group('frac_num'))
  158. except Exception: # pragma: no cover
  159. num = 0.0
  160. try:
  161. den = float(m.group('frac_den'))
  162. except Exception: # pragma: no cover
  163. den = 0.0
  164. if den == 0.0:
  165. value = 0.0
  166. else:
  167. value = (num / den) * 100.0
  168. # We can never get a value < 0,
  169. # but we must check for > 100.
  170. if value > 100.0:
  171. value = 100.0
  172. # Round down to nearest increment step and include class if desired
  173. if level_class:
  174. add_classes.append(CLASS_LEVEL % int(value - (value % increment)))
  175. return self.create_tag('%.2f' % value, label, add_classes, alist), m.start(0), m.end(0)
  176. class ProgressBarExtension(Extension):
  177. """Add progress bar extension to Markdown class."""
  178. def __init__(self, *args, **kwargs):
  179. """Initialize."""
  180. self.config = {
  181. 'level_class': [
  182. True,
  183. "Include class that defines progress level - Default: True"
  184. ],
  185. 'progress_increment': [
  186. 20,
  187. "Progress increment step - Default: 20"
  188. ],
  189. 'add_classes': [
  190. '',
  191. "Add additional classes to the progress tag for styling. "
  192. "Classes are separated by spaces. - Default: None"
  193. ]
  194. }
  195. super(ProgressBarExtension, self).__init__(*args, **kwargs)
  196. def extendMarkdown(self, md):
  197. """Add the progress bar pattern handler."""
  198. util.escape_chars(md, ['='])
  199. progress = ProgressBarPattern(RE_PROGRESS, md)
  200. progress.config = self.getConfigs()
  201. md.inlinePatterns.register(progress, "progress-bar", 179)
  202. def makeExtension(*args, **kwargs):
  203. """Return extension."""
  204. return ProgressBarExtension(*args, **kwargs)