|
| 1 | +""" Tabbed views for Sphinx, with HTML builder """ |
| 2 | + |
| 3 | +import base64 |
| 4 | +import json |
| 5 | +import posixpath |
| 6 | +import os |
| 7 | +from docutils.parsers.rst import Directive |
| 8 | +from docutils import nodes |
| 9 | +from pygments.lexers import get_all_lexers |
| 10 | +from sphinx.util.osutil import copyfile |
| 11 | + |
| 12 | +DIR = os.path.dirname(os.path.abspath(__file__)) |
| 13 | + |
| 14 | + |
| 15 | +FILES = [ |
| 16 | + 'tabs.js', |
| 17 | + 'tabs.css', |
| 18 | + 'semantic-ui-2.2.10/segment.min.css', |
| 19 | + 'semantic-ui-2.2.10/menu.min.css', |
| 20 | + 'semantic-ui-2.2.10/tab.min.css', |
| 21 | + 'semantic-ui-2.2.10/tab.min.js', |
| 22 | +] |
| 23 | + |
| 24 | + |
| 25 | +LEXER_MAP = {} |
| 26 | +for lexer in get_all_lexers(): |
| 27 | + for short_name in lexer[1]: |
| 28 | + LEXER_MAP[short_name] = lexer[0] |
| 29 | + |
| 30 | + |
| 31 | +class TabsDirective(Directive): |
| 32 | + """ Top-level tabs directive """ |
| 33 | + |
| 34 | + has_content = True |
| 35 | + |
| 36 | + def run(self): |
| 37 | + """ Parse a tabs directive """ |
| 38 | + self.assert_has_content() |
| 39 | + env = self.state.document.settings.env |
| 40 | + |
| 41 | + node = nodes.container() |
| 42 | + node['classes'] = ['sphinx-tabs'] |
| 43 | + |
| 44 | + tabs_node = nodes.container() |
| 45 | + tabs_node.tagname = 'div' |
| 46 | + |
| 47 | + classes = 'ui top attached tabular menu sphinx-menu' |
| 48 | + tabs_node['classes'] = classes.split(' ') |
| 49 | + |
| 50 | + env.temp_data['tab_titles'] = [] |
| 51 | + env.temp_data['is_first_tab'] = True |
| 52 | + self.state.nested_parse(self.content, self.content_offset, node) |
| 53 | + |
| 54 | + tab_titles = env.temp_data['tab_titles'] |
| 55 | + for idx, [data_tab, tab_name] in enumerate(tab_titles): |
| 56 | + tab = nodes.container() |
| 57 | + tab.tagname = 'a' |
| 58 | + tab['classes'] = ['item'] if idx > 0 else ['active', 'item'] |
| 59 | + tab['classes'].append(data_tab) |
| 60 | + tab += tab_name |
| 61 | + tabs_node += tab |
| 62 | + |
| 63 | + node.children.insert(0, tabs_node) |
| 64 | + |
| 65 | + return [node] |
| 66 | + |
| 67 | + |
| 68 | +class TabDirective(Directive): |
| 69 | + """ Tab directive, for adding a tab to a collection of tabs """ |
| 70 | + |
| 71 | + has_content = True |
| 72 | + |
| 73 | + def run(self): |
| 74 | + """ Parse a tab directive """ |
| 75 | + self.assert_has_content() |
| 76 | + env = self.state.document.settings.env |
| 77 | + |
| 78 | + args = self.content[0].strip() |
| 79 | + try: |
| 80 | + args = json.loads(args) |
| 81 | + self.content.trim_start(1) |
| 82 | + except ValueError: |
| 83 | + args = {} |
| 84 | + |
| 85 | + tab_name = nodes.container() |
| 86 | + self.state.nested_parse( |
| 87 | + self.content[:1], self.content_offset, tab_name) |
| 88 | + args['tab_name'] = tab_name |
| 89 | + |
| 90 | + if 'tab_id' not in args: |
| 91 | + args['tab_id'] = env.new_serialno('tab_id') |
| 92 | + |
| 93 | + data_tab = "sphinx-data-tab-{}".format(args['tab_id']) |
| 94 | + |
| 95 | + env.temp_data['tab_titles'].append((data_tab, args['tab_name'])) |
| 96 | + |
| 97 | + text = '\n'.join(self.content) |
| 98 | + node = nodes.container(text) |
| 99 | + |
| 100 | + classes = 'ui bottom attached sphinx-tab tab segment' |
| 101 | + node['classes'] = classes.split(' ') |
| 102 | + node['classes'].extend(args.get('classes', [])) |
| 103 | + node['classes'].append(data_tab) |
| 104 | + |
| 105 | + if env.temp_data['is_first_tab']: |
| 106 | + node['classes'].append('active') |
| 107 | + env.temp_data['is_first_tab'] = False |
| 108 | + |
| 109 | + self.state.nested_parse(self.content[2:], self.content_offset, node) |
| 110 | + return [node] |
| 111 | + |
| 112 | + |
| 113 | +class GroupTabDirective(Directive): |
| 114 | + """ Tab directive that toggles with same tab names across page""" |
| 115 | + |
| 116 | + has_content = True |
| 117 | + |
| 118 | + def run(self): |
| 119 | + """ Parse a tab directive """ |
| 120 | + self.assert_has_content() |
| 121 | + |
| 122 | + group_name = self.content[0] |
| 123 | + self.content.trim_start(2) |
| 124 | + |
| 125 | + for idx, line in enumerate(self.content.data): |
| 126 | + self.content.data[idx] = ' ' + line |
| 127 | + |
| 128 | + tab_args = { |
| 129 | + 'tab_id': base64.b64encode( |
| 130 | + group_name.encode('utf-8')).decode('utf-8') |
| 131 | + } |
| 132 | + |
| 133 | + new_content = [ |
| 134 | + '.. tab:: {}'.format(json.dumps(tab_args)), |
| 135 | + ' {}'.format(group_name), |
| 136 | + '', |
| 137 | + ] |
| 138 | + |
| 139 | + for idx, line in enumerate(new_content): |
| 140 | + self.content.data.insert(idx, line) |
| 141 | + self.content.items.insert(idx, (None, idx)) |
| 142 | + |
| 143 | + node = nodes.container() |
| 144 | + self.state.nested_parse(self.content, self.content_offset, node) |
| 145 | + return node.children |
| 146 | + |
| 147 | + |
| 148 | +class CodeTabDirective(Directive): |
| 149 | + """ Tab directive with a codeblock as its content""" |
| 150 | + |
| 151 | + has_content = True |
| 152 | + |
| 153 | + def run(self): |
| 154 | + """ Parse a tab directive """ |
| 155 | + self.assert_has_content() |
| 156 | + |
| 157 | + args = self.content[0].strip().split() |
| 158 | + self.content.trim_start(2) |
| 159 | + |
| 160 | + lang = args[0] |
| 161 | + tab_name = ' '.join(args[1:]) if len(args) > 1 else LEXER_MAP[lang] |
| 162 | + |
| 163 | + for idx, line in enumerate(self.content.data): |
| 164 | + self.content.data[idx] = ' ' + line |
| 165 | + |
| 166 | + tab_args = { |
| 167 | + 'tab_id': '-'.join(tab_name.lower().split()), |
| 168 | + 'classes': ['code-tab'], |
| 169 | + } |
| 170 | + |
| 171 | + new_content = [ |
| 172 | + '.. tab:: {}'.format(json.dumps(tab_args)), |
| 173 | + ' {}'.format(tab_name), |
| 174 | + '', |
| 175 | + ' .. code-block:: {}'.format(lang), |
| 176 | + '', |
| 177 | + ] |
| 178 | + |
| 179 | + for idx, line in enumerate(new_content): |
| 180 | + self.content.data.insert(idx, line) |
| 181 | + self.content.items.insert(idx, (None, idx)) |
| 182 | + |
| 183 | + node = nodes.container() |
| 184 | + self.state.nested_parse(self.content, self.content_offset, node) |
| 185 | + return node.children |
| 186 | + |
| 187 | + |
| 188 | +class _FindTabsDirectiveVisitor(nodes.NodeVisitor): |
| 189 | + """ Visitor pattern than looks for a sphinx tabs |
| 190 | + directive in a document """ |
| 191 | + def __init__(self, document): |
| 192 | + nodes.NodeVisitor.__init__(self, document) |
| 193 | + self._found = False |
| 194 | + |
| 195 | + def unknown_visit(self, node): |
| 196 | + if not self._found and isinstance(node, nodes.container) and \ |
| 197 | + 'classes' in node and isinstance(node['classes'], list): |
| 198 | + self._found = 'sphinx-tabs' in node['classes'] |
| 199 | + |
| 200 | + @property |
| 201 | + def found_tabs_directive(self): |
| 202 | + """ Return whether a sphinx tabs directive was found """ |
| 203 | + return self._found |
| 204 | + |
| 205 | + |
| 206 | +# pylint: disable=unused-argument |
| 207 | +def add_assets(app, pagename, templatename, context, doctree): |
| 208 | + """ Add CSS and JS asset files """ |
| 209 | + if doctree is None: |
| 210 | + return |
| 211 | + visitor = _FindTabsDirectiveVisitor(doctree) |
| 212 | + doctree.walk(visitor) |
| 213 | + assets = ['sphinx_tabs/' + f for f in FILES] |
| 214 | + css_files = [posixpath.join('_static', path) |
| 215 | + for path in assets if path.endswith('css')] |
| 216 | + script_files = [posixpath.join('_static', path) |
| 217 | + for path in assets if path.endswith('js')] |
| 218 | + if visitor.found_tabs_directive: |
| 219 | + if 'css_files' not in context: |
| 220 | + context['css_files'] = css_files |
| 221 | + else: |
| 222 | + context['css_files'].extend(css_files) |
| 223 | + if 'script_files' not in context: |
| 224 | + context['script_files'] = script_files |
| 225 | + else: |
| 226 | + context['script_files'].extend(script_files) |
| 227 | + else: |
| 228 | + for path in css_files: |
| 229 | + if 'css_files' in context and path in context['css_files']: |
| 230 | + context['css_files'].remove(path) |
| 231 | + for path in script_files: |
| 232 | + if 'script_files' in context and path in context['script_files']: |
| 233 | + context['script_files'].remove(path) |
| 234 | +# pylint: enable=unused-argument |
| 235 | + |
| 236 | + |
| 237 | +def copy_assets(app, exception): |
| 238 | + """ Copy asset files to the output """ |
| 239 | + builders = ('html', 'readthedocs', 'readthedocssinglehtmllocalmedia', |
| 240 | + 'singlehtml') |
| 241 | + if app.builder.name not in builders: |
| 242 | + app.warn('Not copying tabs assets! Not compatible with %s builder' % |
| 243 | + app.builder.name) |
| 244 | + return |
| 245 | + if exception: |
| 246 | + app.warn('Not copying tabs assets! Error occurred previously') |
| 247 | + return |
| 248 | + app.info('Copying tabs assets... ', nonl=True) |
| 249 | + |
| 250 | + installdir = os.path.join(app.builder.outdir, '_static', 'sphinx_tabs') |
| 251 | + |
| 252 | + for path in FILES: |
| 253 | + source = os.path.join(DIR, path) |
| 254 | + dest = os.path.join(installdir, path) |
| 255 | + |
| 256 | + destdir = os.path.dirname(dest) |
| 257 | + if not os.path.exists(destdir): |
| 258 | + os.makedirs(destdir) |
| 259 | + |
| 260 | + copyfile(source, dest) |
| 261 | + app.info('done') |
| 262 | + |
| 263 | + |
| 264 | +def setup(app): |
| 265 | + """ Set up the plugin """ |
| 266 | + app.add_directive('tabs', TabsDirective) |
| 267 | + app.add_directive('tab', TabDirective) |
| 268 | + app.add_directive('group-tab', GroupTabDirective) |
| 269 | + app.add_directive('code-tab', CodeTabDirective) |
| 270 | + app.connect('html-page-context', add_assets) |
| 271 | + app.connect('build-finished', copy_assets) |
0 commit comments