mirror of
https://github.com/storytold/figcraft.git
synced 2026-10-27 20:06:53 -06:00
#664: Vue layer trees import connected components in <script setup>
This commit is contained in:
@@ -255,3 +255,17 @@ fn vue_links_are_a_default_import_with_quoted_bindings() {
|
||||
assert!(s.execute("codeConnect.set", &json!({"id": c, "language": "css"})).is_err(), "not a code language");
|
||||
assert!(s.execute("codeConnect.set", &json!({"id": c, "language": "vue", "importPath": "a b"})).is_err(), "no spaces in a path");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vue_layer_trees_import_connected_components_in_script_setup() {
|
||||
let mut s = Session::new();
|
||||
let c = card(&mut s);
|
||||
ex(&mut s, "codeConnect.set", json!({"id": c, "language": "vue", "importPath": "./Card.vue"}));
|
||||
let screen = idv(&ex(&mut s, "frame.create", json!({"x": 0, "y": 500, "width": 400, "height": 300, "name": "Screen"})));
|
||||
ex(&mut s, "instance.create", json!({"component": c, "x": 20, "y": 30, "parent": screen}));
|
||||
// A single-file component's imports belong in its `<script setup>`, not before the template.
|
||||
let code = code(&mut s, screen, "vue");
|
||||
let want = "<script setup lang=\"ts\">\n\nimport Card from \"./Card.vue\";\n\n</script>\n\n<template>\n";
|
||||
assert!(code.starts_with(want), "{code}");
|
||||
assert_eq!(code.matches("import Card").count(), 1, "{code}");
|
||||
}
|
||||
|
||||
@@ -147,7 +147,29 @@ pub fn code(doc: &Document, id: NodeId, lang: CodeLang) -> String {
|
||||
}
|
||||
},
|
||||
};
|
||||
crate::code_connect::with_imports(&crate::code_connect::tree_imports(doc, id, lang), code)
|
||||
let imports = crate::code_connect::tree_imports(doc, id, lang);
|
||||
if lang == CodeLang::Vue && !imports.is_empty() {
|
||||
return vue_with_imports(&imports, code);
|
||||
}
|
||||
crate::code_connect::with_imports(&imports, code)
|
||||
}
|
||||
|
||||
/// A Vue single-file component imports in its `<script setup>`, which is added when it has none.
|
||||
fn vue_with_imports(imports: &[String], code: String) -> String {
|
||||
const SETUP: &str = "<script setup lang=\"ts\">\n\n";
|
||||
let lines = imports.join("\n");
|
||||
// `find` returns char boundaries, so the splits below are safe.
|
||||
if let Some(at) = code.find(SETUP).map(|at| at + SETUP.len()) {
|
||||
let (head, tail) = code.split_at(at);
|
||||
return format!("{head}{lines}\n\n{tail}");
|
||||
}
|
||||
match code.find("<template>") {
|
||||
Some(at) => {
|
||||
let (head, tail) = code.split_at(at);
|
||||
format!("{head}{SETUP}{lines}\n\n</script>\n\n{tail}")
|
||||
}
|
||||
None => crate::code_connect::with_imports(imports, code),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_component(doc: &Document, id: NodeId) -> bool {
|
||||
|
||||
Reference in New Issue
Block a user