Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ Callers get Igniter's normal diff preview and confirmation flow.
| | |
|---|---|
| `ensure_at_rule/3`, `remove_at_rule/4` | `@import`, `@plugin`, `@source`, `@layer`, … |
| `remove_at_rules/3` | at-rules `list_at_rules/2` found, at any depth |
| `ensure_at_rule_block/5`, `ensure_at_rule_declarations/5`, `remove_at_rule_declarations/5` | at-rule blocks: a whole body, or only the declarations you own in a shared one such as `@theme` |
| `add_import/4`, `remove_import/3` | `@import` convenience wrappers |
| `ensure_rule/4`, `remove_rule/3` | whole rules |
Expand All @@ -112,9 +113,9 @@ Callers get Igniter's normal diff preview and confirmation flow.
| `sort_properties/2`, `remove_duplicates/2` | tidying, by moving and deleting whole lines |

**Queries** — read-only: `has_rule?/3`, `has_declaration?/4`, `has_at_rule?/3`,
`get_declaration/4`, `get_rule_declarations/3`, `get_at_rules/4`,
`get_declaration/4`, `get_rule_declarations/3`, `get_at_rules/4`, `list_at_rules/2`,
`list_selectors/2`, `analyze/2`,
`validate/2`, `extract_colors/2`, `extract_media_queries/2`,
`validate/2`, `validate_block/2`, `extract_colors/2`, `extract_media_queries/2`,
`extract_animations/2`.

**Whole-file transforms** (`IgniterCss.Transform`) — `minify/2`, `beautify/2`,
Expand Down
101 changes: 97 additions & 4 deletions lib/igniter_css.ex
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,53 @@ defmodule IgniterCss do
Native.get_at_rules_nif(source, name, matching, ParseOpts.new(opts)) |> unwrap()
end

@doc """
Every at-rule in the file, as `IgniterCss.AtRule` structs in source order,
wherever it is: nested in `@media`, `@layer`, a rule or another at-rule's
block, and where the parser could not place one, such as an `@import` inside
`@font-face` or a keyframe. Biome keeps that one as bogus tokens, but a reader
with a looser grammar, Tailwind for one, still acts on it, so it is here too,
running from its `@` to the `;` or the block that ends it.

An `@` inside a string, a comment or a `url()` starts nothing. The name keeps
any escape as written (`@\\69mport` is named `\\69mport`).

For a caller that must know everything a stylesheet asks for, such as one
that keeps a build tool from reading files; the codemods stay top-level.

iex> css = ~s|@media print {\\n @import "a.css";\\n}\\n@font-face { @plugin "p"; }\\n|
iex> {:ok, rules} = IgniterCss.list_at_rules(css)
iex> Enum.map(rules, &{&1.name, &1.target})
[{"media", nil}, {"import", "a.css"}, {"font-face", nil}, {"plugin", "p"}]
"""
@spec list_at_rules(String.t(), opts()) ::
{:ok, [IgniterCss.AtRule.t()]} | {:error, String.t()}
def list_at_rules(source, opts \\ []) do
Native.list_at_rules_nif(source, ParseOpts.new(opts)) |> unwrap()
end

@doc """
Remove, wherever it is, every at-rule written exactly as one of `at_rules`:
at-rules `list_at_rules/2` returned for this `source`, read with the same
`opts`. One inside another being removed goes with it, and the comments a
removed at-rule owns go too, as with `remove_at_rule/4`.

Matched on the at-rule's text, so a second run on the output finds nothing
and reports `changed: false`.

iex> css = ~s|@media print {\\n @import "a.css";\\n .a { color: red; }\\n}\\n|
iex> {:ok, rules} = IgniterCss.list_at_rules(css)
iex> {:ok, out} = IgniterCss.remove_at_rules(css, Enum.filter(rules, &(&1.name == "import")))
iex> out.source
~s|@media print {\\n .a { color: red; }\\n}\\n|
"""
@spec remove_at_rules(String.t(), [IgniterCss.AtRule.t()], opts()) :: result()
def remove_at_rules(source, at_rules, opts \\ []) when is_list(at_rules) do
source
|> Native.remove_at_rules_nif(Enum.map(at_rules, & &1.text), ParseOpts.new(opts))
|> unwrap()
end

@doc """
Add an `@import`, building the line for you.

Expand Down Expand Up @@ -502,10 +549,53 @@ defmodule IgniterCss do
"""
@spec validate(String.t(), opts()) :: {:ok, Validation.t()} | {:error, Validation.t()}
def validate(source, opts \\ []) do
case Native.validate_nif(source, ParseOpts.new(opts)) do
{:ok, _fun, validation} -> {:ok, validation}
{:error, _fun, validation} -> {:error, validation}
end
Native.validate_nif(source, ParseOpts.new(opts)) |> validation()
end

@doc """
Is `body` valid as the contents of one rule's block?

What an editor that styles one element takes: declarations, nested rules
such as `&:hover { … }`, and at-rules such as `@media (…) { … }` or Tailwind's
`@apply`. It is read as the parser reads a block, by putting it inside one,
and every error is placed by line and column in `body` itself.

On top of what `validate/2` checks, a `}` that closes the block the body is
written in is an error, though what follows it may parse: in a stylesheet,
everything after it would be outside the block.

No error points past the body or names the block it is put in. A body that
ends in the middle of a statement has one error on that statement, and one
that leaves a block open has one where its `}` is missing. A declaration
with no `:`, which the parser reads as a nested rule, is named as one. A
string with no closing quote keeps the parser's own error, whatever it
misreads after it. A message quotes the author's text on one line, a line
break in it written `\\n`.

Returns `{:ok, %IgniterCss.Validation{}}` or `{:error, %IgniterCss.Validation{}}`.

iex> {:ok, v} = IgniterCss.validate_block("padding: 4px;\\n&:hover { color: red; }")
iex> v.errors
[]

iex> {:error, v} = IgniterCss.validate_block("gap: 1px;\\ncolor: red background: blue;")
iex> [%IgniterCss.Diagnostic{line: 2, column: 22, text: ": blue"}] = v.errors
iex> v.valid
false

iex> {:error, v} = IgniterCss.validate_block("gap: 1px;\\ncolor crimson")
iex> [%IgniterCss.Diagnostic{line: 2, column: 1, text: "color crimson", message: message}] = v.errors
iex> message
"Expected a `:` after the property name `color`"

iex> {:error, v} = IgniterCss.validate_block("gap: 1px; } body { display: none; ")
iex> [%IgniterCss.Diagnostic{line: 1, column: 11, text: "}"}] = v.errors
iex> v.valid
false
"""
@spec validate_block(String.t(), opts()) :: {:ok, Validation.t()} | {:error, Validation.t()}
def validate_block(body, opts \\ []) do
Native.validate_block_nif(body, ParseOpts.new(opts)) |> validation()
end

@doc """
Expand Down Expand Up @@ -542,4 +632,7 @@ defmodule IgniterCss do

defp unwrap({:ok, _fun, value}), do: {:ok, value}
defp unwrap({:error, _fun, reason}), do: {:error, reason}

defp validation({:ok, _fun, validation}), do: {:ok, validation}
defp validation({:error, _fun, validation}), do: {:error, validation}
end
3 changes: 3 additions & 0 deletions lib/igniter_css/native.ex
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ defmodule IgniterCss.Native do
do: error()

def remove_at_rule_nif(_source, _name, _matching, _opts), do: error()
def remove_at_rules_nif(_source, _texts, _opts), do: error()
def has_at_rule_nif(_source, _line, _opts), do: error()
def add_import_nif(_source, _url, _media, _opts), do: error()
def remove_import_nif(_source, _url, _opts), do: error()
Expand Down Expand Up @@ -90,7 +91,9 @@ defmodule IgniterCss.Native do

def analyze_nif(_source, _opts), do: error()
def get_at_rules_nif(_source, _name, _matching, _opts), do: error()
def list_at_rules_nif(_source, _opts), do: error()
def validate_nif(_source, _opts), do: error()
def validate_block_nif(_body, _opts), do: error()
def extract_colors_nif(_source, _opts), do: error()
def extract_media_queries_nif(_source, _opts), do: error()
def extract_animations_nif(_source, _opts), do: error()
Expand Down
30 changes: 28 additions & 2 deletions lib/igniter_css/structs.ex
Original file line number Diff line number Diff line change
Expand Up @@ -111,16 +111,42 @@ defmodule IgniterCss.Validation do
checks before touching a file. A stylesheet that round-trips but has
diagnostics is still patchable; one that does not round-trip is not, and
`IgniterCss` will refuse rather than risk a wrong edit.

`errors` is the verdict, each placed by line and column: the parser's errors
less the ones it raises against valid CSS, such as a `:` in a custom
property's value or an `@apply` with no `;` written last in a block.
`diagnostics` counts what the parser raised before that.
"""

@type t :: %__MODULE__{
valid: boolean(),
diagnostics: non_neg_integer(),
round_trips: boolean(),
message: String.t()
message: String.t(),
errors: [IgniterCss.Diagnostic.t()]
}

defstruct valid: false, diagnostics: 0, round_trips: false, message: "", errors: []
end

defmodule IgniterCss.Diagnostic do
@moduledoc """
One reason CSS is not valid, placed in the text that was checked.

`line` and `column` are 1-based, the column counted in characters. `offset` is
the byte offset of `text`, the part of the source the error is about; `text`
is empty when the error is about the end of the source.
"""

@type t :: %__MODULE__{
message: String.t(),
line: pos_integer(),
column: pos_integer(),
offset: non_neg_integer(),
text: String.t()
}

defstruct valid: false, diagnostics: 0, round_trips: false, message: ""
defstruct message: "", line: 1, column: 1, offset: 0, text: ""
end

defmodule IgniterCss.AtRule do
Expand Down
1 change: 1 addition & 0 deletions native/igniter_css/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions native/igniter_css/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ crate-type = ["cdylib", "rlib"]
biome_css_parser = "=0.5.8"
biome_css_syntax = "=0.5.8"
biome_rowan = "=0.5.8"
# Already in the graph through biome_css_parser; named here only for the
# `Diagnostic` trait, which is how a parse error gives up its span.
biome_diagnostics = "=0.5.8"
rustler = "=0.38.0"

[dev-dependencies]
Expand Down
Loading
Loading