File: util.py

package info (click to toggle)
django-iconify 0.4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 168 kB
  • sloc: python: 462; makefile: 9
file content (51 lines) | stat: -rw-r--r-- 1,409 bytes parent folder | download | duplicates (2)
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
"""Utility code used by other parts of django-iconify."""
import os
import re

from .conf import COLLECTIONS_ALLOWED, COLLECTIONS_DISALLOWED, JSON_ROOT


def split_css_unit(string: str):
    """Split string into value and unit.

    >>> split_css_unit("12px")
    (12, 'px')
    >>> split_css_unit("1.5em")
    (1.5, 'em')
    >>> split_css_unit("18%")
    (18, '%')
    >>> split_css_unit("200")
    (200, '')
    """
    _value = re.findall("^[0-9.]+", string)
    value = float(_value[0]) if "." in _value[0] else int(_value[0])
    unit = string[len(_value[0]) :]

    return value, unit


def collection_allowed(collection: str) -> bool:
    """Determine whether a collection is allowed by settings."""

    if collection in COLLECTIONS_DISALLOWED:
        return False

    if COLLECTIONS_ALLOWED and collection not in COLLECTIONS_ALLOWED:
        return False

    return True


def icon_choices(collection: str) -> list[tuple[str, str]]:
    """Get Django model/form choices for icons in one collection."""

    from .types import IconifyJSON

    if not collection_allowed(collection):
        raise KeyError("The collection %s is disallowed." % collection)

    # Load icon set through Iconify types
    collection_file = os.path.join(JSON_ROOT, "json", f"{collection}.json")
    icon_set = IconifyJSON.from_file(collection_file)

    return [(name, name) for name in sorted(icon_set.icons.keys())]