srcset 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- srcset/__init__.py +26 -0
- srcset/__main__.py +10 -0
- srcset/_build.py +57 -0
- srcset/_calc.py +142 -0
- srcset/_cli.py +78 -0
- srcset/_css_reader.py +98 -0
- srcset/_css_tokens.py +152 -0
- srcset/_css_values.py +113 -0
- srcset/_descriptors.py +57 -0
- srcset/_math_functions.py +81 -0
- srcset/_media.py +130 -0
- srcset/_media_features.py +115 -0
- srcset/_model.py +111 -0
- srcset/_numbers.py +62 -0
- srcset/_parse.py +32 -0
- srcset/_scan.py +85 -0
- srcset/_select.py +81 -0
- srcset/_sizes.py +102 -0
- srcset/_validate.py +111 -0
- srcset/py.typed +0 -0
- srcset-0.2.0.dist-info/METADATA +198 -0
- srcset-0.2.0.dist-info/RECORD +25 -0
- srcset-0.2.0.dist-info/WHEEL +4 -0
- srcset-0.2.0.dist-info/entry_points.txt +2 -0
- srcset-0.2.0.dist-info/licenses/LICENSE +21 -0
srcset/_select.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Create a source set and pick an image from it (WHATWG HTML 4.8.4.3.7 to 4.8.4.3.12)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
|
|
7
|
+
from ._model import Environment, ImageSource
|
|
8
|
+
from ._parse import parse
|
|
9
|
+
from ._sizes import parse_sizes
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def source_set(
|
|
13
|
+
srcset: str,
|
|
14
|
+
environment: Environment,
|
|
15
|
+
*,
|
|
16
|
+
sizes: str = "",
|
|
17
|
+
src: str = "",
|
|
18
|
+
auto_width: float | None = None,
|
|
19
|
+
) -> list[ImageSource]:
|
|
20
|
+
"""The normalized source set: every candidate with the pixel density it stands for.
|
|
21
|
+
|
|
22
|
+
A width candidate gets ``width / size`` where the size comes from ``sizes``; a bare
|
|
23
|
+
candidate is ``1x``. ``src`` joins as ``1x`` when nothing else is ``1x`` and no candidate
|
|
24
|
+
has a width. Later entries with a density already present are dropped.
|
|
25
|
+
"""
|
|
26
|
+
if not isinstance(src, str):
|
|
27
|
+
raise TypeError(f"src must be a str, got {type(src).__name__}")
|
|
28
|
+
candidates = parse(srcset)
|
|
29
|
+
size = parse_sizes(sizes, environment, auto_width=auto_width)
|
|
30
|
+
sources: list[ImageSource] = []
|
|
31
|
+
has_one = any(candidate.density == 1 for candidate in candidates)
|
|
32
|
+
has_width = any(candidate.width is not None for candidate in candidates)
|
|
33
|
+
for candidate in candidates:
|
|
34
|
+
if candidate.density is not None:
|
|
35
|
+
density = candidate.density
|
|
36
|
+
elif candidate.width is not None:
|
|
37
|
+
density = _ratio(candidate.width, size)
|
|
38
|
+
else:
|
|
39
|
+
density = 1.0
|
|
40
|
+
sources.append(ImageSource(candidate.url, density))
|
|
41
|
+
if src and not has_one and not has_width:
|
|
42
|
+
sources.append(ImageSource(src, 1.0))
|
|
43
|
+
seen: set[float] = set()
|
|
44
|
+
unique: list[ImageSource] = []
|
|
45
|
+
for source in sources:
|
|
46
|
+
if source.density not in seen:
|
|
47
|
+
seen.add(source.density)
|
|
48
|
+
unique.append(source)
|
|
49
|
+
return unique
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def select(
|
|
53
|
+
srcset: str,
|
|
54
|
+
environment: Environment,
|
|
55
|
+
*,
|
|
56
|
+
sizes: str = "",
|
|
57
|
+
src: str = "",
|
|
58
|
+
auto_width: float | None = None,
|
|
59
|
+
) -> ImageSource | None:
|
|
60
|
+
"""The image a browser would fetch, or ``None`` when there is no candidate at all.
|
|
61
|
+
|
|
62
|
+
The standard leaves the final choice to the browser; this picks the lowest density
|
|
63
|
+
that covers ``environment.density`` and, when none does, the highest density, which
|
|
64
|
+
is what browsers do on a first load.
|
|
65
|
+
"""
|
|
66
|
+
sources = source_set(srcset, environment, sizes=sizes, src=src, auto_width=auto_width)
|
|
67
|
+
if not sources:
|
|
68
|
+
return None
|
|
69
|
+
covering = [source for source in sources if source.density >= environment.density]
|
|
70
|
+
if covering:
|
|
71
|
+
return min(covering, key=lambda source: source.density)
|
|
72
|
+
return max(sources, key=lambda source: source.density)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _ratio(width: int, size: float) -> float:
|
|
76
|
+
if not size:
|
|
77
|
+
return math.inf
|
|
78
|
+
try:
|
|
79
|
+
return width / size
|
|
80
|
+
except OverflowError:
|
|
81
|
+
return math.inf
|
srcset/_sizes.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Parse a sizes attribute (WHATWG HTML 4.8.4.3.11) into a width in CSS pixels."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from collections.abc import Iterator
|
|
7
|
+
from typing import NamedTuple
|
|
8
|
+
|
|
9
|
+
from ._calc import quantity
|
|
10
|
+
from ._css_reader import Token
|
|
11
|
+
from ._css_values import Value, comma_separated, ident, strip
|
|
12
|
+
from ._media import Invalid, evaluate
|
|
13
|
+
from ._model import Environment, SrcsetError
|
|
14
|
+
|
|
15
|
+
AUTO = "auto"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class SourceSize(NamedTuple):
|
|
19
|
+
"""One entry of a sizes list: its size (``None`` when invalid) and its condition."""
|
|
20
|
+
|
|
21
|
+
size: float | str | None
|
|
22
|
+
condition: list[Value]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def source_size_value(value: Value, env: Environment) -> float | str | None:
|
|
26
|
+
"""A ``<source-size-value>``: px for a length, ``"auto"``, or ``None`` when invalid.
|
|
27
|
+
|
|
28
|
+
A literal must not be negative; a math function result is clamped at zero, as CSS
|
|
29
|
+
clamps it for a property that takes no negative lengths.
|
|
30
|
+
"""
|
|
31
|
+
if ident(value, AUTO) is not None:
|
|
32
|
+
return AUTO
|
|
33
|
+
found = quantity(value, env)
|
|
34
|
+
if found is None:
|
|
35
|
+
return None
|
|
36
|
+
number, is_length = found
|
|
37
|
+
if not is_length:
|
|
38
|
+
literal = isinstance(value, Token) and value.kind == "number"
|
|
39
|
+
return 0.0 if literal and number == 0 else None
|
|
40
|
+
if isinstance(value, Token):
|
|
41
|
+
return None if number < 0 else number + 0.0
|
|
42
|
+
return max(number, 0.0)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def entries(value: str, env: Environment) -> Iterator[SourceSize]:
|
|
46
|
+
"""Each comma-separated entry with its trailing size split off."""
|
|
47
|
+
for group in comma_separated(value):
|
|
48
|
+
group = strip(group)
|
|
49
|
+
if not group:
|
|
50
|
+
yield SourceSize(None, [])
|
|
51
|
+
continue
|
|
52
|
+
yield SourceSize(source_size_value(group[-1], env), strip(group[:-1]))
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def parse_sizes(value: str, environment: Environment, *, auto_width: float | None = None) -> float:
|
|
56
|
+
"""The layout width in CSS pixels that a sizes attribute gives for an environment.
|
|
57
|
+
|
|
58
|
+
Entries are tried in order; the first valid size whose media condition is true wins,
|
|
59
|
+
and ``100vw`` is the fallback. ``auto`` stands for ``auto_width`` when one is given
|
|
60
|
+
and the value is ``auto`` or starts with ``auto,`` (an image that allows auto-sizes,
|
|
61
|
+
rendered at that width); otherwise it is skipped.
|
|
62
|
+
"""
|
|
63
|
+
if not isinstance(value, str):
|
|
64
|
+
raise TypeError(f"sizes value must be a str, got {type(value).__name__}")
|
|
65
|
+
if not isinstance(environment, Environment):
|
|
66
|
+
raise TypeError("environment must be an Environment")
|
|
67
|
+
auto_width = _check_width(auto_width) if allows_auto(value) else None
|
|
68
|
+
for entry in entries(value, environment):
|
|
69
|
+
size = entry.size
|
|
70
|
+
if size == AUTO and auto_width is not None:
|
|
71
|
+
size = auto_width
|
|
72
|
+
if size is None:
|
|
73
|
+
continue
|
|
74
|
+
if entry.condition:
|
|
75
|
+
try:
|
|
76
|
+
matched = evaluate(entry.condition, environment)
|
|
77
|
+
except Invalid:
|
|
78
|
+
continue
|
|
79
|
+
if matched is not True:
|
|
80
|
+
continue
|
|
81
|
+
if size != AUTO:
|
|
82
|
+
return float(size)
|
|
83
|
+
return environment.width
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def allows_auto(value: str) -> bool:
|
|
87
|
+
"""True when the raw value is ``auto`` or starts with ``auto,`` (ASCII any case)."""
|
|
88
|
+
head = value[:5].translate(_ASCII_LOWER)
|
|
89
|
+
return head == AUTO or head == AUTO + ","
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
_ASCII_LOWER = str.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _check_width(width: float | None) -> float | None:
|
|
96
|
+
if width is None:
|
|
97
|
+
return None
|
|
98
|
+
if isinstance(width, bool) or not isinstance(width, (int, float)):
|
|
99
|
+
raise TypeError(f"auto_width must be a number, got {type(width).__name__}")
|
|
100
|
+
if not math.isfinite(width) or width < 0:
|
|
101
|
+
raise SrcsetError(f"auto_width must be finite and not negative, got {width}")
|
|
102
|
+
return float(width)
|
srcset/_validate.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Authoring checks for srcset and sizes (WHATWG HTML 4.8.4.2.1 and 4.8.4.2.2).
|
|
2
|
+
|
|
3
|
+
Browsers forgive a lot; these checks report what the standard asks authors not to write.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from collections import Counter
|
|
9
|
+
from collections.abc import Callable, Sequence
|
|
10
|
+
from typing import TypeVar
|
|
11
|
+
|
|
12
|
+
from ._media import Invalid, evaluate
|
|
13
|
+
from ._model import Candidate, Environment, Issue
|
|
14
|
+
from ._numbers import format_density, int_text
|
|
15
|
+
from ._parse import to_candidate
|
|
16
|
+
from ._scan import WHITESPACE, RawCandidate, scan
|
|
17
|
+
from ._sizes import AUTO, SourceSize, allows_auto, entries
|
|
18
|
+
|
|
19
|
+
T = TypeVar("T", int, float)
|
|
20
|
+
|
|
21
|
+
# Any environment works: validity never depends on the viewport.
|
|
22
|
+
_PROBE = Environment(width=1000, height=1000)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def validate(srcset: str, sizes: str | None = None) -> list[Issue]:
|
|
26
|
+
"""List the authoring errors in a srcset value and, if given, its sizes value.
|
|
27
|
+
|
|
28
|
+
``sizes=None`` means the attribute is absent. An empty list means the pair conforms.
|
|
29
|
+
"""
|
|
30
|
+
if not isinstance(srcset, str):
|
|
31
|
+
raise TypeError(f"srcset value must be a str, got {type(srcset).__name__}")
|
|
32
|
+
if sizes is not None and not isinstance(sizes, str):
|
|
33
|
+
raise TypeError(f"sizes value must be a str or None, got {type(sizes).__name__}")
|
|
34
|
+
issues: list[Issue] = []
|
|
35
|
+
candidates: list[Candidate] = []
|
|
36
|
+
for raw in scan(srcset):
|
|
37
|
+
stray = raw if isinstance(raw, int) else raw.stray_commas
|
|
38
|
+
if stray:
|
|
39
|
+
issues.append(Issue("extra-comma", "a comma with no image candidate before it"))
|
|
40
|
+
elif isinstance(raw, int) and srcset.rstrip(WHITESPACE).endswith(","):
|
|
41
|
+
issues.append(Issue("extra-comma", "a comma after the last image candidate"))
|
|
42
|
+
if isinstance(raw, RawCandidate):
|
|
43
|
+
if raw.trailing_commas > 1:
|
|
44
|
+
issues.append(Issue("extra-comma", f"more than one comma after {raw.url!r:.80}"))
|
|
45
|
+
candidate = to_candidate(raw)
|
|
46
|
+
if candidate is None:
|
|
47
|
+
text = " ".join(raw.tokens)
|
|
48
|
+
issues.append(Issue("invalid-descriptor", f"{raw.url!r:.80} {text!r:.80}"))
|
|
49
|
+
else:
|
|
50
|
+
candidates.append(candidate)
|
|
51
|
+
issues.extend(_candidate_issues(candidates, sizes))
|
|
52
|
+
if sizes is not None:
|
|
53
|
+
issues.extend(_sizes_issues(sizes))
|
|
54
|
+
return issues
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _candidate_issues(candidates: list[Candidate], sizes: str | None) -> list[Issue]:
|
|
58
|
+
if not candidates:
|
|
59
|
+
return [Issue("empty", "srcset needs at least one image candidate")]
|
|
60
|
+
issues: list[Issue] = []
|
|
61
|
+
widths = [c.width for c in candidates if c.width is not None]
|
|
62
|
+
densities = [1.0 if c.density is None else c.density for c in candidates if not c.width]
|
|
63
|
+
issues.extend(_duplicates("width", widths, int_text))
|
|
64
|
+
issues.extend(_duplicates("density", densities, lambda d: format_density(d)[:-1]))
|
|
65
|
+
if any(c.density == 0 for c in candidates):
|
|
66
|
+
issues.append(Issue("zero-density", "a density descriptor must be greater than zero"))
|
|
67
|
+
if any(c.height is not None for c in candidates):
|
|
68
|
+
issues.append(Issue("height-descriptor", "the h descriptor is reserved, not standard"))
|
|
69
|
+
if widths and len(widths) != len(candidates):
|
|
70
|
+
issues.append(Issue("mixed-descriptors", "if one candidate has a width, all must"))
|
|
71
|
+
if sizes is not None and len(widths) != len(candidates):
|
|
72
|
+
issues.append(Issue("sizes-without-width", "with sizes, every candidate needs a width"))
|
|
73
|
+
if sizes is None and widths:
|
|
74
|
+
issues.append(Issue("missing-sizes", "width descriptors need a sizes attribute"))
|
|
75
|
+
return issues
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _duplicates(kind: str, values: Sequence[T], text: Callable[[T], str]) -> list[Issue]:
|
|
79
|
+
counts = Counter(values)
|
|
80
|
+
return [
|
|
81
|
+
Issue(f"duplicate-{kind}", f"{count} candidates share the {kind} {text(value):.80}")
|
|
82
|
+
for value, count in counts.items()
|
|
83
|
+
if count > 1
|
|
84
|
+
]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _sizes_issues(sizes: str) -> list[Issue]:
|
|
88
|
+
found = list(entries(sizes, _PROBE))
|
|
89
|
+
issues: list[Issue] = []
|
|
90
|
+
for index, entry in enumerate(found):
|
|
91
|
+
where = f"sizes entry {index + 1}"
|
|
92
|
+
last = index == len(found) - 1
|
|
93
|
+
if entry.size is None:
|
|
94
|
+
issues.append(Issue("invalid-sizes", f"{where} does not end with a valid length"))
|
|
95
|
+
elif entry.size == AUTO and (index or entry.condition or not allows_auto(sizes)):
|
|
96
|
+
issues.append(Issue("invalid-sizes", f"{where}: auto must open the value as auto,"))
|
|
97
|
+
elif last and entry.condition:
|
|
98
|
+
issues.append(Issue("invalid-sizes", f"{where}: the last entry takes no condition"))
|
|
99
|
+
elif not last and not entry.condition and entry.size != AUTO:
|
|
100
|
+
issues.append(Issue("invalid-sizes", f"{where} needs a media condition"))
|
|
101
|
+
elif entry.condition and not _parses(entry):
|
|
102
|
+
issues.append(Issue("invalid-sizes", f"{where} has an invalid media condition"))
|
|
103
|
+
return issues
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _parses(entry: SourceSize) -> bool:
|
|
107
|
+
try:
|
|
108
|
+
evaluate(entry.condition, _PROBE, strict=True)
|
|
109
|
+
except Invalid:
|
|
110
|
+
return False
|
|
111
|
+
return True
|
srcset/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: srcset
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Parse, build, check and resolve the HTML srcset and sizes attributes like a browser
|
|
5
|
+
Project-URL: Homepage, https://lianes8studio.com
|
|
6
|
+
Project-URL: Repository, https://github.com/JaviLianes8/srcset
|
|
7
|
+
Project-URL: Issues, https://github.com/JaviLianes8/srcset/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/JaviLianes8/srcset/blob/main/CHANGELOG.md
|
|
9
|
+
Project-URL: LinkedIn, https://www.linkedin.com/in/jlianes/
|
|
10
|
+
Project-URL: Funding, https://buymeacoffee.com/jlianesglrs
|
|
11
|
+
Author-email: Javier Lianes <javier@lianes8studio.com>
|
|
12
|
+
License-Expression: MIT
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Keywords: html,image,media-queries,parser,picture,responsive-images,sizes,srcset,whatwg
|
|
15
|
+
Classifier: Development Status :: 4 - Beta
|
|
16
|
+
Classifier: Environment :: Console
|
|
17
|
+
Classifier: Intended Audience :: Developers
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Programming Language :: Python :: 3
|
|
20
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
26
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
|
|
27
|
+
Classifier: Topic :: Text Processing :: Markup :: HTML
|
|
28
|
+
Classifier: Typing :: Typed
|
|
29
|
+
Requires-Python: >=3.10
|
|
30
|
+
Provides-Extra: dev
|
|
31
|
+
Requires-Dist: build; extra == 'dev'
|
|
32
|
+
Requires-Dist: mypy; extra == 'dev'
|
|
33
|
+
Requires-Dist: pytest; extra == 'dev'
|
|
34
|
+
Requires-Dist: ruff; extra == 'dev'
|
|
35
|
+
Requires-Dist: twine; extra == 'dev'
|
|
36
|
+
Description-Content-Type: text/markdown
|
|
37
|
+
|
|
38
|
+
# srcset
|
|
39
|
+
|
|
40
|
+
Parse, build, check and resolve the HTML `srcset` and `sizes` attributes with the WHATWG
|
|
41
|
+
algorithms, checked against the web-platform-tests cases browsers run: which candidates
|
|
42
|
+
survive, what layout width `sizes` gives, and which image a browser fetches for a viewport
|
|
43
|
+
and a device pixel ratio.
|
|
44
|
+
|
|
45
|
+
## Install
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
pip install srcset
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Python 3.10 or newer, no dependencies.
|
|
52
|
+
|
|
53
|
+
## Usage
|
|
54
|
+
|
|
55
|
+
Parse a `srcset` value into typed candidates. Invalid candidates are dropped, as browsers
|
|
56
|
+
drop them, and a comma inside a URL (a data URI, for example) does not split the list:
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from srcset import Candidate, build, parse
|
|
60
|
+
|
|
61
|
+
candidates = parse("small.png 1x, large.png 2x, data:image/png;base64,iVBO 3x")
|
|
62
|
+
print([c.url for c in candidates])
|
|
63
|
+
# ['small.png', 'large.png', 'data:image/png;base64,iVBO']
|
|
64
|
+
print(parse("hero.jpg 800w, bad.jpg 1.x"))
|
|
65
|
+
# [Candidate(url='hero.jpg', width=800, density=None, height=None)]
|
|
66
|
+
print(build([Candidate("a.png", 320), ("b.png", "2x")]))
|
|
67
|
+
# a.png 320w, b.png 2x
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Resolve `sizes` and pick the image a browser would load:
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from srcset import Environment, parse_sizes, select
|
|
74
|
+
|
|
75
|
+
phone = Environment(width=390, height=844, density=3)
|
|
76
|
+
sizes = "(min-width: 1024px) 33vw, calc(100vw - 2rem)"
|
|
77
|
+
print(parse_sizes(sizes, phone))
|
|
78
|
+
# 358.0
|
|
79
|
+
srcset = "s.jpg 480w, m.jpg 960w, l.jpg 1440w"
|
|
80
|
+
print(select(srcset, phone, sizes=sizes))
|
|
81
|
+
# ImageSource(url='l.jpg', density=4.022346368715084)
|
|
82
|
+
print(select(srcset, Environment(width=1440), sizes=sizes).url)
|
|
83
|
+
# s.jpg
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Check what authors wrote:
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
from srcset import validate
|
|
90
|
+
|
|
91
|
+
for issue in validate("a.jpg 400w, b.jpg 400w, c.jpg 2x", sizes="100vw"):
|
|
92
|
+
print(issue.code)
|
|
93
|
+
# duplicate-width
|
|
94
|
+
# mixed-descriptors
|
|
95
|
+
# sizes-without-width
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Command line
|
|
99
|
+
|
|
100
|
+
```
|
|
101
|
+
$ srcset parse "a.png 100w 50h, b.png 2x"
|
|
102
|
+
[{"url": "a.png", "width": 100, "density": null, "height": 50}, {"url": "b.png", "width": null, "density": 2.0, "height": null}]
|
|
103
|
+
$ srcset select "s.jpg 480w, l.jpg 1440w" --sizes "50vw" --width 1280 --dpr 2
|
|
104
|
+
l.jpg
|
|
105
|
+
$ srcset check "a.png 1x,, b.png 1x"
|
|
106
|
+
extra-comma: a comma with no image candidate before it
|
|
107
|
+
duplicate-density: 2 candidates share the density 1
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`select` takes `--sizes`, `--src`, `--width` (1280 by default), `--height`, `--dpr` and
|
|
111
|
+
`--json`. `check` exits with status 1 when it finds an issue. `python -m srcset` works too.
|
|
112
|
+
|
|
113
|
+
## API
|
|
114
|
+
|
|
115
|
+
| Name | What it does |
|
|
116
|
+
| --- | --- |
|
|
117
|
+
| `parse(value)` | The candidates a browser keeps, as `Candidate` values. Never raises for malformed input. |
|
|
118
|
+
| `build(candidates)` | Serializes `Candidate` values or `(url, descriptor)` pairs; raises `SrcsetError` for anything that would not read back the same. |
|
|
119
|
+
| `parse_sizes(value, environment, *, auto_width=None)` | The layout width in CSS pixels, `100vw` when no entry applies. |
|
|
120
|
+
| `source_set(srcset, environment, *, sizes="", src="", auto_width=None)` | Every candidate as an `ImageSource` with the density it stands for, later duplicates removed. |
|
|
121
|
+
| `select(srcset, environment, *, sizes="", src="", auto_width=None)` | The `ImageSource` a browser would fetch, or `None`. |
|
|
122
|
+
| `validate(srcset, sizes=None)` | Authoring errors as `Issue` values; `sizes=None` means the attribute is absent. |
|
|
123
|
+
| `Candidate(url, width=None, density=None, height=None)` | A frozen candidate; `descriptor` gives its text, such as `320w` or `1.5x`. |
|
|
124
|
+
| `Environment(width, height=None, density=1.0, font_size=16.0)` | Viewport size in CSS pixels, device pixel ratio and root font size. |
|
|
125
|
+
| `ImageSource(url, density)` | A named tuple from a normalized source set. |
|
|
126
|
+
| `Issue(code, message)` | A named tuple with a stable code. |
|
|
127
|
+
| `SrcsetError` | A `ValueError` for values that cannot be built or are out of range. Wrong types raise `TypeError`. |
|
|
128
|
+
|
|
129
|
+
## Behaviour
|
|
130
|
+
|
|
131
|
+
- **Descriptors.** A width is a valid non-negative integer above zero followed by `w`; a
|
|
132
|
+
density is a valid HTML floating-point number followed by `x` (`.5x` and `1e1x` are fine,
|
|
133
|
+
`1.x`, `+1x` and `1X` are not), with only ASCII digits. `0x` is kept, as browsers keep it.
|
|
134
|
+
The `h` descriptor is accepted only next to a width. Two descriptors of one kind, or a
|
|
135
|
+
width with a density, drop the candidate.
|
|
136
|
+
- **Sizes.** Entries are read with a CSS tokenizer (comments, escapes, unclosed blocks).
|
|
137
|
+
Lengths cover the absolute units, `em`, `rem`, and the viewport units with their `s`, `l`
|
|
138
|
+
and `d` forms. Math functions: `calc`, `min`, `max`, `clamp`, `abs`, `sign`, `round`,
|
|
139
|
+
`mod`, `rem`, `hypot`, `sqrt`, `pow`, `exp` and `log`, with the constants `e` and `pi`.
|
|
140
|
+
A negative literal is invalid and a negative math result becomes 0. A result that is
|
|
141
|
+
infinite or not a number (division by zero, for example) makes the entry invalid, which
|
|
142
|
+
is what the web-platform-tests expect from browsers. `ex`, `ch`, `cap`, `ic` and `lh` use
|
|
143
|
+
fixed ratios of the font size, because the real values depend on the font. Blocks nested
|
|
144
|
+
more than 32 deep make their entry invalid.
|
|
145
|
+
- **Media conditions.** `not`, `and`, `or`, nesting, the `min-` and `max-` forms and range
|
|
146
|
+
syntax such as `(400px <= width < 800px)`, for `width`, `height`, `aspect-ratio`,
|
|
147
|
+
`orientation` and `resolution` (including `infinite`). Other features, and media types such as `screen`, never
|
|
148
|
+
match: the first are unknown under the three-valued logic of Media Queries 4, the second
|
|
149
|
+
are not allowed in `sizes`. A height-based condition is unknown while
|
|
150
|
+
`Environment.height` is `None`.
|
|
151
|
+
- **`auto`.** When the value is `auto` or starts with `auto,` (any ASCII case), `auto`
|
|
152
|
+
stands for `auto_width` if one is given: an image that allows auto-sizes, rendered at
|
|
153
|
+
that width. Otherwise it is skipped and the next entry applies.
|
|
154
|
+
- **Selection.** The standard leaves the final pick to the browser. `select` takes the
|
|
155
|
+
lowest density that covers `environment.density`, or the highest density when none
|
|
156
|
+
does; this is the usual policy and it reproduces every web-platform-tests selection
|
|
157
|
+
case. Width candidates with a zero size get an infinite density.
|
|
158
|
+
- **Issue codes.** `empty`, `extra-comma`, `invalid-descriptor`, `duplicate-width`,
|
|
159
|
+
`duplicate-density`, `zero-density`, `height-descriptor`, `mixed-descriptors`,
|
|
160
|
+
`sizes-without-width`, `missing-sizes` and `invalid-sizes`.
|
|
161
|
+
|
|
162
|
+
## Why
|
|
163
|
+
|
|
164
|
+
The `srcset` syntax looks like a comma-separated list, yet a URL may contain commas, so a
|
|
165
|
+
naive `split(",")` corrupts it. And reading the attribute is only half the job: knowing
|
|
166
|
+
which file a phone downloads takes the `sizes` attribute, which is CSS (lengths, `calc`,
|
|
167
|
+
media conditions), and the density arithmetic that ties the two together. This library
|
|
168
|
+
implements the WHATWG algorithms for all three steps, typed and without dependencies, and
|
|
169
|
+
checks itself against the web-platform-tests cases that browsers run.
|
|
170
|
+
|
|
171
|
+
## Standards
|
|
172
|
+
|
|
173
|
+
- WHATWG HTML: parsing a srcset attribute, parsing a sizes attribute, creating and
|
|
174
|
+
normalizing a source set, and the srcset and sizes authoring requirements
|
|
175
|
+
(https://html.spec.whatwg.org/multipage/images.html).
|
|
176
|
+
- CSS Syntax 3 (https://drafts.csswg.org/css-syntax-3/) and Media Queries 4
|
|
177
|
+
(https://drafts.csswg.org/mediaqueries-4/).
|
|
178
|
+
|
|
179
|
+
## Development
|
|
180
|
+
|
|
181
|
+
```
|
|
182
|
+
pip install -r requirements-dev.txt
|
|
183
|
+
python scripts/fetch_upstream.py # optional: the web-platform-tests files
|
|
184
|
+
pwsh scripts/check.ps1
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
The web-platform-tests files are not part of the repository; `tests/upstream/MANIFEST.json`
|
|
188
|
+
records where they come from, and their tests skip until the script has fetched them.
|
|
189
|
+
|
|
190
|
+
## License
|
|
191
|
+
|
|
192
|
+
MIT. See [LICENSE](LICENSE).
|
|
193
|
+
|
|
194
|
+
## Links
|
|
195
|
+
|
|
196
|
+
- Website: https://lianes8studio.com
|
|
197
|
+
- GitHub: https://github.com/JaviLianes8
|
|
198
|
+
- LinkedIn: https://www.linkedin.com/in/jlianes/
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
srcset/__init__.py,sha256=mRvb6Tq81q24PTN8Rdyf8IgbDIDNYAmp-5aW0j8dKvU,578
|
|
2
|
+
srcset/__main__.py,sha256=E269lrSfdoZfx2SECKG1HG0s0WsanjpBTEyi-0rmcrI,155
|
|
3
|
+
srcset/_build.py,sha256=oDipK6wsHDHoBTo9CD0vM1FPwUVSGtv-xi49bOjzloI,2408
|
|
4
|
+
srcset/_calc.py,sha256=ir32dvX6vs461XJIv5OAVp0U-RVQ3-mJ1p8Q-DW_FwA,5578
|
|
5
|
+
srcset/_cli.py,sha256=ZSPz1L0FJnn7BV0U2bhjbON8OWJTN7qE3gOAEu5yysM,3186
|
|
6
|
+
srcset/_css_reader.py,sha256=2-IrE57lqo4Mocq7CEGjLrBvmAmdPkZDPbhVO8C5maM,3102
|
|
7
|
+
srcset/_css_tokens.py,sha256=sinIpBtAdX6SEZU9nfecdFuWvBb4ku2tH1mdMDLFrZA,5133
|
|
8
|
+
srcset/_css_values.py,sha256=CM1_hR1HKiFCpH6LQkw0T4mpHnCnNSxmsFXtoGLD5t0,3468
|
|
9
|
+
srcset/_descriptors.py,sha256=me7RAjXRM4_DDJ5qLZ4pglazHqkzDkknFKEMe3dTdZk,1973
|
|
10
|
+
srcset/_math_functions.py,sha256=iOuz6H2qHuPyxuS6CX77xXBwokynDbb4ublsvKLvB6g,3265
|
|
11
|
+
srcset/_media.py,sha256=y0dnRleYXr4IaVrWcEFo9wsmkUELIvgXugdOab-BKgQ,5041
|
|
12
|
+
srcset/_media_features.py,sha256=V8KAHb2Ynb8zBPLNmVqQGKByd8szUd9qsEGMBI2-wXk,4045
|
|
13
|
+
srcset/_model.py,sha256=LY8P61EsblNa2w5R3QUU66UDXtuhlG4eOMOs-_FSoMA,3934
|
|
14
|
+
srcset/_numbers.py,sha256=obgxN7RfF977CyBfgoNj-D85QdA-4gvnApij3I9Jy4E,2052
|
|
15
|
+
srcset/_parse.py,sha256=0jWDEGybQz70hJd1TB5jSm1dMJ4D_k67yautYXMS6nc,1196
|
|
16
|
+
srcset/_scan.py,sha256=Asudkr8Fj7xM2hO-xpo2yPLqzKRRtiqsN6GnRuqYIK0,2917
|
|
17
|
+
srcset/_select.py,sha256=g9xq1SG2SgxbMKIpdwr3_yUboKyQFwnHuERJQstR3F8,2792
|
|
18
|
+
srcset/_sizes.py,sha256=pwdlq0M6T0hNJDFqwpdwq8oPiNO-GF62PtcceDGHHqE,3766
|
|
19
|
+
srcset/_validate.py,sha256=hCP2DsofQ4fVqvt42CmrTgfTt6i6iW-me2s-tb7zW14,5021
|
|
20
|
+
srcset/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
21
|
+
srcset-0.2.0.dist-info/METADATA,sha256=_-03lFcLQN5EGWtlShdpJkdSlVGVX9xS5aV-hn0nwmc,9218
|
|
22
|
+
srcset-0.2.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
23
|
+
srcset-0.2.0.dist-info/entry_points.txt,sha256=smKxmIcXTY-2YYiv6j5JLhuYI9ZD4rbRPPSlWGbhwPs,44
|
|
24
|
+
srcset-0.2.0.dist-info/licenses/LICENSE,sha256=wirD5nCA2aQa5UusK_1YHLBogI3CGcw23xAnulp3L_U,1091
|
|
25
|
+
srcset-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Javier Lianes
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|