Add fields method to content (#1340)

This commit is contained in:
MALO 2023-05-30 10:13:27 +02:00 committed by GitHub
parent b6b6666efd
commit 644bbf9914
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 28 additions and 2 deletions

View File

@ -604,6 +604,13 @@ field does not exist or fails with an error if no default value was specified.
A default value to return if the field does not exist.
- returns: any
### fields()
Return the fields of this content.
```example
#repr(rect(width: 10cm, height: 10cm).fields())
```
### location()
The location of the content. This is only available on content returned by
[query]($func/query), for other content it will fail with an error. The

View File

@ -81,6 +81,7 @@ pub fn call(
"at" => content
.at(&args.expect::<EcoString>("field")?, args.named("default")?)
.at(span)?,
"fields" => Value::Dict(content.dict()),
"location" => content
.location()
.ok_or("this method can only be called on content returned by query(..)")
@ -332,7 +333,13 @@ pub fn methods_on(type_name: &str) -> &[(&'static str, bool)] {
("starts-with", true),
("trim", true),
],
"content" => &[("func", false), ("has", true), ("at", true), ("location", false)],
"content" => &[
("func", false),
("has", true),
("at", true),
("fields", false),
("location", false),
],
"array" => &[
("all", true),
("any", true),

View File

@ -12,7 +12,7 @@ use super::{
};
use crate::diag::{SourceResult, StrResult};
use crate::doc::Meta;
use crate::eval::{Cast, Str, Value, Vm};
use crate::eval::{Cast, Dict, Str, Value, Vm};
use crate::syntax::Span;
use crate::util::pretty_array_like;
@ -251,6 +251,13 @@ impl Content {
.ok_or_else(|| missing_field_no_default(field))
}
/// Return the fields of the content as a dict.
pub fn dict(&self) -> Dict {
self.fields()
.map(|(key, value)| (key.to_owned().into(), value))
.collect()
}
/// The content's label.
pub fn label(&self) -> Option<&Label> {
match self.field_ref("label")? {

View File

@ -48,3 +48,8 @@
---
// Error: 2-5 cannot mutate a constant: box
#box.push(1)
---
// Test content fields method.
#test([a].fields(), (text: "a"))
#test([a *b*].fields(), (children: ([a], [ ], strong[b])))