Skip to content

Commit 95d4a6f

Browse files
authoredSep 1, 2017
Merge pull request godotengine#453 from djrm/pr_code_tabs
Added tabs for multiple programming languages
2 parents a616707 + 54a5c50 commit 95d4a6f

File tree

13 files changed

+443
-2
lines changed

13 files changed

+443
-2
lines changed
 

‎.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
_build/
22
env/
33
extensions/__pycache__/
4+
__pycache__
5+
*.pyc
46
*~
57
.directory

‎conf.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
# Sphinx extension module names and templates location
1313
sys.path.append(os.path.abspath('extensions'))
14-
extensions = ['gdscript']
14+
extensions = ['gdscript', 'sphinx_tabs.tabs']
1515
templates_path = ['_templates']
1616

1717
# You can specify multiple suffix as a list of string: ['.rst', '.md']

‎extensions/gdscript.py

+3
Original file line numberDiff line numberDiff line change
@@ -164,3 +164,6 @@ def innerstring_rules(ttype):
164164
(r'\n', String.Single)
165165
],
166166
}
167+
168+
def setup(sphinx):
169+
sphinx.add_lexer('gdscript', GDScriptLexer())

‎extensions/sphinx_tabs/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__import__('pkg_resources').declare_namespace(__name__)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# The MIT License
2+
3+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4+
5+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6+
7+
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

‎extensions/sphinx_tabs/semantic-ui-2.2.10/menu.min.css

+1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎extensions/sphinx_tabs/semantic-ui-2.2.10/segment.min.css

+9
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎extensions/sphinx_tabs/semantic-ui-2.2.10/tab.min.css

+9
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎extensions/sphinx_tabs/semantic-ui-2.2.10/tab.min.js

+10
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎extensions/sphinx_tabs/tabs.css

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
.sphinx-tabs {
2+
margin-bottom: 2em;
3+
}
4+
5+
.sphinx-tabs .sphinx-menu a.item {
6+
color: #2980b9 !important;
7+
}
8+
9+
.sphinx-tabs .sphinx-menu {
10+
border-bottom-color: #a0b3bf !important;
11+
}
12+
13+
.sphinx-tabs .sphinx-menu a.active.item {
14+
border-color: #a0b3bf !important;
15+
}
16+
17+
.sphinx-tab {
18+
border-color: #a0b3bf !important;
19+
box-sizing: border-box;
20+
}
21+
22+
.tab div[class^='highlight']:last-child {
23+
margin-bottom: 0;
24+
}
25+
26+
.tab .wy-plain-list-disc:last-child,
27+
.rst-content .section ul:last-child,
28+
.rst-content .toctree-wrapper ul:last-child,
29+
article ul:last-child {
30+
margin-bottom: 0;
31+
}
32+
33+
/* Code tabs don't need the code-block border */
34+
.code-tab.tab {
35+
padding: 0.4em !important;
36+
}
37+
38+
.code-tab.tab div[class^='highlight'] {
39+
border: none;
40+
}
41+
42+
/* Semantic UI tabs don't shrink, make font smaller when viewing in mobile devices */
43+
@media screen and (max-width: 768px) {
44+
.sphinx-tabs .sphinx-menu a.item {
45+
font-size: 0.9em !important;
46+
}
47+
}

‎extensions/sphinx_tabs/tabs.js

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
// From http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport
2+
function elementIsInView (el) {
3+
if (typeof jQuery === "function" && el instanceof jQuery) {
4+
el = el[0];
5+
}
6+
7+
const rect = el.getBoundingClientRect();
8+
9+
return (
10+
rect.top >= 0 &&
11+
rect.left >= 0 &&
12+
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
13+
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
14+
);
15+
}
16+
17+
$(function() {
18+
// Change container tags <div> -> <a>
19+
$('.sphinx-menu.menu .item').each(function() {
20+
var this_ = $(this);
21+
var a_this = $('<a>');
22+
23+
a_this.html(this_.html());
24+
$.each(this_.prop('attributes'), function() {
25+
a_this.attr(this.name, this.value);
26+
});
27+
28+
this_.replaceWith(a_this);
29+
});
30+
31+
// We store the data-tab values as sphinx-data-<data-tab value>
32+
// Add data-tab attribute with the extracted value
33+
$('.sphinx-menu.menu .item, .sphinx-tab.tab').each(function() {
34+
var this_ = $(this);
35+
const prefix = 'sphinx-data-';
36+
const classes = this_.attr('class').split(/\s+/);
37+
$.each(classes, function(idx, clazz) {
38+
if (clazz.startsWith(prefix)) {
39+
this_.attr('data-tab',
40+
clazz.substring(prefix.length));
41+
}
42+
});
43+
});
44+
45+
// Mimic the Semantic UI behaviour
46+
$('.sphinx-menu.menu .item').each(function() {
47+
var this1 = $(this);
48+
var data_tab = this1.attr('data-tab');
49+
50+
this1.on('click', function() {
51+
// Find offset in view
52+
const offset = (this1.offset().top - $(window).scrollTop());
53+
54+
$('[data-tab]').each(function() {
55+
var this2 = $(this);
56+
// Remove 'active' class from tabs that aren't the same
57+
if (this2.attr('data-tab') !== data_tab) {
58+
// Keep 'active' if there isn't a tab with the same data-tab value
59+
if (0 < this2.parent().find('[data-tab="' + data_tab + '"]').length) {
60+
this2.removeClass('active');
61+
}
62+
} else {
63+
// Add 'active' if data-tab value is the same
64+
this2.addClass('active');
65+
}
66+
});
67+
68+
// Keep tab with the original view offset
69+
$(window).scrollTop(this1.offset().top - offset);
70+
});
71+
});
72+
});

‎extensions/sphinx_tabs/tabs.py

+271
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,271 @@
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)

‎learning/step_by_step/scripting.rst

+10-1
Original file line numberDiff line numberDiff line change
@@ -185,11 +185,20 @@ where the script is attached, you can fetch the button as follows:
185185

186186
Next, write a function which will be called when the button is pressed:
187187

188-
::
188+
.. tabs::
189+
.. code-tab:: gdscript GDScript
189190

190191
func _on_button_pressed():
191192
get_node("Label").set_text("HELLO!")
192193

194+
.. code-tab:: csharp
195+
196+
// i dont know how this is supposed to be in C#
197+
198+
.. group-tab:: VS
199+
200+
.. image:: /img/signals.png
201+
193202
Finally, connect the button's "pressed" signal to that callback in _ready(), by
194203
using :ref:`Object.connect() <class_Object_connect>`.
195204

0 commit comments

Comments
 (0)
Please sign in to comment.