parsoid/image.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
/*
Copyright (C) 2022 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/>.
*/
//! Image-related code
use crate::{assert_element, clean_link, WikinodeIterator};
use kuchikiki::NodeRef;
use serde::Deserialize;
use urlencoding::decode;
/// Represents an image (`[[File:Foobar.jpg]]`)
///
/// See the [spec](https://www.mediawiki.org/wiki/Specs/HTML/2.8.0#Images) for more details.
#[derive(Debug, Clone)]
pub struct Image(pub(crate) NodeRef);
impl Image {
// Could be mw:File, mw:File/Frameless, mw:File/Thumb, mw:File/Frame
pub(crate) const TYPEOF_PREFIX: &'static str = "mw:File";
pub(crate) const SELECTOR: &'static str = "[typeof^=\"mw:File\"]";
pub(crate) fn new_from_node(element: &NodeRef) -> Self {
assert_element(element);
Self(element.clone())
}
/// Get the errors, if any, that apply to this image. For example,
/// if an image is missing.
pub fn error(&self) -> Option<Vec<ImageError>> {
let node = self.select_first("[typeof~=\"mw:Error\"]")?;
let attrs = node.as_element()?.attributes.borrow();
// XXX: Do we want better error handling here instead of silently
// pretending there's no error?
let data: DataMw = serde_json::from_str(attrs.get("data-mw")?).ok()?;
Some(data.errors)
}
/// Get the MediaWiki page title corresponding to the image being embedded,
/// including `File:` namespace prefix.
pub fn title(&self) -> String {
let node = self
.select_first(".mw-file-element[resource]")
.expect("Unable to find .mw-file-element[resource] node");
let attrs = node.as_element().unwrap().attributes.borrow();
clean_link(&decode(attrs.get("resource").unwrap()).unwrap())
}
/// Get the horizontal alignment of the image, see the [documentation](https://www.mediawiki.org/wiki/Help:Images#Horizontal_alignment)
/// for more details.
pub fn horizontal_alignment(&self) -> HorizontalAlignment {
let attrs = self.as_element().unwrap().attributes.borrow();
let class = attrs.get("class").unwrap_or("");
for part in class.split(' ') {
if part.starts_with("mw-halign-") {
return HorizontalAlignment::from_class(part);
}
}
// Not h-aligned
HorizontalAlignment::Unspecified
}
/// Set the horizontal alignment of the image, see the [documentation](https://www.mediawiki.org/wiki/Help:Images#Horizontal_alignment)
/// for more details.
pub fn set_horizontal_alignment(&self, halign: HorizontalAlignment) {
let mut class: Vec<_> = self
.as_element()
.unwrap()
.attributes
.borrow()
.get("class")
.unwrap_or("")
.split(' ')
// Remove all existing mw-halign- classes
.filter(|part| !part.starts_with("mw-halign-"))
.map(|part| part.to_string())
.collect();
// Insert in our desired class
if let Some(halign) = halign.as_class() {
class.push(halign.to_string());
}
self.as_element()
.unwrap()
.attributes
.borrow_mut()
.insert("class", class.join(" ").trim().to_string());
}
}
/// How the image should be horizontally aligned, see the [documentation](https://www.mediawiki.org/wiki/Help:Images#Horizontal_alignment)
/// for more details.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum HorizontalAlignment {
Left,
Right,
Center,
None,
Unspecified,
}
impl HorizontalAlignment {
fn from_class(class: &str) -> Self {
match class {
"mw-halign-left" => Self::Left,
"mw-halign-right" => Self::Right,
"mw-halign-center" => Self::Center,
"mw-halign-none" => Self::None,
// TODO: Should we error out on an invalid halign class?
_ => Self::Unspecified,
}
}
fn as_class(&self) -> Option<&'static str> {
match self {
HorizontalAlignment::Left => Some("mw-halign-left"),
HorizontalAlignment::Right => Some("mw-halign-right"),
HorizontalAlignment::Center => Some("mw-halign-center"),
HorizontalAlignment::None => Some("mw-halign-none"),
HorizontalAlignment::Unspecified => None,
}
}
}
#[derive(Deserialize)]
struct DataMw {
errors: Vec<ImageError>,
}
#[derive(Deserialize, Clone, Debug)]
pub struct ImageError {
pub key: String,
pub message: String,
}