Source code for wuttaweb.grids.renderers

# -*- coding: utf-8; -*-
################################################################################
#
#  wuttaweb -- Web App for Wutta Framework
#  Copyright © 2024-2026 Lance Edgar
#
#  This file is part of Wutta Framework.
#
#  Wutta Framework is free software: you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by the Free
#  Software Foundation, either version 3 of the License, or (at your option) any
#  later version.
#
#  Wutta Framework is distributed in the hope that it will be useful, but
#  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
#  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
#  more details.
#
#  You should have received a copy of the GNU General Public License along with
#  Wutta Framework.  If not, see <http://www.gnu.org/licenses/>.
#
################################################################################
"""
Grid renderers
"""

import warnings

from pyramid.renderers import render
from webhelpers2.html import HTML

from wuttaweb.util import make_json_safe, render_vue_finalize


[docs] class GridRenderer: # pylint: disable=too-few-public-methods """ Base class and default implementation for grid renderers. This will render the grid as a simple HTML table, with Bulma classes for styling but no JS or (e.g. Buefy) components involved. """ def __init__(self, request, grid=None): self.request = request self.config = self.request.wutta_config self.app = self.config.get_app() self.grid = grid
[docs] def render_element(self, template=None, **context): """ Render the HTML ``<table>`` element. :param template: Optional path to custom Mako template. :param \\**context: Additional context for the template. :returns: HTML literal of the rendered table. """ if not template: template = "/grids/html_template.mako" # must have grid reference grid = context.get("grid", self.grid) if not grid: raise ValueError("must set grid reference") self.grid = grid # nb. this fetches visible grid data context.update(self.get_html_context()) context.update({"request": self.request, "grid": self.grid}) return HTML.literal(self.render_mako(template, context))
[docs] def render_mako(self, template, context): """ Render a Mako template. This method exists for sake of non-Pyramid web frameworks to override the final render call. The default logic calls :func:`~pyramid:pyramid.renderers.render()` for the Pyramid framework. :param template: Path to Mako template. :param context: Context dict for the template. :returns: HTML output from rendering the template. """ return render(template, context)
[docs] def get_html_context(self): """ Returns a context dict for the basic HTML template. """ original_data = self.grid.get_visible_data() # loop thru data data = [] for i, original_record in enumerate(original_data, 1): # customize value rendering where applicable rendered = {} for key, renderer in self.grid.renderers.items(): # nb. no need to render if column not included if key in self.grid.columns: value = getattr(original_record, key, None) rendered[key] = renderer(original_record, key, value) for key in self.grid.columns: if key not in rendered: value = getattr(original_record, key, None) rendered[key] = str("" if value is None else value) # add action urls to each record action_urls = {} for action in self.grid.actions: if action.key not in action_urls: if url := action.get_url(original_record, i): action_urls[action.key] = url data.append( { "raw": original_record, "rendered": rendered, "action_urls": action_urls, "view_url": action_urls.get("view"), } ) return { "data": data, }
[docs] class WuttaGridRenderer(GridRenderer): """ Renders the traditional ``<wutta-grid>`` component, which uses the Buefy ``<b-table>`` under the hood. .. attribute:: vue_tagname String name for Vue component tag. By default this is ``"wutta-grid"``. See also :meth:`render_element()` and :attr:`vue_component`. .. attribute:: vue_component String name for the Vue component, e.g. ``"WuttaGrid"``. This is a generated value based on :attr:`vue_tagname`. """ def __init__(self, request, grid=None, vue_tagname="wutta-grid"): super().__init__(request, grid) self.vue_tagname = vue_tagname words = self.vue_tagname.split("-") self.vue_component = "".join([word.capitalize() for word in words])
[docs] def render_element(self, template=None, **attrs): """ Render the Vue component tag for the grid. By default this simply returns: .. code-block:: html <wutta-grid></wutta-grid> The actual output will depend on :attr:`vue_tagname` and caller-provided attrs. :param template: Optional path to custom Mako template. (This is currently ignored.) :param \\**attrs: Additional HTML attributes for the Vue component tag. :returns: HTML literal for the component tag. """ # nb. throw away 'grid' attr if prresent attrs.pop("grid", None) return HTML.tag(self.vue_tagname, **attrs)
def render_vue_tag(self, **attrs): # pylint: disable=missing-function-docstring warnings.warn( "WuttaGridRenderer.render_vue_tag() is deprecated; " "please use WuttaGridRenderer.render_element() instead", DeprecationWarning, stacklevel=2, ) return self.render_element(**attrs)
[docs] def render_vue_template(self, template=None, **context): """ Render the Vue "component" block for the grid. This is what you want for a "full-featured" grid which will exist as its own unique Vue component on the frontend. This returns something like: .. code-block:: none <script type="text/x-template" id="wutta-grid-template"> <b-table> <!-- columns etc. --> </b-table> </script> <script> WuttaGridData = {} WuttaGrid = { template: 'wutta-grid-template', } </script> .. todo:: Why can't Sphinx render the above code block as 'html' ? It acts like it can't handle a ``<script>`` tag at all? Actual output will of course depend on grid attributes, :attr:`vue_tagname` etc. :param template: Optional path to custom Mako template. :param \\**context: Additional context for the template. :returns: HTML literal containing the Vue script blocks. """ if not template: template = "/grids/vue_template.mako" # nb. this fetches visible grid data vue_context = self.get_vue_context() context.update( { "request": self.request, "grid": self.grid, "vue_tagname": self.vue_tagname, "vue_component": self.vue_component, "vue_context": vue_context, "vue_columns": self.get_vue_columns(), } ) if self.grid.sortable: context.update( { "vue_active_sorters": self.get_vue_active_sorters(), "vue_first_sorter": self.get_vue_first_sorter(), } ) if self.grid.filterable: context.update( { "vue_filters": self.get_vue_filters(), } ) if self.grid.paginated and self.grid.paginate_on_backend: context.update( { "vue_pager_stats": self.get_vue_pager_stats(), } ) return HTML.literal(render(template, context))
[docs] def render_vue_finalize(self): """ Render the Vue "finalize" script for the grid. By default this simply returns: .. code-block:: html <script> WuttaGrid.data = function() { return WuttaGridData } Vue.component('wutta-grid', WuttaGrid) </script> The actual output may depend on various grid attributes, in particular :attr:`vue_tagname`. """ return render_vue_finalize(self.vue_tagname, self.vue_component)
############################## # template context getters ##############################
[docs] def get_vue_context(self): """ Returns a dict of context for the grid, for use with the Vue component. This contains the following keys: * ``data`` - list of Vue-compatible data records * ``row_classes`` - dict of per-row CSS classes This first calls :meth:`~wuttaweb.grids.base.Grid.get_visible_data()` to get the original data set. Each record is converted to a dict. Then it calls :func:`~wuttaweb.util.make_json_safe()` to ensure each record can be serialized to JSON. Then it invokes any :attr:`~wuttaweb.grids.base.Grid.renderers` which are defined, to obtain the "final" values for each record. Then it adds a URL key/value for each of the :attr:`~wuttaweb.grids.base.Grid.actions` defined, to each record. Then it calls :meth:`~wuttaweb.grids.base.Grid.get_row_class()` for each record. If a value is returned, it is added to the ``row_classes`` dict. Note that this dict is keyed by "zero-based row sequence as string" - the Vue component expects that. :returns: Dict of grid data/CSS context as described above. """ original_data = self.grid.get_visible_data() # loop thru data data = [] row_classes = {} for i, original_record in enumerate(original_data, 1): # convert record to new dict record = self.grid.object_to_dict(original_record) # discard non-declared fields (but always keep uuid) record = { field: record[field] for field in record if field in self.grid.columns or field == "uuid" } # make all values safe for json record = make_json_safe(record, warn=False) # customize value rendering where applicable for key, renderer in self.grid.renderers.items(): # nb. no need to render if column not included if key in self.grid.columns: value = record.get(key, None) record[f"_rendered_{key}"] = renderer(original_record, key, value) # add action urls to each record for action in self.grid.actions: key = f"_action_url_{action.key}" if key not in record: if url := action.get_url(original_record, i): record[key] = url # set row css class if applicable if css_class := self.grid.get_row_class(original_record, record, i): # nb. use *string* zero-based index, for js compat row_classes[str(i - 1)] = css_class data.append(record) return { "data": data, "row_classes": row_classes, }
[docs] def get_vue_columns(self): """ Returns a list of Vue-compatible column definitions. This uses :attr:`~wuttaweb.grids.base.Grid.columns` as the basis; each definition returned will be a dict in this format:: { "field": "foo", "label": "Foo", "sortable": True, "searchable": False, } The full format is determined by Buefy; see the Column section in its `Table docs <https://buefy.org/documentation/table/#api-view>`_. See also :meth:`get_vue_context()`. """ if not self.grid.columns: raise ValueError( f"you must define columns for the grid! key = {self.grid.key}" ) columns = [] for name in self.grid.columns: columns.append( { "field": name, "label": self.grid.get_column_label(name), "hidden": self.grid.is_hidden(name), "sortable": self.grid.is_sortable(name), "searchable": self.grid.is_searchable(name), } ) return columns
[docs] def get_vue_active_sorters(self): """ Returns a list of Vue-compatible column sorter definitions. The list returned is the same as :attr:`~wuttaweb.grids.base.Grid.active_sorters`; however the format used in Vue is different. So this method just "converts" them to the required format, e.g.:: # active_sorters format {"key": "name", "dir": "asc"} # get_vue_active_sorters() format {"field": "name", "order": "asc"} :returns: The :attr:`~wuttaweb.grids.base.Grid.active_sorters` list, converted as described above. """ sorters = [] for sorter in self.grid.active_sorters: sorters.append({"field": sorter["key"], "order": sorter["dir"]}) return sorters
[docs] def get_vue_first_sorter(self): """ Returns the first active sorter, if applicable. This method is used to declare the initial sort for a simple table component, i.e. for use with the ``table-element.mako`` template. It generally is assumed that frontend sorting is in use, as opposed to backend sorting, although it should work for either scenario. This checks :attr:`~wuttaweb.grids.base.Grid.active_sorters` and if set, will use the first sorter from that. Note that ``active_sorters`` will *not* be set unless :meth:`~wuttaweb.grids.base.Grid.load_settings()` has been called. Otherwise this will use the first sorter from :attr:`~wuttaweb.grids.base.Grid.sort_defaults` which is defined in the grid constructor. :returns: The first sorter in format ``[sortkey, sortdir]``, or ``None``. """ if self.grid.active_sorters: sorter = self.grid.active_sorters[0] return [sorter["key"], sorter["dir"]] if self.grid.sort_defaults: sorter = self.grid.sort_defaults[0] return [sorter.sortkey, sorter.sortdir] return None
[docs] def get_vue_filters(self): """ Returns a list of Vue-compatible filter definitions. This returns the full set of :attr:`~wuttaweb.grids.base.Grid.filters` but represents each as a simple dict with the filter state. """ filters = [] for filtr in self.grid.filters.values(): choices = [] choice_labels = {} if filtr.choices: choices = list(filtr.choices) choice_labels = dict(filtr.choices) filters.append( { "key": filtr.key, "data_type": filtr.data_type, "active": filtr.active, "visible": filtr.active, "verbs": filtr.get_verbs(), "verb_labels": filtr.get_verb_labels(), "valueless_verbs": filtr.get_valueless_verbs(), "verb": filtr.verb, "choices": choices, "choice_labels": choice_labels, "value": filtr.value, "label": filtr.label, } ) return filters
[docs] def get_vue_pager_stats(self): """ Returns a simple dict with current grid pager stats. This is used when :attr:`~wuttaweb.grids.base.Grid.paginate_on_backend` is in effect. """ pager = self.grid.pager return { "item_count": pager.item_count, "items_per_page": pager.items_per_page, "page": pager.page, "page_count": pager.page_count, "first_item": pager.first_item, "last_item": pager.last_item, }
[docs] class BuefyGridRenderer(WuttaGridRenderer): """ Renders the standalone Buefy ``<b-table>`` element. """
[docs] def render_element(self, template=None, form=None, **context): """ Render a simple Vue table element for the grid. This is what you want for a "simple" grid which does not require a unique Vue component, but can instead use the standard table component. This returns something like: .. code-block:: html <b-table :data="gridContext['mykey'].data"> <!-- columns etc. --> </b-table> Actual output will of course depend on grid attributes, :attr:`~wuttaweb.grids.base.Grid.key`, :attr:`~wuttaweb.grids.base.Grid.columns` etc. :param template: Optional path to custom Mako template. :param form: Reference to the :class:`~wuttaweb.forms.base.Form` instance which "contains" this grid. This is needed in order to ensure the grid data is available to the form Vue component. :param \\**context: Additional context for the template. :returns: HTML literal of the rendered table. .. note:: The above example shows ``gridContext['mykey'].data`` as the Vue data reference. This should "just work" if you provide the correct ``form`` arg and the grid is contained directly by that form's Vue component. However, this may not account for all use cases. For now we wait and see what comes up, but know the dust may not yet be settled here. """ if not template: template = "/grids/table_element.mako" # nb. must register data for inclusion on page template if form: form.add_grid_vue_context(self.grid) # otherwise logic is the same, just different template return self.render_vue_template(template, **context)