Good people of Anvil Nation,
Just want to share my “ninja_style” module . It’s a collection of functions that provide enhanced style control from Anvil Python code. Link to the module and a demo of its use can be found below.
Anvil’s ability to directly style Anvil-native UI component with respect to certain style properties (‘foreground’, ‘background’ etc.) as well as the ability to define and set “roles” gives us very good control of component styling. However, anvil.js opens the full range of style control options that the core web technologies offer.
The ninja_style module enables style control at three levels:
- Direct styling of both Anvil components and HTML elements (somewhat similar to what jQuery provides – but without the use of jQuery).
- Adding and removing (potentially multiple) classes for Anvil components and HTML elements (again, somewhat similar to what jQuery can do – but again without using jQuery).
- Dynamic manipulation of stylesheets, i.e., adding, deleting, and changing classes (incl. Anvil roles) from Anvil Python code. This is implemented by using the CSS Object Model (CSSOM) and not by simple string manipulation. Some of this manipulation could have been done with Python string methods, but the use of CSSOM makes it possible to extend the functionality of the utility module in more advanced ways. Granted, the practical use cases for such stylesheet manipulation are probably limited, but working with it has been a good learning experience for me .
Moreover, I’ve added a simple but fully functional feature to “encapsulate” Anvil form styling. The “encapsulate_styles” function effectively makes it possible to prevent styles defined in a style tag in Anvil-form HTML from leaking to other Anvil forms and components. I’ve recently shared a Forum post (Into the shadow (DOM)) about using the shadow DOM. This is of course the “proper way” of creating “Anvil form private CSS”, but the “encapsulate_styles” function achieves much of the same but in a simpler way (at least from the perspective of implementation ).
I’ve done my best to provide docstrings and comments in both the demo form and “ninja_style” module itself as well as to provide print statements that track what’s going on during execution.
I still consider myself a novice, so any feedback and suggestions will be much appreciated. Thanks.
Utility module and demo:
Happy ninja styling