diff --git a/README.md b/README.md index d78611c..d6ed830 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,21 @@ dprint config add g-plane/malva dprint config add typescript ``` +If you also want to format JSON in ` + + + + diff --git a/dprint_plugin/tests/integration/dprint_ts/json.html.snap b/dprint_plugin/tests/integration/dprint_ts/json.html.snap new file mode 100644 index 0000000..851724f --- /dev/null +++ b/dprint_plugin/tests/integration/dprint_ts/json.html.snap @@ -0,0 +1,19 @@ +--- +source: dprint_plugin/tests/integration.rs +--- + + + + + + + diff --git a/dprint_plugin/tests/integration/json.html b/dprint_plugin/tests/integration/json.html new file mode 100644 index 0000000..475a7cc --- /dev/null +++ b/dprint_plugin/tests/integration/json.html @@ -0,0 +1,10 @@ + + + + + + diff --git a/markup_fmt/src/ctx.rs b/markup_fmt/src/ctx.rs index 8932a43..72ea1bd 100644 --- a/markup_fmt/src/ctx.rs +++ b/markup_fmt/src/ctx.rs @@ -198,6 +198,20 @@ where ) } + pub(crate) fn format_json<'a>(&mut self, code: &'a str) -> Cow<'a, str> { + self.format_with_external_formatter( + Path::new("code.json"), + code, + self.print_width + .saturating_sub(self.indent_level) + .saturating_sub(if self.script_indent() { + self.indent_width + } else { + 0 + }), + ) + } + fn format_with_external_formatter<'a>( &mut self, path: &Path, diff --git a/markup_fmt/src/printer.rs b/markup_fmt/src/printer.rs index 28580ab..53f750a 100644 --- a/markup_fmt/src/printer.rs +++ b/markup_fmt/src/printer.rs @@ -322,24 +322,39 @@ impl<'s> DocGen<'s> for Element<'s> { let is_root = mem::replace(&mut ctx.is_root, false); if tag_name.eq_ignore_ascii_case("script") { if let [Node::TextNode(text_node)] = &self.children[..] { - let formatted = ctx.format_script( - text_node.raw, - self.attrs - .iter() - .find_map(|attr| match attr { - Attribute::NativeAttribute(native_attribute) - if native_attribute.name.eq_ignore_ascii_case("lang") => - { - native_attribute.value - } - _ => None, - }) - .unwrap_or(if matches!(ctx.language, Language::Astro) { - "ts" - } else { - "js" - }), - ); + let is_json = self.attrs.iter().any(|attr| { + if let Attribute::NativeAttribute(native_attr) = attr { + native_attr.name.eq_ignore_ascii_case("type") + && native_attr + .value + .map(|value| value == "importmap" || value == "application/json") + .unwrap_or_default() + } else { + false + } + }); + let formatted = if is_json { + ctx.format_json(text_node.raw) + } else { + ctx.format_script( + text_node.raw, + self.attrs + .iter() + .find_map(|attr| match attr { + Attribute::NativeAttribute(native_attribute) + if native_attribute.name.eq_ignore_ascii_case("lang") => + { + native_attribute.value + } + _ => None, + }) + .unwrap_or(if matches!(ctx.language, Language::Astro) { + "ts" + } else { + "js" + }), + ) + }; let doc = Doc::hard_line().concat(reflow_with_indent(formatted.trim())); docs.push( if ctx.script_indent() {