parsoid/inclusion.rs
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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
/*
Copyright (C) 2021 Kunal Mehta <legoktm@debian.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use crate::node::Wikinode;
use crate::WikiMultinode;
use kuchikiki::{Attribute, ExpandedName, NodeRef};
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)]
pub(crate) struct IncludeOnlyDataMw {
pub(crate) src: String,
}
/// Represents a noinclude tag (`<noinclude>`)
///
/// This tag is special as it spans multiple nodes, similar to templates.
/// However, because of the way wikitext is written, it's possible for
/// noinclude tags to be unbalanced, crossing normal HTML tags.
///
/// There are a few gotchas to using this because of how the contents
/// are tracked. You can only go through the descendant nodes using
/// `inclusive_descendants`. It's not possible to use a tree structure
/// because there's no guarantee the contents are balanced HTML nodes.
///
/// Mutating nodes inside the noinclude is straightforward, but trying
/// to change the tag itself is complicated. Trying to detach and reattach
/// the same NoInclude instance probably won't work as expected. Instead
/// it's recommended to only attach NoInclude instances that you create.
/// ```
/// # use parsoid::Result;
/// # use parsoid::prelude::*;
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
/// # let client = ParsoidClient::new("https://www.mediawiki.org/w/rest.php","parsoid-rs testing").unwrap();
/// let code = client.transform_to_html("foo<noinclude>bar</noinclude>baz").await?.into_mutable();
/// // Get the `NoInclude` instance
/// let noinclude = code.filter_noinclude()[0].clone();
/// assert_eq!(&noinclude.inclusive_descendants()[0].text_contents(), "bar");
/// # Ok(())
/// # }
/// ```
///
/// A more sophisticated example:
/// ```
/// # use parsoid::Result;
/// # use parsoid::prelude::*;
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
/// # let client = ParsoidClient::new("https://www.mediawiki.org/w/rest.php","parsoid-rs testing").unwrap();
/// let code = client.transform_to_html("foo<noinclude>[[bar]] baz</noinclude>!").await?.into_mutable();
/// // Get the `NoInclude` instance
/// let noinclude = code.filter_noinclude()[0].clone();
/// // Get the wikilink
/// let links: Vec<WikiLink> = noinclude
/// .inclusive_descendants()
/// .iter()
/// .filter_map(|node| node.as_wikilink())
/// .collect();
/// assert_eq!(&links[0].target(), "Bar");
/// # Ok(())
/// # }
/// ```
/// See the [spec](https://www.mediawiki.org/wiki/Specs/HTML/2.8.0#noinclude_/_includeonly_/_onlyinclude) for more details.
#[derive(Clone, Debug)]
pub struct NoInclude {
start: NodeRef,
end: NodeRef,
between: Vec<NodeRef>,
}
impl NoInclude {
pub(crate) const TYPEOF_START: &'static str = "mw:Includes/NoInclude";
pub(crate) const TYPEOF_END: &'static str = "mw:Includes/NoInclude/End";
pub fn new(contents: &NodeRef) -> Self {
Self {
start: NodeRef::new_element(
crate::build_qual_name(local_name!("meta")),
vec![(
ExpandedName::new(ns!(), "typeof"),
Attribute {
prefix: None,
value: Self::TYPEOF_START.to_string(),
},
)],
),
end: NodeRef::new_element(
crate::build_qual_name(local_name!("meta")),
vec![(
ExpandedName::new(ns!(), "typeof"),
Attribute {
prefix: None,
value: Self::TYPEOF_END.to_string(),
},
)],
),
between: vec![contents.clone()],
}
}
pub(crate) fn new_from_node(
start: &NodeRef,
end: &NodeRef,
between: &[NodeRef],
) -> Self {
if start.as_element().is_none() {
unreachable!("Non-element start node passed");
} else if end.as_element().is_none() {
unreachable!("Non-element end node passed");
}
Self {
start: start.clone(),
end: end.clone(),
between: between.to_vec(),
}
}
/// Iterate through all the nodes between the noinclude opening
/// and closing tags, recursively.
pub fn inclusive_descendants(&self) -> Vec<Wikinode> {
self.between.iter().map(Wikinode::new_from_node).collect()
}
}
impl WikiMultinode for NoInclude {
fn as_nodes(&self) -> Vec<NodeRef> {
let mut nodes = vec![self.start.clone()];
for node in &self.between {
nodes.push(node.clone());
}
nodes.push(self.end.clone());
nodes
}
}
/// Represents a onlyinclude tag (`<onlyinclude>`)
///
/// This tag is special as it spans multiple nodes, similar to templates.
/// However, because of the way wikitext is written, it's possible for
/// onlyinclude tags to be unbalanced, crossing normal HTML tags.
///
/// There are a few gotchas to using this because of how the contents
/// are tracked. You can only go through the descendant nodes using
/// `inclusive_descendants`. It's not possible to use a tree structure
/// because there's no guarantee the contents are balanced HTML nodes.
///
/// Mutating nodes inside the onlyinclude is straightforward, but trying
/// to change the tag itself is complicated. Trying to detach and reattach
/// the same OnlyInclude instance probably won't work as expected. Instead
/// it's recommended to only attach OnlyInclude instances that you create.
/// ```
/// # use parsoid::Result;
/// # use parsoid::prelude::*;
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
/// # let client = ParsoidClient::new("https://www.mediawiki.org/w/rest.php","parsoid-rs testing").unwrap();
/// let code = client.transform_to_html("foo<onlyinclude>bar</onlyinclude>baz").await?.into_mutable();
/// // Get the `OnlyInclude` instance
/// let onlyinclude = code.filter_onlyinclude()[0].clone();
/// assert_eq!(&onlyinclude.inclusive_descendants()[0].text_contents(), "bar");
/// # Ok(())
/// # }
/// ```
/// See the [spec](https://www.mediawiki.org/wiki/Specs/HTML/2.8.0#noinclude_/_includeonly_/_onlyinclude) for more details.
#[derive(Clone, Debug)]
pub struct OnlyInclude {
start: NodeRef,
end: NodeRef,
between: Vec<NodeRef>,
}
impl OnlyInclude {
pub(crate) const TYPEOF_START: &'static str = "mw:Includes/OnlyInclude";
pub(crate) const TYPEOF_END: &'static str = "mw:Includes/OnlyInclude/End";
pub fn new(contents: &NodeRef) -> Self {
Self {
start: NodeRef::new_element(
crate::build_qual_name(local_name!("meta")),
vec![(
ExpandedName::new(ns!(), "typeof"),
Attribute {
prefix: None,
value: Self::TYPEOF_START.to_string(),
},
)],
),
end: NodeRef::new_element(
crate::build_qual_name(local_name!("meta")),
vec![(
ExpandedName::new(ns!(), "typeof"),
Attribute {
prefix: None,
value: Self::TYPEOF_END.to_string(),
},
)],
),
between: vec![contents.clone()],
}
}
pub(crate) fn new_from_node(
start: &NodeRef,
end: &NodeRef,
between: &[NodeRef],
) -> Self {
if start.as_element().is_none() {
unreachable!("Non-element start node passed");
} else if end.as_element().is_none() {
unreachable!("Non-element end node passed");
}
Self {
start: start.clone(),
end: end.clone(),
between: between.to_vec(),
}
}
/// Iterate through all the nodes between the onlyinclude opening
/// and closing tags, recursively.
pub fn inclusive_descendants(&self) -> Vec<Wikinode> {
self.between.iter().map(Wikinode::new_from_node).collect()
}
}
impl WikiMultinode for OnlyInclude {
fn as_nodes(&self) -> Vec<NodeRef> {
let mut nodes = vec![self.start.clone()];
for node in &self.between {
nodes.push(node.clone());
}
nodes.push(self.end.clone());
nodes
}
}