//! Prettier's `language-html/utilities/index.js` and `utilities/html-whitespace.js`. use super::Whitespace as HtmlWhitespaceSensitivity; use super::ast::{Attribute, Flags, Id, Kind, Node, Span, Tree}; use super::data::{self, Display}; use super::strings; use super::{Options, Parser}; use std::borrow::Cow; // ───────────────────────────── `htmlWhitespace` ───────────────────────────── /// `htmlWhitespace.split(text)`. Yields an empty string where the text starts or ends with whitespace. pub(crate) fn html_split(text: &[u8]) -> impl Iterator { let mut rest = Some(text); std::iter::from_fn(move || { let text = rest?; let len = text.iter().take_while(|byte| !byte.is_ascii_whitespace()).count(); let after = &text[len..]; rest = (!after.is_empty()).then(|| after.trim_ascii_start()); Some(&text[..len]) }) } /// The first half of `htmlWhitespace.dedentString(text)`: returns how many bytes to remove from the start of every /// line. pub(crate) fn min_indentation(text: &[u8]) -> usize { let mut min_indentation = usize::MAX; for line in strings::split(text, b"\n") { if line.is_empty() { continue; } let indentation = line.len() - line.trim_ascii_start().len(); if indentation == 0 { return 0; } if line.len() != indentation { min_indentation = min_indentation.min(indentation); } } if min_indentation == usize::MAX { 0 } else { min_indentation } } /// `htmlWhitespace.dedentString(text)` pub(crate) fn dedent_string(text: &[u8]) -> Cow<'_, [u8]> { let min_indentation = min_indentation(text); if min_indentation == 0 { return Cow::Borrowed(text); } let mut result = Vec::with_capacity(text.len()); for (index, line) in strings::split(text, b"\n").enumerate() { if index > 0 { result.push(b'\n'); } result.extend_from_slice(line.get(min_indentation..).unwrap_or_default()); } Cow::Owned(result) } /// `htmlTrimPreserveIndentation` pub(crate) fn html_trim_preserve_indentation(text: &[u8]) -> &[u8] { // `.replaceAll(/^[\t\f\r ]*\n/g, "")`: without the `m` flag, it removes one line at most. let text = text.trim_ascii_end(); let whitespace_len = text.iter().take_while(|byte| matches!(byte, b'\t' | 0x0C | b'\r' | b' ')).count(); match text.get(whitespace_len) { Some(b'\n') => &text[whitespace_len + 1..], _ => text, } } // ───────────────────────────── nodes ───────────────────────────── /// `isUnknownNamespace` pub(crate) fn is_unknown_namespace(node: &Node<'_>) -> bool { node.kind == Kind::Element && !node.has(Flags::HAS_EXPLICIT_NAMESPACE) && !matches!(node.namespace, b"html" | b"svg") } /// `isTextLikeNode` #[inline] pub(crate) fn is_text_like(node: &Node<'_>) -> bool { matches!(node.kind, Kind::Text | Kind::Comment) } /// `isPreLikeNode` and `isIndentationSensitiveNode` pub(crate) fn is_pre_like(node: &Node<'_>) -> bool { node.kind == Kind::Element && (node.namespace.is_empty() || is_unknown_namespace(node)) && data::is_pre_tag(&node.name) } /// `isScriptLikeTag` pub(crate) fn is_script_like_tag(node: &Node<'_>, options: &Options<'_>) -> bool { if node.kind != Kind::Element { return false; } match &node.name[..] { b"script" | b"style" => matches!(node.namespace, b"" | b"svg") || is_unknown_namespace(node), b"mj-style" => node.namespace.is_empty() && options.parser == Parser::Mjml, _ => false, } } /// `isPrettierIgnore` fn is_prettier_ignore(node: &Node<'_>) -> bool { node.kind == Kind::Comment && strings::trim_js_whitespace(&node.value) == b"prettier-ignore" } /// `unescapeQuoteEntities` pub(crate) fn unescape_quote_entities(text: &[u8]) -> Cow<'_, [u8]> { if !strings::contains_char(text, b'&') || (!strings::contains(text, b"'") && !strings::contains(text, b""")) { return Cow::Borrowed(text); } let mut result = Vec::with_capacity(text.len()); let mut rest = text; while let Some(at) = strings::index_of_char_usize(rest, b'&') { result.extend_from_slice(&rest[..at]); rest = &rest[at..]; if let Some(after) = rest.strip_prefix(b"'") { result.push(b'\''); rest = after; } else if let Some(after) = rest.strip_prefix(b""") { result.push(b'"'); rest = after; } else { result.push(b'&'); rest = &rest[1..]; } } result.extend_from_slice(rest); Cow::Owned(result) } /// `/^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(value)` pub(crate) fn is_placeholder_in_js(value: &[u8]) -> bool { let digits = |text: &'_ [u8]| -> Option { Some(text.iter().take_while(|byte| byte.is_ascii_digit()).count()).filter(|&count| count > 0) }; (|| { let rest = value.strip_prefix(b"PRETTIER_HTML_PLACEHOLDER_")?; let rest = rest[digits(rest)?..].strip_prefix(b"_")?; Some(&rest[digits(rest)?..] == b"_IN_JS") })() .unwrap_or(false) } /// `shouldUnquoteAttributeValue` pub(crate) fn should_unquote_attribute_value(attr: &Attribute<'_>, options: &Options<'_>) -> bool { let (Some(span), Some(value)) = (attr.value_span, attr.value) else { return false; }; // `isAttributeValueQuoted` if span.len() as usize == value.len() + 2 { return false; } is_placeholder_in_js(value) || (options.parser == Parser::Lwc && value.starts_with(b"{") && value.ends_with(b"}")) } /// `preferHardlineAsSurroundingSpaces` fn prefer_hardline_as_surrounding_spaces(node: &Node<'_>) -> bool { match node.kind { Kind::IeConditionalComment | Kind::Comment => true, Kind::Element => matches!(&node.name[..], b"script" | b"select"), _ => false, } } fn is_text_or_interpolation(node: &Node<'_>) -> bool { matches!(node.kind, Kind::Text | Kind::Interpolation) } /// Returns how many lines the start of `second` is below the end of `first`, capped at two. fn lines_between(options: &Options<'_>, first: Span, second: Span) -> usize { let Some(between) = options.original_text.get(first.end as usize..second.start as usize) else { return 0; }; match strings::index_of_char_usize(between, b'\n') { None => 0, Some(first) => 1 + usize::from(strings::contains_char(&between[first + 1..], b'\n')), } } impl<'a> Tree<'a> { fn node_at(&self, id: Option) -> Option<&Node<'a>> { id.map(|id| &self[id]) } pub(crate) fn parent_of(&self, id: Id) -> Option<&Node<'a>> { self.node_at(self.parent(id)) } pub(crate) fn prev_of(&self, id: Id) -> Option<&Node<'a>> { self.node_at(self.prev(id)) } pub(crate) fn next_of(&self, id: Id) -> Option<&Node<'a>> { self.node_at(self.next(id)) } /// `hasPrettierIgnore` pub(crate) fn has_prettier_ignore(&self, id: Id) -> bool { self.prev_of(id).is_some_and(is_prettier_ignore) } /// `isVueSfcBlock` pub(crate) fn is_vue_sfc_block(&self, id: Id, options: &Options<'_>) -> bool { options.parser == Parser::Vue && self[id].kind == Kind::Element && self.parent_of(id).is_some_and(|parent| parent.kind == Kind::Root) && !(self[id].namespace.is_empty() && self[id].name.eq_ignore_ascii_case(b"html")) } /// `isVueCustomBlock` pub(crate) fn is_vue_custom_block(&self, id: Id, options: &Options<'_>) -> bool { self.is_vue_sfc_block(id, options) && !(self[id].namespace.is_empty() && matches!(&self[id].name[..], b"template" | b"style" | b"script")) } /// `isVueNonHtmlBlock` pub(crate) fn is_vue_non_html_block(&self, id: Id, options: &Options<'_>) -> bool { self.is_vue_sfc_block(id, options) && (self.is_vue_custom_block(id, options) || self.attribute_value(id, b"lang").is_some_and(|lang| lang != b"html")) } /// `isVueScriptTag` pub(crate) fn is_vue_script_tag(&self, id: Id, options: &Options<'_>) -> bool { self.is_vue_sfc_block(id, options) && &self[id].name[..] == b"script" } /// `shouldPreserveContent`. Call it once nothing in `id` changes anymore. It looks at all children. pub(crate) fn should_preserve_content(&self, id: Id, options: &Options<'_>) -> bool { let node = &self[id]; if node.kind == Kind::IeConditionalComment { // An element that isn't closed inside the comment, or contents that couldn't be parsed. if self .node_at(self.last_child(id)) .is_some_and(|last| !last.has(Flags::IS_SELF_CLOSING) && !last.has(Flags::HAS_END_SPAN)) { return true; } if !node.has(Flags::IS_COMPLETE) { return true; } } if is_pre_like(node) && self.children(id).any(|child| !is_text_or_interpolation(&self[child])) { return true; } // Whitespace-only content of a `
` is rendered, and in a `