1#!/usr/bin/python
2
3"""
4Copyright 2014 Google Inc.
5
6Use of this source code is governed by a BSD-style license that can be
7found in the LICENSE file.
8
9ColumnHeaderFactory class (see class docstring for details)
10"""
11
12# Keys used within dictionary representation of each column header.
13# NOTE: Keep these in sync with static/constants.js
14KEY__EXTRACOLUMNHEADERS__HEADER_TEXT = 'headerText'
15KEY__EXTRACOLUMNHEADERS__HEADER_URL = 'headerUrl'
16KEY__EXTRACOLUMNHEADERS__IS_FILTERABLE = 'isFilterable'
17KEY__EXTRACOLUMNHEADERS__IS_SORTABLE = 'isSortable'
18KEY__EXTRACOLUMNHEADERS__USE_FREEFORM_FILTER = 'useFreeformFilter'
19KEY__EXTRACOLUMNHEADERS__VALUES_AND_COUNTS = 'valuesAndCounts'
20
21
22class ColumnHeaderFactory(object):
23  """Factory which assembles the header for a single column of data."""
24
25  def __init__(self, header_text, header_url=None,
26               is_filterable=True, is_sortable=True,
27               use_freeform_filter=False):
28    """
29    Args:
30      header_text: string; text the client should display within column header.
31      header_url: string; target URL if user clicks on column header.
32          If None, nothing to click on.
33      is_filterable: boolean; whether client should allow filtering on this
34          column.
35      is_sortable: boolean; whether client should allow sorting on this column.
36      use_freeform_filter: boolean; *recommendation* to the client indicating
37          whether to allow freeform text matching, as opposed to listing all
38          values alongside checkboxes.  If is_filterable==false, this is
39          meaningless.
40    """
41    self._header_text = header_text
42    self._header_url = header_url
43    self._is_filterable = is_filterable
44    self._is_sortable = is_sortable
45    self._use_freeform_filter = use_freeform_filter
46
47  def create_as_dict(self, values_and_counts_dict=None):
48    """Creates the header for this column, in dictionary form.
49
50    Creates the header for this column in dictionary form, as needed when
51    constructing the JSON representation.  Uses the KEY__EXTRACOLUMNHEADERS__*
52    constants as keys.
53
54    Args:
55      values_and_counts_dict: dictionary mapping each possible column value
56          to its count (how many entries in the column have this value), or
57          None if this information is not available.
58    """
59    asdict = {
60        KEY__EXTRACOLUMNHEADERS__HEADER_TEXT: self._header_text,
61        KEY__EXTRACOLUMNHEADERS__IS_FILTERABLE: self._is_filterable,
62        KEY__EXTRACOLUMNHEADERS__IS_SORTABLE: self._is_sortable,
63        KEY__EXTRACOLUMNHEADERS__USE_FREEFORM_FILTER: self._use_freeform_filter,
64    }
65    if self._header_url:
66      asdict[KEY__EXTRACOLUMNHEADERS__HEADER_URL] = self._header_url
67    if values_and_counts_dict:
68      asdict[KEY__EXTRACOLUMNHEADERS__VALUES_AND_COUNTS] = sorted(
69          values_and_counts_dict.items())
70    return asdict
71