This repository was archived by the owner on Apr 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathextension.py
430 lines (359 loc) · 15.8 KB
/
extension.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
import os
import inspect
import types
from docutils import nodes
import sphinx
from sphinx.ext.intersphinx import InventoryAdapter
from sphinx.ext.intersphinx import missing_reference as sphinx_missing_reference
from sphinx.roles import XRefRole
from sphinx.util.fileutil import copy_asset
from sphinx.util import logging
from . import version
from .domains import (
HoverXRefBaseDomain,
HoverXRefPythonDomainMixin,
HoverXRefStandardDomainMixin,
)
from .translators import HoverXRefHTMLTranslatorMixin
logger = logging.getLogger(__name__)
HOVERXREF_ASSETS_FILES = [
'js/hoverxref.js_t', # ``_t`` tells Sphinx this is a template
]
TOOLTIP_ASSETS_FILES = [
# Tooltipster's Styles
'js/tooltipster.bundle.min.js',
'css/tooltipster.custom.css',
'css/tooltipster.bundle.min.css',
# Tooltipster's Themes
'css/tooltipster-sideTip-shadow.min.css',
'css/tooltipster-sideTip-punk.min.css',
'css/tooltipster-sideTip-noir.min.css',
'css/tooltipster-sideTip-light.min.css',
'css/tooltipster-sideTip-borderless.min.css',
]
MODAL_ASSETS_FILES = [
'js/micromodal.min.js',
'css/micromodal.css',
]
ASSETS_FILES = HOVERXREF_ASSETS_FILES + TOOLTIP_ASSETS_FILES + MODAL_ASSETS_FILES
def copy_asset_files(app, exception):
"""
Copy all assets after build finished successfully.
Assets that are templates (ends with ``_t``) are previously rendered using
using all the configs starting with ``hoverxref_`` as a context.
"""
if exception is None: # build succeeded
context = {}
for attr in app.config.values:
if attr.startswith('hoverxref_'):
# First, add the default values to the context
context[attr] = app.config.values[attr][0]
for attr in dir(app.config):
if attr.startswith('hoverxref_'):
# Then, add the values that the user overrides
context[attr] = getattr(app.config, attr)
# Finally, add some non-hoverxref extra configs
configs = ['html_theme']
for attr in configs:
context[attr] = getattr(app.config, attr)
for f in ASSETS_FILES:
path = os.path.join(os.path.dirname(__file__), '_static', f)
copy_asset(
path,
os.path.join(app.outdir, '_static', f.split('.')[-1].replace('js_t', 'js')),
context=context,
)
def setup_domains(app, config):
"""
Override domains respecting the one defined (if any).
We create a new class by inheriting the Sphinx Domain already defined
and our own ``HoverXRef...DomainMixin`` that includes the logic for
``_hoverxref`` attributes.
"""
# Add ``hoverxref`` role replicating the behavior of ``ref``
for role in HoverXRefBaseDomain.hoverxref_types:
app.add_role_to_domain(
'std',
role,
XRefRole(
lowercase=True,
innernodeclass=nodes.inline,
warn_dangling=True,
),
)
domain = types.new_class(
'HoverXRefStandardDomain',
(
HoverXRefStandardDomainMixin,
app.registry.domains.get('std'),
),
{}
)
app.add_domain(domain, override=True)
if 'py' in app.config.hoverxref_domains:
domain = types.new_class(
'HoverXRefPythonDomain',
(
HoverXRefPythonDomainMixin,
app.registry.domains.get('py'),
),
{}
)
app.add_domain(domain, override=True)
def setup_sphinx_tabs(app, config):
"""
Disconnect ``update_context`` function from ``sphinx-tabs``.
Sphinx Tabs removes the CSS/JS from pages that does not use the directive.
Although, we need them to use inside the tooltip.
"""
if sphinx.version_info < (3, 0, 0):
listeners = list(app.events.listeners.get('html-page-context').items())
else:
listeners = [
(listener.id, listener.handler)
for listener in app.events.listeners.get('html-page-context')
]
for listener_id, function in listeners:
module_name = inspect.getmodule(function).__name__
if module_name == 'sphinx_tabs.tabs':
app.disconnect(listener_id)
def setup_intersphinx(app, config):
"""
Disconnect ``missing-reference`` from ``sphinx.ext.intershinx``.
As there is no way to hook into the ``missing_referece`` function to add
some extra data to the docutils node returned by this function, we
disconnect the original listener and add our custom one.
https://github.com/sphinx-doc/sphinx/blob/53c1dff/sphinx/ext/intersphinx.py
"""
if not app.config.hoverxref_intersphinx:
# Do not disconnect original intersphinx missing-reference if the user
# does not have hoverxref intersphinx enabled
return
if sphinx.version_info < (3, 0, 0):
listeners = list(app.events.listeners.get('missing-reference').items())
else:
listeners = [
(listener.id, listener.handler)
for listener in app.events.listeners.get('missing-reference')
]
for listener_id, function in listeners:
module_name = inspect.getmodule(function).__name__
if module_name == 'sphinx.ext.intersphinx':
app.disconnect(listener_id)
def missing_reference(app, env, node, contnode):
"""
Override original ``missing_referece`` to add data into the node.
We call the original intersphinx extension and add hoverxref CSS classes
plus the ``data-url`` to the node returned from it.
Sphinx intersphinx downloads all the ``objects.inv`` and load each of them
into a "named inventory" and also updates the "main inventory". We check if
reference is part of any of the "named invetories" the user defined in
``hoverxref_intersphinx`` and we add hoverxref to the node **only if** the
reference is on those inventories.
See https://github.com/sphinx-doc/sphinx/blob/4d90277c/sphinx/ext/intersphinx.py#L244-L250
"""
if not app.config.hoverxref_intersphinx:
# Do nothing if the user doesn't have hoverxref intersphinx enabled
return
# We need to grab all the attributes before calling
# ``sphinx_missing_reference`` because it modifies the node in-place
domain = node.get('refdomain') # ``std`` if used on ``:ref:``
target = node['reftarget']
reftype = node['reftype']
# By default we skip adding hoverxref to the node to avoid possible
# problems. We want to be sure we have to add hoverxref on it
skip_node = True
inventory_name_matched = None
if domain == 'std':
# Using ``:ref:`` manually, we could write intersphinx like:
# :ref:`datetime <python:datetime.datetime>`
# and the node will have these attribues:
# refdomain: std
# reftype: ref
# reftarget: python:datetime.datetime
# refexplicit: True
if ':' in target:
inventory_name, _ = target.split(':', 1)
if inventory_name in app.config.hoverxref_intersphinx:
skip_node = False
inventory_name_matched = inventory_name
else:
# Using intersphinx via ``sphinx.ext.autodoc`` generates links for docstrings like:
# :py:class:`float`
# and the node will have these attribues:
# refdomain: py
# reftype: class
# reftarget: float
# refexplicit: False
inventories = InventoryAdapter(env)
for inventory_name in app.config.hoverxref_intersphinx:
inventory = inventories.named_inventory.get(inventory_name, {})
if inventory.get(f'{domain}:{reftype}', {}).get(target) is not None:
# The object **does** exist on the inventories defined by the
# user: enable hoverxref on this node
skip_node = False
inventory_name_matched = inventory_name
break
newnode = sphinx_missing_reference(app, env, node, contnode)
if newnode is not None and not skip_node:
hoverxref_type = app.config.hoverxref_intersphinx_types.get(inventory_name_matched)
if isinstance(hoverxref_type, dict):
# Specific style for a particular reftype
hoverxref_type = hoverxref_type.get(reftype)
hoverxref_type = hoverxref_type or app.config.hoverxref_default_type
classes = newnode.get('classes')
classes.extend(['hoverxref', hoverxref_type])
newnode.replace_attr('classes', classes)
newnode._hoverxref = {
'data-url': newnode.get('refuri'),
}
return newnode
def setup_translators(app):
"""
Override translators respecting the one defined (if any).
We create a new class by inheriting the Sphinx Translator already defined
and our own ``HoverXRefHTMLTranslatorMixin`` that includes the logic to
``_hoverxref`` attributes.
"""
if app.builder.format != 'html':
# do not modify non-html builders
return
for name, klass in app.registry.translators.items():
translator = types.new_class(
'HoverXRefHTMLTranslator',
(
HoverXRefHTMLTranslatorMixin,
klass,
),
{},
)
app.set_translator(name, translator, override=True)
translator = types.new_class(
'HoverXRefHTMLTranslator',
(
HoverXRefHTMLTranslatorMixin,
app.builder.default_translator_class,
),
{},
)
app.set_translator(app.builder.name, translator, override=True)
def is_hoverxref_configured(app, config):
"""
Save a config if hoverxref is properly configured.
It checks for ``hoverxref_project`` and ``hoverxref_version`` being defined
and set ``hoverxref_is_configured=True`` if configured.
"""
config.hoverxref_is_configured = True
project = config.hoverxref_project
version = config.hoverxref_version
if not project or not version:
config.hoverxref_is_configured = False
# ``hoverxref`` extension is not fully configured
logger.info(
'hoverxref extension is not fully configured. '
'Tooltips may not work as expected. '
'Check out the documentation for hoverxref_project and hoverxref_version configuration options.',
)
def setup_theme(app, exception):
"""
Auto-configure default settings for known themes.
Add a small custom CSS file for a specific theme and set hoverxref configs
(if not overwritten by the user) with better defaults for these themes.
"""
css_file = None
theme = app.config.html_theme
default, rebuild, types = app.config.values.get('hoverxref_modal_class')
if theme == 'sphinx_material':
if app.config.hoverxref_modal_class == default:
app.config.hoverxref_modal_class = 'md-typeset'
css_file = 'css/sphinx_material.css'
elif theme == 'alabaster':
if app.config.hoverxref_modal_class == default:
app.config.hoverxref_modal_class = 'body'
css_file = 'css/alabaster.css'
elif theme == 'sphinx_rtd_theme':
if app.config.hoverxref_modal_class == default:
css_file = 'css/sphinx_rtd_theme.css'
if css_file:
app.add_css_file(css_file)
path = os.path.join(os.path.dirname(__file__), '_static', css_file)
copy_asset(
path,
os.path.join(app.outdir, '_static', 'css'),
)
def setup_assets_policy(app, exception):
"""Tell Sphinx to always include assets in all HTML pages."""
if hasattr(app, 'set_html_assets_policy'):
# ``app.set_html_assets_policy`` was introduced in Sphinx 4.1.0
# https://github.com/sphinx-doc/sphinx/pull/9174
app.set_html_assets_policy('always')
def deprecated_configs_warning(app, exception):
"""Log warning message if old configs are used."""
default, rebuild, types = app.config.values.get('hoverxref_tooltip_api_host')
if app.config.hoverxref_tooltip_api_host != default:
message = '"hoverxref_tooltip_api_host" is deprecated and replaced by "hoverxref_api_host".'
logger.warning(message)
app.config.hoverxref_api_host = app.config.hoverxref_tooltip_api_host
def setup(app):
"""Setup ``hoverxref`` Sphinx extension."""
# ``override`` was introduced in 1.8
app.require_sphinx('1.8')
default_project = os.environ.get('READTHEDOCS_PROJECT')
default_version = os.environ.get('READTHEDOCS_VERSION')
app.add_config_value('hoverxref_project', default_project, 'html')
app.add_config_value('hoverxref_version', default_version, 'html')
app.add_config_value('hoverxref_auto_ref', False, 'env')
app.add_config_value('hoverxref_mathjax', False, 'env')
app.add_config_value('hoverxref_sphinxtabs', False, 'env')
app.add_config_value('hoverxref_roles', [], 'env')
app.add_config_value('hoverxref_domains', [], 'env')
app.add_config_value('hoverxref_ignore_refs', ['genindex', 'modindex', 'search'], 'env')
app.add_config_value('hoverxref_role_types', {}, 'env')
app.add_config_value('hoverxref_default_type', 'tooltip', 'env')
app.add_config_value('hoverxref_intersphinx', [], 'env')
app.add_config_value('hoverxref_intersphinx_types', {}, 'env')
app.add_config_value('hoverxref_api_host', 'https://readthedocs.org', 'env')
app.add_config_value('hoverxref_sphinx_version', sphinx.__version__, 'env')
# Tooltipster settings
# Deprecated in favor of ``hoverxref_api_host``
app.add_config_value('hoverxref_tooltip_api_host', 'https://readthedocs.org', 'env')
app.add_config_value('hoverxref_tooltip_theme', ['tooltipster-shadow', 'tooltipster-shadow-custom'], 'env')
app.add_config_value('hoverxref_tooltip_interactive', True, 'env')
app.add_config_value('hoverxref_tooltip_maxwidth', 450, 'env')
app.add_config_value('hoverxref_tooltip_side', 'right', 'env')
app.add_config_value('hoverxref_tooltip_animation', 'fade', 'env')
app.add_config_value('hoverxref_tooltip_animation_duration', 0, 'env')
app.add_config_value('hoverxref_tooltip_content', 'Loading...', 'env')
app.add_config_value('hoverxref_tooltip_class', 'rst-content', 'env')
# MicroModal settings
app.add_config_value('hoverxref_modal_hover_delay', 350, 'env')
app.add_config_value('hoverxref_modal_class', 'rst-content', 'env')
app.add_config_value('hoverxref_modal_onshow_function', None, 'env')
app.add_config_value('hoverxref_modal_openclass', 'is-open', 'env')
app.add_config_value('hoverxref_modal_disable_focus', True, 'env')
app.add_config_value('hoverxref_modal_disable_scroll', False, 'env')
app.add_config_value('hoverxref_modal_awaitopenanimation', False, 'env')
app.add_config_value('hoverxref_modal_awaitcloseanimation', False, 'env')
app.add_config_value('hoverxref_modal_debugmode', False, 'env')
app.add_config_value('hoverxref_modal_default_title', 'Note', 'env')
app.add_config_value('hoverxref_modal_prefix_title', '📝 ', 'env')
app.connect('builder-inited', setup_translators)
app.connect('config-inited', deprecated_configs_warning)
app.connect('config-inited', setup_domains)
app.connect('config-inited', setup_sphinx_tabs)
app.connect('config-inited', setup_intersphinx)
app.connect('config-inited', is_hoverxref_configured)
app.connect('config-inited', setup_theme)
app.connect('config-inited', setup_assets_policy)
app.connect('build-finished', copy_asset_files)
app.connect('missing-reference', missing_reference)
for f in ASSETS_FILES:
if f.endswith('.js') or f.endswith('.js_t'):
app.add_js_file(f.replace('.js_t', '.js'))
if f.endswith('.css'):
app.add_css_file(f)
return {
'version': version,
'parallel_read_safe': True,
'parallel_write_safe': True,
}