@antheo/morph 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +266 -2
- package/SKILL.md +61 -0
- package/dist/ai/cli-provider.d.ts +80 -0
- package/dist/ai/cli-provider.js +250 -0
- package/dist/ai/gate.d.ts +39 -0
- package/dist/ai/gate.js +124 -0
- package/dist/ai/provider.d.ts +36 -0
- package/dist/ai/provider.js +168 -0
- package/dist/ai/repair.d.ts +90 -0
- package/dist/ai/repair.js +172 -0
- package/dist/analyzer/deps.d.ts +30 -0
- package/dist/analyzer/deps.js +265 -0
- package/dist/analyzer/manifest.d.ts +5 -0
- package/dist/analyzer/manifest.js +119 -0
- package/dist/analyzer/parse.d.ts +21 -0
- package/dist/analyzer/parse.js +29 -0
- package/dist/batch-worker.d.ts +16 -0
- package/dist/batch-worker.js +10 -0
- package/dist/batch.d.ts +26 -0
- package/dist/batch.js +227 -0
- package/dist/bridge/index.d.ts +26 -0
- package/dist/bridge/index.js +138 -0
- package/dist/bridge/props.d.ts +56 -0
- package/dist/bridge/props.js +191 -0
- package/dist/bridge/wrappers.d.ts +24 -0
- package/dist/bridge/wrappers.js +276 -0
- package/dist/cli/format.d.ts +7 -0
- package/dist/cli/format.js +30 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +492 -0
- package/dist/fonts/carry.d.ts +34 -0
- package/dist/fonts/carry.js +113 -0
- package/dist/fonts/fallback.d.ts +11 -0
- package/dist/fonts/fallback.js +21 -0
- package/dist/fonts/google.d.ts +65 -0
- package/dist/fonts/google.js +343 -0
- package/dist/fonts/index.d.ts +27 -0
- package/dist/fonts/index.js +48 -0
- package/dist/fonts/local.d.ts +46 -0
- package/dist/fonts/local.js +150 -0
- package/dist/fonts/sfnt.d.ts +19 -0
- package/dist/fonts/sfnt.js +174 -0
- package/dist/fonts/shim.d.ts +14 -0
- package/dist/fonts/shim.js +96 -0
- package/dist/gate.d.ts +105 -0
- package/dist/gate.js +157 -0
- package/dist/index.d.ts +55 -0
- package/dist/index.js +74 -0
- package/dist/ir/annotate.d.ts +16 -0
- package/dist/ir/annotate.js +145 -0
- package/dist/ir/as-child.d.ts +18 -0
- package/dist/ir/as-child.js +239 -0
- package/dist/ir/compounds.d.ts +27 -0
- package/dist/ir/compounds.js +183 -0
- package/dist/ir/contexts.d.ts +26 -0
- package/dist/ir/contexts.js +185 -0
- package/dist/ir/dom.d.ts +11 -0
- package/dist/ir/dom.js +60 -0
- package/dist/ir/effect-returns.d.ts +10 -0
- package/dist/ir/effect-returns.js +25 -0
- package/dist/ir/extract-ui-types.d.ts +33 -0
- package/dist/ir/extract-ui-types.js +224 -0
- package/dist/ir/extract-ui.d.ts +34 -0
- package/dist/ir/extract-ui.js +567 -0
- package/dist/ir/falsy.d.ts +13 -0
- package/dist/ir/falsy.js +66 -0
- package/dist/ir/forward-refs.d.ts +11 -0
- package/dist/ir/forward-refs.js +155 -0
- package/dist/ir/fragment-source.d.ts +4 -0
- package/dist/ir/fragment-source.js +13 -0
- package/dist/ir/fragments.d.ts +32 -0
- package/dist/ir/fragments.js +192 -0
- package/dist/ir/helper-snippets.d.ts +30 -0
- package/dist/ir/helper-snippets.js +550 -0
- package/dist/ir/latest-refs.d.ts +11 -0
- package/dist/ir/latest-refs.js +187 -0
- package/dist/ir/live-args.d.ts +26 -0
- package/dist/ir/live-args.js +335 -0
- package/dist/ir/lower.d.ts +83 -0
- package/dist/ir/lower.js +6016 -0
- package/dist/ir/markup-values.d.ts +16 -0
- package/dist/ir/markup-values.js +188 -0
- package/dist/ir/model.d.ts +605 -0
- package/dist/ir/model.js +1 -0
- package/dist/ir/oracle.d.ts +91 -0
- package/dist/ir/oracle.js +610 -0
- package/dist/ir/radix.d.ts +122 -0
- package/dist/ir/radix.js +344 -0
- package/dist/ir/rename.d.ts +15 -0
- package/dist/ir/rename.js +151 -0
- package/dist/ir/render-props.d.ts +31 -0
- package/dist/ir/render-props.js +67 -0
- package/dist/ir/rewrite.d.ts +44 -0
- package/dist/ir/rewrite.js +381 -0
- package/dist/ir/running-index.d.ts +11 -0
- package/dist/ir/running-index.js +217 -0
- package/dist/ir/snapshots.d.ts +12 -0
- package/dist/ir/snapshots.js +140 -0
- package/dist/ir/style.d.ts +19 -0
- package/dist/ir/style.js +76 -0
- package/dist/ir/types.d.ts +42 -0
- package/dist/ir/types.js +271 -0
- package/dist/ir/walk.d.ts +11 -0
- package/dist/ir/walk.js +18 -0
- package/dist/mcp/server.d.ts +81 -0
- package/dist/mcp/server.js +518 -0
- package/dist/pipeline.d.ts +26 -0
- package/dist/pipeline.js +750 -0
- package/dist/registry/add.d.ts +91 -0
- package/dist/registry/add.js +273 -0
- package/dist/registry/fetch.d.ts +40 -0
- package/dist/registry/fetch.js +186 -0
- package/dist/registry/ip.d.ts +18 -0
- package/dist/registry/ip.js +153 -0
- package/dist/registry/item.d.ts +39 -0
- package/dist/registry/item.js +131 -0
- package/dist/registry/load.d.ts +35 -0
- package/dist/registry/load.js +106 -0
- package/dist/registry/paths.d.ts +8 -0
- package/dist/registry/paths.js +43 -0
- package/dist/registry/publish.d.ts +119 -0
- package/dist/registry/publish.js +439 -0
- package/dist/targets/angular/bank/bank.d.ts +39 -0
- package/dist/targets/angular/bank/bank.js +61 -0
- package/dist/targets/angular/bank/helpers.d.ts +64 -0
- package/dist/targets/angular/bank/helpers.js +246 -0
- package/dist/targets/angular/bank/kept.d.ts +98 -0
- package/dist/targets/angular/bank/kept.js +791 -0
- package/dist/targets/angular/bank/plan-helpers.d.ts +17 -0
- package/dist/targets/angular/bank/plan-helpers.js +286 -0
- package/dist/targets/angular/bank/plan.d.ts +22 -0
- package/dist/targets/angular/bank/plan.js +152 -0
- package/dist/targets/angular/bank/receivers.d.ts +66 -0
- package/dist/targets/angular/bank/receivers.js +293 -0
- package/dist/targets/angular/bank/runtime.d.ts +14 -0
- package/dist/targets/angular/bank/runtime.js +152 -0
- package/dist/targets/angular/controlled.d.ts +7 -0
- package/dist/targets/angular/controlled.js +37 -0
- package/dist/targets/angular/dynamic-tags.d.ts +34 -0
- package/dist/targets/angular/dynamic-tags.js +192 -0
- package/dist/targets/angular/emit.d.ts +41 -0
- package/dist/targets/angular/emit.js +5970 -0
- package/dist/targets/angular/exports.d.ts +48 -0
- package/dist/targets/angular/exports.js +243 -0
- package/dist/targets/angular/helpers.d.ts +15 -0
- package/dist/targets/angular/helpers.js +33 -0
- package/dist/targets/angular/host-boundary.d.ts +5 -0
- package/dist/targets/angular/host-boundary.js +166 -0
- package/dist/targets/angular/host-form.d.ts +150 -0
- package/dist/targets/angular/host-form.js +727 -0
- package/dist/targets/angular/markup-values.d.ts +58 -0
- package/dist/targets/angular/markup-values.js +661 -0
- package/dist/targets/angular/motion-directive.d.ts +12 -0
- package/dist/targets/angular/motion-directive.js +257 -0
- package/dist/targets/angular/motion-hooks.d.ts +73 -0
- package/dist/targets/angular/motion-hooks.js +293 -0
- package/dist/targets/angular/motion-layout.d.ts +14 -0
- package/dist/targets/angular/motion-layout.js +74 -0
- package/dist/targets/angular/motion-templates.d.ts +10 -0
- package/dist/targets/angular/motion-templates.js +65 -0
- package/dist/targets/angular/motion.d.ts +57 -0
- package/dist/targets/angular/motion.js +202 -0
- package/dist/targets/angular/narrowing.d.ts +24 -0
- package/dist/targets/angular/narrowing.js +205 -0
- package/dist/targets/angular/ngc.d.ts +23 -0
- package/dist/targets/angular/ngc.js +134 -0
- package/dist/targets/angular/passed-handle.d.ts +39 -0
- package/dist/targets/angular/passed-handle.js +154 -0
- package/dist/targets/angular/projected.d.ts +9 -0
- package/dist/targets/angular/projected.js +63 -0
- package/dist/targets/angular/radix/cores/alert-dialog.d.ts +13 -0
- package/dist/targets/angular/radix/cores/alert-dialog.js +388 -0
- package/dist/targets/angular/radix/cores/index.d.ts +17 -0
- package/dist/targets/angular/radix/cores/index.js +50 -0
- package/dist/targets/angular/radix/cores/slider.d.ts +8 -0
- package/dist/targets/angular/radix/cores/slider.js +202 -0
- package/dist/targets/angular/radix/index.d.ts +21 -0
- package/dist/targets/angular/radix/index.js +35 -0
- package/dist/targets/angular/radix/packages.d.ts +3 -0
- package/dist/targets/angular/radix/packages.js +558 -0
- package/dist/targets/angular/radix/part.d.ts +236 -0
- package/dist/targets/angular/radix/part.js +71 -0
- package/dist/targets/angular/radix/prepare.d.ts +66 -0
- package/dist/targets/angular/radix/prepare.js +548 -0
- package/dist/targets/angular/radix/template.d.ts +43 -0
- package/dist/targets/angular/radix/template.js +172 -0
- package/dist/targets/angular/refs.d.ts +68 -0
- package/dist/targets/angular/refs.js +443 -0
- package/dist/targets/angular/slots.d.ts +22 -0
- package/dist/targets/angular/slots.js +60 -0
- package/dist/targets/angular/source-types.d.ts +10 -0
- package/dist/targets/angular/source-types.js +45 -0
- package/dist/targets/angular/spread-forward.d.ts +24 -0
- package/dist/targets/angular/spread-forward.js +72 -0
- package/dist/targets/angular/spread.d.ts +32 -0
- package/dist/targets/angular/spread.js +182 -0
- package/dist/targets/angular/svg-hosts.d.ts +25 -0
- package/dist/targets/angular/svg-hosts.js +107 -0
- package/dist/targets/angular/template-expr.d.ts +36 -0
- package/dist/targets/angular/template-expr.js +287 -0
- package/dist/targets/angular/types.d.ts +9 -0
- package/dist/targets/angular/types.js +63 -0
- package/dist/targets/angular/walk.d.ts +11 -0
- package/dist/targets/angular/walk.js +26 -0
- package/dist/targets/react-native/emit.d.ts +14 -0
- package/dist/targets/react-native/emit.js +585 -0
- package/dist/targets/react-native/fidelity.d.ts +5 -0
- package/dist/targets/react-native/fidelity.js +43 -0
- package/dist/targets/react-native/motion.d.ts +10 -0
- package/dist/targets/react-native/motion.js +290 -0
- package/dist/targets/react-native/skia.d.ts +30 -0
- package/dist/targets/react-native/skia.js +358 -0
- package/dist/targets/shared/context.d.ts +47 -0
- package/dist/targets/shared/context.js +195 -0
- package/dist/targets/shared/foreign.d.ts +10 -0
- package/dist/targets/shared/foreign.js +72 -0
- package/dist/targets/shared/fragments.d.ts +21 -0
- package/dist/targets/shared/fragments.js +309 -0
- package/dist/targets/shared/handles.d.ts +65 -0
- package/dist/targets/shared/handles.js +299 -0
- package/dist/targets/shared/inline.d.ts +53 -0
- package/dist/targets/shared/inline.js +524 -0
- package/dist/targets/shared/layout.d.ts +70 -0
- package/dist/targets/shared/layout.js +224 -0
- package/dist/targets/shared/markup.d.ts +26 -0
- package/dist/targets/shared/markup.js +65 -0
- package/dist/targets/shared/module.d.ts +84 -0
- package/dist/targets/shared/module.js +468 -0
- package/dist/targets/shared/motion-hooks.d.ts +37 -0
- package/dist/targets/shared/motion-hooks.js +87 -0
- package/dist/targets/shared/motion-layout.d.ts +70 -0
- package/dist/targets/shared/motion-layout.js +392 -0
- package/dist/targets/shared/portal.d.ts +10 -0
- package/dist/targets/shared/portal.js +23 -0
- package/dist/targets/shared/prop-writes.d.ts +11 -0
- package/dist/targets/shared/prop-writes.js +32 -0
- package/dist/targets/shared/prune.d.ts +54 -0
- package/dist/targets/shared/prune.js +405 -0
- package/dist/targets/shared/react-libs.d.ts +25 -0
- package/dist/targets/shared/react-libs.js +142 -0
- package/dist/targets/shared/react-types.d.ts +16 -0
- package/dist/targets/shared/react-types.js +374 -0
- package/dist/targets/shared/react-values.d.ts +20 -0
- package/dist/targets/shared/react-values.js +145 -0
- package/dist/targets/shared/ref-callback.d.ts +16 -0
- package/dist/targets/shared/ref-callback.js +114 -0
- package/dist/targets/shared/script.d.ts +65 -0
- package/dist/targets/shared/script.js +406 -0
- package/dist/targets/shared/unused.d.ts +12 -0
- package/dist/targets/shared/unused.js +146 -0
- package/dist/targets/svelte/dom-spread.d.ts +27 -0
- package/dist/targets/svelte/dom-spread.js +146 -0
- package/dist/targets/svelte/emit.d.ts +15 -0
- package/dist/targets/svelte/emit.js +3784 -0
- package/dist/targets/svelte/handle-branches.d.ts +22 -0
- package/dist/targets/svelte/handle-branches.js +146 -0
- package/dist/targets/svelte/html-keys.d.ts +9 -0
- package/dist/targets/svelte/html-keys.js +40 -0
- package/dist/targets/svelte/markup-data/data.d.ts +51 -0
- package/dist/targets/svelte/markup-data/data.js +305 -0
- package/dist/targets/svelte/markup-data/helper.d.ts +12 -0
- package/dist/targets/svelte/markup-data/helper.js +81 -0
- package/dist/targets/svelte/markup-data/module-data.d.ts +21 -0
- package/dist/targets/svelte/markup-data/module-data.js +473 -0
- package/dist/targets/svelte/markup-data/sites.d.ts +52 -0
- package/dist/targets/svelte/markup-data/sites.js +303 -0
- package/dist/targets/svelte/motion-layout.d.ts +13 -0
- package/dist/targets/svelte/motion-layout.js +70 -0
- package/dist/targets/svelte/motion-table.d.ts +14 -0
- package/dist/targets/svelte/motion-table.js +308 -0
- package/dist/targets/svelte/motion.d.ts +46 -0
- package/dist/targets/svelte/motion.js +405 -0
- package/dist/targets/svelte/presence.d.ts +71 -0
- package/dist/targets/svelte/presence.js +318 -0
- package/dist/targets/svelte/radix/accordion.d.ts +9 -0
- package/dist/targets/svelte/radix/accordion.js +24 -0
- package/dist/targets/svelte/radix/aspect-ratio.d.ts +6 -0
- package/dist/targets/svelte/radix/aspect-ratio.js +8 -0
- package/dist/targets/svelte/radix/avatar.d.ts +6 -0
- package/dist/targets/svelte/radix/avatar.js +10 -0
- package/dist/targets/svelte/radix/checkbox.d.ts +10 -0
- package/dist/targets/svelte/radix/checkbox.js +24 -0
- package/dist/targets/svelte/radix/collapsible.d.ts +7 -0
- package/dist/targets/svelte/radix/collapsible.js +16 -0
- package/dist/targets/svelte/radix/context-menu.d.ts +8 -0
- package/dist/targets/svelte/radix/context-menu.js +49 -0
- package/dist/targets/svelte/radix/cores/alert-dialog.d.ts +17 -0
- package/dist/targets/svelte/radix/cores/alert-dialog.js +449 -0
- package/dist/targets/svelte/radix/cores/collapsible.d.ts +12 -0
- package/dist/targets/svelte/radix/cores/collapsible.js +214 -0
- package/dist/targets/svelte/radix/cores/core.d.ts +32 -0
- package/dist/targets/svelte/radix/cores/core.js +80 -0
- package/dist/targets/svelte/radix/cores/direction.d.ts +10 -0
- package/dist/targets/svelte/radix/cores/direction.js +64 -0
- package/dist/targets/svelte/radix/cores/index.d.ts +19 -0
- package/dist/targets/svelte/radix/cores/index.js +85 -0
- package/dist/targets/svelte/radix/cores/modal-layer.d.ts +11 -0
- package/dist/targets/svelte/radix/cores/modal-layer.js +244 -0
- package/dist/targets/svelte/radix/cores/presence.d.ts +12 -0
- package/dist/targets/svelte/radix/cores/presence.js +129 -0
- package/dist/targets/svelte/radix/cores/slider-logic.d.ts +10 -0
- package/dist/targets/svelte/radix/cores/slider-logic.js +287 -0
- package/dist/targets/svelte/radix/cores/slider.d.ts +13 -0
- package/dist/targets/svelte/radix/cores/slider.js +267 -0
- package/dist/targets/svelte/radix/dialog.d.ts +8 -0
- package/dist/targets/svelte/radix/dialog.js +20 -0
- package/dist/targets/svelte/radix/dropdown-menu.d.ts +9 -0
- package/dist/targets/svelte/radix/dropdown-menu.js +38 -0
- package/dist/targets/svelte/radix/emit.d.ts +12 -0
- package/dist/targets/svelte/radix/emit.js +1339 -0
- package/dist/targets/svelte/radix/hover-card.d.ts +7 -0
- package/dist/targets/svelte/radix/hover-card.js +22 -0
- package/dist/targets/svelte/radix/index.d.ts +12 -0
- package/dist/targets/svelte/radix/index.js +28 -0
- package/dist/targets/svelte/radix/label.d.ts +3 -0
- package/dist/targets/svelte/radix/label.js +5 -0
- package/dist/targets/svelte/radix/menubar.d.ts +7 -0
- package/dist/targets/svelte/radix/menubar.js +34 -0
- package/dist/targets/svelte/radix/navigation-menu.d.ts +8 -0
- package/dist/targets/svelte/radix/navigation-menu.js +25 -0
- package/dist/targets/svelte/radix/packages.d.ts +34 -0
- package/dist/targets/svelte/radix/packages.js +100 -0
- package/dist/targets/svelte/radix/part.d.ts +161 -0
- package/dist/targets/svelte/radix/part.js +85 -0
- package/dist/targets/svelte/radix/popover.d.ts +7 -0
- package/dist/targets/svelte/radix/popover.js +15 -0
- package/dist/targets/svelte/radix/progress.d.ts +11 -0
- package/dist/targets/svelte/radix/progress.js +27 -0
- package/dist/targets/svelte/radix/radio-group.d.ts +9 -0
- package/dist/targets/svelte/radix/radio-group.js +26 -0
- package/dist/targets/svelte/radix/scroll-area.d.ts +7 -0
- package/dist/targets/svelte/radix/scroll-area.js +19 -0
- package/dist/targets/svelte/radix/select.d.ts +13 -0
- package/dist/targets/svelte/radix/select.js +81 -0
- package/dist/targets/svelte/radix/separator.d.ts +3 -0
- package/dist/targets/svelte/radix/separator.js +5 -0
- package/dist/targets/svelte/radix/slider.d.ts +6 -0
- package/dist/targets/svelte/radix/slider.js +8 -0
- package/dist/targets/svelte/radix/switch.d.ts +6 -0
- package/dist/targets/svelte/radix/switch.js +10 -0
- package/dist/targets/svelte/radix/tabs.d.ts +8 -0
- package/dist/targets/svelte/radix/tabs.js +15 -0
- package/dist/targets/svelte/radix/toggle-group.d.ts +9 -0
- package/dist/targets/svelte/radix/toggle-group.js +17 -0
- package/dist/targets/svelte/radix/toggle.d.ts +6 -0
- package/dist/targets/svelte/radix/toggle.js +9 -0
- package/dist/targets/svelte/radix/tooltip.d.ts +6 -0
- package/dist/targets/svelte/radix/tooltip.js +24 -0
- package/dist/targets/svelte/strip.d.ts +2 -0
- package/dist/targets/svelte/strip.js +5 -0
- package/dist/targets/vue/emit.d.ts +15 -0
- package/dist/targets/vue/emit.js +4092 -0
- package/dist/targets/vue/events.d.ts +11 -0
- package/dist/targets/vue/events.js +13 -0
- package/dist/targets/vue/module-builders.d.ts +28 -0
- package/dist/targets/vue/module-builders.js +258 -0
- package/dist/targets/vue/motion-layout.d.ts +19 -0
- package/dist/targets/vue/motion-layout.js +79 -0
- package/dist/targets/vue/motion.d.ts +12 -0
- package/dist/targets/vue/motion.js +46 -0
- package/dist/targets/vue/radix/accordion.d.ts +3 -0
- package/dist/targets/vue/radix/accordion.js +12 -0
- package/dist/targets/vue/radix/alert-dialog.d.ts +6 -0
- package/dist/targets/vue/radix/alert-dialog.js +18 -0
- package/dist/targets/vue/radix/aspect-ratio.d.ts +6 -0
- package/dist/targets/vue/radix/aspect-ratio.js +8 -0
- package/dist/targets/vue/radix/avatar.d.ts +3 -0
- package/dist/targets/vue/radix/avatar.js +7 -0
- package/dist/targets/vue/radix/checkbox.d.ts +3 -0
- package/dist/targets/vue/radix/checkbox.js +9 -0
- package/dist/targets/vue/radix/collapsible.d.ts +7 -0
- package/dist/targets/vue/radix/collapsible.js +11 -0
- package/dist/targets/vue/radix/context-menu.d.ts +3 -0
- package/dist/targets/vue/radix/context-menu.js +30 -0
- package/dist/targets/vue/radix/dialog.d.ts +3 -0
- package/dist/targets/vue/radix/dialog.js +12 -0
- package/dist/targets/vue/radix/direction.d.ts +7 -0
- package/dist/targets/vue/radix/direction.js +9 -0
- package/dist/targets/vue/radix/dropdown-menu.d.ts +3 -0
- package/dist/targets/vue/radix/dropdown-menu.js +29 -0
- package/dist/targets/vue/radix/hover-card.d.ts +3 -0
- package/dist/targets/vue/radix/hover-card.js +11 -0
- package/dist/targets/vue/radix/index.d.ts +65 -0
- package/dist/targets/vue/radix/index.js +225 -0
- package/dist/targets/vue/radix/label.d.ts +3 -0
- package/dist/targets/vue/radix/label.js +5 -0
- package/dist/targets/vue/radix/menubar.d.ts +6 -0
- package/dist/targets/vue/radix/menubar.js +29 -0
- package/dist/targets/vue/radix/navigation-menu.d.ts +6 -0
- package/dist/targets/vue/radix/navigation-menu.js +21 -0
- package/dist/targets/vue/radix/part.d.ts +41 -0
- package/dist/targets/vue/radix/part.js +46 -0
- package/dist/targets/vue/radix/popover.d.ts +3 -0
- package/dist/targets/vue/radix/popover.js +11 -0
- package/dist/targets/vue/radix/progress.d.ts +3 -0
- package/dist/targets/vue/radix/progress.js +6 -0
- package/dist/targets/vue/radix/radio-group.d.ts +3 -0
- package/dist/targets/vue/radix/radio-group.js +10 -0
- package/dist/targets/vue/radix/scroll-area.d.ts +3 -0
- package/dist/targets/vue/radix/scroll-area.js +11 -0
- package/dist/targets/vue/radix/select.d.ts +3 -0
- package/dist/targets/vue/radix/select.js +29 -0
- package/dist/targets/vue/radix/separator.d.ts +3 -0
- package/dist/targets/vue/radix/separator.js +5 -0
- package/dist/targets/vue/radix/slider.d.ts +3 -0
- package/dist/targets/vue/radix/slider.js +13 -0
- package/dist/targets/vue/radix/switch.d.ts +3 -0
- package/dist/targets/vue/radix/switch.js +9 -0
- package/dist/targets/vue/radix/tabs.d.ts +3 -0
- package/dist/targets/vue/radix/tabs.js +12 -0
- package/dist/targets/vue/radix/toggle-group.d.ts +3 -0
- package/dist/targets/vue/radix/toggle-group.js +10 -0
- package/dist/targets/vue/radix/toggle.d.ts +3 -0
- package/dist/targets/vue/radix/toggle.js +8 -0
- package/dist/targets/vue/radix/tooltip.d.ts +3 -0
- package/dist/targets/vue/radix/tooltip.js +14 -0
- package/dist/targets/vue/render-fn/h.d.ts +52 -0
- package/dist/targets/vue/render-fn/h.js +442 -0
- package/dist/targets/vue/render-fn.d.ts +21 -0
- package/dist/targets/vue/render-fn.js +357 -0
- package/dist/targets/vue/slot.d.ts +9 -0
- package/dist/targets/vue/slot.js +57 -0
- package/dist/typecheck/host.d.ts +45 -0
- package/dist/typecheck/host.js +309 -0
- package/dist/typecheck/index.d.ts +16 -0
- package/dist/typecheck/index.js +17 -0
- package/dist/typecheck/lucide.d.ts +8 -0
- package/dist/typecheck/lucide.js +45 -0
- package/dist/typecheck/sourcemap.d.ts +9 -0
- package/dist/typecheck/sourcemap.js +54 -0
- package/dist/typecheck/svelte.d.ts +9 -0
- package/dist/typecheck/svelte.js +116 -0
- package/dist/typecheck/vue.d.ts +8 -0
- package/dist/typecheck/vue.js +78 -0
- package/dist/types.d.ts +446 -0
- package/dist/types.js +11 -0
- package/dist/utils/cleanup.d.ts +32 -0
- package/dist/utils/cleanup.js +119 -0
- package/dist/utils/errors.d.ts +7 -0
- package/dist/utils/errors.js +15 -0
- package/dist/utils/fs-safe.d.ts +14 -0
- package/dist/utils/fs-safe.js +64 -0
- package/dist/validate.d.ts +16 -0
- package/dist/validate.js +204 -0
- package/dist/verify/auto-steps.d.ts +107 -0
- package/dist/verify/auto-steps.js +471 -0
- package/dist/verify/bundle.d.ts +68 -0
- package/dist/verify/bundle.js +548 -0
- package/dist/verify/diff.d.ts +31 -0
- package/dist/verify/diff.js +133 -0
- package/dist/verify/leaks.d.ts +25 -0
- package/dist/verify/leaks.js +261 -0
- package/dist/verify/link-worker.d.ts +1 -0
- package/dist/verify/link-worker.js +27 -0
- package/dist/verify/runner.d.ts +57 -0
- package/dist/verify/runner.js +867 -0
- package/dist/verify/sandbox.d.ts +40 -0
- package/dist/verify/sandbox.js +496 -0
- package/dist/verify/steps.d.ts +42 -0
- package/dist/verify/steps.js +475 -0
- package/dist/verify/verdict.d.ts +15 -0
- package/dist/verify/verdict.js +19 -0
- package/package.json +118 -4
|
@@ -0,0 +1,4092 @@
|
|
|
1
|
+
import * as t from '@babel/types';
|
|
2
|
+
import { childAt, setChildAt } from '../../ir/walk.js';
|
|
3
|
+
import { parseSource } from '../../analyzer/parse.js';
|
|
4
|
+
import { resolveLocal } from '../../analyzer/deps.js';
|
|
5
|
+
import { assertPaths, containsJSX, nonNullFacts, patternNames, unwrap } from '../../ir/lower.js';
|
|
6
|
+
import { isDomEventProp } from '../../ir/dom.js';
|
|
7
|
+
import { KEPT_CASTS, bindingsUsed, cloneWithRefs, renameFree, rewrite, stripTypes, transform, writesState } from '../../ir/rewrite.js';
|
|
8
|
+
import { isStringy, isUnitless, numericLiteral, reactStyleValue, styleKey, unitlessSource } from '../../ir/style.js';
|
|
9
|
+
import { ImportSet, importPath, keepProvidersFiled } from '../shared/layout.js';
|
|
10
|
+
import { markupNames, pruneUnused, wordsIn } from '../shared/prune.js';
|
|
11
|
+
import { isElementTest, reactRuntimeReads, reactValues, replaceElementTests, reportReactRuntime } from '../shared/react-values.js';
|
|
12
|
+
import { renderFunction, renderHelperValue } from './render-fn.js';
|
|
13
|
+
import { writeMarkup } from './render-fn/h.js';
|
|
14
|
+
import { MARKUP_NODES_SOURCE, buildsModuleElements, planElementBuilders } from './module-builders.js';
|
|
15
|
+
import { expandUse } from '../shared/inline.js';
|
|
16
|
+
import { addOriginalImport, moduleFacts, namesIn, ownTypeOnly, rewriteImportTypes, rewriteReexport, transformModuleBody } from '../shared/module.js';
|
|
17
|
+
import { bareExpression, holdsMotionValue } from '../shared/motion-hooks.js';
|
|
18
|
+
import { inheritedAttrType, mapReactTypes } from '../shared/react-types.js';
|
|
19
|
+
import { NameAllocator, buildCore, cutLeftoverJsx, moduleLets, moduleSetters, orNull, reactiveDeps, refHolds, routeModuleWrites, replaceReturns, returnsValue, trimTrailingReturn, typedCall } from '../shared/script.js';
|
|
20
|
+
import { SVG_TAGS, VOID_TAGS, componentStyle, escapeAttr, escapeText, genericsAttr, innerHtmlWarning, printExpr, printProgram } from '../shared/markup.js';
|
|
21
|
+
import { vueMotionAttrs } from './motion.js';
|
|
22
|
+
// M2: the line a bare layout or drag prop is reported at
|
|
23
|
+
import { DRAG_PROPS, elementLine, layoutDragParams } from '../shared/motion-layout.js';
|
|
24
|
+
import { VUE_DRAG, VUE_LAYOUT, VUE_LAYOUT_FILE, useVueLayout } from './motion-layout.js';
|
|
25
|
+
import { VUE_SLOT, VUE_SLOT_FILE, useVueSlot } from './slot.js';
|
|
26
|
+
import { PRESS_FOCUS_LISTENER, PRESS_FOCUS_SOURCE, RADIX_PROPS_SOURCE, vueRadixPart, vueRadixRenames, vueRadixRestType } from './radix/index.js';
|
|
27
|
+
import { readsPage } from '../shared/portal.js';
|
|
28
|
+
import { droppedSlotMessage, renderProp as renderPropOf, rendersSlot, renderSignature, slotName } from '../../ir/render-props.js';
|
|
29
|
+
import { writeFragmentsInPlace } from '../shared/fragments.js';
|
|
30
|
+
// M4: the function a tree helper was lowered from
|
|
31
|
+
import { fragmentSource } from '../../ir/fragment-source.js';
|
|
32
|
+
import { contextModuleBody, defaultName, guardedContext, inlineDefault, linkContexts } from '../shared/context.js';
|
|
33
|
+
import { contextOfRead } from '../../ir/contexts.js';
|
|
34
|
+
import { childComponent, domElementType, forwardedElement, forwardsElement, handleMemberNamesAcross, handleMembers, handleProblem, handleType, handleValue, passesHandle, passesHandleEach, readsReactive } from '../shared/handles.js';
|
|
35
|
+
import { propWrites } from '../shared/prop-writes.js';
|
|
36
|
+
import { vueDomEvent } from './events.js';
|
|
37
|
+
import { settlesLikeReact } from '../shared/ref-callback.js';
|
|
38
|
+
const VUE_APIS = ['ref', 'computed', 'watch', 'watchEffect', 'watchPostEffect', 'onMounted', 'onUnmounted', 'useAttrs', 'useId', 'useSlots', 'reactive', 'inject', 'provide', 'shallowRef'];
|
|
39
|
+
/** `props.className` is `props.class` in Vue */
|
|
40
|
+
export const VUE_PROP_RENAMES = new Map([['className', 'class']]);
|
|
41
|
+
/** Script-side emission shared by components and composables. */
|
|
42
|
+
class VueScript {
|
|
43
|
+
ir;
|
|
44
|
+
alloc;
|
|
45
|
+
ctx;
|
|
46
|
+
facts;
|
|
47
|
+
outPath;
|
|
48
|
+
vue = new Map();
|
|
49
|
+
helpers = new Set();
|
|
50
|
+
typeImports = [];
|
|
51
|
+
cores = [];
|
|
52
|
+
imports = new ImportSet();
|
|
53
|
+
/** types copied from props declared in other files: their names are imported from there */
|
|
54
|
+
foreignTypes = [];
|
|
55
|
+
constructor(ir, alloc, ctx, facts,
|
|
56
|
+
/** the output file this script goes into (imports are written relative to it) */
|
|
57
|
+
outPath) {
|
|
58
|
+
this.ir = ir;
|
|
59
|
+
this.alloc = alloc;
|
|
60
|
+
this.ctx = ctx;
|
|
61
|
+
this.facts = facts;
|
|
62
|
+
this.outPath = outPath;
|
|
63
|
+
}
|
|
64
|
+
api(name) {
|
|
65
|
+
let local = this.vue.get(name);
|
|
66
|
+
if (!local) {
|
|
67
|
+
local = this.alloc.has(name) ? this.alloc.alloc(`vue${name.charAt(0).toUpperCase()}${name.slice(1)}`) : name;
|
|
68
|
+
this.alloc.reserve(local);
|
|
69
|
+
this.vue.set(name, local);
|
|
70
|
+
}
|
|
71
|
+
return local;
|
|
72
|
+
}
|
|
73
|
+
r(node, skip) {
|
|
74
|
+
return this.slotReads(rewrite(node, { ir: this.ir, mode: 'vue-script', propRenames: VUE_PROP_RENAMES, ...(skip ? { skip } : {}) }));
|
|
75
|
+
}
|
|
76
|
+
/** The name `useSlots()` is kept under, once script code reads whether children were given. */
|
|
77
|
+
slotsName = null;
|
|
78
|
+
/** The name `useSlots()` is kept under, declared once something reads the slots. */
|
|
79
|
+
slotsLocal() {
|
|
80
|
+
this.slotsName ??= this.alloc.alloc('slots');
|
|
81
|
+
return this.slotsName;
|
|
82
|
+
}
|
|
83
|
+
/** The `useSlots()` name when something reads the slots already, else null. */
|
|
84
|
+
slotsDeclared() {
|
|
85
|
+
return this.slotsName;
|
|
86
|
+
}
|
|
87
|
+
/** Code that would have read the slots was not written: `useSlots()` is declared only if it was before. */
|
|
88
|
+
restoreSlots(before) {
|
|
89
|
+
this.slotsName = before;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* `children` read in script code (`children || !errors?.length ? …`): Vue's children are the default slot, a
|
|
93
|
+
* function exactly when the parent gave some, so a test of it reads the same through `useSlots()`.
|
|
94
|
+
*/
|
|
95
|
+
slotReads(node) {
|
|
96
|
+
const children = childrenLocal(this.ir);
|
|
97
|
+
if (!children)
|
|
98
|
+
return node;
|
|
99
|
+
for (const at of childrenTests(node, this.ir, children)) {
|
|
100
|
+
this.slotsName ??= this.alloc.alloc('slots');
|
|
101
|
+
const slot = t.memberExpression(t.identifier(this.slotsName), t.identifier('default'));
|
|
102
|
+
const held = childAt(at.holder, at.key);
|
|
103
|
+
if (Array.isArray(held) && at.index !== null)
|
|
104
|
+
held[at.index] = slot;
|
|
105
|
+
else
|
|
106
|
+
setChildAt(at.holder, at.key, slot);
|
|
107
|
+
}
|
|
108
|
+
return node;
|
|
109
|
+
}
|
|
110
|
+
type(type) {
|
|
111
|
+
return type ? mapReactTypes(t.cloneNode(type, true), 'vue', this.facts.reactNames, this.typeImports) : null;
|
|
112
|
+
}
|
|
113
|
+
warn(code, message, severity = 'warning', line) {
|
|
114
|
+
// an error about a component with no line of its own points at the component (see sparesUnusedComponents)
|
|
115
|
+
const at = line ?? (severity === 'error' ? this.ir.line : undefined);
|
|
116
|
+
this.ctx.diagnostics.push({ code, severity, message, file: this.ctx.sourceRel, target: 'vue', ...(at ? { line: at } : {}) });
|
|
117
|
+
}
|
|
118
|
+
constDecl(name, init, kind = 'const') {
|
|
119
|
+
return t.variableDeclaration(kind, [t.variableDeclarator(typeof name === 'string' ? t.identifier(name) : name, init)]);
|
|
120
|
+
}
|
|
121
|
+
computed(body, type) {
|
|
122
|
+
return typedCall(this.api('computed'), this.type(type), [t.arrowFunctionExpression([], body)]);
|
|
123
|
+
}
|
|
124
|
+
items() {
|
|
125
|
+
const out = [];
|
|
126
|
+
for (const item of this.ir.items)
|
|
127
|
+
out.push(...this.item(item).map((s) => mapReactTypes(s, 'vue', this.facts.reactNames, this.typeImports)));
|
|
128
|
+
return out;
|
|
129
|
+
}
|
|
130
|
+
item(item) {
|
|
131
|
+
const b = (name) => this.ir.bindings.get(name);
|
|
132
|
+
switch (item.kind) {
|
|
133
|
+
case 'state':
|
|
134
|
+
return [this.constDecl(item.name, typedCall(this.api('ref'), this.type(item.type), item.init ? [this.r(item.init)] : []))];
|
|
135
|
+
case 'reducer': {
|
|
136
|
+
const action = t.identifier('action');
|
|
137
|
+
if (t.isIdentifier(item.reducer)) {
|
|
138
|
+
action.typeAnnotation = t.tsTypeAnnotation(t.tsIndexedAccessType(t.tsTypeReference(t.identifier('Parameters'), t.tsTypeParameterInstantiation([t.tsTypeQuery(t.identifier(item.reducer.name))])), t.tsLiteralType(t.numericLiteral(1))));
|
|
139
|
+
}
|
|
140
|
+
const value = t.memberExpression(t.identifier(item.name), t.identifier('value'));
|
|
141
|
+
return [
|
|
142
|
+
this.constDecl(item.name, t.callExpression(t.identifier(this.api('ref')), [this.r(item.init)])),
|
|
143
|
+
t.functionDeclaration(t.identifier(item.dispatch), [action], t.blockStatement([t.expressionStatement(t.assignmentExpression('=', value, t.callExpression(this.r(item.reducer), [t.cloneNode(value), t.identifier('action')])))])),
|
|
144
|
+
];
|
|
145
|
+
}
|
|
146
|
+
case 'ref': {
|
|
147
|
+
const binding = b(item.name);
|
|
148
|
+
const type = this.type(item.type);
|
|
149
|
+
if (binding?.refKind === 'dom') {
|
|
150
|
+
const elType = type ?? t.tsTypeReference(t.identifier('HTMLElement'));
|
|
151
|
+
return [this.constDecl(item.name, typedCall(this.api('ref'), orNull(elType), [t.nullLiteral()]))];
|
|
152
|
+
}
|
|
153
|
+
const init = item.init ? this.r(item.init) : null;
|
|
154
|
+
if (binding?.escapes) {
|
|
155
|
+
const id = t.identifier(item.name);
|
|
156
|
+
if (type)
|
|
157
|
+
id.typeAnnotation = t.tsTypeAnnotation(t.tsTypeLiteral([t.tsPropertySignature(t.identifier('current'), t.tsTypeAnnotation(refHolds(type, init)))]));
|
|
158
|
+
return [this.constDecl(id, t.objectExpression([t.objectProperty(t.identifier('current'), init ?? t.identifier('undefined'))]))];
|
|
159
|
+
}
|
|
160
|
+
const id = t.identifier(item.name);
|
|
161
|
+
if (type)
|
|
162
|
+
id.typeAnnotation = t.tsTypeAnnotation(refHolds(type, init));
|
|
163
|
+
return [t.variableDeclaration('let', [t.variableDeclarator(id, init)])];
|
|
164
|
+
}
|
|
165
|
+
case 'derived': {
|
|
166
|
+
// a value that awaits (an async component, refused as async-component) cannot be a computed, whose getter is
|
|
167
|
+
// not async: it stays a const of the setup script, where Vue allows `await`, so the refused file still compiles
|
|
168
|
+
const reactive = item.names.some((n) => b(n)?.reactive) && !awaitsInPlace(item.init);
|
|
169
|
+
if (!reactive) {
|
|
170
|
+
const id = t.cloneNode(item.id, true);
|
|
171
|
+
if (t.isIdentifier(id) && id.typeAnnotation && t.isTSTypeAnnotation(id.typeAnnotation))
|
|
172
|
+
id.typeAnnotation = t.tsTypeAnnotation(this.type(id.typeAnnotation.typeAnnotation) ?? t.tsUnknownKeyword());
|
|
173
|
+
return [t.variableDeclaration(item.declKind, [t.variableDeclarator(id, this.r(item.init))])];
|
|
174
|
+
}
|
|
175
|
+
if (t.isIdentifier(item.id))
|
|
176
|
+
return [this.constDecl(item.id.name, this.computed(this.r(item.init), item.type))];
|
|
177
|
+
return this.destructuredComputed(item.id, this.r(item.init));
|
|
178
|
+
}
|
|
179
|
+
case 'block': {
|
|
180
|
+
const reactive = b(item.name)?.reactive && !item.statements.some((s) => awaitsInPlace(s));
|
|
181
|
+
const skip = new Set([item.name]);
|
|
182
|
+
const statements = item.statements.map((s) => this.r(s, skip));
|
|
183
|
+
const fnBody = t.blockStatement(item.returns ? statements : [...statements, t.returnStatement(t.identifier(item.name))]);
|
|
184
|
+
if (reactive)
|
|
185
|
+
return [this.constDecl(item.name, this.computed(fnBody, item.type))];
|
|
186
|
+
if (!item.returns)
|
|
187
|
+
return statements;
|
|
188
|
+
return [this.constDecl(item.name, t.callExpression(t.parenthesizedExpression(t.arrowFunctionExpression([], fnBody)), []))];
|
|
189
|
+
}
|
|
190
|
+
case 'function': {
|
|
191
|
+
const node = this.r(item.node);
|
|
192
|
+
if (t.isFunctionDeclaration(node))
|
|
193
|
+
return [node];
|
|
194
|
+
return [this.constDecl(item.name, node)];
|
|
195
|
+
}
|
|
196
|
+
case 'effect':
|
|
197
|
+
return this.effect(item);
|
|
198
|
+
case 'id':
|
|
199
|
+
return [this.constDecl(item.name, t.callExpression(t.identifier(this.api('useId')), []))];
|
|
200
|
+
case 'hook': {
|
|
201
|
+
// motion-v's useInView watches the element Ref itself (not a { current } box, which it would take for the
|
|
202
|
+
// element), and a `ref as RefObject<Element>` cast names React's types (read before the rewrite boxes it)
|
|
203
|
+
const watched = item.source === 'motion' && item.hook === 'useInView' && t.isExpression(item.call.arguments[0]) ? bareExpression(item.call.arguments[0]) : null;
|
|
204
|
+
const watchedRef = t.isIdentifier(watched) && this.ir.bindings.get(watched.name)?.refKind === 'dom' ? watched.name : null;
|
|
205
|
+
const call = this.r(item.call);
|
|
206
|
+
if (item.source === 'local' && !item.live)
|
|
207
|
+
this.checkHookArgs(item.call, item.hook);
|
|
208
|
+
// Framer's useTransform reads its ranges and useSpring its options on every render; motion-v's read them once,
|
|
209
|
+
// when the component is set up (`useTransform(x, [-distance, 0, distance], [size, big, size])` keeps the first size)
|
|
210
|
+
// Where an exact form exists it is written instead: the ranges read inside motion-v's computed form, which a
|
|
211
|
+
// Vue effect re-runs when a prop or state it reads changes (as Framer recomputes on render), and useSpring's
|
|
212
|
+
// options as a computed (motion-v watches them)
|
|
213
|
+
const live = item.source === 'motion' ? this.liveMotionArgs(item.call, call, item.hook) : false;
|
|
214
|
+
if (item.source === 'motion' && !live && (item.hook === 'useTransform' || item.hook === 'useSpring'))
|
|
215
|
+
this.checkHookArgs(item.call, item.hook);
|
|
216
|
+
if (item.hook === 'useAnimation') {
|
|
217
|
+
// motion-v names Framer's useAnimation useAnimationControls
|
|
218
|
+
call.callee = t.identifier('useAnimationControls');
|
|
219
|
+
}
|
|
220
|
+
if (watchedRef)
|
|
221
|
+
call.arguments[0] = t.identifier(watchedRef);
|
|
222
|
+
// `const ctl = useSliderControl()` with refs among its members: reactive() reads them unwrapped (`ctl.value` is
|
|
223
|
+
// the number, in script and template alike), as the React object held plain values
|
|
224
|
+
if (item.id && item.wholeReactive)
|
|
225
|
+
return [this.constDecl(item.id, t.callExpression(t.identifier(this.api('reactive')), [call]))];
|
|
226
|
+
return item.id ? [this.constDecl(item.id, call)] : [t.expressionStatement(call)];
|
|
227
|
+
}
|
|
228
|
+
case 'statement': {
|
|
229
|
+
// an assignment to a prop is refused (prop-write); written, Vue's compiler rejects the whole file
|
|
230
|
+
if ('template' in this.ir && assignsProp(item.node, this.ir)) {
|
|
231
|
+
const left = t.emptyStatement();
|
|
232
|
+
t.addComment(left, 'leading', ' antheo-morph: not converted: this statement assigns to a prop (see the prop-write diagnostic) ');
|
|
233
|
+
return [left];
|
|
234
|
+
}
|
|
235
|
+
return [this.r(item.node)];
|
|
236
|
+
}
|
|
237
|
+
case 'expose':
|
|
238
|
+
return [t.expressionStatement(t.callExpression(t.identifier('defineExpose'), [this.r(item.object)]))];
|
|
239
|
+
case 'context':
|
|
240
|
+
return [this.constDecl(item.name, this.inject(item))];
|
|
241
|
+
case 'forward': {
|
|
242
|
+
const b = this.ir.bindings.get(item.ref);
|
|
243
|
+
if (b?.refKind !== 'dom') {
|
|
244
|
+
this.warn('imperative-handle', `The handle is ${item.ref}.current, which is not an element ref the template fills: not exposed.`, 'error');
|
|
245
|
+
return [];
|
|
246
|
+
}
|
|
247
|
+
return [this.exposeElement(item.ref)];
|
|
248
|
+
}
|
|
249
|
+
case 'handle':
|
|
250
|
+
return this.handle(item);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
/** The element a parent's ref reaches, exposed as `el`, with `focus` and `blur` (what a parent calls on an element). */
|
|
254
|
+
exposeElement(ref) {
|
|
255
|
+
const value = () => t.optionalMemberExpression(t.memberExpression(t.identifier(ref), t.identifier('value')), t.identifier('focus'), false, true);
|
|
256
|
+
const options = t.identifier('options');
|
|
257
|
+
options.optional = true;
|
|
258
|
+
options.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier('FocusOptions')));
|
|
259
|
+
const focus = t.arrowFunctionExpression([options], t.optionalCallExpression(value(), [t.identifier('options')], false));
|
|
260
|
+
const blurRead = value();
|
|
261
|
+
blurRead.property = t.identifier('blur');
|
|
262
|
+
const blur = t.arrowFunctionExpression([], t.optionalCallExpression(blurRead, [], false));
|
|
263
|
+
return t.expressionStatement(t.callExpression(t.identifier('defineExpose'), [
|
|
264
|
+
t.objectExpression([t.objectProperty(t.identifier('el'), t.identifier(ref), false, ref === 'el'), t.objectProperty(t.identifier('focus'), focus), t.objectProperty(t.identifier('blur'), blur)]),
|
|
265
|
+
]));
|
|
266
|
+
}
|
|
267
|
+
/** A component the template renders, by tag (set by the emitter, which knows the graph). */
|
|
268
|
+
childOf = () => null;
|
|
269
|
+
/** A template ref for the element `ref={ref}` forwards to, declared once (see forwardStatements). */
|
|
270
|
+
forwarded = null;
|
|
271
|
+
forwardTarget(tag) {
|
|
272
|
+
if (!this.forwarded) {
|
|
273
|
+
const name = this.alloc.alloc('el');
|
|
274
|
+
this.alloc.reserve(name);
|
|
275
|
+
this.forwarded = { name, type: domElementType(tag) };
|
|
276
|
+
}
|
|
277
|
+
return this.forwarded.name;
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* The forwarded ref put on a child component that exposes an imperative handle (an object literal of members, see
|
|
281
|
+
* handleMemberNames), always rendered while this one is: a template ref of the child, whose members this component
|
|
282
|
+
* exposes as getters of the child's current ones, so a parent's ref reaches the same members React's ref.current had.
|
|
283
|
+
*/
|
|
284
|
+
passed = null;
|
|
285
|
+
/**
|
|
286
|
+
* The ref may also go to one of several child components, exactly one of them rendered on every path (see
|
|
287
|
+
* passesHandleEach): they share the one template ref (Vue empties it when a branch unmounts and fills it with the one
|
|
288
|
+
* that mounts), and the members are the ones all of them expose.
|
|
289
|
+
*/
|
|
290
|
+
passedHandle(tag) {
|
|
291
|
+
const ir = this.ir;
|
|
292
|
+
const isComponent = (x) => 'template' in x;
|
|
293
|
+
if (!isComponent(ir) || !ir.forwardRef || itemsRead(ir, ir.forwardRef))
|
|
294
|
+
return null;
|
|
295
|
+
const single = passesHandle(ir);
|
|
296
|
+
const tags = single ? [single.node.tag] : [...new Set((passesHandleEach(ir) ?? []).map((n) => n.tag))];
|
|
297
|
+
if (!tags.includes(tag))
|
|
298
|
+
return null;
|
|
299
|
+
let members = null;
|
|
300
|
+
for (const each of tags) {
|
|
301
|
+
const child = this.childOf(each);
|
|
302
|
+
const got = child ? handleMemberNamesAcross(child, (parent, inner) => this.childOfAny(parent, inner))?.map((m) => m.name) : null;
|
|
303
|
+
if (!got || !got.every((m) => /^[A-Za-z_$][\w$]*$/.test(m)))
|
|
304
|
+
return null;
|
|
305
|
+
members ??= got;
|
|
306
|
+
}
|
|
307
|
+
if (!members)
|
|
308
|
+
return null;
|
|
309
|
+
if (!this.passed) {
|
|
310
|
+
const name = this.alloc.alloc('inner');
|
|
311
|
+
this.alloc.reserve(name);
|
|
312
|
+
this.passed = { name, tags, members };
|
|
313
|
+
}
|
|
314
|
+
return this.passed.name;
|
|
315
|
+
}
|
|
316
|
+
/** Why a forwarded ref put on a child component is not passed on. */
|
|
317
|
+
forwardProblem(tag) {
|
|
318
|
+
const child = this.childOf(tag);
|
|
319
|
+
if (!child)
|
|
320
|
+
return `<${tag}> is not a component of this conversion, so what its ref holds is unknown; a Vue parent's template ref on this component holds this component's instance, not <${tag}>'s.`;
|
|
321
|
+
if (forwardsElement(child))
|
|
322
|
+
return `<${tag}> exposes its element as { el, focus, blur }; a Vue parent's template ref on this component holds this component's instance, not <${tag}>'s.`;
|
|
323
|
+
return `a Vue parent's template ref on this component holds this component's instance, not <${tag}>'s (the ref is passed on only to one component that is always rendered, or to several of which exactly one is rendered on every path, each exposing the same handle written as an object literal).`;
|
|
324
|
+
}
|
|
325
|
+
/** A component another component of the graph renders (set by the emitter, which knows the graph). */
|
|
326
|
+
childOfAny = () => null;
|
|
327
|
+
forwardStatements() {
|
|
328
|
+
const out = [];
|
|
329
|
+
if (this.passed) {
|
|
330
|
+
const { name, tags, members } = this.passed;
|
|
331
|
+
const instances = tags.map((tag) => t.tsTypeReference(t.identifier('InstanceType'), t.tsTypeParameterInstantiation([t.tsTypeQuery(t.identifier(tag))])));
|
|
332
|
+
out.push(this.constDecl(name, typedCall(this.api('ref'), t.tsUnionType([...instances, t.tsNullKeyword()]), [t.nullLiteral()])));
|
|
333
|
+
const current = t.memberExpression(t.identifier(name), t.identifier('value'));
|
|
334
|
+
const getters = members.map((m) => t.objectMethod('get', t.identifier(m), [], t.blockStatement([t.returnStatement(t.optionalMemberExpression(t.cloneNode(current), t.identifier(m), false, true))])));
|
|
335
|
+
out.push(t.expressionStatement(t.callExpression(t.identifier('defineExpose'), [t.objectExpression(getters)])));
|
|
336
|
+
}
|
|
337
|
+
if (!this.forwarded)
|
|
338
|
+
return out;
|
|
339
|
+
const { name, type } = this.forwarded;
|
|
340
|
+
return [...out, this.constDecl(name, typedCall(this.api('ref'), t.tsUnionType([type, t.tsNullKeyword()]), [t.nullLiteral()])), this.exposeElement(name)];
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* A handle that is not an object literal. Built from values that never change, it is exposed as it is; reading
|
|
344
|
+
* reactive values, it is computed, and each member a parent reaches is a getter of the current handle's.
|
|
345
|
+
*/
|
|
346
|
+
handle(item) {
|
|
347
|
+
const members = handleMembers(item, this.ir, this.ctx);
|
|
348
|
+
const reactive = readsReactive(item.value, this.ir);
|
|
349
|
+
const problem = handleProblem(members, reactive, false);
|
|
350
|
+
if (problem || (reactive && !members)) {
|
|
351
|
+
this.warn('imperative-handle', problem ?? 'useImperativeHandle: the handle is not converted.', 'error');
|
|
352
|
+
return [];
|
|
353
|
+
}
|
|
354
|
+
const value = this.r(handleValue(item.value));
|
|
355
|
+
if (!reactive || !members)
|
|
356
|
+
return [t.expressionStatement(t.callExpression(t.identifier('defineExpose'), [value]))];
|
|
357
|
+
const handle = this.alloc.alloc('handle');
|
|
358
|
+
this.alloc.reserve(handle);
|
|
359
|
+
const type = handleType(item, this.ir);
|
|
360
|
+
const current = t.memberExpression(t.identifier(handle), t.identifier('value'));
|
|
361
|
+
const getters = members.map((m) => {
|
|
362
|
+
const key = /^[A-Za-z_$][\w$]*$/.test(m.name) ? t.identifier(m.name) : t.stringLiteral(m.name);
|
|
363
|
+
const read = t.isIdentifier(key) ? t.memberExpression(t.cloneNode(current), t.identifier(m.name)) : t.memberExpression(t.cloneNode(current), t.stringLiteral(m.name), true);
|
|
364
|
+
// a member only some forms of an untyped handle have: read where the current one has it
|
|
365
|
+
const value = m.always || type ? read : t.conditionalExpression(t.binaryExpression('in', t.stringLiteral(m.name), t.cloneNode(current)), read, t.identifier('undefined'));
|
|
366
|
+
return t.objectMethod('get', key, [], t.blockStatement([t.returnStatement(value)]));
|
|
367
|
+
});
|
|
368
|
+
return [this.constDecl(handle, typedCall(this.api('computed'), this.type(type), [t.arrowFunctionExpression([], value)])), t.expressionStatement(t.callExpression(t.identifier('defineExpose'), [t.objectExpression(getters)]))];
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* `inject(Ctx, shallowRef(fallback))`: the provider's ref (see shared/context), or, with no provider above, a ref of
|
|
372
|
+
* the default, so a consumer always reads `.value` and never holds a snapshot.
|
|
373
|
+
*/
|
|
374
|
+
inject(item) {
|
|
375
|
+
const ref = contextOfRead(item);
|
|
376
|
+
if (!ref)
|
|
377
|
+
return t.identifier('undefined');
|
|
378
|
+
return this.injectRef(ref, item.context);
|
|
379
|
+
}
|
|
380
|
+
injectRef(ref, local) {
|
|
381
|
+
let fallback = inlineDefault(ref.decl);
|
|
382
|
+
if (!fallback) {
|
|
383
|
+
const name = defaultName(ref.decl);
|
|
384
|
+
fallback = t.identifier(name);
|
|
385
|
+
// a context of another file: its default comes from there too (one of this file's is a module name already)
|
|
386
|
+
const layout = ref.file === this.ctx.sourceFile ? null : this.ctx.layoutOf(ref.file);
|
|
387
|
+
if (layout)
|
|
388
|
+
this.imports.named(importPath(this.outPath, layout.modulePath), name);
|
|
389
|
+
}
|
|
390
|
+
return t.callExpression(t.identifier(this.api('inject')), [t.identifier(local), t.callExpression(t.identifier(this.api('shallowRef')), [fallback])]);
|
|
391
|
+
}
|
|
392
|
+
/** `provide(Ctx, …)` for each provider the markup had: the component's own ref, or a computed of the value. */
|
|
393
|
+
provides(comp) {
|
|
394
|
+
return comp.provides.flatMap((p) => {
|
|
395
|
+
if (p.when) {
|
|
396
|
+
// a provider under a condition: its value while the condition holds, the one from above otherwise
|
|
397
|
+
const above = this.alloc.alloc(`${p.context.local.charAt(0).toLowerCase()}${p.context.local.slice(1)}Above`);
|
|
398
|
+
this.alloc.reserve(above);
|
|
399
|
+
const choice = t.conditionalExpression(this.r(p.when), this.r(p.value), t.memberExpression(t.identifier(above), t.identifier('value')));
|
|
400
|
+
return [this.constDecl(above, this.injectRef(p.context, p.context.local)), t.expressionStatement(t.callExpression(t.identifier(this.api('provide')), [t.identifier(p.context.local), t.callExpression(t.identifier(this.api('computed')), [t.arrowFunctionExpression([], choice)])]))];
|
|
401
|
+
}
|
|
402
|
+
const value = unwrap(p.value);
|
|
403
|
+
const b = t.isIdentifier(value) ? this.ir.bindings.get(this.ir.refs.get(value) ?? '') : undefined;
|
|
404
|
+
const isRef = !!b && (b.kind === 'state' || b.kind === 'reducer' || ((b.kind === 'derived' || b.kind === 'hook') && b.reactive));
|
|
405
|
+
const provided = isRef && b ? t.identifier(b.name) : t.callExpression(t.identifier(this.api('computed')), [t.arrowFunctionExpression([], this.r(p.value))]);
|
|
406
|
+
return [t.expressionStatement(t.callExpression(t.identifier(this.api('provide')), [t.identifier(p.context.local), provided]))];
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
/** Whether an argument reads a prop or state (a value React passes anew on every render). */
|
|
410
|
+
readsReactive(e) {
|
|
411
|
+
if (t.isFunction(e))
|
|
412
|
+
return false;
|
|
413
|
+
if (t.isObjectExpression(e))
|
|
414
|
+
return e.properties.some((p) => (t.isObjectProperty(p) ? this.readsReactive(p.value) : t.isSpreadElement(p) ? this.readsReactive(p.argument) : false));
|
|
415
|
+
for (const name of bindingsUsed(e, this.ir)) {
|
|
416
|
+
const binding = this.ir.bindings.get(name);
|
|
417
|
+
if (binding && (binding.kind === 'prop' || binding.kind === 'state' || binding.kind === 'reducer' || binding.kind === 'propsObject' || (binding.kind === 'derived' && binding.reactive)))
|
|
418
|
+
return true;
|
|
419
|
+
}
|
|
420
|
+
return false;
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Framer's `useTransform(x, inputRange, outputRange, options?)` and `useSpring(source, options)` read their ranges and
|
|
424
|
+
* options on every render. With props or state among them, the exact motion-v form: `useTransform(() =>
|
|
425
|
+
* transform(x.get(), inputRange, outputRange, options))` (motion-v's computed form runs in a Vue effect, so a prop it
|
|
426
|
+
* reads recomputes the value at once, and `x.get()` subscribes to x), and `useSpring(source, computed(() =>
|
|
427
|
+
* options))` (motion-v watches its options). Rewrites `call` (already written for the script); false when the call
|
|
428
|
+
* is not one of these shapes (the caller then warns).
|
|
429
|
+
*/
|
|
430
|
+
liveMotionArgs(original, call, hook) {
|
|
431
|
+
const args = original.arguments;
|
|
432
|
+
if (args.some((a) => !t.isExpression(a)))
|
|
433
|
+
return false;
|
|
434
|
+
if (hook === 'useTransform' && args.length === 2 && args[0] && args[1] && !t.isArrayExpression(args[0]) && (t.isArrowFunctionExpression(args[1]) || t.isFunctionExpression(args[1]))) {
|
|
435
|
+
// `useTransform(x, (v) => …)` whose input is a prop (another motion value may be passed) or whose function reads
|
|
436
|
+
// a prop or state: `useTransform(() => ((v) => …)(x.get()))`, recomputed when either changes
|
|
437
|
+
const fn = args[1];
|
|
438
|
+
const readsInBody = [...bindingsUsed(fn.body, this.ir)].some((name) => {
|
|
439
|
+
const b = this.ir.bindings.get(name);
|
|
440
|
+
return !!b && (b.kind === 'prop' || b.kind === 'state' || b.kind === 'reducer' || b.kind === 'propsObject' || (b.kind === 'derived' && b.reactive));
|
|
441
|
+
});
|
|
442
|
+
if (!this.readsReactive(args[0]) && !readsInBody)
|
|
443
|
+
return false;
|
|
444
|
+
const [x, written] = call.arguments;
|
|
445
|
+
if (!t.isExpression(x) || !(t.isArrowFunctionExpression(written) || t.isFunctionExpression(written)) || fn.params.length !== 1)
|
|
446
|
+
return false;
|
|
447
|
+
call.arguments = [t.arrowFunctionExpression([], t.callExpression(t.parenthesizedExpression(written), [t.callExpression(t.memberExpression(t.parenthesizedExpression(x), t.identifier('get')), [])]))];
|
|
448
|
+
return true;
|
|
449
|
+
}
|
|
450
|
+
if (hook === 'useTransform') {
|
|
451
|
+
const [input, inRange, outRange] = args;
|
|
452
|
+
if (args.length < 3 || args.length > 4 || !input || !inRange || !outRange || t.isFunction(inRange) || t.isArrayExpression(input) || t.isObjectExpression(unwrap(outRange)))
|
|
453
|
+
return false;
|
|
454
|
+
if (this.readsReactive(input) || !args.slice(1).some((a) => this.readsReactive(a)))
|
|
455
|
+
return false;
|
|
456
|
+
const written = call.arguments.filter((a) => t.isExpression(a));
|
|
457
|
+
const [x, ...rest] = written;
|
|
458
|
+
if (!x || written.length !== args.length)
|
|
459
|
+
return false;
|
|
460
|
+
this.imports.named('motion-v', 'transform');
|
|
461
|
+
const value = t.callExpression(t.identifier('transform'), [t.callExpression(t.memberExpression(x, t.identifier('get')), []), ...rest]);
|
|
462
|
+
call.arguments = [t.arrowFunctionExpression([], value)];
|
|
463
|
+
return true;
|
|
464
|
+
}
|
|
465
|
+
if (hook === 'useSpring') {
|
|
466
|
+
const [source, options] = args;
|
|
467
|
+
if (args.length !== 2 || !source || !options || this.readsReactive(source) || !this.readsReactive(options))
|
|
468
|
+
return false;
|
|
469
|
+
const written = call.arguments[1];
|
|
470
|
+
if (!t.isExpression(written))
|
|
471
|
+
return false;
|
|
472
|
+
call.arguments[1] = t.callExpression(t.identifier(this.api('computed')), [t.arrowFunctionExpression([], written)]);
|
|
473
|
+
return true;
|
|
474
|
+
}
|
|
475
|
+
return false;
|
|
476
|
+
}
|
|
477
|
+
/** A hook called with reactive values receives them once (composables run once per component). */
|
|
478
|
+
checkHookArgs(call, hook) {
|
|
479
|
+
const reactiveIn = (e) => {
|
|
480
|
+
if (t.isFunction(e))
|
|
481
|
+
return false;
|
|
482
|
+
if (t.isObjectExpression(e))
|
|
483
|
+
return e.properties.some((p) => (t.isObjectProperty(p) ? reactiveIn(p.value) : t.isSpreadElement(p) ? reactiveIn(p.argument) : false));
|
|
484
|
+
for (const name of bindingsUsed(e, this.ir)) {
|
|
485
|
+
const binding = this.ir.bindings.get(name);
|
|
486
|
+
if (binding && (binding.kind === 'prop' || binding.kind === 'state' || binding.kind === 'reducer' || binding.kind === 'propsObject' || (binding.kind === 'derived' && binding.reactive)))
|
|
487
|
+
return true;
|
|
488
|
+
}
|
|
489
|
+
return false;
|
|
490
|
+
};
|
|
491
|
+
if (call.arguments.some((a) => reactiveIn(a))) {
|
|
492
|
+
this.warn('hook-args-once', `${hook}() is called with reactive values; a composable reads its arguments once, so later prop or state changes do not reach it.`);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
destructuredComputed(pattern, init) {
|
|
496
|
+
const names = patternNames(pattern);
|
|
497
|
+
// a ref read as it is (`theme.value`, from a context or a hook) needs no computed of its own to read from
|
|
498
|
+
const direct = t.isMemberExpression(init) && !init.computed && t.isIdentifier(init.object) && t.isIdentifier(init.property, { name: 'value' });
|
|
499
|
+
const out = [];
|
|
500
|
+
let read;
|
|
501
|
+
if (direct)
|
|
502
|
+
read = init;
|
|
503
|
+
else {
|
|
504
|
+
const source = this.alloc.alloc(`${names[0] ?? 'value'}Source`);
|
|
505
|
+
out.push(this.constDecl(source, this.computed(init, null)));
|
|
506
|
+
read = t.memberExpression(t.identifier(source), t.identifier('value'));
|
|
507
|
+
}
|
|
508
|
+
const simple = (t.isObjectPattern(pattern) && pattern.properties.every((p) => t.isObjectProperty(p) && t.isIdentifier(p.key) && !p.computed && (t.isIdentifier(p.value) || (t.isAssignmentPattern(p.value) && t.isIdentifier(p.value.left))))) || (t.isArrayPattern(pattern) && pattern.elements.every((el) => el === null || t.isIdentifier(el)));
|
|
509
|
+
if (!simple) {
|
|
510
|
+
// rest, nested or defaulted shapes: each name re-destructures the source
|
|
511
|
+
for (const name of names) {
|
|
512
|
+
const body = t.blockStatement([t.variableDeclaration('const', [t.variableDeclarator(t.cloneNode(pattern, true), t.cloneNode(read))]), t.returnStatement(t.identifier(name))]);
|
|
513
|
+
out.push(this.constDecl(name, this.computed(body, null)));
|
|
514
|
+
}
|
|
515
|
+
return out;
|
|
516
|
+
}
|
|
517
|
+
if (t.isObjectPattern(pattern)) {
|
|
518
|
+
for (const p of pattern.properties) {
|
|
519
|
+
if (!t.isObjectProperty(p) || !t.isIdentifier(p.key)) {
|
|
520
|
+
this.warn('derived-pattern', 'A rest or computed key in a destructured derived value is not converted.', 'error');
|
|
521
|
+
continue;
|
|
522
|
+
}
|
|
523
|
+
const access = t.memberExpression(t.cloneNode(read), t.identifier(p.key.name));
|
|
524
|
+
if (t.isIdentifier(p.value))
|
|
525
|
+
out.push(this.constDecl(p.value.name, this.computed(access, null)));
|
|
526
|
+
else if (t.isAssignmentPattern(p.value) && t.isIdentifier(p.value.left))
|
|
527
|
+
out.push(this.constDecl(p.value.left.name, this.computed(t.logicalExpression('??', access, this.r(p.value.right)), null)));
|
|
528
|
+
else
|
|
529
|
+
this.warn('derived-pattern', 'A nested pattern in a destructured derived value is not converted.', 'error');
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
else if (t.isArrayPattern(pattern)) {
|
|
533
|
+
pattern.elements.forEach((el, i) => {
|
|
534
|
+
if (t.isIdentifier(el))
|
|
535
|
+
out.push(this.constDecl(el.name, this.computed(t.memberExpression(t.cloneNode(read), t.numericLiteral(i), true), null)));
|
|
536
|
+
else if (el)
|
|
537
|
+
this.warn('derived-pattern', 'A nested or rest element in a destructured derived value is not converted.', 'error');
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
return out;
|
|
541
|
+
}
|
|
542
|
+
effect(item) {
|
|
543
|
+
let body;
|
|
544
|
+
if (item.core && this.ir.bindings.size && 'template' in this.ir) {
|
|
545
|
+
const comp = this.ir;
|
|
546
|
+
const core = buildCore(comp, item, item.core, (name) => this.ctx.oracle?.typeOf(this.ctx.sourceFile, comp.name, name) ?? null);
|
|
547
|
+
this.cores.push({ module: core, name: item.core.name });
|
|
548
|
+
body = core.call('vue', (name) => this.readBinding(name), t.tsNonNullExpression(t.memberExpression(t.identifier(item.core.elementRef), t.identifier('value'))), (name) => this.boxFor(name), (name) => this.setterFn(name));
|
|
549
|
+
}
|
|
550
|
+
else
|
|
551
|
+
body = this.r(item.body);
|
|
552
|
+
const deps = item.deps;
|
|
553
|
+
if (item.phase === 'render')
|
|
554
|
+
return [t.expressionStatement(t.callExpression(t.identifier(this.api('watchEffect')), [t.arrowFunctionExpression([], body)]))];
|
|
555
|
+
if (deps === null) {
|
|
556
|
+
const onCleanup = t.identifier('onCleanup');
|
|
557
|
+
// asked before the returns are rewritten into onCleanup calls
|
|
558
|
+
const uses = returnsValue(body);
|
|
559
|
+
const cleaned = trimTrailingReturn(replaceReturns(body, (v) => cleanupWith(onCleanup, v, this.alloc)));
|
|
560
|
+
return [t.expressionStatement(t.callExpression(t.identifier(this.api('watchPostEffect')), [t.arrowFunctionExpression(uses ? [onCleanup] : [], cleaned)]))];
|
|
561
|
+
}
|
|
562
|
+
const sources = reactiveDeps(deps, this.ir).map((d) => t.arrowFunctionExpression([], this.r(d)));
|
|
563
|
+
if (!sources.length) {
|
|
564
|
+
if (!returnsValue(body))
|
|
565
|
+
return [t.expressionStatement(t.callExpression(t.identifier(this.api('onMounted')), [t.arrowFunctionExpression([], body)]))];
|
|
566
|
+
const cleanup = this.alloc.alloc('cleanup');
|
|
567
|
+
const decl = t.identifier(cleanup);
|
|
568
|
+
decl.typeAnnotation = t.tsTypeAnnotation(t.tsUnionType([t.tsParenthesizedType(t.tsFunctionType(null, [], t.tsTypeAnnotation(t.tsVoidKeyword()))), t.tsUndefinedKeyword()]));
|
|
569
|
+
const assigned = trimTrailingReturn(replaceReturns(body, (v) => [t.expressionStatement(t.assignmentExpression('=', t.identifier(cleanup), v))]));
|
|
570
|
+
return [
|
|
571
|
+
t.variableDeclaration('let', [t.variableDeclarator(decl)]),
|
|
572
|
+
t.expressionStatement(t.callExpression(t.identifier(this.api('onMounted')), [t.arrowFunctionExpression([], assigned)])),
|
|
573
|
+
t.expressionStatement(t.callExpression(t.identifier(this.api('onUnmounted')), [t.arrowFunctionExpression([], t.optionalCallExpression(t.identifier(cleanup), [], true))])),
|
|
574
|
+
];
|
|
575
|
+
}
|
|
576
|
+
const onCleanup = t.identifier('onCleanup');
|
|
577
|
+
const uses = returnsValue(body);
|
|
578
|
+
const cb = trimTrailingReturn(replaceReturns(body, (v) => cleanupWith(onCleanup, v, this.alloc)));
|
|
579
|
+
const source = sources.length === 1 && sources[0] ? sources[0] : t.arrayExpression(sources);
|
|
580
|
+
const watchCall = t.callExpression(t.identifier(this.api('watch')), [
|
|
581
|
+
source,
|
|
582
|
+
t.arrowFunctionExpression(uses ? [t.identifier('_value'), t.identifier('_previous'), onCleanup] : [], cb),
|
|
583
|
+
// React runs effects (layout ones too) after the DOM is updated; Vue's default 'pre' watcher runs before the
|
|
584
|
+
// DOM shows the change, so it would read stale refs and layout. 'post' runs after the update, before paint.
|
|
585
|
+
t.objectExpression([t.objectProperty(t.identifier('immediate'), t.booleanLiteral(true)), t.objectProperty(t.identifier('flush'), t.stringLiteral('post'))]),
|
|
586
|
+
]);
|
|
587
|
+
// useEffect runs after the first render, when template refs are set: start watching once mounted
|
|
588
|
+
return [t.expressionStatement(t.callExpression(t.identifier(this.api('onMounted')), [t.arrowFunctionExpression([], t.blockStatement([t.expressionStatement(watchCall)]))]))];
|
|
589
|
+
}
|
|
590
|
+
readBinding(name) {
|
|
591
|
+
const b = this.ir.bindings.get(name);
|
|
592
|
+
if (b && (b.kind === 'state' || b.kind === 'reducer' || ((b.kind === 'derived' || b.kind === 'hook') && b.reactive)))
|
|
593
|
+
return t.memberExpression(t.identifier(name), t.identifier('value'));
|
|
594
|
+
return t.identifier(name);
|
|
595
|
+
}
|
|
596
|
+
boxFor(name) {
|
|
597
|
+
const b = this.ir.bindings.get(name);
|
|
598
|
+
if (b?.refKind === 'dom') {
|
|
599
|
+
const getter = t.objectMethod('get', t.identifier('current'), [], t.blockStatement([t.returnStatement(t.memberExpression(t.identifier(name), t.identifier('value')))]));
|
|
600
|
+
return t.objectExpression([getter]);
|
|
601
|
+
}
|
|
602
|
+
return t.identifier(name);
|
|
603
|
+
}
|
|
604
|
+
setterFn(name) {
|
|
605
|
+
const state = this.ir.bindings.get(name)?.state ?? name;
|
|
606
|
+
return t.arrowFunctionExpression([t.identifier('value')], t.assignmentExpression('=', t.memberExpression(t.identifier(state), t.identifier('value')), t.identifier('value')));
|
|
607
|
+
}
|
|
608
|
+
/** Page globals a template expression reads (see templateGlobals): bound here to the page's own, `globalThis.CSS`. */
|
|
609
|
+
globalAliases = new Set();
|
|
610
|
+
helperStatements() {
|
|
611
|
+
const out = [];
|
|
612
|
+
for (const name of [...this.globalAliases].sort()) {
|
|
613
|
+
out.push(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(name), t.memberExpression(t.identifier('globalThis'), t.identifier(name)))]));
|
|
614
|
+
}
|
|
615
|
+
if (this.slotsName)
|
|
616
|
+
out.push(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(this.slotsName), t.callExpression(t.identifier(this.api('useSlots')), []))]));
|
|
617
|
+
const parse = (src) => parseSource(src, 'helper.ts').program.body;
|
|
618
|
+
if (this.helpers.has('toStyle')) {
|
|
619
|
+
this.typeImports.push({ source: 'vue', name: 'CSSProperties' });
|
|
620
|
+
out.push(...parse(unitlessSource()));
|
|
621
|
+
out.push(...parse("/** React's style rule: numbers get px, except unitless properties, zero and custom properties. */\nfunction toStyle(style: object | null | undefined): CSSProperties {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(style ?? {})) out[key] = typeof value === 'number' && value !== 0 && !key.startsWith('--') && !UNITLESS.has(key) ? `${value}px` : value;\n return out as CSSProperties;\n}"));
|
|
622
|
+
}
|
|
623
|
+
if (this.helpers.has('selectDefault')) {
|
|
624
|
+
out.push(...parse([
|
|
625
|
+
"/** React's `defaultValue` on a <select> is the option it starts on: Vue sets that as `value`, once the options exist. */",
|
|
626
|
+
'function selectDefault(attrs: Record<string, unknown>): Record<string, unknown> {',
|
|
627
|
+
' const { defaultValue, ...rest } = attrs;',
|
|
628
|
+
' return defaultValue === undefined || rest.value !== undefined ? rest : { ...rest, value: defaultValue };',
|
|
629
|
+
'}',
|
|
630
|
+
].join('\n')));
|
|
631
|
+
}
|
|
632
|
+
if (this.helpers.has('slotChildren')) {
|
|
633
|
+
this.typeImports.push({ source: 'vue', name: 'VNode' });
|
|
634
|
+
this.imports.named('vue', 'Comment');
|
|
635
|
+
this.imports.named('vue', 'Fragment');
|
|
636
|
+
this.imports.named('vue', 'isVNode');
|
|
637
|
+
out.push(...parse([
|
|
638
|
+
"/** The children React's Children API sees in a slot: a v-for list as its items, a v-if placeholder as an empty node (null). */",
|
|
639
|
+
'function slotChildren(nodes: VNode[] | undefined): (VNode | null)[] {',
|
|
640
|
+
' return (nodes ?? []).flatMap((node): (VNode | null)[] => {',
|
|
641
|
+
' if (node.type === Comment) return [null];',
|
|
642
|
+
' // a v-for list is a keyed (128), unkeyed (256) or, over a constant list, stable (64) fragment with no key; a',
|
|
643
|
+
" // v-if branch's fragment has its branch's key and stays one child, as React's fragment (<>…</>) does",
|
|
644
|
+
' if (node.type === Fragment && Array.isArray(node.children) && (node.patchFlag & (128 | 256) || (node.patchFlag & 64 && node.key == null))) return slotChildren(node.children.filter(isVNode));',
|
|
645
|
+
' return [node];',
|
|
646
|
+
' });',
|
|
647
|
+
'}',
|
|
648
|
+
].join('\n')));
|
|
649
|
+
}
|
|
650
|
+
if (this.helpers.has('domProps')) {
|
|
651
|
+
out.push(...parse([
|
|
652
|
+
"/** React's DOM props spread on an element, as Vue reads them: an event under its DOM event's name, a style with React's px. */",
|
|
653
|
+
"function domProps(props: object | null | undefined, change = 'change'): Record<string, unknown> {",
|
|
654
|
+
' const out: Record<string, unknown> = {};',
|
|
655
|
+
' for (const [key, value] of Object.entries(props ?? {})) {',
|
|
656
|
+
' if (/^on[A-Z]/.test(key)) {',
|
|
657
|
+
' let name = key.slice(2);',
|
|
658
|
+
" const capture = name.endsWith('Capture') && !/^(Got|Lost)PointerCapture$/.test(name);",
|
|
659
|
+
' if (capture) name = name.slice(0, -7);',
|
|
660
|
+
" const event = name === 'DoubleClick' ? 'dblclick' : name === 'Focus' ? 'focusin' : name === 'Blur' ? 'focusout' : name === 'Change' ? change : name.toLowerCase();",
|
|
661
|
+
" const passive = event === 'wheel' || event === 'touchstart' || event === 'touchmove';",
|
|
662
|
+
" out[`on${event.charAt(0).toUpperCase()}${event.slice(1)}${passive ? 'Passive' : ''}${capture ? 'Capture' : ''}`] = value;",
|
|
663
|
+
" } else if (key === 'style' && value && typeof value === 'object' && !Array.isArray(value)) out[key] = toStyle(value);",
|
|
664
|
+
' else out[key] = value;',
|
|
665
|
+
' }',
|
|
666
|
+
' return out;',
|
|
667
|
+
'}',
|
|
668
|
+
].join('\n')));
|
|
669
|
+
}
|
|
670
|
+
if (this.helpers.has('markupNodes')) {
|
|
671
|
+
this.imports.named('vue', 'h');
|
|
672
|
+
this.imports.named('vue', 'Fragment');
|
|
673
|
+
this.typeImports.push({ source: 'vue', name: 'VNode' });
|
|
674
|
+
this.typeImports.push({ source: 'vue', name: 'VNodeChild' });
|
|
675
|
+
out.push(...parse(MARKUP_NODES_SOURCE));
|
|
676
|
+
}
|
|
677
|
+
if (this.helpers.has('markupChild')) {
|
|
678
|
+
this.typeImports.push({ source: 'vue', name: 'FunctionalComponent' });
|
|
679
|
+
this.typeImports.push({ source: 'vue', name: 'VNodeChild' });
|
|
680
|
+
this.imports.named('vue', 'h');
|
|
681
|
+
out.push(...parse([
|
|
682
|
+
'/** A child React renders: markup held as a value (a functional component here) as that component, anything else as it is. */',
|
|
683
|
+
'function markupChild(value: VNodeChild | FunctionalComponent): VNodeChild {',
|
|
684
|
+
" return typeof value === 'function' ? h(value) : value;",
|
|
685
|
+
'}',
|
|
686
|
+
].join('\n')));
|
|
687
|
+
}
|
|
688
|
+
if (this.helpers.has('radixProps'))
|
|
689
|
+
out.push(...parse(RADIX_PROPS_SOURCE));
|
|
690
|
+
if (this.helpers.has('focusOnPress'))
|
|
691
|
+
out.push(...parse(PRESS_FOCUS_SOURCE));
|
|
692
|
+
if (this.helpers.has('slotText')) {
|
|
693
|
+
this.typeImports.push({ source: 'vue', name: 'Slot' });
|
|
694
|
+
out.push(...parse([
|
|
695
|
+
"/** The text of what a parent wrote inside the component (React's children as a string). */",
|
|
696
|
+
'function slotText(slot: Slot | undefined): string | undefined {',
|
|
697
|
+
' const nodes = slot?.();',
|
|
698
|
+
" return nodes ? nodes.map((node) => (typeof node.children === 'string' ? node.children : '')).join('') : undefined;",
|
|
699
|
+
'}',
|
|
700
|
+
].join('\n')));
|
|
701
|
+
}
|
|
702
|
+
// a string keeps its own type through the helper (`objectFit: fit` with `fit: 'cover' | 'contain'` is still an
|
|
703
|
+
// ObjectFit to Vue's CSSProperties); a number becomes px
|
|
704
|
+
if (this.helpers.has('toPx')) {
|
|
705
|
+
out.push(...parse("/** React's rule for style numbers: px, except zero; any other value as it is. */\nfunction toPx(value: number): string;\nfunction toPx<T extends string | undefined>(value: T): T;\nfunction toPx(value: string | number | null | undefined): string | undefined;\nfunction toPx(value: string | number | null | undefined): string | undefined {\n if (typeof value === 'number') return value === 0 ? '0' : `${value}px`;\n return value ?? undefined;\n}"));
|
|
706
|
+
}
|
|
707
|
+
return out;
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
/** Prints one component's template, hoisting long handlers and loop locals into the script. */
|
|
711
|
+
class VueTemplate {
|
|
712
|
+
comp;
|
|
713
|
+
script;
|
|
714
|
+
facts;
|
|
715
|
+
restSpread;
|
|
716
|
+
moduleWrites;
|
|
717
|
+
inline;
|
|
718
|
+
hoisted = [];
|
|
719
|
+
/** setters handed on as values: one typed script function each, named as React named the setter */
|
|
720
|
+
setterFunctions = new Set();
|
|
721
|
+
/** `onValueChange={setShape}`: `const setShape = (value: S | ((previous: S) => S)) => …` in the script, read by name. */
|
|
722
|
+
setterFunction(setter, fn) {
|
|
723
|
+
if (!this.setterFunctions.has(setter)) {
|
|
724
|
+
this.setterFunctions.add(setter);
|
|
725
|
+
this.hoisted.push(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(setter), fn)]));
|
|
726
|
+
}
|
|
727
|
+
return t.identifier(setter);
|
|
728
|
+
}
|
|
729
|
+
constructor(comp, script, facts, restSpread, moduleWrites,
|
|
730
|
+
/** private components written in place, and the module names their markup brings in */
|
|
731
|
+
inline = { comps: new Map(), used: new Set() }) {
|
|
732
|
+
this.comp = comp;
|
|
733
|
+
this.script = script;
|
|
734
|
+
this.facts = facts;
|
|
735
|
+
this.restSpread = restSpread;
|
|
736
|
+
this.moduleWrites = moduleWrites;
|
|
737
|
+
this.inline = inline;
|
|
738
|
+
}
|
|
739
|
+
/** The local name of the conversion's Slot helper (targets/vue/slot), imported once. */
|
|
740
|
+
slotLocal = null;
|
|
741
|
+
slotHelper() {
|
|
742
|
+
if (this.slotLocal)
|
|
743
|
+
return this.slotLocal;
|
|
744
|
+
const local = this.script.alloc.has(VUE_SLOT) ? this.script.alloc.alloc(`Radix${VUE_SLOT}`) : VUE_SLOT;
|
|
745
|
+
this.script.alloc.reserve(local);
|
|
746
|
+
const ctx = this.script.ctx;
|
|
747
|
+
this.script.imports.named(importPath(this.script.outPath, ctx.helperPath?.(VUE_SLOT_FILE) ?? VUE_SLOT_FILE), VUE_SLOT, local);
|
|
748
|
+
useVueSlot(ctx.diagnostics);
|
|
749
|
+
this.slotLocal = local;
|
|
750
|
+
return local;
|
|
751
|
+
}
|
|
752
|
+
/** The local name of a reka-ui component (ir/radix), imported once; aliased when the file has the name already. */
|
|
753
|
+
rekaLocals = new Map();
|
|
754
|
+
rekaLocal(name) {
|
|
755
|
+
const known = this.rekaLocals.get(name);
|
|
756
|
+
if (known)
|
|
757
|
+
return known;
|
|
758
|
+
const local = this.script.alloc.has(name) || this.comp.name === name ? this.script.alloc.alloc(`${name}Primitive`) : name;
|
|
759
|
+
this.script.alloc.reserve(local);
|
|
760
|
+
this.script.imports.named('reka-ui', name, local);
|
|
761
|
+
this.rekaLocals.set(name, local);
|
|
762
|
+
return local;
|
|
763
|
+
}
|
|
764
|
+
/** A private component written where it is used: its markup, with the caller's directives on it. */
|
|
765
|
+
inlined(n, comp, indent, scope, extra) {
|
|
766
|
+
for (const name of comp.moduleNames)
|
|
767
|
+
this.inline.used.add(name);
|
|
768
|
+
const nodes = expandUse(n, comp, this.comp.refs).flatMap((x) => (x.type === 'fragment' ? x.children : [x]));
|
|
769
|
+
const only = nodes.length === 1 ? nodes[0] : undefined;
|
|
770
|
+
if (only?.type === 'element')
|
|
771
|
+
return this.element(only, indent, scope, extra);
|
|
772
|
+
if (extra.length)
|
|
773
|
+
return `<template ${extra.join(' ')}>${this.children(nodes, indent, scope)}</template>`;
|
|
774
|
+
return this.children(nodes, indent, scope).trim();
|
|
775
|
+
}
|
|
776
|
+
expr(e, scope, test = false) {
|
|
777
|
+
// children tested (`{children && <div>…</div>}`) are the default slot, which is not a prop in Vue
|
|
778
|
+
// and read as a value (`text={children}`) they are the slot's text
|
|
779
|
+
const rename = new Map(scope.rename);
|
|
780
|
+
// `typeof count === 'number'` (the branch React renders a falsy number in) reads the prop's own value
|
|
781
|
+
const valueTest = t.isBinaryExpression(e) && t.isUnaryExpression(e.left, { operator: 'typeof' });
|
|
782
|
+
for (const p of this.comp.props) {
|
|
783
|
+
if (rename.has(p.local) || scope.loopNames.has(p.local) || (valueTest && p.kind !== 'children'))
|
|
784
|
+
continue;
|
|
785
|
+
const slotOf = (key) => (/^[A-Za-z_$][\w$]*$/.test(key) ? t.memberExpression(t.identifier('$slots'), t.identifier(key)) : t.memberExpression(t.identifier('$slots'), t.stringLiteral(key), true));
|
|
786
|
+
if (p.kind === 'children') {
|
|
787
|
+
const slot = slotOf('default');
|
|
788
|
+
if (test)
|
|
789
|
+
rename.set(p.local, slot);
|
|
790
|
+
else
|
|
791
|
+
rename.set(p.local, t.callExpression(t.identifier('slotText'), [slot]));
|
|
792
|
+
}
|
|
793
|
+
else if (test && renderSignature(p.type)) {
|
|
794
|
+
// a render prop is a slot: tested, it is there when the caller fills the slot
|
|
795
|
+
rename.set(p.local, slotOf(p.key));
|
|
796
|
+
}
|
|
797
|
+
else if (test && p.kind === 'node') {
|
|
798
|
+
// markup arrives as the slot, text as the prop: either is there (the prop when it was passed, as React read it)
|
|
799
|
+
rename.set(p.local, t.parenthesizedExpression(t.logicalExpression('??', t.identifier(p.local), slotOf(p.key))));
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
const renamed = renameFree(e, rename);
|
|
803
|
+
// the helper exists only if an expression that is printed reads the children as text
|
|
804
|
+
t.traverseFast(renamed, (n) => {
|
|
805
|
+
if (t.isCallExpression(n) && t.isIdentifier(n.callee, { name: 'slotText' }))
|
|
806
|
+
this.script.helpers.add('slotText');
|
|
807
|
+
});
|
|
808
|
+
const holder = t.expressionStatement(rewrite(renamed, { ir: this.comp, mode: 'vue-template', propRenames: VUE_PROP_RENAMES, setterValue: (setter, fn) => this.setterFunction(setter, fn) }));
|
|
809
|
+
if (this.moduleWrites)
|
|
810
|
+
for (const n of routeModuleWrites([holder], this.moduleWrites.names, new Set(this.comp.bindings.keys())))
|
|
811
|
+
this.moduleWrites.written.add(n);
|
|
812
|
+
this.templateGlobals(holder.expression, scope);
|
|
813
|
+
return printExpr(stripTypes(holder.expression, true, (type) => ownTypeOnly(type, this.facts.ownTypes) || domTypeOnly(type, this.facts.reactNames)));
|
|
814
|
+
}
|
|
815
|
+
/**
|
|
816
|
+
* The page's globals a template expression reads (`CSS.escape(id)`, `document.activeElement` in a handler kept in a
|
|
817
|
+
* loop): a Vue template sees only the component and a short list of globals, so each becomes a binding of the setup
|
|
818
|
+
* script that holds the page's own (see VueScript.globalAliases).
|
|
819
|
+
*/
|
|
820
|
+
templateGlobals(e, scope) {
|
|
821
|
+
const declared = new Set([...scope.loopNames, ...scope.rename.keys()]);
|
|
822
|
+
t.traverseFast(e, (n) => {
|
|
823
|
+
const names = t.isFunction(n) ? n.params.flatMap((p) => Object.keys(t.getBindingIdentifiers(p))) : t.isVariableDeclarator(n) ? Object.keys(t.getBindingIdentifiers(n.id)) : t.isCatchClause(n) && n.param ? Object.keys(t.getBindingIdentifiers(n.param)) : [];
|
|
824
|
+
names.forEach((x) => declared.add(x));
|
|
825
|
+
});
|
|
826
|
+
const mod = this.script.ctx.moduleOf?.(this.script.ctx.sourceFile) ?? null;
|
|
827
|
+
const moduleNames = new Set([...(mod?.moduleJsx.moduleNames ?? []), ...(mod?.imports.flatMap((d) => d.specifiers.map((s) => s.local.name)) ?? []), ...(mod?.moduleBody.flatMap((s) => Object.keys(t.getOuterBindingIdentifiers(s))) ?? []), ...(mod?.components.map((c) => c.name) ?? []), ...(mod?.hooks.map((h) => h.name) ?? [])]);
|
|
828
|
+
t.traverse(e, (n, ancestors) => {
|
|
829
|
+
if (!t.isIdentifier(n))
|
|
830
|
+
return;
|
|
831
|
+
const parent = ancestors[ancestors.length - 1]?.node;
|
|
832
|
+
if (parent && (t.isMemberExpression(parent) || t.isOptionalMemberExpression(parent)) && parent.property === n && !parent.computed)
|
|
833
|
+
return;
|
|
834
|
+
if (parent && (t.isObjectProperty(parent) || t.isObjectMethod(parent)) && parent.key === n && !parent.computed)
|
|
835
|
+
return;
|
|
836
|
+
if (parent && (t.isTSTypeReference(parent) || t.isTSQualifiedName(parent)))
|
|
837
|
+
return;
|
|
838
|
+
if (ancestors.some(({ node }) => t.isTSType(node)))
|
|
839
|
+
return;
|
|
840
|
+
const name = n.name;
|
|
841
|
+
if (declared.has(name) || moduleNames.has(name) || this.comp.bindings.has(name) || this.comp.refs.get(n) || VUE_TEMPLATE_GLOBALS.has(name))
|
|
842
|
+
return;
|
|
843
|
+
if ((BROWSER_GLOBALS.has(name) || name in globalThis) && !NODE_ONLY.has(name))
|
|
844
|
+
this.script.globalAliases.add(name);
|
|
845
|
+
});
|
|
846
|
+
}
|
|
847
|
+
attr(name, e, scope) {
|
|
848
|
+
return `:${name}="${escapeAttr(this.expr(e, scope))}"`;
|
|
849
|
+
}
|
|
850
|
+
usesLoopNames(e, scope) {
|
|
851
|
+
if (!scope.loopNames.size && !scope.rename.size)
|
|
852
|
+
return false;
|
|
853
|
+
let found = false;
|
|
854
|
+
// a loop's own names, and the row locals the template reads as `row.name`: both exist only inside the loop
|
|
855
|
+
t.traverseFast(e, (n) => {
|
|
856
|
+
if (t.isIdentifier(n) && (scope.loopNames.has(n.name) || scope.rename.has(n.name)))
|
|
857
|
+
found = true;
|
|
858
|
+
});
|
|
859
|
+
return found;
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* Markup a template has no form for, kept by lowering as React wrote it (`{active && (() => { …; return <b/>; })()}`,
|
|
863
|
+
* TNode `unconverted` with `expr`): a setup function that returns it as a VNode written with `h()`, rendered with
|
|
864
|
+
* `<component :is="renderBlock()" />`. The template calls it while the component renders, so it reads the props and
|
|
865
|
+
* state it uses as the render does, follows them, and is computed again on every render as React computes it. Written
|
|
866
|
+
* only when it reads no name of an enclosing loop or slot (those exist only in the template) and every element in it
|
|
867
|
+
* has an exact `h()` form; the error lowering reported for it is then withdrawn. Null: not written, the error stays.
|
|
868
|
+
*/
|
|
869
|
+
renderPiece(e, diagnostic, scope) {
|
|
870
|
+
if (this.usesLoopNames(e, scope) || this.readsHeldMarkup(e) || this.readsUnknownNames(e))
|
|
871
|
+
return null;
|
|
872
|
+
// an immediately called function (`(() => { … })()`) is the function's own body
|
|
873
|
+
const call = unwrap(e);
|
|
874
|
+
const callee = t.isCallExpression(call) && !call.arguments.length && t.isExpression(call.callee) ? unwrap(call.callee) : null;
|
|
875
|
+
const iife = (t.isArrowFunctionExpression(callee) || t.isFunctionExpression(callee)) && !callee.params.length && !callee.async && !callee.generator ? callee : null;
|
|
876
|
+
const body = iife ? (t.isBlockStatement(iife.body) ? iife.body.body : [t.returnStatement(iife.body)]) : [t.returnStatement(e)];
|
|
877
|
+
// the function runs only inside the v-if branches around it: their tests, stated again at its top, always pass and
|
|
878
|
+
// give the type checker the narrowing React's code had there (only tests that read values and call nothing, so
|
|
879
|
+
// reading them again changes nothing)
|
|
880
|
+
const tests = scope.tests ?? [];
|
|
881
|
+
const guards = tests.filter((g) => plainTest(g.test)).map((g) => t.ifStatement(g.holds ? negated(g.test) : g.test, t.returnStatement(t.nullLiteral())));
|
|
882
|
+
// a function made inside it that reads a tested name: React's const keeps the narrowing there, a ref's `.value`
|
|
883
|
+
// does not, so the output would not type-check; left unconverted
|
|
884
|
+
const tested = new Map();
|
|
885
|
+
for (const g of tests)
|
|
886
|
+
t.traverseFast(g.test, (n) => void (t.isIdentifier(n) && !tested.has(n.name) && tested.set(n.name, n)));
|
|
887
|
+
const closed = new Set();
|
|
888
|
+
const declared = new Set();
|
|
889
|
+
for (const s of body) {
|
|
890
|
+
t.traverseFast(s, (n) => {
|
|
891
|
+
if (t.isFunction(n))
|
|
892
|
+
t.traverseFast(n.body, (m) => void (t.isIdentifier(m) && tested.has(m.name) && closed.add(m.name)));
|
|
893
|
+
if (t.isFunction(n))
|
|
894
|
+
for (const p of n.params)
|
|
895
|
+
for (const b of Object.keys(t.getBindingIdentifiers(p)))
|
|
896
|
+
declared.add(b);
|
|
897
|
+
if (t.isVariableDeclarator(n))
|
|
898
|
+
for (const b of Object.keys(t.getBindingIdentifiers(n.id)))
|
|
899
|
+
declared.add(b);
|
|
900
|
+
if (t.isCatchClause(n) && n.param)
|
|
901
|
+
for (const b of Object.keys(t.getBindingIdentifiers(n.param)))
|
|
902
|
+
declared.add(b);
|
|
903
|
+
});
|
|
904
|
+
}
|
|
905
|
+
// such a name is read once, at the top, into a const (`const activeNow = active.value`), and the guards and the body
|
|
906
|
+
// read that const: React's closures made during a render see that render's value, and the const keeps the narrowing.
|
|
907
|
+
// Only a binding of the component, which is never assigned in the piece, and only when nothing in it declares the name.
|
|
908
|
+
const snapshots = [];
|
|
909
|
+
for (const name of closed) {
|
|
910
|
+
const source = tested.get(name);
|
|
911
|
+
let assigned = false;
|
|
912
|
+
for (const s of body) {
|
|
913
|
+
t.traverseFast(s, (n) => {
|
|
914
|
+
const target = t.isAssignmentExpression(n) ? n.left : t.isUpdateExpression(n) ? n.argument : null;
|
|
915
|
+
if (target && t.isIdentifier(target, { name }))
|
|
916
|
+
assigned = true;
|
|
917
|
+
});
|
|
918
|
+
}
|
|
919
|
+
if (!source || !this.comp.bindings.has(name) || declared.has(name) || assigned)
|
|
920
|
+
return null;
|
|
921
|
+
snapshots.push([name, this.script.alloc.alloc(`${name}Now`), source]);
|
|
922
|
+
}
|
|
923
|
+
const copy = cloneWithRefs(t.blockStatement([...guards, ...body]), this.comp);
|
|
924
|
+
if (snapshots.length) {
|
|
925
|
+
const names = new Map(snapshots.map(([name, local]) => [name, local]));
|
|
926
|
+
transform(copy, (n, parent) => {
|
|
927
|
+
if (!t.isIdentifier(n) || !names.has(n.name))
|
|
928
|
+
return null;
|
|
929
|
+
if (parent && (t.isMemberExpression(parent) || t.isOptionalMemberExpression(parent)) && parent.property === n && !parent.computed)
|
|
930
|
+
return null;
|
|
931
|
+
if (parent && (t.isObjectProperty(parent) || t.isObjectMethod(parent)) && parent.key === n && !parent.computed)
|
|
932
|
+
return null;
|
|
933
|
+
if (parent && t.isObjectProperty(parent) && parent.shorthand)
|
|
934
|
+
parent.shorthand = false;
|
|
935
|
+
return t.identifier(names.get(n.name) ?? n.name);
|
|
936
|
+
});
|
|
937
|
+
copy.body.unshift(...snapshots.map(([, local, source]) => t.variableDeclaration('const', [t.variableDeclarator(t.identifier(local), cloneWithRefs(source, this.comp))])));
|
|
938
|
+
}
|
|
939
|
+
// paths the guards do not narrow (a test that calls something) are stated as known, as hoisted handlers state them
|
|
940
|
+
if (scope.facts?.size && guards.length < tests.length)
|
|
941
|
+
assertPaths(copy, scope.facts);
|
|
942
|
+
const written = this.renderBody(copy);
|
|
943
|
+
if (!written)
|
|
944
|
+
return null;
|
|
945
|
+
const name = this.script.alloc.alloc('renderBlock');
|
|
946
|
+
this.hoisted.push(t.functionDeclaration(t.identifier(name), [], written));
|
|
947
|
+
// M4: a list it draws may move a focused element
|
|
948
|
+
this.drawsScriptMarkup = true;
|
|
949
|
+
withdraw(this.script.ctx.diagnostics, diagnostic);
|
|
950
|
+
return `<component :is="${name}()" />`;
|
|
951
|
+
}
|
|
952
|
+
/**
|
|
953
|
+
* A value of the component computed from others (`const picture = isPerState(art) ? art[key] : art`) that React's
|
|
954
|
+
* types say may be an element: it holds markup a prop's data passed (a functional component in Vue) as often as text,
|
|
955
|
+
* so it renders as markup where it is one, as data reads already do (ir/markup-values), never as its source text.
|
|
956
|
+
*/
|
|
957
|
+
derivedMarkup(e) {
|
|
958
|
+
// a prop read as a value (`{header}` where the component also tests it in script) holds what its caller passed: the
|
|
959
|
+
// caller passes markup to it as a functional component (VueTemplate.valueSlots), as data reads hold it
|
|
960
|
+
const binding = this.comp.bindings.get(t.isIdentifier(e) ? e.name : '')?.kind;
|
|
961
|
+
if (!t.isIdentifier(e) || !e.loc || (binding !== 'derived' && binding !== 'prop'))
|
|
962
|
+
return false;
|
|
963
|
+
// children and markup props that arrive as slots are read through the slot, never as a value that holds markup
|
|
964
|
+
const declared = binding === 'prop' ? this.comp.props.find((p) => p.local === e.name) : undefined;
|
|
965
|
+
if (declared && (declared.kind === 'children' || declared.kind === 'node'))
|
|
966
|
+
return false;
|
|
967
|
+
const kind = this.script.ctx.oracle?.elementKind(this.script.ctx.sourceFile, e.loc);
|
|
968
|
+
return !!kind && kind.element && !kind.unknown;
|
|
969
|
+
}
|
|
970
|
+
/** Render helpers written as setup functions (by React's name, or null when one could not be written). */
|
|
971
|
+
helperFns = new Map();
|
|
972
|
+
/**
|
|
973
|
+
* A value that calls a render helper (`{cell(r, c)}`, TNode `expr` with `kept`): the helper becomes a setup function
|
|
974
|
+
* that returns one VNode, written with `h()`, and the template renders its call with `<component :is="cell(r, c)" />`,
|
|
975
|
+
* the arguments read in the template where the loop names exist. Null: not written, the error stays.
|
|
976
|
+
*/
|
|
977
|
+
keptRead(n, scope) {
|
|
978
|
+
const kept = this.comp.keptMarkup?.find((k) => k.kind === 'expression' && k.id === n.kept);
|
|
979
|
+
if (kept?.kind !== 'expression')
|
|
980
|
+
return null;
|
|
981
|
+
const call = unwrap(kept.expr);
|
|
982
|
+
const listed = t.isCallExpression(call) ? this.mappedHelper(call, kept.diagnostic, scope) : null;
|
|
983
|
+
if (listed)
|
|
984
|
+
return listed;
|
|
985
|
+
if (!t.isCallExpression(call) || !t.isIdentifier(call.callee) || !call.arguments.every((a) => t.isExpression(a)))
|
|
986
|
+
return null;
|
|
987
|
+
const helperName = call.callee.name;
|
|
988
|
+
const helper = this.comp.keptMarkup?.find((k) => k.kind === 'value' && k.item.kind === 'function' && k.item.name === helperName);
|
|
989
|
+
if (helper?.kind !== 'value' || helper.item.kind !== 'function')
|
|
990
|
+
return null;
|
|
991
|
+
if (call.arguments.some((a) => this.readsHeldMarkup(a)))
|
|
992
|
+
return null;
|
|
993
|
+
const name = this.helperFn(helper.item, helper.diagnostic, helper.calls);
|
|
994
|
+
if (!name)
|
|
995
|
+
return null;
|
|
996
|
+
withdraw(this.script.ctx.diagnostics, kept.diagnostic);
|
|
997
|
+
const written = t.callExpression(t.identifier(name), call.arguments);
|
|
998
|
+
return `<component :is="${escapeAttr(this.expr(written, scope))}" />`;
|
|
999
|
+
}
|
|
1000
|
+
/**
|
|
1001
|
+
* The component's template, with its early returns (`if (variant === 'compact') { const label = …; return <b/>; }`,
|
|
1002
|
+
* kept `statement` entries) in front: each is a render function written with `h()`, rendered with
|
|
1003
|
+
* `<component :is="renderEarly()" v-if="test" />`, the next one `v-else-if`, and the markup React returns last
|
|
1004
|
+
* `v-else`. React leaves the rest of the body when a test holds; in Vue the tests are read while the component
|
|
1005
|
+
* renders, in the same order, and the code after them that Vue keeps in setup is lazy computeds, plain values and
|
|
1006
|
+
* functions, which run only when read. Only when every kept statement is such an early return (a test that reads
|
|
1007
|
+
* values and calls nothing, no else, a block that ends in a return) and no render-time statement or watcher follows
|
|
1008
|
+
* one; otherwise the template is printed as before and the errors stay.
|
|
1009
|
+
*/
|
|
1010
|
+
root(node, indent, scope) {
|
|
1011
|
+
const statements = (this.comp.keptMarkup ?? []).filter((k) => k.kind === 'statement');
|
|
1012
|
+
const early = statements.length ? this.earlyReturns(statements) : null;
|
|
1013
|
+
if (!early)
|
|
1014
|
+
return this.node(node, indent, scope);
|
|
1015
|
+
const lines = early.map((e, i) => `<component :is="${e.name}()" ${i ? 'v-else-if' : 'v-if'}="${escapeAttr(this.expr(e.test, scope, true))}" />`);
|
|
1016
|
+
return [...lines, `<template v-else>${this.children([node], indent, scope)}</template>`].join(`\n${indent}`);
|
|
1017
|
+
}
|
|
1018
|
+
earlyReturns(statements) {
|
|
1019
|
+
const shapes = [];
|
|
1020
|
+
for (const k of statements) {
|
|
1021
|
+
const s = k.node;
|
|
1022
|
+
if (!t.isIfStatement(s) || s.alternate || !plainTest(s.test))
|
|
1023
|
+
return null;
|
|
1024
|
+
const body = t.isBlockStatement(s.consequent) ? s.consequent.body : [s.consequent];
|
|
1025
|
+
const last = body[body.length - 1];
|
|
1026
|
+
if (!t.isReturnStatement(last) || !last.argument)
|
|
1027
|
+
return null;
|
|
1028
|
+
// after it, nothing React would skip that Vue runs anyway: a render-time statement or watcher
|
|
1029
|
+
const at = k.after ? this.comp.items.indexOf(k.after) : -1;
|
|
1030
|
+
if (k.after && at < 0)
|
|
1031
|
+
return null;
|
|
1032
|
+
if (this.comp.items.slice(at + 1).some((i) => i.kind === 'statement' || (i.kind === 'effect' && i.phase === 'render')))
|
|
1033
|
+
return null;
|
|
1034
|
+
shapes.push({ test: s.test, body, kept: k });
|
|
1035
|
+
}
|
|
1036
|
+
const out = [];
|
|
1037
|
+
for (const { test, body, kept } of shapes) {
|
|
1038
|
+
// the test, stated again at its top, always passes and gives the type checker React's narrowing there
|
|
1039
|
+
const block = t.blockStatement([t.ifStatement(negated(test), t.returnStatement(t.nullLiteral())), ...body]);
|
|
1040
|
+
if (this.readsHeldMarkup(block) || this.readsUnknownNames(t.arrowFunctionExpression([], block)))
|
|
1041
|
+
return null;
|
|
1042
|
+
const written = this.renderBody(cloneWithRefs(block, this.comp));
|
|
1043
|
+
if (!written)
|
|
1044
|
+
return null;
|
|
1045
|
+
const name = this.script.alloc.alloc('renderEarly');
|
|
1046
|
+
out.push({ name, test, fn: t.functionDeclaration(t.identifier(name), [], written), kept });
|
|
1047
|
+
}
|
|
1048
|
+
for (const o of out) {
|
|
1049
|
+
this.hoisted.push(o.fn);
|
|
1050
|
+
withdraw(this.script.ctx.diagnostics, o.kept.diagnostic);
|
|
1051
|
+
}
|
|
1052
|
+
return out.map((o) => ({ name: o.name, test: o.test }));
|
|
1053
|
+
}
|
|
1054
|
+
/** Kept values written as render functions, by React's name (null: tried, not written). */
|
|
1055
|
+
valueFns = new Map();
|
|
1056
|
+
/**
|
|
1057
|
+
* A value the render body builds out of elements (`const rows = []; for (…) rows.push(<li/>)`, a memo returning a
|
|
1058
|
+
* list; TNode `unconverted` with `value`), rendered once by the template: its code becomes a setup function written
|
|
1059
|
+
* with `h()`, and the template renders its call with `<component :is="renderRows()" />`. React computes the value on
|
|
1060
|
+
* every render and renders it at that one place; the template calls the function while the component renders, so it
|
|
1061
|
+
* reads the props, state and slots it uses as the render does and follows them. Only when that template node is the
|
|
1062
|
+
* value's one read (no script code, handler, other kept code or second node reads it, so building it here builds it
|
|
1063
|
+
* as often as React shows it), outside a loop, and when its code writes nothing outside itself (it runs only while
|
|
1064
|
+
* its branch shows). Null: not written, the error stays.
|
|
1065
|
+
*/
|
|
1066
|
+
keptValue(name, scope) {
|
|
1067
|
+
if (this.valueFns.has(name))
|
|
1068
|
+
return null;
|
|
1069
|
+
this.valueFns.set(name, null);
|
|
1070
|
+
const kept = this.comp.keptMarkup?.find((k) => k.kind === 'value' && k.names.includes(name));
|
|
1071
|
+
if (kept?.kind !== 'value' || kept.item.kind === 'function' || scope.loopNames.size)
|
|
1072
|
+
return null;
|
|
1073
|
+
const item = kept.item;
|
|
1074
|
+
let body;
|
|
1075
|
+
if (item.kind === 'block' && (item.members || kept.names.length !== 1 || kept.names[0] !== item.name))
|
|
1076
|
+
return null;
|
|
1077
|
+
if (item.kind === 'block')
|
|
1078
|
+
body = item.returns ? item.statements : [...item.statements, t.returnStatement(t.identifier(item.name))];
|
|
1079
|
+
else if (t.isIdentifier(item.id) && kept.names.length === 1)
|
|
1080
|
+
body = [t.returnStatement(item.init)];
|
|
1081
|
+
else
|
|
1082
|
+
return null;
|
|
1083
|
+
if (this.valueReads(kept) !== 1)
|
|
1084
|
+
return null;
|
|
1085
|
+
const block = t.blockStatement(body);
|
|
1086
|
+
if (this.usesLoopNames(block, scope) || this.readsHeldMarkup(block, kept.names) || this.readsUnknownNames(t.arrowFunctionExpression([], block)) || writesOutside(block, this.comp))
|
|
1087
|
+
return null;
|
|
1088
|
+
const written = this.renderBody(cloneWithRefs(block, this.comp), new Set(kept.names));
|
|
1089
|
+
if (!written)
|
|
1090
|
+
return null;
|
|
1091
|
+
const fn = this.script.alloc.alloc(`render${name.charAt(0).toUpperCase()}${name.slice(1)}`);
|
|
1092
|
+
this.hoisted.push(t.functionDeclaration(t.identifier(fn), [], written));
|
|
1093
|
+
withdraw(this.script.ctx.diagnostics, kept.diagnostic);
|
|
1094
|
+
// M4: a list it draws may move a focused element
|
|
1095
|
+
this.drawsScriptMarkup = true;
|
|
1096
|
+
this.valueFns.set(name, fn);
|
|
1097
|
+
return `<component :is="${fn}()" />`;
|
|
1098
|
+
}
|
|
1099
|
+
/**
|
|
1100
|
+
* How many template nodes render a kept value; -1 when anything else reads it (script code, a handler, an attribute,
|
|
1101
|
+
* other kept code, or a render helper's markup, which Vue writes in place at each call).
|
|
1102
|
+
*/
|
|
1103
|
+
valueReads(kept) {
|
|
1104
|
+
const names = new Set(kept.names);
|
|
1105
|
+
let renders = 0;
|
|
1106
|
+
let other = false;
|
|
1107
|
+
const seen = new WeakSet();
|
|
1108
|
+
const visit = (v, helper) => {
|
|
1109
|
+
if (Array.isArray(v)) {
|
|
1110
|
+
for (const x of v)
|
|
1111
|
+
visit(x, helper);
|
|
1112
|
+
return;
|
|
1113
|
+
}
|
|
1114
|
+
if (!v || typeof v !== 'object' || seen.has(v) || v === kept)
|
|
1115
|
+
return;
|
|
1116
|
+
seen.add(v);
|
|
1117
|
+
const type = Reflect.get(v, 'type');
|
|
1118
|
+
if (typeof type === 'string' && type in t.VISITOR_KEYS && t.isNode(v)) {
|
|
1119
|
+
t.traverseFast(v, (n) => {
|
|
1120
|
+
if (t.isIdentifier(n) && names.has(this.comp.refs.get(n) ?? n.name))
|
|
1121
|
+
other = true;
|
|
1122
|
+
});
|
|
1123
|
+
return;
|
|
1124
|
+
}
|
|
1125
|
+
if (type === 'unconverted' && names.has(String(Reflect.get(v, 'value')))) {
|
|
1126
|
+
if (helper)
|
|
1127
|
+
other = true;
|
|
1128
|
+
else
|
|
1129
|
+
renders++;
|
|
1130
|
+
}
|
|
1131
|
+
for (const x of Object.values(v))
|
|
1132
|
+
visit(x, helper);
|
|
1133
|
+
};
|
|
1134
|
+
visit([this.comp.items, this.comp.template, this.comp.markupValues ?? [], this.comp.provides, (this.comp.keptMarkup ?? []).filter((k) => k !== kept)], false);
|
|
1135
|
+
visit(this.comp.fragments, true);
|
|
1136
|
+
return other ? -1 : renders;
|
|
1137
|
+
}
|
|
1138
|
+
/**
|
|
1139
|
+
* `{PARTS[id].map(part)}`: a render helper handed to `.map` as its callback (React renders the list of what it
|
|
1140
|
+
* returns). The helper is a setup function written with `h()` (helperFn), and a second one returns the list in a
|
|
1141
|
+
* fragment, `h(Fragment, null, PARTS[id].map(part))`, which the template renders with `<component :is>` while the
|
|
1142
|
+
* component renders; each element keeps the key the helper gives it. Only when the list reads no name that exists
|
|
1143
|
+
* only in the template (a loop's). Null: not written, the error stays.
|
|
1144
|
+
*/
|
|
1145
|
+
mappedHelper(call, diagnostic, scope) {
|
|
1146
|
+
const callee = call.callee;
|
|
1147
|
+
const fnArg = call.arguments[0];
|
|
1148
|
+
if (!t.isMemberExpression(callee) || callee.computed || !t.isIdentifier(callee.property, { name: 'map' }) || call.arguments.length !== 1 || !t.isIdentifier(fnArg) || !t.isExpression(callee.object))
|
|
1149
|
+
return null;
|
|
1150
|
+
const helper = this.comp.keptMarkup?.find((k) => k.kind === 'value' && k.item.kind === 'function' && k.item.name === fnArg.name);
|
|
1151
|
+
if (helper?.kind !== 'value' || helper.item.kind !== 'function')
|
|
1152
|
+
return null;
|
|
1153
|
+
const list = callee.object;
|
|
1154
|
+
if (this.usesLoopNames(list, scope) || this.readsHeldMarkup(list) || this.readsUnknownNames(list))
|
|
1155
|
+
return null;
|
|
1156
|
+
const name = this.helperFn(helper.item, helper.diagnostic, helper.calls);
|
|
1157
|
+
if (!name)
|
|
1158
|
+
return null;
|
|
1159
|
+
const fn = this.script.alloc.alloc(`render${fnArg.name.charAt(0).toUpperCase()}${fnArg.name.slice(1)}List`);
|
|
1160
|
+
const listed = t.callExpression(t.memberExpression(cloneWithRefs(list, this.comp), t.identifier('map')), [t.identifier(name)]);
|
|
1161
|
+
const body = this.script.r(t.blockStatement([t.returnStatement(t.callExpression(t.identifier('h'), [t.identifier('Fragment'), t.nullLiteral(), listed]))]), new Set([name]));
|
|
1162
|
+
this.script.imports.named('vue', 'h');
|
|
1163
|
+
this.script.imports.named('vue', 'Fragment');
|
|
1164
|
+
this.hoisted.push(t.functionDeclaration(t.identifier(fn), [], body));
|
|
1165
|
+
withdraw(this.script.ctx.diagnostics, diagnostic);
|
|
1166
|
+
return `<component :is="${fn}()" />`;
|
|
1167
|
+
}
|
|
1168
|
+
/** Component functions that run React's element tools, as React wrote them (see emitVue), by name. */
|
|
1169
|
+
toolFns = new Map();
|
|
1170
|
+
/** Those the template wrote as render functions: the setup script leaves out their React form. */
|
|
1171
|
+
dropped = new Set();
|
|
1172
|
+
/**
|
|
1173
|
+
* A call of a component function that runs React's element tools on the children (`{renderChildren()}` where
|
|
1174
|
+
* `renderChildren = () => Children.map(children, (child) => isValidElement(child) && child.type === Icon ?
|
|
1175
|
+
* cloneElement(child, { size }) : child)`): it builds the markup React renders there, so it is written as a render
|
|
1176
|
+
* function (render-fn/h: `slotChildren`, `isVNode`, `cloneVNode` with known keys) and the template renders its call
|
|
1177
|
+
* with `<component :is>`. Only when nothing but such template calls reads the function (no script code, handler or
|
|
1178
|
+
* attribute), so leaving its React form out of the setup changes nothing else. Null: not written.
|
|
1179
|
+
*/
|
|
1180
|
+
toolHelper(e, scope) {
|
|
1181
|
+
const call = unwrap(e);
|
|
1182
|
+
if (!t.isCallExpression(call) || !t.isIdentifier(call.callee) || !call.arguments.every((a) => t.isExpression(a)))
|
|
1183
|
+
return null;
|
|
1184
|
+
const fnName = call.callee.name;
|
|
1185
|
+
const node = this.toolFns.get(fnName);
|
|
1186
|
+
const item = this.comp.items.find((i) => i.kind === 'function' && i.name === fnName);
|
|
1187
|
+
if (!node || !item || (this.comp.refs.get(call.callee) ?? fnName) !== fnName || scope.loopNames.has(fnName) || !this.onlyTemplateCalls(fnName, item))
|
|
1188
|
+
return null;
|
|
1189
|
+
if (call.arguments.some((a) => this.readsHeldMarkup(a)))
|
|
1190
|
+
return null;
|
|
1191
|
+
this.dropped.add(fnName);
|
|
1192
|
+
const name = this.helperFn({ kind: 'function', name: fnName, node }, null);
|
|
1193
|
+
if (!name) {
|
|
1194
|
+
this.dropped.delete(fnName);
|
|
1195
|
+
return null;
|
|
1196
|
+
}
|
|
1197
|
+
return `<component :is="${escapeAttr(this.expr(t.callExpression(t.identifier(name), call.arguments), scope))}" />`;
|
|
1198
|
+
}
|
|
1199
|
+
/** M4: a render function draws markup built in script (a list whose keyed elements may move): see restoreFocus. */
|
|
1200
|
+
drawsScriptMarkup = false;
|
|
1201
|
+
/**
|
|
1202
|
+
* M4. React's commit puts the focus back on the element that had it when the update moved that element (a keyed
|
|
1203
|
+
* element of a list reordered): the DOM drops the focus of a node it moves. The component does the same around its
|
|
1204
|
+
* own updates. Written only for a component whose render functions draw markup built in script.
|
|
1205
|
+
*/
|
|
1206
|
+
restoreFocus() {
|
|
1207
|
+
if (!this.drawsScriptMarkup)
|
|
1208
|
+
return;
|
|
1209
|
+
const saved = this.script.alloc.alloc('focusedBefore');
|
|
1210
|
+
this.script.imports.named('vue', 'onBeforeUpdate');
|
|
1211
|
+
this.script.imports.named('vue', 'onUpdated');
|
|
1212
|
+
const el = t.identifier('el');
|
|
1213
|
+
const element = t.tsTypeAnnotation(t.tsUnionType([t.tsTypeReference(t.identifier('Element')), t.tsNullKeyword()]));
|
|
1214
|
+
const declared = t.identifier(saved);
|
|
1215
|
+
declared.typeAnnotation = element;
|
|
1216
|
+
const active = t.memberExpression(t.identifier('document'), t.identifier('activeElement'));
|
|
1217
|
+
this.hoisted.push(t.variableDeclaration('let', [t.variableDeclarator(declared, t.nullLiteral())]), t.expressionStatement(t.callExpression(t.identifier('onBeforeUpdate'), [t.arrowFunctionExpression([], t.blockStatement([t.expressionStatement(t.assignmentExpression('=', t.identifier(saved), active))]))])), t.expressionStatement(t.callExpression(t.identifier('onUpdated'), [
|
|
1218
|
+
t.arrowFunctionExpression([], t.blockStatement([
|
|
1219
|
+
t.variableDeclaration('const', [t.variableDeclarator(el, t.identifier(saved))]),
|
|
1220
|
+
t.expressionStatement(t.assignmentExpression('=', t.identifier(saved), t.nullLiteral())),
|
|
1221
|
+
t.ifStatement(t.logicalExpression('&&', t.logicalExpression('&&', t.binaryExpression('instanceof', t.identifier('el'), t.identifier('HTMLElement')), t.binaryExpression('!==', t.identifier('el'), t.cloneNode(active))), t.memberExpression(t.identifier('el'), t.identifier('isConnected'))), t.expressionStatement(t.callExpression(t.memberExpression(t.identifier('el'), t.identifier('focus')), []))),
|
|
1222
|
+
])),
|
|
1223
|
+
])));
|
|
1224
|
+
}
|
|
1225
|
+
/** M4: the errors writeFragmentsInPlace reported for render helpers it could not write in place, by helper. */
|
|
1226
|
+
treeFailures = new Map();
|
|
1227
|
+
/** M4: the helpers of treeFailures whose every call the template drew (helperDrawn) or did not (helperLeft). */
|
|
1228
|
+
helperDrawn = new Set();
|
|
1229
|
+
helperLeft = new Set();
|
|
1230
|
+
/**
|
|
1231
|
+
* M4. A call of a render helper that writeFragmentsInPlace could not write in place: one that renders itself (a
|
|
1232
|
+
* tree, `renderNode(node, 0)` whose markup calls `renderNode(child, depth + 1)`), renders a component picked from
|
|
1233
|
+
* its arguments, or computes a value it reads more than once outside a loop. The helper is written as a setup
|
|
1234
|
+
* function with `h()` from the function React wrote (helperFn), calling itself as React's did, and the template
|
|
1235
|
+
* renders the call with `<component :is>` while the component renders. Each call builds its elements anew with the
|
|
1236
|
+
* values of that render (a handler closes over its own `node` and the state it read), and each element keeps the key
|
|
1237
|
+
* React gives it. Null when the helper or this call has no exact `h()` form; the errors are withdrawn only when every
|
|
1238
|
+
* call of the helper was drawn (withdrawDrawnHelpers).
|
|
1239
|
+
*/
|
|
1240
|
+
treeCall(n, scope) {
|
|
1241
|
+
const def = this.comp.fragments.find((f) => f.name === n.name);
|
|
1242
|
+
const source = def ? fragmentSource(def) : undefined;
|
|
1243
|
+
const written = def && source && this.treeFailures.has(n.name) ? this.drawHelperCall(n, def, source, scope) : null;
|
|
1244
|
+
if (written)
|
|
1245
|
+
this.helperDrawn.add(n.name);
|
|
1246
|
+
else
|
|
1247
|
+
this.helperLeft.add(n.name);
|
|
1248
|
+
return written;
|
|
1249
|
+
}
|
|
1250
|
+
drawHelperCall(n, def, source, scope) {
|
|
1251
|
+
const own = [def.name, ...def.params.map((p) => p.name), ...def.locals.flatMap((l) => l.declarations.flatMap((d) => Object.keys(t.getBindingIdentifiers(d.id))))];
|
|
1252
|
+
// the call's arguments are the template's values (a loop item may share a name with the helper's parameter)
|
|
1253
|
+
if (n.args.some((a) => this.readsHeldMarkup(a, own)))
|
|
1254
|
+
return null;
|
|
1255
|
+
const name = this.helperFn({ kind: 'function', name: def.name, node: source }, null, [], own);
|
|
1256
|
+
if (!name)
|
|
1257
|
+
return null;
|
|
1258
|
+
this.drawsScriptMarkup = true;
|
|
1259
|
+
// it may call itself: the type checker needs what it returns written (a VNode, or nothing)
|
|
1260
|
+
const fn = this.hoisted.find((h) => t.isFunctionDeclaration(h) && h.id?.name === name);
|
|
1261
|
+
if (fn && !fn.returnType) {
|
|
1262
|
+
fn.returnType = t.tsTypeAnnotation(t.tsUnionType([t.tsTypeReference(t.identifier('VNode')), t.tsNullKeyword()]));
|
|
1263
|
+
this.script.typeImports.push({ source: 'vue', name: 'VNode' });
|
|
1264
|
+
}
|
|
1265
|
+
return `<component :is="${escapeAttr(this.expr(t.callExpression(t.identifier(name), n.args.map((a) => t.cloneNode(a, true))), scope))}" />`;
|
|
1266
|
+
}
|
|
1267
|
+
/** M4. The errors of the helpers whose every call the template drew, withdrawn (see treeCall). */
|
|
1268
|
+
withdrawDrawnHelpers() {
|
|
1269
|
+
for (const [name, diagnostics] of this.treeFailures) {
|
|
1270
|
+
if (!this.helperDrawn.has(name) || this.helperLeft.has(name))
|
|
1271
|
+
continue;
|
|
1272
|
+
for (const d of diagnostics)
|
|
1273
|
+
withdraw(this.script.ctx.diagnostics, d);
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
/** Whether the only reads of a component function are template value nodes that call it. */
|
|
1277
|
+
onlyTemplateCalls(name, own) {
|
|
1278
|
+
let other = false;
|
|
1279
|
+
const reads = (node) => {
|
|
1280
|
+
t.traverseFast(node, (n) => {
|
|
1281
|
+
if (t.isIdentifier(n) && n.name === name)
|
|
1282
|
+
other = true;
|
|
1283
|
+
});
|
|
1284
|
+
};
|
|
1285
|
+
const seen = new WeakSet();
|
|
1286
|
+
const visit = (v) => {
|
|
1287
|
+
if (Array.isArray(v)) {
|
|
1288
|
+
for (const x of v)
|
|
1289
|
+
visit(x);
|
|
1290
|
+
return;
|
|
1291
|
+
}
|
|
1292
|
+
if (!v || typeof v !== 'object' || seen.has(v) || v === own)
|
|
1293
|
+
return;
|
|
1294
|
+
seen.add(v);
|
|
1295
|
+
const type = Reflect.get(v, 'type');
|
|
1296
|
+
if (typeof type === 'string' && type in t.VISITOR_KEYS && t.isNode(v))
|
|
1297
|
+
return reads(v);
|
|
1298
|
+
if (type === 'expr') {
|
|
1299
|
+
const e = Reflect.get(v, 'expr');
|
|
1300
|
+
const call = t.isNode(e) && t.isExpression(e) ? unwrap(e) : null;
|
|
1301
|
+
if (call && t.isCallExpression(call) && t.isIdentifier(call.callee, { name })) {
|
|
1302
|
+
for (const a of call.arguments)
|
|
1303
|
+
reads(a);
|
|
1304
|
+
return;
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
for (const x of Object.values(v))
|
|
1308
|
+
visit(x);
|
|
1309
|
+
};
|
|
1310
|
+
visit([this.comp.items, this.comp.template, this.comp.fragments, this.comp.markupValues ?? [], this.comp.provides, this.comp.keptMarkup ?? []]);
|
|
1311
|
+
return !other;
|
|
1312
|
+
}
|
|
1313
|
+
// M4: `ownNames`, a render helper's own name, parameters and values (a tree's), which its body reads as its own
|
|
1314
|
+
helperFn(item, diagnostic, calls = [], ownNames = []) {
|
|
1315
|
+
const known = this.helperFns.get(item.name);
|
|
1316
|
+
if (known !== undefined)
|
|
1317
|
+
return known;
|
|
1318
|
+
this.helperFns.set(item.name, null);
|
|
1319
|
+
const fn = item.node;
|
|
1320
|
+
// the helper's own name, as its declaration or a recursive call, is no read of held markup
|
|
1321
|
+
const params = fn.params;
|
|
1322
|
+
const bodyNode = fn.body;
|
|
1323
|
+
if (fn.async || fn.generator || !params.every((p) => t.isIdentifier(p) || t.isObjectPattern(p) || t.isArrayPattern(p) || t.isAssignmentPattern(p)))
|
|
1324
|
+
return null;
|
|
1325
|
+
const own = t.isBlockStatement(bodyNode) ? bodyNode : t.blockStatement([t.returnStatement(bodyNode)]);
|
|
1326
|
+
const probe = t.arrowFunctionExpression(params, own);
|
|
1327
|
+
// the component's other render helpers it calls that lowering kept only for it (KeptMarkup `calls`): each is
|
|
1328
|
+
// written the same way, before it, and called by its written name
|
|
1329
|
+
const renames = this.calledHelpers(own, calls);
|
|
1330
|
+
if (!renames)
|
|
1331
|
+
return null;
|
|
1332
|
+
// M4: a tree helper's own names (ownNames) are no held markup and no unknown names
|
|
1333
|
+
if (this.readsHeldMarkup(own, ownNames) || this.readsUnknownNames(probe, new Set([...renames.keys(), ...ownNames])))
|
|
1334
|
+
return null;
|
|
1335
|
+
const copy = cloneWithRefs(own, this.comp);
|
|
1336
|
+
if ([...renames].some(([from, to]) => from !== to)) {
|
|
1337
|
+
t.traverseFast(copy, (n) => {
|
|
1338
|
+
if (t.isCallExpression(n) && t.isIdentifier(n.callee) && renames.has(n.callee.name))
|
|
1339
|
+
n.callee = t.identifier(renames.get(n.callee.name) ?? n.callee.name);
|
|
1340
|
+
});
|
|
1341
|
+
}
|
|
1342
|
+
const written = this.renderBody(copy);
|
|
1343
|
+
if (!written)
|
|
1344
|
+
return null;
|
|
1345
|
+
// a function whose React form the setup leaves out keeps its name
|
|
1346
|
+
const name = this.script.alloc.has(item.name) && !this.dropped.has(item.name) ? this.script.alloc.alloc(item.name) : item.name;
|
|
1347
|
+
this.script.alloc.reserve(name);
|
|
1348
|
+
const typedParams = params.map((p) => cloneWithRefs(p, this.comp));
|
|
1349
|
+
for (const param of typedParams)
|
|
1350
|
+
this.vnodeTypes(param);
|
|
1351
|
+
this.hoisted.push(t.functionDeclaration(t.identifier(name), typedParams, written));
|
|
1352
|
+
if (diagnostic)
|
|
1353
|
+
withdraw(this.script.ctx.diagnostics, diagnostic);
|
|
1354
|
+
this.helperFns.set(item.name, name);
|
|
1355
|
+
return name;
|
|
1356
|
+
}
|
|
1357
|
+
/**
|
|
1358
|
+
* The render helpers (of `calls`) a helper's body calls, each written as a setup function (helperFn), by React's
|
|
1359
|
+
* name to the written one. Only calls whose result React renders as it is: a markup child (`<span>{quiet(n)}</span>`)
|
|
1360
|
+
* or the value the body returns, where the VNode the written helper returns renders as React renders what the
|
|
1361
|
+
* original returned (an element, a list, text or nothing). Null when one is read any other way (`quiet(n).length`, a
|
|
1362
|
+
* test, passed on as a value, a name the body shadows) or cannot be written.
|
|
1363
|
+
*/
|
|
1364
|
+
calledHelpers(body, calls) {
|
|
1365
|
+
const out = new Map();
|
|
1366
|
+
if (!calls.length)
|
|
1367
|
+
return out;
|
|
1368
|
+
const byName = new Map(calls.map((c) => [c.name, c]));
|
|
1369
|
+
const used = new Set();
|
|
1370
|
+
let wrong = false;
|
|
1371
|
+
const visit = (n, parent, grand) => {
|
|
1372
|
+
if (wrong)
|
|
1373
|
+
return;
|
|
1374
|
+
if (t.isIdentifier(n) && byName.has(n.name)) {
|
|
1375
|
+
const property = parent && (t.isMemberExpression(parent) || t.isOptionalMemberExpression(parent)) && parent.property === n && !parent.computed;
|
|
1376
|
+
const key = parent && (t.isObjectProperty(parent) || t.isObjectMethod(parent)) && parent.key === n && !parent.computed;
|
|
1377
|
+
if (property || key)
|
|
1378
|
+
return;
|
|
1379
|
+
const call = parent && t.isCallExpression(parent) && parent.callee === n ? parent : null;
|
|
1380
|
+
// the call's own place: a JSX child, or what a function returns
|
|
1381
|
+
const rendered = !!call && !!grand && ((t.isJSXExpressionContainer(grand) && grand.expression === call) || (t.isReturnStatement(grand) && grand.argument === call) || (t.isArrowFunctionExpression(grand) && grand.body === call));
|
|
1382
|
+
if (!rendered || (this.comp.refs.get(n) ?? null) !== n.name)
|
|
1383
|
+
wrong = true;
|
|
1384
|
+
else
|
|
1385
|
+
used.add(n.name);
|
|
1386
|
+
return;
|
|
1387
|
+
}
|
|
1388
|
+
for (const field of t.VISITOR_KEYS[n.type] ?? []) {
|
|
1389
|
+
const child = Reflect.get(n, field);
|
|
1390
|
+
for (const c of Array.isArray(child) ? child : [child])
|
|
1391
|
+
if (t.isNode(c))
|
|
1392
|
+
visit(c, n, parent);
|
|
1393
|
+
}
|
|
1394
|
+
};
|
|
1395
|
+
// a JSX child's container sits in an element's or fragment's children, never an attribute's value
|
|
1396
|
+
const attributeValues = new WeakSet();
|
|
1397
|
+
t.traverseFast(body, (n) => {
|
|
1398
|
+
if (t.isJSXAttribute(n) && n.value)
|
|
1399
|
+
attributeValues.add(n.value);
|
|
1400
|
+
});
|
|
1401
|
+
visit(body, null, null);
|
|
1402
|
+
if (wrong)
|
|
1403
|
+
return null;
|
|
1404
|
+
for (const name of used) {
|
|
1405
|
+
const c = byName.get(name);
|
|
1406
|
+
if (!c)
|
|
1407
|
+
return null;
|
|
1408
|
+
let inAttribute = false;
|
|
1409
|
+
t.traverseFast(body, (n) => {
|
|
1410
|
+
if (attributeValues.has(n))
|
|
1411
|
+
t.traverseFast(n, (m) => void (t.isIdentifier(m, { name }) && (inAttribute = true)));
|
|
1412
|
+
});
|
|
1413
|
+
if (inAttribute)
|
|
1414
|
+
return null;
|
|
1415
|
+
const written = this.helperFn({ kind: 'function', name, node: c.node }, null, calls);
|
|
1416
|
+
if (!written)
|
|
1417
|
+
return null;
|
|
1418
|
+
out.set(name, written);
|
|
1419
|
+
}
|
|
1420
|
+
return out;
|
|
1421
|
+
}
|
|
1422
|
+
/**
|
|
1423
|
+
* A body of React code that returns markup, written for the setup script: state and props read as the script reads
|
|
1424
|
+
* them, children as the default slot's nodes, markup with `h()` (render-fn/h), and each value it returns made one
|
|
1425
|
+
* VNode for `:is`. Null when some markup has no exact form (its errors are reported) or a name is shadowed.
|
|
1426
|
+
*/
|
|
1427
|
+
renderBody(copy, skip) {
|
|
1428
|
+
const problems = [];
|
|
1429
|
+
const slotsBefore = this.script.slotsDeclared();
|
|
1430
|
+
const imports = [['vue', 'h']];
|
|
1431
|
+
const helpers = [];
|
|
1432
|
+
const rewritten = this.script.r(copy, skip);
|
|
1433
|
+
// children read as markup (`{children}`, `Children.map(children, …)`) are what the default slot renders now: a
|
|
1434
|
+
// test of them was already made a test of the slot (VueScript.slotReads)
|
|
1435
|
+
const children = childrenLocal(this.comp);
|
|
1436
|
+
if (children) {
|
|
1437
|
+
let shadowed = false;
|
|
1438
|
+
t.traverseFast(rewritten, (n) => {
|
|
1439
|
+
const declared = t.isFunction(n) ? n.params.flatMap((p) => Object.keys(t.getBindingIdentifiers(p))) : t.isVariableDeclarator(n) ? Object.keys(t.getBindingIdentifiers(n.id)) : [];
|
|
1440
|
+
if (declared.includes(children))
|
|
1441
|
+
shadowed = true;
|
|
1442
|
+
});
|
|
1443
|
+
if (shadowed)
|
|
1444
|
+
return null;
|
|
1445
|
+
transform(rewritten, (n, parent) => {
|
|
1446
|
+
if (!t.isIdentifier(n, { name: children }))
|
|
1447
|
+
return null;
|
|
1448
|
+
if (parent && (t.isMemberExpression(parent) || t.isOptionalMemberExpression(parent)) && parent.property === n && !parent.computed)
|
|
1449
|
+
return null;
|
|
1450
|
+
if (parent && t.isObjectProperty(parent) && parent.key === n && !parent.computed)
|
|
1451
|
+
return null;
|
|
1452
|
+
return slotNodes(this.script.slotsLocal());
|
|
1453
|
+
});
|
|
1454
|
+
}
|
|
1455
|
+
const hctx = this.hContext(problems, imports, helpers);
|
|
1456
|
+
const written = writeMarkup(rewritten, hctx);
|
|
1457
|
+
const errors = problems.filter((p) => p.severity === 'error');
|
|
1458
|
+
if (!written || errors.length) {
|
|
1459
|
+
this.script.ctx.diagnostics.push(...errors);
|
|
1460
|
+
this.script.restoreSlots(slotsBefore);
|
|
1461
|
+
return null;
|
|
1462
|
+
}
|
|
1463
|
+
// what it returns is what `:is` renders: an element as it is, nothing as null, anything else (text, a list) in a
|
|
1464
|
+
// fragment, since `:is` given a string would look up a component by that name
|
|
1465
|
+
for (const r of ownReturns(written)) {
|
|
1466
|
+
const value = r.argument;
|
|
1467
|
+
if (!value || t.isIdentifier(value, { name: 'undefined' }))
|
|
1468
|
+
r.argument = t.nullLiteral();
|
|
1469
|
+
else if (!t.isNullLiteral(value) && !(t.isCallExpression(value) && t.isIdentifier(value.callee, { name: 'h' }))) {
|
|
1470
|
+
imports.push(['vue', 'Fragment']);
|
|
1471
|
+
// a value read from data or a prop's function (`c.cell(r)`) that React's types say may be an element: markup a
|
|
1472
|
+
// caller's data holds may be a functional component, rendered as the template renders it (markupChild)
|
|
1473
|
+
const held = (t.isCallExpression(value) || t.isMemberExpression(value) || t.isOptionalCallExpression(value) || t.isOptionalMemberExpression(value)) && hctx.markupChild(value);
|
|
1474
|
+
if (held)
|
|
1475
|
+
helpers.push('markupChild');
|
|
1476
|
+
r.argument = t.callExpression(t.identifier('h'), [t.identifier('Fragment'), t.nullLiteral(), t.arrayExpression([held ? t.callExpression(t.identifier('markupChild'), [value]) : value])]);
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1479
|
+
for (const [from, imported] of imports)
|
|
1480
|
+
this.script.imports.named(from, imported);
|
|
1481
|
+
for (const helper of helpers)
|
|
1482
|
+
this.script.helpers.add(helper);
|
|
1483
|
+
this.script.ctx.diagnostics.push(...problems);
|
|
1484
|
+
this.vnodeTypes(written);
|
|
1485
|
+
return written;
|
|
1486
|
+
}
|
|
1487
|
+
/**
|
|
1488
|
+
* React's markup types in render-function code are VNode types: what a render function holds is a VNode, not the
|
|
1489
|
+
* functional component the template path makes of markup held as a value (`ReactNode` is `VNodeChild`,
|
|
1490
|
+
* `ReactElement` and `JSX.Element` are `VNode`).
|
|
1491
|
+
*/
|
|
1492
|
+
vnodeTypes(node) {
|
|
1493
|
+
const name = (n) => (t.isIdentifier(n) ? n.name : `${name(n.left)}.${n.right.name}`);
|
|
1494
|
+
t.traverseFast(node, (n) => {
|
|
1495
|
+
if (!t.isTSTypeReference(n))
|
|
1496
|
+
return;
|
|
1497
|
+
const written = name(n.typeName).replace(/^React\./, '');
|
|
1498
|
+
const vue = written === 'ReactNode' ? 'VNodeChild' : written === 'ReactElement' || written === 'JSX.Element' ? 'VNode' : null;
|
|
1499
|
+
if (!vue)
|
|
1500
|
+
return;
|
|
1501
|
+
n.typeName = t.identifier(vue);
|
|
1502
|
+
n.typeParameters = null;
|
|
1503
|
+
this.script.typeImports.push({ source: 'vue', name: vue });
|
|
1504
|
+
});
|
|
1505
|
+
}
|
|
1506
|
+
/**
|
|
1507
|
+
* Whether an expression reads markup the Vue output holds in another form (a render helper written in place in the
|
|
1508
|
+
* template, a value built out of elements, module markup inlined or kept as a functional component): a render
|
|
1509
|
+
* function calling it would get no VNode. Also a parameter or local of a render helper: the expression sits in the
|
|
1510
|
+
* helper, whose markup the template writes in place with the call's arguments.
|
|
1511
|
+
*/
|
|
1512
|
+
readsHeldMarkup(e, own = []) {
|
|
1513
|
+
const ctx = this.script.ctx;
|
|
1514
|
+
const mod = ctx.moduleOf?.(ctx.sourceFile) ?? null;
|
|
1515
|
+
const held = new Set([
|
|
1516
|
+
...this.comp.fragments.map((f) => f.name),
|
|
1517
|
+
// a render helper's parameters and locals: written in place, the template reads the call's arguments instead,
|
|
1518
|
+
// while the kept expression still names the parameters
|
|
1519
|
+
...this.comp.fragments.flatMap((f) => [...f.params.map((p) => p.name), ...f.locals.flatMap((l) => l.declarations.flatMap((d) => Object.keys(t.getBindingIdentifiers(d.id))))]),
|
|
1520
|
+
...(this.comp.markupValues ?? []).map((v) => v.name),
|
|
1521
|
+
...(this.comp.keptMarkup ?? []).flatMap((k) => (k.kind === 'value' ? k.names : [])),
|
|
1522
|
+
...this.comp.items.flatMap((i) => (i.kind === 'function' && containsJSX(i.node) ? [i.name] : i.kind === 'derived' && containsJSX(i.init) ? i.names : [])),
|
|
1523
|
+
...(mod ? [...mod.moduleJsx.renderFns.keys(), ...mod.moduleJsx.constants.keys(), ...mod.moduleJsx.maps.keys(), ...(mod.markupValues ?? []).map((v) => v.name)] : []),
|
|
1524
|
+
]);
|
|
1525
|
+
// the value's own name, which its code declares and fills
|
|
1526
|
+
for (const name of own)
|
|
1527
|
+
held.delete(name);
|
|
1528
|
+
let found = false;
|
|
1529
|
+
const visit = (n, parent) => {
|
|
1530
|
+
if (found)
|
|
1531
|
+
return;
|
|
1532
|
+
// a member's name (`c.cell(r)`) or an object key is no read of the name
|
|
1533
|
+
const property = parent && (t.isMemberExpression(parent) || t.isOptionalMemberExpression(parent)) && parent.property === n && !parent.computed;
|
|
1534
|
+
const key = parent && (t.isObjectProperty(parent) || t.isObjectMethod(parent)) && parent.key === n && !parent.computed;
|
|
1535
|
+
if (t.isIdentifier(n) && held.has(n.name) && !property && !key)
|
|
1536
|
+
found = true;
|
|
1537
|
+
for (const field of t.VISITOR_KEYS[n.type] ?? []) {
|
|
1538
|
+
const child = Reflect.get(n, field);
|
|
1539
|
+
for (const c of Array.isArray(child) ? child : [child])
|
|
1540
|
+
if (t.isNode(c))
|
|
1541
|
+
visit(c, n);
|
|
1542
|
+
}
|
|
1543
|
+
};
|
|
1544
|
+
visit(e, null);
|
|
1545
|
+
return found;
|
|
1546
|
+
}
|
|
1547
|
+
/**
|
|
1548
|
+
* Whether an expression reads a name the setup script does not have: one bound by code around it in the template
|
|
1549
|
+
* (a `.map` callback's item or locals, a render helper's parameters, a function lowering left out) rather than by
|
|
1550
|
+
* the component (its bindings), the module (its names and imports), the expression itself or the browser.
|
|
1551
|
+
*/
|
|
1552
|
+
readsUnknownNames(e, helpers = new Set()) {
|
|
1553
|
+
const ctx = this.script.ctx;
|
|
1554
|
+
const mod = ctx.moduleOf?.(ctx.sourceFile) ?? null;
|
|
1555
|
+
const known = new Set([...(mod?.moduleJsx.moduleNames ?? []), ...(mod?.imports.flatMap((d) => d.specifiers.map((s) => s.local.name)) ?? [])]);
|
|
1556
|
+
const declaredHere = new Set();
|
|
1557
|
+
t.traverseFast(e, (n) => {
|
|
1558
|
+
const declared = t.isFunction(n) ? [...n.params.flatMap((p) => Object.keys(t.getBindingIdentifiers(p))), ...(t.isFunctionDeclaration(n) && n.id ? [n.id.name] : [])] : t.isVariableDeclarator(n) ? Object.keys(t.getBindingIdentifiers(n.id)) : t.isCatchClause(n) && n.param ? Object.keys(t.getBindingIdentifiers(n.param)) : [];
|
|
1559
|
+
for (const name of declared) {
|
|
1560
|
+
known.add(name);
|
|
1561
|
+
declaredHere.add(name);
|
|
1562
|
+
}
|
|
1563
|
+
});
|
|
1564
|
+
const resolves = (id) => {
|
|
1565
|
+
const own = t.isIdentifier(id) ? this.comp.refs.get(id) : undefined;
|
|
1566
|
+
// a name of the component lowering left out of its bindings resolves only when the code declares it itself (a
|
|
1567
|
+
// kept value's own name)
|
|
1568
|
+
if (own)
|
|
1569
|
+
return this.comp.bindings.has(own) || helpers.has(own) || (own === id.name && declaredHere.has(own));
|
|
1570
|
+
return known.has(id.name) || (!this.comp.bindings.has(id.name) && (id.name in globalThis || BROWSER_GLOBALS.has(id.name)));
|
|
1571
|
+
};
|
|
1572
|
+
let unknown = false;
|
|
1573
|
+
const visit = (n, parent) => {
|
|
1574
|
+
if (unknown || t.isTSType(n) || t.isTSTypeAnnotation(n) || t.isTSTypeParameterInstantiation(n) || t.isTSTypeParameterDeclaration(n))
|
|
1575
|
+
return;
|
|
1576
|
+
if (t.isIdentifier(n)) {
|
|
1577
|
+
const property = parent && (t.isMemberExpression(parent) || t.isOptionalMemberExpression(parent)) && parent.property === n && !parent.computed;
|
|
1578
|
+
const key = parent && (t.isObjectProperty(parent) || t.isObjectMethod(parent)) && parent.key === n && !parent.computed;
|
|
1579
|
+
if (!property && !key && !resolves(n))
|
|
1580
|
+
unknown = true;
|
|
1581
|
+
return;
|
|
1582
|
+
}
|
|
1583
|
+
// a component tag (`<Badge/>`, `<Icons.Close/>`) names a binding too
|
|
1584
|
+
if (t.isJSXOpeningElement(n)) {
|
|
1585
|
+
let root = null;
|
|
1586
|
+
if (t.isJSXIdentifier(n.name) && /^[A-Z_$]/.test(n.name.name))
|
|
1587
|
+
root = n.name;
|
|
1588
|
+
else if (t.isJSXMemberExpression(n.name)) {
|
|
1589
|
+
let object = n.name.object;
|
|
1590
|
+
while (t.isJSXMemberExpression(object))
|
|
1591
|
+
object = object.object;
|
|
1592
|
+
root = object;
|
|
1593
|
+
}
|
|
1594
|
+
if (root && !resolves(root))
|
|
1595
|
+
unknown = true;
|
|
1596
|
+
}
|
|
1597
|
+
for (const field of t.VISITOR_KEYS[n.type] ?? []) {
|
|
1598
|
+
const child = Reflect.get(n, field);
|
|
1599
|
+
for (const c of Array.isArray(child) ? child : [child])
|
|
1600
|
+
if (t.isNode(c))
|
|
1601
|
+
visit(c, n);
|
|
1602
|
+
}
|
|
1603
|
+
};
|
|
1604
|
+
visit(e, null);
|
|
1605
|
+
return unknown;
|
|
1606
|
+
}
|
|
1607
|
+
/** What the render-function writer (render-fn/h) asks of this component. */
|
|
1608
|
+
hContext(problems, imports, helpers) {
|
|
1609
|
+
const ctx = this.script.ctx;
|
|
1610
|
+
const mod = ctx.moduleOf?.(ctx.sourceFile) ?? null;
|
|
1611
|
+
const layout = ctx.layoutOf(ctx.sourceFile);
|
|
1612
|
+
const radix = new Set(mod?.imports.filter((d) => /^@radix-ui\/|^radix-ui$/.test(d.source.value)).flatMap((d) => d.specifiers.map((s) => s.local.name)) ?? []);
|
|
1613
|
+
// React's own names by local name: `React` for the namespace or default import
|
|
1614
|
+
const reactImports = new Map();
|
|
1615
|
+
for (const d of mod?.imports ?? []) {
|
|
1616
|
+
if (d.source.value !== 'react')
|
|
1617
|
+
continue;
|
|
1618
|
+
for (const s of d.specifiers)
|
|
1619
|
+
reactImports.set(s.local.name, t.isImportSpecifier(s) ? (t.isIdentifier(s.imported) ? s.imported.name : s.imported.value) : 'React');
|
|
1620
|
+
}
|
|
1621
|
+
const push = (code, severity, message, line) => {
|
|
1622
|
+
problems.push({ code, severity, message, file: ctx.sourceRel, target: 'vue', ...(line ? { line } : {}) });
|
|
1623
|
+
};
|
|
1624
|
+
return {
|
|
1625
|
+
refKind: (name) => {
|
|
1626
|
+
const b = this.comp.bindings.get(name);
|
|
1627
|
+
return b?.refKind === 'dom' && (b.kind === 'ref' || b.kind === 'hook') ? 'dom' : null;
|
|
1628
|
+
},
|
|
1629
|
+
isMotion: (name) => mod?.motionNames.has(name) ?? false,
|
|
1630
|
+
isMotionValue: (name) => holdsMotionValue(this.comp, name),
|
|
1631
|
+
tagProblem: (tag) => {
|
|
1632
|
+
if (radix.has(tag.split('.')[0] ?? tag))
|
|
1633
|
+
return "is a Radix part (reka-ui's components are written for templates)";
|
|
1634
|
+
// React 19's `<Ctx value={v}>`: the context object itself, which Vue provides with provide() in a setup
|
|
1635
|
+
if (mod?.contexts.some((c) => c.name === tag))
|
|
1636
|
+
return "is a React context used as its provider (Vue provides values with provide() in a component's setup)";
|
|
1637
|
+
const own = mod?.components.some((c) => c.name === tag) ?? false;
|
|
1638
|
+
if (this.inline.comps.has(tag) || (own && !layout?.components.has(tag)))
|
|
1639
|
+
return 'is written in place in Vue, so there is no component to pass to h()';
|
|
1640
|
+
return null;
|
|
1641
|
+
},
|
|
1642
|
+
markupProp: (tag, prop) => {
|
|
1643
|
+
const child = this.script.childOf(tag);
|
|
1644
|
+
return child ? (rendersSlot(child, prop) ? 'slot' : 'value') : null;
|
|
1645
|
+
},
|
|
1646
|
+
use: (source, name) => void imports.push([source, name]),
|
|
1647
|
+
helper: (name) => void helpers.push(name),
|
|
1648
|
+
markupChild: (e) => {
|
|
1649
|
+
// the values the child may be (through `&&`, `||`, `??` and `?:`): markup written there is a VNode already, any
|
|
1650
|
+
// other value may be markup held as a value where React's types say it may be an element
|
|
1651
|
+
const leaves = (x) => {
|
|
1652
|
+
const v = unwrap(x);
|
|
1653
|
+
// (`a && b` renders `a` only while it is falsy, which markup held as a value never is)
|
|
1654
|
+
if (t.isLogicalExpression(v))
|
|
1655
|
+
return v.operator === '&&' ? leaves(v.right) : [...leaves(v.left), ...leaves(v.right)];
|
|
1656
|
+
if (t.isConditionalExpression(v))
|
|
1657
|
+
return [...leaves(v.consequent), ...leaves(v.alternate)];
|
|
1658
|
+
return [v];
|
|
1659
|
+
};
|
|
1660
|
+
return leaves(e).some((v) => {
|
|
1661
|
+
if (t.isJSXElement(v) || t.isJSXFragment(v))
|
|
1662
|
+
return false;
|
|
1663
|
+
// a value that is never markup by its form (text, a number, a sum)
|
|
1664
|
+
if (t.isStringLiteral(v) || t.isNumericLiteral(v) || t.isBooleanLiteral(v) || t.isNullLiteral(v) || t.isTemplateLiteral(v) || t.isBinaryExpression(v) || t.isUnaryExpression(v) || (t.isIdentifier(v) && v.name === 'undefined'))
|
|
1665
|
+
return false;
|
|
1666
|
+
// the code was already written for the script (state `badge` read as `badge.value`): React's types are asked
|
|
1667
|
+
// of the name as React wrote it
|
|
1668
|
+
if (v.loc)
|
|
1669
|
+
return !!ctx.oracle?.elementKind(ctx.sourceFile, v.loc).element;
|
|
1670
|
+
// (the rewritten read carries no place in the source: `badge.value` is the component's `badge`, whose declared
|
|
1671
|
+
// type React's checker gives)
|
|
1672
|
+
const name = t.isMemberExpression(v) && !v.computed && t.isIdentifier(v.property, { name: 'value' }) && t.isIdentifier(v.object) ? v.object.name : t.isIdentifier(v) ? v.name : null;
|
|
1673
|
+
const type = name && this.comp.bindings.has(name) ? (ctx.oracle?.typeOf(ctx.sourceFile, this.comp.name, name) ?? null) : null;
|
|
1674
|
+
// a name React's types cannot be asked about may be markup held as a value: markupChild renders either (code
|
|
1675
|
+
// this writer made itself, the default slot's nodes, is no such name)
|
|
1676
|
+
if (!type || t.isTSAnyKeyword(type) || t.isTSUnknownKeyword(type))
|
|
1677
|
+
return t.isIdentifier(v) || t.isMemberExpression(v) || t.isOptionalMemberExpression(v);
|
|
1678
|
+
let element = false;
|
|
1679
|
+
t.traverseFast(type, (n) => {
|
|
1680
|
+
const ref = t.isTSTypeReference(n) ? n.typeName : null;
|
|
1681
|
+
const last = t.isIdentifier(ref) ? ref.name : t.isTSQualifiedName(ref) ? ref.right.name : '';
|
|
1682
|
+
if (/^(ReactNode|ReactElement|ReactPortal|ReactChild|Element)$/.test(last))
|
|
1683
|
+
element = true;
|
|
1684
|
+
});
|
|
1685
|
+
return element;
|
|
1686
|
+
});
|
|
1687
|
+
},
|
|
1688
|
+
reactApi: (e) => {
|
|
1689
|
+
const name = t.isIdentifier(e) ? (reactImports.get(e.name) ?? null) : t.isMemberExpression(e) && !e.computed && t.isIdentifier(e.object) && reactImports.get(e.object.name) === 'React' && t.isIdentifier(e.property) ? e.property.name : null;
|
|
1690
|
+
return name === 'Children' || name === 'isValidElement' || name === 'cloneElement' ? name : null;
|
|
1691
|
+
},
|
|
1692
|
+
childrenNodes: (e) => {
|
|
1693
|
+
// the children prop, already read as the default slot's nodes (renderPiece), or `props.children`
|
|
1694
|
+
const declared = this.script.slotsDeclared();
|
|
1695
|
+
if (declared && t.isOptionalCallExpression(e) && printExpr(e) === printExpr(slotNodes(declared)))
|
|
1696
|
+
return e;
|
|
1697
|
+
const reads = this.comp.propsObject && t.isMemberExpression(e) && !e.computed && t.isIdentifier(e.object, { name: this.comp.propsObject }) && t.isIdentifier(e.property, { name: 'children' });
|
|
1698
|
+
return reads ? slotNodes(this.script.slotsLocal()) : null;
|
|
1699
|
+
},
|
|
1700
|
+
warn: (code, message, line) => push(code, 'warning', message, line),
|
|
1701
|
+
refuse: (code, message, line) => push(code, 'error', message, line),
|
|
1702
|
+
};
|
|
1703
|
+
}
|
|
1704
|
+
/** A handler: names and short expressions inline; functions that write state or run statements become script functions. */
|
|
1705
|
+
handler(e, event, scope, listener = false) {
|
|
1706
|
+
const written = unwrap(e);
|
|
1707
|
+
if ((t.isArrowFunctionExpression(written) || t.isFunctionExpression(written)) && !this.usesLoopNames(written, scope) && (t.isBlockStatement(written.body) || writesState(written, this.comp) || printExpr(written).length > 60)) {
|
|
1708
|
+
const name = this.script.alloc.alloc(`handle${event.charAt(0).toUpperCase()}${event.slice(1).replace(/-(\w)/g, (_, c) => c.toUpperCase())}`);
|
|
1709
|
+
// moved out of its v-if branch, the function no longer follows the test that proved a value there (as it did in
|
|
1710
|
+
// React, where it was written inside the branch): its reads of those paths state it
|
|
1711
|
+
const fn = scope.facts?.size ? cloneWithRefs(written, this.comp) : written;
|
|
1712
|
+
if (scope.facts?.size)
|
|
1713
|
+
assertPaths(fn.body, scope.facts);
|
|
1714
|
+
const body = t.isBlockStatement(fn.body) ? fn.body : t.blockStatement([t.expressionStatement(fn.body)]);
|
|
1715
|
+
const decl = t.functionDeclaration(t.identifier(name), fn.params, body, false, fn.async);
|
|
1716
|
+
this.hoisted.push(this.script.r(decl));
|
|
1717
|
+
return name;
|
|
1718
|
+
}
|
|
1719
|
+
// a listener that only calls (`() => toggle(row.id)`) is an inline statement in Vue: `@click="toggle(row.id)"`
|
|
1720
|
+
if (listener && t.isArrowFunctionExpression(written) && !written.params.length && !written.async && (t.isCallExpression(written.body) || t.isOptionalCallExpression(written.body) || t.isAssignmentExpression(written.body)))
|
|
1721
|
+
return this.expr(written.body, scope);
|
|
1722
|
+
return this.expr(e, scope);
|
|
1723
|
+
}
|
|
1724
|
+
isElementish(n) {
|
|
1725
|
+
if (n.type === 'text' || n.type === 'expr' || n.type === 'unconverted' || n.type === 'render')
|
|
1726
|
+
return false;
|
|
1727
|
+
if (n.type === 'fragment')
|
|
1728
|
+
return n.children.every((c) => this.isElementish(c));
|
|
1729
|
+
return true;
|
|
1730
|
+
}
|
|
1731
|
+
children(nodes, indent, scope) {
|
|
1732
|
+
const flat = nodes.flatMap((n) => (n.type === 'fragment' ? n.children : [n]));
|
|
1733
|
+
if (!flat.length)
|
|
1734
|
+
return '';
|
|
1735
|
+
const inner = indent + ' ';
|
|
1736
|
+
if (flat.every((n) => this.isElementish(n))) {
|
|
1737
|
+
return flat.map((n) => `\n${inner}${this.node(n, inner, scope)}`).join('') + `\n${indent}`;
|
|
1738
|
+
}
|
|
1739
|
+
return flat.map((n) => this.node(n, indent, scope)).join('');
|
|
1740
|
+
}
|
|
1741
|
+
node(n, indent, scope, extra = []) {
|
|
1742
|
+
switch (n.type) {
|
|
1743
|
+
case 'text':
|
|
1744
|
+
return escapeText(n.value, false);
|
|
1745
|
+
case 'unconverted':
|
|
1746
|
+
{
|
|
1747
|
+
const kept = n.kept ? this.comp.keptMarkup?.find((k) => k.kind === 'expression' && k.id === n.kept) : undefined;
|
|
1748
|
+
const written = kept?.kind === 'expression' ? this.renderPiece(kept.expr, kept.diagnostic, scope) : n.value ? this.keptValue(n.value, scope) : null;
|
|
1749
|
+
return written ?? `<!-- antheo-morph: not converted: ${n.reason.replace(/--/g, '- -')} -->`;
|
|
1750
|
+
}
|
|
1751
|
+
case 'render':
|
|
1752
|
+
// a call writeFragmentsInPlace could not write in place (reported there); M4: a tree is drawn by a function
|
|
1753
|
+
return this.treeCall(n, scope) ?? `<!-- antheo-morph: not converted: a call of ${n.name} -->`;
|
|
1754
|
+
case 'expr': {
|
|
1755
|
+
// a call of a module function that builds elements (module-builders): what it returns, rendered as React renders a child
|
|
1756
|
+
if (buildsModuleElements(n)) {
|
|
1757
|
+
this.script.helpers.add('markupNodes');
|
|
1758
|
+
return `<component :is="${escapeAttr(`markupNodes(${this.expr(n.expr, scope)})`)}" />`;
|
|
1759
|
+
}
|
|
1760
|
+
const kept = n.kept ? this.keptRead(n, scope) : this.toolFns.size ? this.toolHelper(n.expr, scope) : null;
|
|
1761
|
+
if (kept)
|
|
1762
|
+
return kept;
|
|
1763
|
+
if (n.markup || this.derivedMarkup(n.expr)) {
|
|
1764
|
+
// markup held as a value is a functional component; anything else it may hold renders as text
|
|
1765
|
+
const value = escapeAttr(this.expr(n.expr, scope));
|
|
1766
|
+
// under its element test (`isValidElement(x) ? x : …`) it is only ever markup
|
|
1767
|
+
if (n.markup === 'element')
|
|
1768
|
+
return `<component :is="${value}" />`;
|
|
1769
|
+
return `<component :is="${value}" v-if="typeof ${value} === 'function'" /><template v-else>{{ ${this.expr(n.expr, scope)} }}</template>`;
|
|
1770
|
+
}
|
|
1771
|
+
return `{{ ${this.expr(n.expr, scope)} }}`;
|
|
1772
|
+
}
|
|
1773
|
+
case 'fragment':
|
|
1774
|
+
if (extra.length)
|
|
1775
|
+
return `<template ${extra.join(' ')}>${this.children(n.children, indent, scope)}</template>`;
|
|
1776
|
+
return this.children(n.children, indent, scope).trim();
|
|
1777
|
+
case 'element':
|
|
1778
|
+
return this.element(n, indent, scope, extra);
|
|
1779
|
+
case 'if':
|
|
1780
|
+
return this.ifNode(n.branches, indent, scope);
|
|
1781
|
+
case 'for':
|
|
1782
|
+
return this.forNode(n, indent, scope);
|
|
1783
|
+
case 'slot':
|
|
1784
|
+
return this.slot(n, indent, scope, extra);
|
|
1785
|
+
case 'keyed': {
|
|
1786
|
+
const only = n.children.length === 1 ? n.children[0] : undefined;
|
|
1787
|
+
const keyAttr = this.attr('key', n.key, scope);
|
|
1788
|
+
if (only && only.type === 'element')
|
|
1789
|
+
return this.element(only, indent, scope, [...extra, keyAttr]);
|
|
1790
|
+
this.script.warn('keyed-fragment', 'A key on a fragment re-creates its children through a wrapping <template v-if>.', 'info');
|
|
1791
|
+
return `<template ${[...extra, 'v-if="true"', keyAttr].join(' ')}>${this.children(n.children, indent, scope)}</template>`;
|
|
1792
|
+
}
|
|
1793
|
+
case 'presence': {
|
|
1794
|
+
const attrs = this.attrs(n.attrs, 'AnimatePresence', true, scope);
|
|
1795
|
+
this.script.imports.named('motion-v', 'AnimatePresence');
|
|
1796
|
+
return `<AnimatePresence${attrs.length ? ' ' + attrs.join(' ') : ''}${extra.length ? ' ' + extra.join(' ') : ''}>${this.children(n.children, indent, scope)}</AnimatePresence>`;
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
carrier(children, directive, indent, scope) {
|
|
1801
|
+
const only = children.length === 1 ? children[0] : undefined;
|
|
1802
|
+
if (only && (only.type === 'element' || only.type === 'slot' || (only.type === 'keyed' && only.children.length === 1 && only.children[0]?.type === 'element')))
|
|
1803
|
+
return this.node(only, indent, scope, [directive]);
|
|
1804
|
+
return `<template ${directive}>${this.children(children, indent, scope)}</template>`;
|
|
1805
|
+
}
|
|
1806
|
+
ifNode(branches, indent, scope) {
|
|
1807
|
+
return branches
|
|
1808
|
+
.map((b, i) => {
|
|
1809
|
+
const directive = b.test === null ? 'v-else' : `${i === 0 ? 'v-if' : 'v-else-if'}="${escapeAttr(this.expr(b.test, scope, true))}"`;
|
|
1810
|
+
// Vue needs keys unique across v-if branches: prefix a branch's key with its position
|
|
1811
|
+
const children = b.children.map((c) => (c.type === 'keyed' && branches.length > 1 ? { ...c, key: t.templateLiteral([t.templateElement({ raw: `${i}:`, cooked: `${i}:` }), t.templateElement({ raw: '', cooked: '' }, true)], [c.key]) } : c));
|
|
1812
|
+
// what this branch's test, and the failed tests before it, prove (for the handlers hoisted out of it)
|
|
1813
|
+
const facts = new Set(scope.facts);
|
|
1814
|
+
for (const before of branches.slice(0, i))
|
|
1815
|
+
if (before.test)
|
|
1816
|
+
nonNullFacts(before.test, false, facts);
|
|
1817
|
+
if (b.test)
|
|
1818
|
+
nonNullFacts(b.test, true, facts);
|
|
1819
|
+
const tests = [...(scope.tests ?? []), ...branches.slice(0, i).flatMap((before) => (before.test ? [{ test: before.test, holds: false }] : [])), ...(b.test ? [{ test: b.test, holds: true }] : [])];
|
|
1820
|
+
return this.carrier(children, directive, indent, { ...scope, facts, tests });
|
|
1821
|
+
})
|
|
1822
|
+
.join(`\n${indent}`);
|
|
1823
|
+
}
|
|
1824
|
+
forNode(n, indent, scope) {
|
|
1825
|
+
let children = n.children;
|
|
1826
|
+
let key = n.key;
|
|
1827
|
+
const only = children.length === 1 ? children[0] : undefined;
|
|
1828
|
+
if (!key && only?.type === 'keyed') {
|
|
1829
|
+
key = only.key;
|
|
1830
|
+
children = only.children;
|
|
1831
|
+
}
|
|
1832
|
+
const itemNames = n.item ? patternNames(n.item) : [];
|
|
1833
|
+
const loopNames = new Set([...scope.loopNames, ...itemNames, ...(n.index ? [n.index] : [])]);
|
|
1834
|
+
if (n.locals.length) {
|
|
1835
|
+
return this.forWithLocals(n, children, key, indent, scope);
|
|
1836
|
+
}
|
|
1837
|
+
const alias = n.item ? printExpr(stripTypes(t.cloneNode(n.item, true))) : '_item';
|
|
1838
|
+
const head = n.index ? `(${alias}, ${n.index})` : alias;
|
|
1839
|
+
// a loop's own names typed for script code of the rows inside (a row helper taking them as parameters): the index
|
|
1840
|
+
// is a number, the item has the type React's checker gave it
|
|
1841
|
+
const types = new Map(scope.types);
|
|
1842
|
+
if (n.index)
|
|
1843
|
+
types.set(n.index, t.tsNumberKeyword());
|
|
1844
|
+
const itemType = n.item && t.isIdentifier(n.item) && n.item.loc ? this.script.ctx.oracle?.typeAtLocation(this.script.ctx.sourceFile, n.item.loc.start.line, n.item.loc.start.column) : null;
|
|
1845
|
+
const mapped = itemType ? this.script.type(itemType) : null;
|
|
1846
|
+
if (mapped && n.item && t.isIdentifier(n.item))
|
|
1847
|
+
types.set(n.item.name, mapped);
|
|
1848
|
+
const inner = { rename: scope.rename, loopNames, depth: scope.depth + 1, ...(types.size ? { types } : {}) };
|
|
1849
|
+
const directive = `v-for="${escapeAttr(`${head} in ${this.expr(n.iterable, scope)}`)}"${key ? ' ' + this.attr('key', key, inner) : ''}`;
|
|
1850
|
+
return this.carrier(children, directive, indent, inner);
|
|
1851
|
+
}
|
|
1852
|
+
/** `.map((x, i) => { const a = ..; return <el/> })`: Vue has no template locals, so rows are computed in the script. */
|
|
1853
|
+
forWithLocals(n, children, key, indent, scope) {
|
|
1854
|
+
const localNames = n.locals.flatMap((l) => patternNames(l));
|
|
1855
|
+
const itemNames = n.item ? patternNames(n.item) : [];
|
|
1856
|
+
// a row carries what its markup reads (a value only other values use stays inside the mapper)
|
|
1857
|
+
const read = new Set();
|
|
1858
|
+
const collect = (v) => {
|
|
1859
|
+
if (!v || typeof v !== 'object')
|
|
1860
|
+
return;
|
|
1861
|
+
if (Array.isArray(v))
|
|
1862
|
+
v.forEach(collect);
|
|
1863
|
+
else if (t.isNode(v))
|
|
1864
|
+
namesIn([v], read);
|
|
1865
|
+
else {
|
|
1866
|
+
// a component tag (`<Icon/>`) reads its name too
|
|
1867
|
+
const tag = Reflect.get(v, 'tag');
|
|
1868
|
+
if (Reflect.get(v, 'type') === 'element' && typeof tag === 'string')
|
|
1869
|
+
read.add(tag.split('.')[0] ?? tag);
|
|
1870
|
+
Object.values(v).forEach(collect);
|
|
1871
|
+
}
|
|
1872
|
+
};
|
|
1873
|
+
collect(children);
|
|
1874
|
+
if (key)
|
|
1875
|
+
namesIn([key], read);
|
|
1876
|
+
const exported = [...new Set([...itemNames, ...(n.index ? [n.index] : []), ...localNames])].filter((name) => read.has(name));
|
|
1877
|
+
const tagHint = children.find((c) => c.type === 'element')?.tag.replace(/[^A-Za-z]/g, '') ?? 'row';
|
|
1878
|
+
const listName = this.script.alloc.alloc(`${tagHint.charAt(0).toLowerCase()}${tagHint.slice(1)}Rows`);
|
|
1879
|
+
const row = this.script.alloc.alloc('row');
|
|
1880
|
+
const params = [n.item ? t.cloneNode(n.item, true) : t.identifier('_item')];
|
|
1881
|
+
if (n.index)
|
|
1882
|
+
params.push(t.identifier(n.index));
|
|
1883
|
+
const mapper = t.arrowFunctionExpression(params, t.blockStatement([...n.locals.map((l) => cloneWithRefs(l, this.comp)), t.returnStatement(t.objectExpression(exported.map((name) => t.objectProperty(t.identifier(name), t.identifier(name), false, true))))]));
|
|
1884
|
+
// names of enclosing template loops the rows read (`s` of an outer v-for): they exist only in the template, so
|
|
1885
|
+
// the rows become a function of them, called from the template with the outer row's values
|
|
1886
|
+
const declared = new Set([...itemNames, ...(n.index ? [n.index] : []), ...localNames]);
|
|
1887
|
+
const outerNames = new Set([...scope.loopNames, ...scope.rename.keys()]);
|
|
1888
|
+
const outer = [...namesIn([n.iterable, ...n.locals])].filter((name) => outerNames.has(name) && !declared.has(name) && !this.comp.bindings.has(name));
|
|
1889
|
+
const listExpr = t.callExpression(t.memberExpression(t.callExpression(t.memberExpression(t.identifier('Array'), t.identifier('from')), [cloneWithRefs(n.iterable, this.comp)]), t.identifier('map')), [mapper]);
|
|
1890
|
+
// the mapper's own params and locals shadow component bindings; rewrite reads of component bindings only
|
|
1891
|
+
const rewritten = rewrite(outer.length ? listExpr : renameFree(listExpr, scope.rename), { ir: this.comp, mode: 'vue-script' });
|
|
1892
|
+
let source;
|
|
1893
|
+
if (outer.length) {
|
|
1894
|
+
// an outer name that is a field of an outer list of rows is typed by that list
|
|
1895
|
+
const typed = outer.map((name) => {
|
|
1896
|
+
const id = t.identifier(name);
|
|
1897
|
+
const type = scope.types?.get(name);
|
|
1898
|
+
if (type)
|
|
1899
|
+
id.typeAnnotation = t.tsTypeAnnotation(t.cloneNode(type, true));
|
|
1900
|
+
return id;
|
|
1901
|
+
});
|
|
1902
|
+
this.hoisted.push(t.functionDeclaration(t.identifier(listName), typed, t.blockStatement([t.returnStatement(rewritten)])));
|
|
1903
|
+
source = `${listName}(${outer.map((name) => this.expr(t.identifier(name), scope)).join(', ')})`;
|
|
1904
|
+
}
|
|
1905
|
+
else {
|
|
1906
|
+
this.hoisted.push(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(listName), t.callExpression(t.identifier(this.script.api('computed')), [t.arrowFunctionExpression([], rewritten)]))]));
|
|
1907
|
+
source = listName;
|
|
1908
|
+
}
|
|
1909
|
+
const rename = new Map(scope.rename);
|
|
1910
|
+
for (const name of exported)
|
|
1911
|
+
rename.set(name, t.memberExpression(t.identifier(row), t.identifier(name)));
|
|
1912
|
+
// the type of one row: `(typeof liRows.value)[number]`, or `ReturnType<typeof liRows>[number]`
|
|
1913
|
+
const rowType = t.tsIndexedAccessType(outer.length ? t.tsTypeReference(t.identifier('ReturnType'), t.tsTypeParameterInstantiation([t.tsTypeQuery(t.identifier(listName))])) : t.tsTypeQuery(t.tsQualifiedName(t.identifier(listName), t.identifier('value'))), t.tsNumberKeyword());
|
|
1914
|
+
const types = new Map(scope.types);
|
|
1915
|
+
for (const name of exported)
|
|
1916
|
+
types.set(name, t.tsIndexedAccessType(rowType, t.tsLiteralType(t.stringLiteral(name))));
|
|
1917
|
+
const inner = { rename, loopNames: new Set([...scope.loopNames, row]), depth: scope.depth + 1, types };
|
|
1918
|
+
const directive = `v-for="${escapeAttr(`${row} in ${source}`)}"${key ? ' ' + this.attr('key', key, inner) : ''}`;
|
|
1919
|
+
return this.carrier(children, directive, indent, inner);
|
|
1920
|
+
}
|
|
1921
|
+
slot(n, indent, scope, extra) {
|
|
1922
|
+
const name = n.name === 'default' ? '' : ` name="${n.name}"`;
|
|
1923
|
+
const prop = this.comp.props.find((p) => p.local === n.prop);
|
|
1924
|
+
if (n.args) {
|
|
1925
|
+
// a render prop called with values: the slot passes them as its props, named as the prop's type names them
|
|
1926
|
+
const params = prop ? renderPropOf(this.comp, prop.key)?.params : undefined;
|
|
1927
|
+
const bound = n.args.map((a, i) => this.attr(params?.[i]?.name ?? `arg${i}`, a, scope));
|
|
1928
|
+
return `<slot${name}${[...extra, ...bound].map((x) => ` ${x}`).join('')} />`;
|
|
1929
|
+
}
|
|
1930
|
+
// a node prop given as a value: markup held as a value (a functional component) renders, anything else is text
|
|
1931
|
+
const held = `<component :is="${n.prop}" v-if="typeof ${n.prop} === 'function'" />`;
|
|
1932
|
+
const fallback = prop?.kind === 'node'
|
|
1933
|
+
? n.fallback.length
|
|
1934
|
+
? `${held}<template v-else-if="${n.prop} !== undefined">{{ ${n.prop} }}</template><template v-else>${this.children(n.fallback, indent, scope)}</template>`
|
|
1935
|
+
: `${held}<template v-else>{{ ${n.prop} }}</template>`
|
|
1936
|
+
: this.children(n.fallback, indent, scope);
|
|
1937
|
+
return `<slot${name}${extra.length ? ' ' + extra.join(' ') : ''}>${fallback}</slot>`;
|
|
1938
|
+
}
|
|
1939
|
+
isDynamicTag(tag) {
|
|
1940
|
+
const b = this.comp.bindings.get(tag);
|
|
1941
|
+
return !!b && b.kind !== 'function';
|
|
1942
|
+
}
|
|
1943
|
+
/**
|
|
1944
|
+
* createPortal(children, container): `<Teleport>`. A container the page names (`document.body`, an element found by
|
|
1945
|
+
* id or selector) becomes the selector Teleport takes; any other value is passed as it is, computed in the script
|
|
1946
|
+
* when it reads the page (a template cannot reach `document`).
|
|
1947
|
+
*/
|
|
1948
|
+
teleport(n, container, indent, scope, extra) {
|
|
1949
|
+
const c = unwrap(container);
|
|
1950
|
+
const docCall = (method) => {
|
|
1951
|
+
if (!t.isCallExpression(c) || !t.isMemberExpression(c.callee) || !t.isIdentifier(c.callee.object, { name: 'document' }) || !t.isIdentifier(c.callee.property, { name: method }))
|
|
1952
|
+
return null;
|
|
1953
|
+
const arg = c.arguments[0];
|
|
1954
|
+
return c.arguments.length === 1 && t.isStringLiteral(arg) ? arg.value : null;
|
|
1955
|
+
};
|
|
1956
|
+
const id = docCall('getElementById');
|
|
1957
|
+
const selector = t.isMemberExpression(c) && !c.computed && t.isIdentifier(c.object, { name: 'document' }) && t.isIdentifier(c.property) && /^(body|head|documentElement)$/.test(c.property.name) ? (c.property.name === 'documentElement' ? 'html' : c.property.name) : id !== null && /^[A-Za-z][\w-]*$/.test(id) ? `#${id}` : docCall('querySelector');
|
|
1958
|
+
let to;
|
|
1959
|
+
if (selector !== null)
|
|
1960
|
+
to = `to="${escapeAttr(selector)}"`;
|
|
1961
|
+
else if (readsPage(c)) {
|
|
1962
|
+
const name = this.script.alloc.alloc('teleportTarget');
|
|
1963
|
+
this.hoisted.push(this.script.r(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(name), t.callExpression(t.identifier(this.script.api('computed')), [t.arrowFunctionExpression([], cloneWithRefs(container, this.comp))]))])));
|
|
1964
|
+
to = `:to="${name}"`;
|
|
1965
|
+
}
|
|
1966
|
+
else
|
|
1967
|
+
to = this.attr('to', container, scope);
|
|
1968
|
+
return `<Teleport ${[...extra, to].join(' ')}>${this.children(n.children, indent, scope)}</Teleport>`;
|
|
1969
|
+
}
|
|
1970
|
+
element(n, indent, scope, extra) {
|
|
1971
|
+
if (n.portal)
|
|
1972
|
+
return this.teleport(n, n.portal, indent, scope, extra);
|
|
1973
|
+
const inlined = n.component ? this.inline.comps.get(n.tag) : undefined;
|
|
1974
|
+
// markup its props' data holds would be functional components of its own setup, which a component written in place has not
|
|
1975
|
+
if (inlined?.markupValues?.length)
|
|
1976
|
+
this.script.warn('jsx-in-expression', `<${n.tag}> is written in place, where the markup its props' data holds (${inlined.markupValues.map((v) => v.name).join(', ')}) has no setup to live in: not converted.`, 'error');
|
|
1977
|
+
if (inlined)
|
|
1978
|
+
return this.inlined(n, inlined, indent, scope, extra);
|
|
1979
|
+
let tag = n.tag;
|
|
1980
|
+
let component = n.component;
|
|
1981
|
+
const attrsList = [...extra];
|
|
1982
|
+
if (component && tag === this.facts.nextImage) {
|
|
1983
|
+
tag = 'img';
|
|
1984
|
+
component = false;
|
|
1985
|
+
n.attrs = n.attrs.filter((a) => !('name' in a) || !/^(priority|quality|placeholder|blurDataURL|loader|unoptimized|fill|sizes)$/.test(a.name));
|
|
1986
|
+
}
|
|
1987
|
+
else if (component && tag === this.facts.nextLink) {
|
|
1988
|
+
tag = 'a';
|
|
1989
|
+
component = false;
|
|
1990
|
+
n.attrs = n.attrs.filter((a) => !('name' in a) || !/^(prefetch|replace|scroll|shallow|passHref|legacyBehavior)$/.test(a.name));
|
|
1991
|
+
}
|
|
1992
|
+
// a Radix part (ir/radix): reka-ui's counterpart, its props renamed and its callbacks printed as its events
|
|
1993
|
+
const radix = n.radix ? vueRadixPart(n) : null;
|
|
1994
|
+
if (radix) {
|
|
1995
|
+
tag = this.rekaLocal(radix.map.name);
|
|
1996
|
+
n.attrs = radix.attrs;
|
|
1997
|
+
// a known difference between reka-ui's part and Radix's is said wherever the part is used
|
|
1998
|
+
if (radix.map.differs)
|
|
1999
|
+
this.script.warn('radix-behaviour', `<${n.tag}> (Radix ${n.radix?.pkg} ${n.radix?.part}): ${radix.map.differs}.`, 'warning', this.script.ir.line);
|
|
2000
|
+
}
|
|
2001
|
+
// the attributes are the element's own (a DOM element's), whichever of the two renders
|
|
2002
|
+
const domTag = tag;
|
|
2003
|
+
if (n.asChild) {
|
|
2004
|
+
// Radix's Slot (ir/as-child): the element, or the one element given as children with these attributes merged on
|
|
2005
|
+
attrsList.unshift(`:is="${escapeAttr(`${this.expr(n.asChild, scope)} ? ${this.slotHelper()} : '${tag}'`)}"`);
|
|
2006
|
+
tag = 'component';
|
|
2007
|
+
}
|
|
2008
|
+
else if (component && (this.isDynamicTag(tag) || scope.rename.has(tag))) {
|
|
2009
|
+
// a tag held in a variable, or picked per row in a loop (`row.Icon`)
|
|
2010
|
+
attrsList.unshift(`:is="${escapeAttr(this.expr(t.identifier(tag), scope))}"`);
|
|
2011
|
+
tag = 'component';
|
|
2012
|
+
}
|
|
2013
|
+
else if (!component && (tag === 'style' || tag === 'script')) {
|
|
2014
|
+
// Vue templates refuse <style> and <script>: render them as dynamic elements
|
|
2015
|
+
attrsList.unshift(`is="${tag}"`);
|
|
2016
|
+
tag = 'component';
|
|
2017
|
+
}
|
|
2018
|
+
// M2: `drag` (and `layout` without `layoutId`) through v-motion-drag / v-motion-layout, motion's own engines as React
|
|
2019
|
+
// plays them, not motion-v's; an element whose Framer props are all of those is a plain element, as on Svelte and
|
|
2020
|
+
// Angular (layoutId stays with motion-v, which plays it as React does)
|
|
2021
|
+
const played = n.motion ? layoutDragParams(n, this.comp.items) : null;
|
|
2022
|
+
const ownLayout = !!played?.layout && !n.motion?.layoutId;
|
|
2023
|
+
const own = (name) => (!!played?.drag && DRAG_PROPS.has(name)) || (ownLayout && (name === 'layout' || name === 'transition'));
|
|
2024
|
+
const plain = !!played && (!!played.drag || ownLayout) && Object.keys(n.motion ?? {}).every(own);
|
|
2025
|
+
if (n.motion) {
|
|
2026
|
+
if (!plain) {
|
|
2027
|
+
this.script.imports.named('motion-v', 'motion');
|
|
2028
|
+
tag = `motion.${tag}`;
|
|
2029
|
+
}
|
|
2030
|
+
let motionProps = n.motion;
|
|
2031
|
+
const helper = importPath(this.script.outPath, this.script.ctx.helperPath?.(VUE_LAYOUT_FILE) ?? VUE_LAYOUT_FILE);
|
|
2032
|
+
if (played?.drag) {
|
|
2033
|
+
for (const w of played.warnings)
|
|
2034
|
+
if (w.of === 'drag')
|
|
2035
|
+
this.script.warn('motion-prop', w.message, 'warning', w.line);
|
|
2036
|
+
if (!plain)
|
|
2037
|
+
this.script.warn('motion-prop', `<motion.${n.tag}> drags with motion's drag() while motion-v plays its other Framer props: the two keep their own values of the element (measured with whileDrag played beside motion-v: 0.92% of React's change at release), so the drag is not played as React plays it.`, 'warning', n.motion.drag?.loc?.start.line ?? elementLine(n));
|
|
2038
|
+
motionProps = Object.fromEntries(Object.entries(motionProps).filter(([name]) => !DRAG_PROPS.has(name)));
|
|
2039
|
+
this.script.imports.named(helper, VUE_DRAG);
|
|
2040
|
+
attrsList.push(`v-motion-drag="${escapeAttr(this.expr(played.drag, scope))}"`);
|
|
2041
|
+
}
|
|
2042
|
+
if (played?.layout && plain) {
|
|
2043
|
+
for (const w of played.warnings)
|
|
2044
|
+
if (w.of === 'layout')
|
|
2045
|
+
this.script.warn('motion-prop', w.message, 'warning', w.line);
|
|
2046
|
+
motionProps = {};
|
|
2047
|
+
this.script.imports.named(helper, VUE_LAYOUT);
|
|
2048
|
+
attrsList.push(`v-motion-layout="${escapeAttr(this.expr(played.layout, scope))}"`);
|
|
2049
|
+
}
|
|
2050
|
+
if (played && (played.drag || (played.layout && plain)))
|
|
2051
|
+
useVueLayout(this.script.ctx.diagnostics, played.features.filter((f) => f !== 'layout' || plain));
|
|
2052
|
+
attrsList.push(...vueMotionAttrs(motionProps, (e) => this.expr(e, scope), (e, event) => this.handler(e, event, scope),
|
|
2053
|
+
// M2: a warning located at the prop's line when it has one
|
|
2054
|
+
(m, line) => this.script.warn('motion-prop', m, 'warning', line), elementLine(n)));
|
|
2055
|
+
}
|
|
2056
|
+
// (a Radix part's spread is renamed for reka-ui below: attributes are not folded into it)
|
|
2057
|
+
attrsList.push(...this.attrs(n.attrs, n.asChild ? domTag : tag, component, scope, !radix));
|
|
2058
|
+
// props spread onto the part arrive under Radix's names: renamed for reka-ui as they pass, and a wrapper's rest props
|
|
2059
|
+
// that React typed as this part's props are reka's props of the part (targets/vue/radix)
|
|
2060
|
+
const spreadAt = radix ? attrsList.findIndex((a) => a.startsWith('v-bind="')) : -1;
|
|
2061
|
+
if (radix && spreadAt >= 0) {
|
|
2062
|
+
const renames = vueRadixRenames(radix.map);
|
|
2063
|
+
let spread = (attrsList[spreadAt] ?? '').slice(8, -1);
|
|
2064
|
+
if (renames) {
|
|
2065
|
+
this.script.helpers.add('radixProps');
|
|
2066
|
+
spread = `radixProps(${spread}, ${escapeAttr(renames)})`;
|
|
2067
|
+
}
|
|
2068
|
+
const restType = n.attrs.some((a) => a.kind === 'spread' && t.isIdentifier(unwrap(a.expr), { name: this.comp.rest ?? '' })) ? vueRadixRestType(this.comp, n) : null;
|
|
2069
|
+
if (restType) {
|
|
2070
|
+
this.script.typeImports.push({ source: 'reka-ui', name: restType });
|
|
2071
|
+
spread = `${spread} as ${restType}`;
|
|
2072
|
+
}
|
|
2073
|
+
attrsList[spreadAt] = `v-bind="${spread}"`;
|
|
2074
|
+
}
|
|
2075
|
+
if (radix?.map.pressFocus) {
|
|
2076
|
+
this.script.helpers.add('focusOnPress');
|
|
2077
|
+
attrsList.push(PRESS_FOCUS_LISTENER);
|
|
2078
|
+
}
|
|
2079
|
+
for (const ev of radix?.events ?? [])
|
|
2080
|
+
if (ev.typeImport)
|
|
2081
|
+
this.script.typeImports.push({ source: 'reka-ui', name: ev.typeImport });
|
|
2082
|
+
for (const ev of radix?.events ?? [])
|
|
2083
|
+
attrsList.push(`@${ev.event}="${escapeAttr(this.handler(ev.handler, ev.label, scope, true))}"`);
|
|
2084
|
+
const slotProps = n.attrs.filter((a) => a.kind === 'slotProp' && !(component && this.valueSlot(a, tag, scope, attrsList)));
|
|
2085
|
+
const childNodes = [...n.children];
|
|
2086
|
+
const htmlAttr = n.attrs.find((a) => a.kind === 'html');
|
|
2087
|
+
let content = '';
|
|
2088
|
+
const inner = indent + ' ';
|
|
2089
|
+
if (slotProps.length) {
|
|
2090
|
+
const named = slotProps.map((s) => `\n${inner}${this.slotTemplate(s, tag, component, inner, scope)}`).join('');
|
|
2091
|
+
const rest = childNodes.length ? `\n${inner}<template #default>${this.children(childNodes, inner, scope)}</template>` : '';
|
|
2092
|
+
content = named + rest + `\n${indent}`;
|
|
2093
|
+
}
|
|
2094
|
+
else if (!htmlAttr)
|
|
2095
|
+
content = this.children(childNodes, indent, scope);
|
|
2096
|
+
const head = attrsList.length ? ` ${attrsList.join(' ')}` : '';
|
|
2097
|
+
const wrapped = head.length > 100 ? `\n${inner}${attrsList.join(`\n${inner}`)}\n${indent}` : head;
|
|
2098
|
+
const selfClose = !content && (VOID_TAGS.has(tag) || component || SVG_TAGS.has(n.tag) || tag === 'component');
|
|
2099
|
+
if (selfClose)
|
|
2100
|
+
return `<${tag}${wrapped}${wrapped.endsWith('\n' + indent) ? '/>' : ' />'}`;
|
|
2101
|
+
return `<${tag}${wrapped}>${content}</${tag}>`;
|
|
2102
|
+
}
|
|
2103
|
+
/**
|
|
2104
|
+
* Markup passed to a prop the receiving component reads as a value and renders where it reads it (`{header}`, with
|
|
2105
|
+
* `header !== undefined` tests in its script): a slot would never reach it, so the markup is passed as the value
|
|
2106
|
+
* itself, a functional component of this setup (`:header="cdPlayerHeader"`), which the receiver renders with
|
|
2107
|
+
* `<component :is>` (VueTemplate.derivedMarkup). Only when every read of the prop in the receiver is that render or
|
|
2108
|
+
* a test that a function answers as an element does (`!== undefined`, `!x`, `x && …`, a dependency list), and the
|
|
2109
|
+
* markup has a render-function form. Pushes the attribute and returns true; false leaves the slot path (and its error).
|
|
2110
|
+
*/
|
|
2111
|
+
valueSlot(s, tag, scope, attrsList) {
|
|
2112
|
+
if (s.render)
|
|
2113
|
+
return false;
|
|
2114
|
+
const receiver = this.script.childOf(tag);
|
|
2115
|
+
if (!receiver || rendersSlot(receiver, s.name))
|
|
2116
|
+
return false;
|
|
2117
|
+
const prop = receiver.props.find((p) => p.key === s.name);
|
|
2118
|
+
if (!prop || prop.kind === 'children')
|
|
2119
|
+
return false;
|
|
2120
|
+
// the receiver renders it where React's types say it may be an element: printed as markup there (derivedMarkup)
|
|
2121
|
+
const renders = markupRenders(receiver, prop.local);
|
|
2122
|
+
const oracle = this.script.ctx.oracle;
|
|
2123
|
+
if (!renders?.length || !oracle || !renders.every((r) => {
|
|
2124
|
+
const kind = oracle.elementKind(receiver.file, r.loc);
|
|
2125
|
+
return kind.element && !kind.unknown;
|
|
2126
|
+
}))
|
|
2127
|
+
return false;
|
|
2128
|
+
// the markup reads no name of a loop around it (those exist only in the template)
|
|
2129
|
+
const probe = s.children.length === 1 && s.children[0] ? s.children[0] : { type: 'fragment', children: s.children };
|
|
2130
|
+
let loopRead = false;
|
|
2131
|
+
walkTNodeExpressions(probe, (e) => void (this.usesLoopNames(e, scope) && (loopRead = true)));
|
|
2132
|
+
if (loopRead)
|
|
2133
|
+
return false;
|
|
2134
|
+
const fn = renderFunction(probe, (node) => cloneWithRefs(node, this.comp));
|
|
2135
|
+
if (!fn)
|
|
2136
|
+
return false;
|
|
2137
|
+
const name = this.script.alloc.alloc(`${tag.charAt(0).toLowerCase()}${tag.slice(1).replace(/\W/g, '')}${s.name.charAt(0).toUpperCase()}${s.name.slice(1)}`);
|
|
2138
|
+
const id = t.identifier(name);
|
|
2139
|
+
id.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier('FunctionalComponent')));
|
|
2140
|
+
this.script.imports.named('vue', 'h');
|
|
2141
|
+
this.script.typeImports.push({ source: 'vue', name: 'FunctionalComponent' });
|
|
2142
|
+
this.hoisted.push(t.variableDeclaration('const', [t.variableDeclarator(id, this.script.r(fn))]));
|
|
2143
|
+
const value = s.when ? `${this.expr(s.when, scope, true)} ? ${name} : undefined` : name;
|
|
2144
|
+
attrsList.push(`:${s.name}="${escapeAttr(value)}"`);
|
|
2145
|
+
return true;
|
|
2146
|
+
}
|
|
2147
|
+
/**
|
|
2148
|
+
* Markup passed to a component prop: `<template #art>`, under `v-if` when React passes it only while a test holds,
|
|
2149
|
+
* and with the render function's parameters as slot props (`#actions="{ picked }"`, named as the receiving
|
|
2150
|
+
* component's prop type names them) for a render prop.
|
|
2151
|
+
*/
|
|
2152
|
+
slotTemplate(s, tag, component, indent, scope) {
|
|
2153
|
+
const when = s.when ? ` v-if="${escapeAttr(this.expr(s.when, scope, true))}"` : '';
|
|
2154
|
+
const receiver = component ? this.script.childOf(tag) : null;
|
|
2155
|
+
if (receiver && !rendersSlot(receiver, s.name)) {
|
|
2156
|
+
this.script.warn('slot-prop', droppedSlotMessage(tag, s.name), 'error');
|
|
2157
|
+
return `<!-- antheo-morph: not converted: markup for ${s.name} -->`;
|
|
2158
|
+
}
|
|
2159
|
+
if (!s.render)
|
|
2160
|
+
return `<template${when} #${s.name}>${this.children(s.children, indent, scope)}</template>`;
|
|
2161
|
+
const child = component ? this.script.childOf(tag) : null;
|
|
2162
|
+
const signature = child ? renderPropOf(child, s.name) : null;
|
|
2163
|
+
const params = s.render.params;
|
|
2164
|
+
if (!signature || signature.params.length < params.length) {
|
|
2165
|
+
this.script.warn('render-prop', `"${s.name}" on <${tag}> passes a render function, but <${tag}>'s own type of "${s.name}" (its parameters, which name the slot props in Vue) is not visible: it is not converted.`, 'error');
|
|
2166
|
+
return `<!-- antheo-morph: not converted: the render prop ${s.name} -->`;
|
|
2167
|
+
}
|
|
2168
|
+
const fields = params.map((p, i) => {
|
|
2169
|
+
const name = signature.params[i]?.name ?? `arg${i}`;
|
|
2170
|
+
const pattern = stripTypes(t.cloneNode(p, true));
|
|
2171
|
+
return t.isIdentifier(pattern) && pattern.name === name ? name : `${name}: ${printExpr(pattern)}`;
|
|
2172
|
+
});
|
|
2173
|
+
const loopNames = new Set([...scope.loopNames, ...params.flatMap((p) => patternNames(p))]);
|
|
2174
|
+
const inner = { ...scope, loopNames };
|
|
2175
|
+
const head = fields.length ? `="${escapeAttr(`{ ${fields.join(', ')} }`)}"` : '';
|
|
2176
|
+
return `<template${when} #${slotName(s.name)}${head}>${this.children(s.children, indent, inner)}</template>`;
|
|
2177
|
+
}
|
|
2178
|
+
/**
|
|
2179
|
+
* Whether a JSX spread on an element may hold `key` (React's name: `className`, `style`): by the shape written (an
|
|
2180
|
+
* object literal, a choice between literals, null) or else by React's checker. Unknown counts as may.
|
|
2181
|
+
*/
|
|
2182
|
+
spreadMayHold(e, key) {
|
|
2183
|
+
const x = unwrap(e);
|
|
2184
|
+
// the component's rest never holds a prop destructured by name, whatever its type says (an index signature)
|
|
2185
|
+
if (t.isIdentifier(x) && x.name === this.comp.rest && this.comp.props.some((p) => p.key === key))
|
|
2186
|
+
return false;
|
|
2187
|
+
if (t.isNullLiteral(x) || t.isBooleanLiteral(x) || (t.isIdentifier(x) && x.name === 'undefined'))
|
|
2188
|
+
return false;
|
|
2189
|
+
if (t.isObjectExpression(x)) {
|
|
2190
|
+
return x.properties.some((p) => {
|
|
2191
|
+
if (t.isSpreadElement(p))
|
|
2192
|
+
return this.spreadMayHold(p.argument, key);
|
|
2193
|
+
if (p.computed)
|
|
2194
|
+
return true;
|
|
2195
|
+
return (t.isIdentifier(p.key) && p.key.name === key) || (t.isStringLiteral(p.key) && p.key.value === key);
|
|
2196
|
+
});
|
|
2197
|
+
}
|
|
2198
|
+
if (t.isConditionalExpression(x))
|
|
2199
|
+
return this.spreadMayHold(x.consequent, key) || this.spreadMayHold(x.alternate, key);
|
|
2200
|
+
if (t.isLogicalExpression(x))
|
|
2201
|
+
return (x.operator !== '&&' && this.spreadMayHold(x.left, key)) || this.spreadMayHold(x.right, key);
|
|
2202
|
+
return this.script.ctx.oracle?.mayHoldProperty(this.script.ctx.sourceFile, x.loc, key) ?? true;
|
|
2203
|
+
}
|
|
2204
|
+
/**
|
|
2205
|
+
* React gives an element the last of its `className` / `style` and a spread that holds the same key (`{...rest}`
|
|
2206
|
+
* after `className={…}`, or before it): one replaces the other. Vue merges `class` and `style` from a separate
|
|
2207
|
+
* attribute and `v-bind="object"` (both apply). Where a spread on the element may hold the key, the attribute is
|
|
2208
|
+
* written into the one spread object at its place, so the object's own JavaScript order decides as in React.
|
|
2209
|
+
* Returns the attributes with each such one folded into the (first) spread; unchanged when no spread may hold one.
|
|
2210
|
+
*/
|
|
2211
|
+
foldIntoSpread(attrs, scope) {
|
|
2212
|
+
const spreads = attrs.filter((a) => a.kind === 'spread');
|
|
2213
|
+
if (!spreads.length)
|
|
2214
|
+
return attrs;
|
|
2215
|
+
const reactKey = (a) => {
|
|
2216
|
+
if (a.kind === 'style')
|
|
2217
|
+
return 'style';
|
|
2218
|
+
if ((a.kind === 'static' || a.kind === 'expr') && (a.name === 'class' || a.name === 'style'))
|
|
2219
|
+
return a.name === 'class' ? 'className' : 'style';
|
|
2220
|
+
return null;
|
|
2221
|
+
};
|
|
2222
|
+
const folded = new Set(attrs.filter((a) => {
|
|
2223
|
+
const key = reactKey(a);
|
|
2224
|
+
return key !== null && spreads.some((s) => this.spreadMayHold(s.expr, key));
|
|
2225
|
+
}));
|
|
2226
|
+
if (!folded.size)
|
|
2227
|
+
return attrs;
|
|
2228
|
+
const props = [];
|
|
2229
|
+
for (const a of attrs) {
|
|
2230
|
+
if (a.kind === 'spread')
|
|
2231
|
+
props.push(t.spreadElement(a.expr));
|
|
2232
|
+
else if (folded.has(a)) {
|
|
2233
|
+
const key = a.kind === 'static' || a.kind === 'expr' ? a.name : 'style';
|
|
2234
|
+
const prop = t.objectProperty(t.identifier(key), t.nullLiteral());
|
|
2235
|
+
// the value as the attribute would print it (a style with React's px added)
|
|
2236
|
+
this.foldedText.set(prop, a.kind === 'static' ? JSON.stringify(a.value) : a.kind === 'style' ? this.styleValue(a.expr, scope) : a.kind === 'expr' ? this.expr(a.expr, scope) : 'null');
|
|
2237
|
+
props.push(prop);
|
|
2238
|
+
}
|
|
2239
|
+
}
|
|
2240
|
+
const merged = { kind: 'spread', expr: t.objectExpression(props) };
|
|
2241
|
+
// at the first spread's place: an attribute between it and a folded one keeps its order against the spread
|
|
2242
|
+
const first = attrs.findIndex((a) => a.kind === 'spread');
|
|
2243
|
+
return attrs.flatMap((a, i) => (i === first ? [merged] : a.kind === 'spread' || folded.has(a) ? [] : [a]));
|
|
2244
|
+
}
|
|
2245
|
+
/**
|
|
2246
|
+
* React's DOM props spread on an element (`<button {...row.props}>`, `<div {...ctl.pointerHandlers}>`), written
|
|
2247
|
+
* with React's names. Vue reads an `on…` key of a bound object by hyphenating it (`onPointerEnter` listens to an
|
|
2248
|
+
* event named "pointer-enter", which never fires), takes `onFocus` / `onBlur` as the non-bubbling events, a style
|
|
2249
|
+
* object without React's px, and `onChange` as the change event where React listens to input. A spread that may
|
|
2250
|
+
* hold such a key (by its written keys, or React's checker; unknown counts) is renamed as it arrives (domProps). The
|
|
2251
|
+
* component's own rest is not: Vue's callers pass it Vue's names.
|
|
2252
|
+
*/
|
|
2253
|
+
domSpreads(attrs, tag) {
|
|
2254
|
+
const textField = tag === 'textarea' || (tag === 'input' && !attrs.some((a) => a.kind === 'static' && a.name === 'type' && !['', 'text', 'search', 'email', 'url', 'tel', 'password', 'number'].includes(a.value)));
|
|
2255
|
+
const change = textField ? 'input' : 'change';
|
|
2256
|
+
const misread = (key) => {
|
|
2257
|
+
if (key === 'style')
|
|
2258
|
+
return true;
|
|
2259
|
+
if (!/^on[A-Z]/.test(key))
|
|
2260
|
+
return false;
|
|
2261
|
+
let name = key.slice(2);
|
|
2262
|
+
const capture = name.endsWith('Capture') && !/^(Got|Lost)PointerCapture$/.test(name);
|
|
2263
|
+
if (capture)
|
|
2264
|
+
name = name.slice(0, -7);
|
|
2265
|
+
const react = name === 'DoubleClick' ? 'dblclick' : name === 'Focus' ? 'focusin' : name === 'Blur' ? 'focusout' : name === 'Change' ? change : name.toLowerCase();
|
|
2266
|
+
const vue = name.replace(/\B([A-Z])/g, '-$1').toLowerCase();
|
|
2267
|
+
return react !== vue || vueDomEvent(react).passive;
|
|
2268
|
+
};
|
|
2269
|
+
const mayMisread = (e) => {
|
|
2270
|
+
const x = unwrap(e);
|
|
2271
|
+
if (t.isIdentifier(x) && x.name === this.comp.rest)
|
|
2272
|
+
return false;
|
|
2273
|
+
if (t.isNullLiteral(x) || t.isBooleanLiteral(x) || (t.isIdentifier(x) && x.name === 'undefined'))
|
|
2274
|
+
return false;
|
|
2275
|
+
if (t.isObjectExpression(x)) {
|
|
2276
|
+
return x.properties.some((p) => {
|
|
2277
|
+
if (t.isSpreadElement(p))
|
|
2278
|
+
return mayMisread(p.argument);
|
|
2279
|
+
if (p.computed)
|
|
2280
|
+
return true;
|
|
2281
|
+
const key = t.isIdentifier(p.key) ? p.key.name : t.isStringLiteral(p.key) ? p.key.value : null;
|
|
2282
|
+
return key === null || misread(key);
|
|
2283
|
+
});
|
|
2284
|
+
}
|
|
2285
|
+
if (t.isConditionalExpression(x))
|
|
2286
|
+
return mayMisread(x.consequent) || mayMisread(x.alternate);
|
|
2287
|
+
if (t.isLogicalExpression(x))
|
|
2288
|
+
return (x.operator !== '&&' && mayMisread(x.left)) || mayMisread(x.right);
|
|
2289
|
+
const keys = this.script.ctx.oracle?.propertiesOf(this.script.ctx.sourceFile, x.loc);
|
|
2290
|
+
return !keys || [...keys.keys()].some(misread);
|
|
2291
|
+
};
|
|
2292
|
+
const wrap = (e) => {
|
|
2293
|
+
if (!mayMisread(e))
|
|
2294
|
+
return e;
|
|
2295
|
+
this.script.helpers.add('domProps');
|
|
2296
|
+
this.script.helpers.add('toStyle');
|
|
2297
|
+
return t.callExpression(t.identifier('domProps'), change === 'input' ? [e, t.stringLiteral('input')] : [e]);
|
|
2298
|
+
};
|
|
2299
|
+
return attrs.map((a) => {
|
|
2300
|
+
if (a.kind !== 'spread')
|
|
2301
|
+
return a;
|
|
2302
|
+
const inner = unwrap(a.expr);
|
|
2303
|
+
// a merged object (foldIntoSpread): each spread in it on its own; attributes folded in keep their place
|
|
2304
|
+
if (t.isObjectExpression(inner) && inner.properties.some((p) => t.isObjectProperty(p) && this.foldedText.has(p))) {
|
|
2305
|
+
for (const p of inner.properties)
|
|
2306
|
+
if (t.isSpreadElement(p))
|
|
2307
|
+
p.argument = wrap(p.argument);
|
|
2308
|
+
return a;
|
|
2309
|
+
}
|
|
2310
|
+
return { kind: 'spread', expr: wrap(a.expr) };
|
|
2311
|
+
});
|
|
2312
|
+
}
|
|
2313
|
+
/**
|
|
2314
|
+
* A DOM event of more than one word passed to a component of this conversion that does not take it by name
|
|
2315
|
+
* (`<Row onPointerEnter={…}>`, Row spreading its rest on an element): it reaches Row's attrs and, through
|
|
2316
|
+
* `v-bind`, the element. Vue reads an attrs key by hyphenating it (`onPointerEnter` listens to "pointer-enter",
|
|
2317
|
+
* which never fires), so the caller writes the listener as Vue's own (`@pointerenter`, attrs key `onPointerenter`).
|
|
2318
|
+
* The listener as written (`pointerenter.capture`), or null to pass the prop as it is.
|
|
2319
|
+
*/
|
|
2320
|
+
passedDomListener(tag, name, capture) {
|
|
2321
|
+
if (!/^on[A-Z][a-z]+[A-Z]/.test(name) || /^on(Got|Lost)PointerCapture$/.test(name))
|
|
2322
|
+
return null;
|
|
2323
|
+
const child = this.script.childOf(tag);
|
|
2324
|
+
if (!child || !child.rest || child.props.some((p) => p.key === name))
|
|
2325
|
+
return null;
|
|
2326
|
+
const react = name.slice(2);
|
|
2327
|
+
const event = react === 'DoubleClick' ? 'dblclick' : react.toLowerCase();
|
|
2328
|
+
if (!isDomEventProp(`on${react}`))
|
|
2329
|
+
return null;
|
|
2330
|
+
const dom = vueDomEvent(event);
|
|
2331
|
+
return `${dom.event}${capture ? '.capture' : ''}${dom.passive ? '.passive' : ''}`;
|
|
2332
|
+
}
|
|
2333
|
+
/** Attributes written into a spread object by foldIntoSpread, with their printed values. */
|
|
2334
|
+
foldedText = new WeakMap();
|
|
2335
|
+
attrs(attrs, tag, component, scope, fold = true) {
|
|
2336
|
+
const out = [];
|
|
2337
|
+
if (fold)
|
|
2338
|
+
attrs = this.foldIntoSpread(attrs, scope);
|
|
2339
|
+
if (fold && !component)
|
|
2340
|
+
attrs = this.domSpreads(attrs, tag);
|
|
2341
|
+
// Vue allows one v-bind="object" per element: several JSX spreads merge into one, in order
|
|
2342
|
+
const spreads = attrs.filter((a) => a.kind === 'spread');
|
|
2343
|
+
if (spreads.length > 1) {
|
|
2344
|
+
const merged = { kind: 'spread', expr: t.objectExpression(spreads.map((s) => t.spreadElement(s.expr))) };
|
|
2345
|
+
const first = attrs.indexOf(spreads[0]);
|
|
2346
|
+
attrs = attrs.flatMap((a, i) => (a.kind === 'spread' ? (i === first ? [merged] : []) : [a]));
|
|
2347
|
+
}
|
|
2348
|
+
for (const a of attrs) {
|
|
2349
|
+
switch (a.kind) {
|
|
2350
|
+
case 'static':
|
|
2351
|
+
out.push(`${a.name}="${escapeAttr(a.value)}"`);
|
|
2352
|
+
break;
|
|
2353
|
+
case 'bool':
|
|
2354
|
+
out.push(component ? `:${a.name}="true"` : a.name);
|
|
2355
|
+
break;
|
|
2356
|
+
case 'expr':
|
|
2357
|
+
if (component && t.isIdentifier(unwrap(a.expr))) {
|
|
2358
|
+
const b = this.comp.bindings.get(unwrap(a.expr).name);
|
|
2359
|
+
if (b && (b.kind === 'ref' || (b.kind === 'hook' && b.refKind === 'dom'))) {
|
|
2360
|
+
this.script.warn('ref-prop', `A ref passed to <${tag}> as "${a.name}": Vue templates unwrap refs, so the child receives the element (or null), not the ref.`);
|
|
2361
|
+
}
|
|
2362
|
+
else if (b && reactRefType(this.script.ctx.oracle?.typeOfExpression(this.script.ctx.sourceFile, a.expr.loc) ?? null)) {
|
|
2363
|
+
// a ref object that reaches the component another way (a hook's result): React's type says it is one
|
|
2364
|
+
this.script.warn('ref-prop', `A ref passed to <${tag}> as "${a.name}": Vue templates unwrap refs, so the child receives the element (or null), not the ref, and a ref={${a.name}} there never fills it.`, 'warning', a.expr.loc?.start.line);
|
|
2365
|
+
}
|
|
2366
|
+
}
|
|
2367
|
+
out.push(this.attr(a.name, a.expr, scope));
|
|
2368
|
+
break;
|
|
2369
|
+
case 'spread': {
|
|
2370
|
+
const inner = unwrap(a.expr);
|
|
2371
|
+
const isRest = t.isIdentifier(inner) && this.comp.rest === inner.name;
|
|
2372
|
+
if (t.isIdentifier(inner) && this.comp.bindings.get(inner.name)?.kind === 'propsObject') {
|
|
2373
|
+
// React's props object holds only the keys the caller passed; Vue's holds every declared prop, undefined
|
|
2374
|
+
// when not passed, and a later v-bind sets those over the attributes written before it
|
|
2375
|
+
const held = this.script.ctx.oracle?.propertiesOf(this.script.ctx.sourceFile, a.expr.loc) ?? null;
|
|
2376
|
+
const has = (key) => this.comp.declared.has(key) || !!held?.has(key);
|
|
2377
|
+
const before = attrs.slice(0, attrs.indexOf(a)).filter((x) => 'name' in x && has(x.name === 'class' ? 'className' : x.name)).map((x) => ('name' in x ? x.name : ''));
|
|
2378
|
+
if (before.length)
|
|
2379
|
+
this.script.warn('props-spread', `{...${inner.name}} on <${tag}> comes after ${before.map((n) => `"${n}"`).join(', ')}: React's props object holds only the props the caller passed, so those stay unless the caller passed them; Vue's holds every declared prop (undefined when not passed), and v-bind sets them over the ones written before it.`, 'warning', a.expr.loc?.start.line);
|
|
2380
|
+
}
|
|
2381
|
+
let spread;
|
|
2382
|
+
if (t.isObjectExpression(inner)) {
|
|
2383
|
+
// merged spreads: the component's rest props stand for its attrs
|
|
2384
|
+
// (and attributes folded in at their place, foldIntoSpread; an object written in the source keeps its own
|
|
2385
|
+
// properties)
|
|
2386
|
+
const parts = inner.properties.map((p) => {
|
|
2387
|
+
// (a rest written as an object, `{ ...rest, ...attrs }`, gives its own parts)
|
|
2388
|
+
const restParts = /^\{ (.*) \}$/.exec(this.restSpread)?.[1];
|
|
2389
|
+
if (t.isSpreadElement(p))
|
|
2390
|
+
return t.isIdentifier(p.argument) && p.argument.name === this.comp.rest ? (restParts ?? `...(${this.restSpread})`) : `...${this.expr(p.argument, scope)}`;
|
|
2391
|
+
const text = t.isObjectProperty(p) ? this.foldedText.get(p) : undefined;
|
|
2392
|
+
if (text !== undefined && t.isObjectProperty(p) && t.isIdentifier(p.key))
|
|
2393
|
+
return `${p.key.name}: ${text}`;
|
|
2394
|
+
return `...${this.expr(t.objectExpression([p]), scope)}`;
|
|
2395
|
+
});
|
|
2396
|
+
spread = `{ ${parts.filter(Boolean).join(', ')} }`;
|
|
2397
|
+
}
|
|
2398
|
+
else
|
|
2399
|
+
spread = isRest ? this.restSpread : this.expr(a.expr, scope);
|
|
2400
|
+
// a spread may carry React's `defaultValue`, which a <select> has no DOM property for: Vue would set an
|
|
2401
|
+
// attribute that selects nothing
|
|
2402
|
+
if (!component && tag === 'select') {
|
|
2403
|
+
this.script.helpers.add('selectDefault');
|
|
2404
|
+
spread = `selectDefault(${spread})`;
|
|
2405
|
+
}
|
|
2406
|
+
out.push(`v-bind="${escapeAttr(spread)}"`);
|
|
2407
|
+
break;
|
|
2408
|
+
}
|
|
2409
|
+
case 'event': {
|
|
2410
|
+
const h = this.handler(component ? a.handler : elementEventReads(a.handler, a.name, tag, this.comp), component ? a.name.slice(2) : a.name, scope, !component);
|
|
2411
|
+
const passed = component ? this.passedDomListener(tag, a.name, a.capture) : null;
|
|
2412
|
+
if (passed)
|
|
2413
|
+
out.push(`@${passed}="${escapeAttr(h)}"`);
|
|
2414
|
+
else if (component)
|
|
2415
|
+
out.push(`:${a.name}="${escapeAttr(h)}"`);
|
|
2416
|
+
else {
|
|
2417
|
+
// React's onFocus / onBlur bubble and its wheel and touch listeners are passive (targets/vue/events)
|
|
2418
|
+
const dom = vueDomEvent(a.name);
|
|
2419
|
+
// a handler React gets as the value of an expression (`onPointerMove={onCardMove(i)}`, `cond ? a : b`): Vue
|
|
2420
|
+
// reads `@x="…"` that is neither a function nor a path to one as a statement run on each event, which would
|
|
2421
|
+
// only build the handler and drop it; bound as the listener prop (`:onPointermove`), the value is the
|
|
2422
|
+
// listener, computed while the component renders as React computes it (no listener when it is undefined)
|
|
2423
|
+
if (isHandlerValue(unwrap(a.handler)) && /^[a-z]+$/.test(dom.event)) {
|
|
2424
|
+
out.push(`:on${dom.event.charAt(0).toUpperCase()}${dom.event.slice(1)}${dom.passive ? 'Passive' : ''}${a.capture ? 'Capture' : ''}="${escapeAttr(h)}"`);
|
|
2425
|
+
break;
|
|
2426
|
+
}
|
|
2427
|
+
out.push(`@${dom.event}${a.capture ? '.capture' : ''}${dom.passive ? '.passive' : ''}="${escapeAttr(h)}"`);
|
|
2428
|
+
}
|
|
2429
|
+
break;
|
|
2430
|
+
}
|
|
2431
|
+
case 'ref': {
|
|
2432
|
+
const e = unwrap(a.expr);
|
|
2433
|
+
const b = t.isIdentifier(e) ? this.comp.bindings.get(e.name) : undefined;
|
|
2434
|
+
const picked = !component && t.isConditionalExpression(e) ? conditionalRef(e, this.comp) : null;
|
|
2435
|
+
if ((t.isArrowFunctionExpression(e) || t.isFunctionExpression(e)) && t.isIdentifier(e.params[0]) && !settlesLikeReact(e)) {
|
|
2436
|
+
this.script.warn('ref-callback', `The callback ref on <${tag}> is a new function on every render, so React calls it with null and then again with the ${component ? 'handle' : 'element'} each time this component re-renders${component ? ' (and whenever the child rebuilds its handle)' : ''}; Vue calls it again with the ${component ? 'handle' : 'element'} only when this component re-renders in Vue, and with null only on unmount, and this body does not end in the same state both ways (it is not a plain store, map set/delete or write to the element).`, 'warning', e.loc?.start.line);
|
|
2437
|
+
}
|
|
2438
|
+
if (t.isIdentifier(e) && b?.refKind === 'dom' && (b.kind === 'ref' || b.kind === 'hook') && tag.startsWith('motion.')) {
|
|
2439
|
+
// <motion.div> is a component in Vue: its template ref is the component, the element is its $el
|
|
2440
|
+
const setter = this.script.alloc.alloc(`set${e.name.charAt(0).toUpperCase()}${e.name.slice(1)}`);
|
|
2441
|
+
this.script.typeImports.push({ source: 'vue', name: 'ComponentPublicInstance' });
|
|
2442
|
+
this.hoisted.push(...parseSource(`function ${setter}(instance: Element | ComponentPublicInstance | null) {\n ${e.name}.value = (instance && '$el' in instance ? instance.$el : instance) as typeof ${e.name}.value;\n}`, 'helper.ts').program.body);
|
|
2443
|
+
out.push(`:ref="${setter}"`);
|
|
2444
|
+
}
|
|
2445
|
+
else if (!component && t.isIdentifier(e) && b?.kind === 'ref' && b.refKind !== 'dom' && b.escapes) {
|
|
2446
|
+
// a ref object the setup declares as a plain `{ current }` (it escapes: `inputRef={all}` on a component
|
|
2447
|
+
// written in place here), on an element: Vue fills a template ref only when it is a Vue ref, so the element
|
|
2448
|
+
// is stored in `.current` as React stores it, and emptied when it goes
|
|
2449
|
+
const cast = t.tsAsExpression(t.identifier('el'), t.tsUnionType([domElementType(tag), t.tsNullKeyword()]));
|
|
2450
|
+
KEPT_CASTS.add(cast);
|
|
2451
|
+
const fill = t.arrowFunctionExpression([t.identifier('el')], t.assignmentExpression('=', t.memberExpression(t.identifier(e.name), t.identifier('current')), cast));
|
|
2452
|
+
out.push(this.attr('ref', fill, scope));
|
|
2453
|
+
}
|
|
2454
|
+
else if (t.isIdentifier(e) && b && (b.kind === 'ref' || b.kind === 'hook')) {
|
|
2455
|
+
// a child that hands its ref one of its elements exposes { el, focus, blur }: anything else read through
|
|
2456
|
+
// the ref reads the handle, not the element
|
|
2457
|
+
const child = component ? this.script.childOf(tag) : null;
|
|
2458
|
+
const other = child && forwardsElement(child) ? elementReads(this.comp, e.name).filter((m) => m !== 'el' && m !== 'focus' && m !== 'blur') : [];
|
|
2459
|
+
// the child forwards its root element, always there (`forwardRef((p, ref) => <div ref={ref}>…`): the ref holds
|
|
2460
|
+
// that element as React's does, read from the handle when Vue fills the ref (and null when it goes)
|
|
2461
|
+
const root = child && other.length && b.kind === 'ref' && b.refKind === 'dom' && !b.escapes ? forwardedElement(child) : null;
|
|
2462
|
+
if (root && root.node === child?.template && !root.node.component) {
|
|
2463
|
+
const cast = t.tsAsExpression(t.identifier('instance'), t.tsUnionType([t.tsTypeLiteral([Object.assign(t.tsPropertySignature(t.identifier('el'), t.tsTypeAnnotation(t.tsUnionType([domElementType(root.node.tag), t.tsNullKeyword()]))), { optional: true })]), t.tsNullKeyword()]));
|
|
2464
|
+
KEPT_CASTS.add(cast);
|
|
2465
|
+
const read = t.logicalExpression('??', t.optionalMemberExpression(t.parenthesizedExpression(cast), t.identifier('el'), false, true), t.nullLiteral());
|
|
2466
|
+
out.push(`:ref="${escapeAttr(`(instance) => (${e.name} = ${printExpr(read)})`)}"`);
|
|
2467
|
+
break;
|
|
2468
|
+
}
|
|
2469
|
+
if (other.length)
|
|
2470
|
+
this.script.warn('forward-ref', `${e.name} is put on <${tag}>, which exposes its element as \`el\` with focus() and blur(): ${e.name}.current.${other[0]} reads that handle, not the element (read ${e.name}.value?.el.${other[0]}).`, 'warning', e.loc?.start.line);
|
|
2471
|
+
out.push(`ref="${e.name}"`);
|
|
2472
|
+
}
|
|
2473
|
+
else if (t.isIdentifier(e) && this.comp.forwardRef === e.name) {
|
|
2474
|
+
// the forwarded ref: a template ref of this component's own, exposed to the parent as `el`
|
|
2475
|
+
const passed = component ? this.script.passedHandle(tag) : null;
|
|
2476
|
+
if (passed)
|
|
2477
|
+
out.push(`ref="${passed}"`);
|
|
2478
|
+
else if (component)
|
|
2479
|
+
this.script.warn('forward-ref', `The ref is forwarded to <${tag}>, another component: ${this.script.forwardProblem(tag)}`);
|
|
2480
|
+
else
|
|
2481
|
+
out.push(`ref="${this.script.forwardTarget(tag)}"`);
|
|
2482
|
+
}
|
|
2483
|
+
else if (t.isIdentifier(e) && b?.kind === 'prop')
|
|
2484
|
+
out.push(this.attr('ref', a.expr, scope));
|
|
2485
|
+
else if ((t.isIdentifier(e, { name: 'undefined' }) && !b) || t.isNullLiteral(e)) {
|
|
2486
|
+
// `ref={undefined}` (a component written in place whose caller passes no ref prop): React attaches no ref,
|
|
2487
|
+
// and neither does Vue without the attribute
|
|
2488
|
+
}
|
|
2489
|
+
else if (!component && (t.isIdentifier(e) || t.isMemberExpression(e)) && b?.kind !== 'ref') {
|
|
2490
|
+
// a callback ref (`ref={take}`, typed for its element in React): Vue hands any element or instance, which on
|
|
2491
|
+
// this element is the element React promised
|
|
2492
|
+
const el = t.identifier('el');
|
|
2493
|
+
const cast = t.tsAsExpression(t.identifier('el'), t.tsUnionType([domElementType(tag), t.tsNullKeyword()]));
|
|
2494
|
+
KEPT_CASTS.add(cast);
|
|
2495
|
+
out.push(this.attr('ref', t.arrowFunctionExpression([el], t.callExpression(a.expr, [cast])), scope));
|
|
2496
|
+
}
|
|
2497
|
+
else if (!component && (t.isArrowFunctionExpression(e) || t.isFunctionExpression(e)) && e.params.length === 1 && t.isIdentifier(e.params[0])) {
|
|
2498
|
+
// an inline callback ref (`ref={(el) => { refs.current[i] = el; }}`): its element, as React typed it
|
|
2499
|
+
const param = e.params[0].name;
|
|
2500
|
+
if (t.isBlockStatement(e.body) && !(e.body.body.length === 1 && t.isExpressionStatement(e.body.body[0]))) {
|
|
2501
|
+
// statements that test the element (`if (el) map.set(k, el)`): the element is a const of the body, typed
|
|
2502
|
+
// once, so the tests narrow it as they did in React
|
|
2503
|
+
const words = new Set();
|
|
2504
|
+
t.traverseFast(e.body, (n) => void (t.isIdentifier(n) && words.add(n.name)));
|
|
2505
|
+
let raw = 'node';
|
|
2506
|
+
for (let i = 2; words.has(raw) || raw === param; i++)
|
|
2507
|
+
raw = `node${i}`;
|
|
2508
|
+
const cast = t.tsAsExpression(t.identifier(raw), t.tsUnionType([domElementType(tag), t.tsNullKeyword()]));
|
|
2509
|
+
KEPT_CASTS.add(cast);
|
|
2510
|
+
const own = t.variableDeclaration('const', [t.variableDeclarator(t.identifier(param), cast)]);
|
|
2511
|
+
out.push(this.attr('ref', t.arrowFunctionExpression([t.identifier(raw)], t.blockStatement([own, ...cloneWithRefs(e.body, this.comp).body])), scope));
|
|
2512
|
+
break;
|
|
2513
|
+
}
|
|
2514
|
+
const typed = () => {
|
|
2515
|
+
const cast = t.tsAsExpression(t.identifier(param), t.tsUnionType([domElementType(tag), t.tsNullKeyword()]));
|
|
2516
|
+
KEPT_CASTS.add(cast);
|
|
2517
|
+
return t.parenthesizedExpression(cast);
|
|
2518
|
+
};
|
|
2519
|
+
const body = transform(cloneWithRefs(e.body, this.comp), (n, parent) => {
|
|
2520
|
+
if (!t.isIdentifier(n, { name: param }))
|
|
2521
|
+
return null;
|
|
2522
|
+
if (parent && (t.isMemberExpression(parent) || t.isOptionalMemberExpression(parent)) && parent.property === n && !parent.computed)
|
|
2523
|
+
return null;
|
|
2524
|
+
if (parent && t.isObjectProperty(parent) && parent.key === n && !parent.computed)
|
|
2525
|
+
return null;
|
|
2526
|
+
return typed();
|
|
2527
|
+
});
|
|
2528
|
+
out.push(this.attr('ref', t.arrowFunctionExpression([t.identifier(param)], t.isBlockStatement(body) || t.isExpression(body) ? body : e.body), scope));
|
|
2529
|
+
}
|
|
2530
|
+
else if (component && (t.isArrowFunctionExpression(e) || t.isFunctionExpression(e)) && e.params.length === 1 && t.isIdentifier(e.params[0]) && this.handleRefType(tag, e.params[0])) {
|
|
2531
|
+
// an inline callback ref on a child that exposes a handle (`ref={(h) => { if (h) map.set(id, h); … }}`): Vue
|
|
2532
|
+
// hands the child's exposed members, the handle React typed the parameter as
|
|
2533
|
+
const param = e.params[0].name;
|
|
2534
|
+
const type = this.handleRefType(tag, e.params[0]) ?? t.tsUnknownKeyword();
|
|
2535
|
+
if (t.isBlockStatement(e.body)) {
|
|
2536
|
+
// statements that test the handle: it is a const of the body, typed once, so the tests narrow it
|
|
2537
|
+
const words = new Set();
|
|
2538
|
+
t.traverseFast(e.body, (n) => void (t.isIdentifier(n) && words.add(n.name)));
|
|
2539
|
+
let raw = 'instance';
|
|
2540
|
+
for (let i = 2; words.has(raw) || raw === param; i++)
|
|
2541
|
+
raw = `instance${i}`;
|
|
2542
|
+
const cast = t.tsAsExpression(t.identifier(raw), type);
|
|
2543
|
+
KEPT_CASTS.add(cast);
|
|
2544
|
+
const own = t.variableDeclaration('const', [t.variableDeclarator(t.identifier(param), cast)]);
|
|
2545
|
+
out.push(this.attr('ref', t.arrowFunctionExpression([t.identifier(raw)], t.blockStatement([own, ...cloneWithRefs(e.body, this.comp).body])), scope));
|
|
2546
|
+
break;
|
|
2547
|
+
}
|
|
2548
|
+
const typed = () => {
|
|
2549
|
+
const cast = t.tsAsExpression(t.identifier(param), t.cloneNode(type, true));
|
|
2550
|
+
KEPT_CASTS.add(cast);
|
|
2551
|
+
return t.parenthesizedExpression(cast);
|
|
2552
|
+
};
|
|
2553
|
+
const body = transform(cloneWithRefs(e.body, this.comp), (n, parent) => {
|
|
2554
|
+
if (!t.isIdentifier(n, { name: param }))
|
|
2555
|
+
return null;
|
|
2556
|
+
if (parent && (t.isMemberExpression(parent) || t.isOptionalMemberExpression(parent)) && parent.property === n && !parent.computed)
|
|
2557
|
+
return null;
|
|
2558
|
+
if (parent && t.isObjectProperty(parent) && parent.key === n && !parent.computed)
|
|
2559
|
+
return null;
|
|
2560
|
+
return typed();
|
|
2561
|
+
});
|
|
2562
|
+
out.push(this.attr('ref', t.arrowFunctionExpression([t.identifier(param)], t.isBlockStatement(body) || t.isExpression(body) ? body : e.body), scope));
|
|
2563
|
+
}
|
|
2564
|
+
else if (picked) {
|
|
2565
|
+
// a ref given only while a test holds (`ref={after ? afterEl : undefined}`): React fills it while the test
|
|
2566
|
+
// holds and empties it when it stops; a callback ref there does the same (Vue calls the one it drops with null)
|
|
2567
|
+
const cast = t.tsAsExpression(t.identifier('el'), t.tsUnionType([domElementType(tag), t.tsNullKeyword()]));
|
|
2568
|
+
KEPT_CASTS.add(cast);
|
|
2569
|
+
const fill = t.arrowFunctionExpression([t.identifier('el')], t.assignmentExpression('=', t.memberExpression(t.identifier(picked.name), t.identifier('current')), cast));
|
|
2570
|
+
const none = t.identifier('undefined');
|
|
2571
|
+
out.push(this.attr('ref', picked.whenTrue ? t.conditionalExpression(picked.test, fill, none) : t.conditionalExpression(picked.test, none, fill), scope));
|
|
2572
|
+
}
|
|
2573
|
+
else
|
|
2574
|
+
out.push(this.attr('ref', a.expr, scope));
|
|
2575
|
+
break;
|
|
2576
|
+
}
|
|
2577
|
+
case 'style':
|
|
2578
|
+
out.push(this.style(a.expr, scope));
|
|
2579
|
+
break;
|
|
2580
|
+
case 'html':
|
|
2581
|
+
this.script.warn('inner-html', innerHtmlWarning(tag, a.expr, 'v-html'), 'warning', a.expr.loc?.start.line);
|
|
2582
|
+
out.push(`v-html="${escapeAttr(this.expr(a.expr, scope))}"`);
|
|
2583
|
+
break;
|
|
2584
|
+
case 'slotProp':
|
|
2585
|
+
break;
|
|
2586
|
+
}
|
|
2587
|
+
}
|
|
2588
|
+
return out;
|
|
2589
|
+
}
|
|
2590
|
+
/**
|
|
2591
|
+
* The type React gives a callback ref's parameter on a child component whose handle Vue exposes member for member
|
|
2592
|
+
* (handleMemberNamesAcross), with inline `import()` types pointing at the output files; null otherwise.
|
|
2593
|
+
*/
|
|
2594
|
+
handleRefType(tag, param) {
|
|
2595
|
+
const child = this.script.childOf(tag);
|
|
2596
|
+
if (!child || forwardsElement(child) || !handleMemberNamesAcross(child, (parent, inner) => this.script.childOfAny(parent, inner)))
|
|
2597
|
+
return null;
|
|
2598
|
+
const type = this.script.ctx.oracle?.typeOfExpression(this.script.ctx.sourceFile, param.loc) ?? null;
|
|
2599
|
+
return type ? rewriteImportTypes(type, this.script.ctx) : null;
|
|
2600
|
+
}
|
|
2601
|
+
/** React adds px to numeric style values and Vue does not: literal numbers are converted here, others at run time. */
|
|
2602
|
+
style(e, scope) {
|
|
2603
|
+
return `:style="${escapeAttr(this.styleValue(e, scope))}"`;
|
|
2604
|
+
}
|
|
2605
|
+
/** The style value as the template prints it (unescaped): React's px added, see style(). */
|
|
2606
|
+
styleValue(e, scope) {
|
|
2607
|
+
const obj = unwrap(e);
|
|
2608
|
+
if (t.isObjectExpression(obj) && obj.properties.every((p) => t.isObjectProperty(p) && styleKey(p) !== null)) {
|
|
2609
|
+
for (const p of obj.properties) {
|
|
2610
|
+
const key = styleKey(p) ?? '';
|
|
2611
|
+
const num = numericLiteral(p.value);
|
|
2612
|
+
if (num !== null) {
|
|
2613
|
+
const v = reactStyleValue(key, num);
|
|
2614
|
+
p.value = typeof v === 'number' ? t.numericLiteral(v) : t.stringLiteral(v);
|
|
2615
|
+
}
|
|
2616
|
+
else if (!isUnitless(key) && t.isExpression(p.value) && !isStringy(unwrap(p.value)) && !(t.isIdentifier(p.value) && holdsMotionValue(this.comp, p.value.name))) {
|
|
2617
|
+
// (a motion value, `style={{ x }}` with `x = useMotionValue(0)`, is motion-v's to apply: it adds px as Framer does)
|
|
2618
|
+
this.script.helpers.add('toPx');
|
|
2619
|
+
p.value = t.callExpression(t.identifier('toPx'), [p.value]);
|
|
2620
|
+
}
|
|
2621
|
+
if (p.computed && styleKey(p) !== null) {
|
|
2622
|
+
p.key = t.stringLiteral(key);
|
|
2623
|
+
p.computed = false;
|
|
2624
|
+
}
|
|
2625
|
+
}
|
|
2626
|
+
return this.expr(obj, scope);
|
|
2627
|
+
}
|
|
2628
|
+
this.script.helpers.add('toStyle');
|
|
2629
|
+
return `toStyle(${this.expr(e, scope)})`;
|
|
2630
|
+
}
|
|
2631
|
+
}
|
|
2632
|
+
/** The props declaration: a type alias with every declared and inherited prop, and the destructuring with defaults. */
|
|
2633
|
+
/**
|
|
2634
|
+
* `defineSlots<{ actions?(props: { picked: Row[] }): unknown; default?(): unknown }>()` for a component that calls a
|
|
2635
|
+
* render prop: its slot props keep the parameter types of the prop's React type. Every slot the template renders is
|
|
2636
|
+
* listed (the declaration is the whole slots type). Null when no render prop is called.
|
|
2637
|
+
*/
|
|
2638
|
+
/**
|
|
2639
|
+
* `cond ? someRef : undefined` (or the other way round) on an element, with `someRef` a ref object of the component
|
|
2640
|
+
* (`{ current }`, not a template ref): the test, the ref and whether it is given when the test holds.
|
|
2641
|
+
*/
|
|
2642
|
+
/**
|
|
2643
|
+
* A handler written as an expression whose value is the function (`select(i)`, `open ? close : undefined`), which Vue's
|
|
2644
|
+
* `@x="…"` would run as a statement on each event instead of calling.
|
|
2645
|
+
*/
|
|
2646
|
+
function isHandlerValue(e) {
|
|
2647
|
+
return t.isCallExpression(e) || t.isOptionalCallExpression(e) || t.isConditionalExpression(e) || t.isLogicalExpression(e);
|
|
2648
|
+
}
|
|
2649
|
+
function conditionalRef(e, comp) {
|
|
2650
|
+
const empty = (x) => t.isNullLiteral(x) || t.isIdentifier(x, { name: 'undefined' });
|
|
2651
|
+
const refOf = (x) => {
|
|
2652
|
+
const b = t.isIdentifier(x) ? comp.bindings.get(x.name) : undefined;
|
|
2653
|
+
return t.isIdentifier(x) && b?.kind === 'ref' && b.refKind !== 'dom' ? x.name : null;
|
|
2654
|
+
};
|
|
2655
|
+
const [yes, no] = [unwrap(e.consequent), unwrap(e.alternate)];
|
|
2656
|
+
const whenTrue = refOf(yes);
|
|
2657
|
+
if (whenTrue && empty(no))
|
|
2658
|
+
return { test: e.test, name: whenTrue, whenTrue: true };
|
|
2659
|
+
const whenFalse = refOf(no);
|
|
2660
|
+
if (whenFalse && empty(yes))
|
|
2661
|
+
return { test: e.test, name: whenFalse, whenTrue: false };
|
|
2662
|
+
return null;
|
|
2663
|
+
}
|
|
2664
|
+
function slotsDeclaration(comp, script) {
|
|
2665
|
+
const used = new Map();
|
|
2666
|
+
const walk = (n) => {
|
|
2667
|
+
if (n.type === 'slot' && !used.has(n.name))
|
|
2668
|
+
used.set(n.name, n);
|
|
2669
|
+
const kids = n.type === 'if' ? n.branches.flatMap((b) => b.children) : n.type === 'slot' ? [...n.fallback] : 'children' in n ? [...n.children] : [];
|
|
2670
|
+
if (n.type === 'element')
|
|
2671
|
+
for (const a of n.attrs)
|
|
2672
|
+
if (a.kind === 'slotProp')
|
|
2673
|
+
kids.push(...a.children);
|
|
2674
|
+
kids.forEach(walk);
|
|
2675
|
+
};
|
|
2676
|
+
walk(comp.template);
|
|
2677
|
+
for (const f of comp.fragments)
|
|
2678
|
+
walk(f.template);
|
|
2679
|
+
if (![...used.values()].some((n) => n.args))
|
|
2680
|
+
return null;
|
|
2681
|
+
const members = [...used.values()].map((n) => {
|
|
2682
|
+
const prop = comp.props.find((p) => p.local === n.prop);
|
|
2683
|
+
const params = n.args && prop ? (renderPropOf(comp, prop.key)?.params ?? []) : [];
|
|
2684
|
+
const fields = params.map((p) => {
|
|
2685
|
+
const sig = t.tsPropertySignature(t.identifier(p.name), t.tsTypeAnnotation(script.type(p.type) ?? t.tsUnknownKeyword()));
|
|
2686
|
+
sig.optional = p.optional;
|
|
2687
|
+
return sig;
|
|
2688
|
+
});
|
|
2689
|
+
const props = t.identifier('props');
|
|
2690
|
+
props.typeAnnotation = t.tsTypeAnnotation(t.tsTypeLiteral(fields));
|
|
2691
|
+
const method = t.tsMethodSignature(/^[A-Za-z_$][\w$]*$/.test(n.name) ? t.identifier(n.name) : t.stringLiteral(n.name), null, fields.length ? [props] : [], t.tsTypeAnnotation(t.tsUnknownKeyword()));
|
|
2692
|
+
method.optional = true;
|
|
2693
|
+
return method;
|
|
2694
|
+
});
|
|
2695
|
+
const call = t.callExpression(t.identifier('defineSlots'), []);
|
|
2696
|
+
call.typeParameters = t.tsTypeParameterInstantiation([t.tsTypeLiteral(members)]);
|
|
2697
|
+
return t.expressionStatement(call);
|
|
2698
|
+
}
|
|
2699
|
+
/** Whether the props rest is read only as `{...rest}` on the markup (not in script code, not by member). */
|
|
2700
|
+
function restOnlySpread(comp, rest) {
|
|
2701
|
+
if (itemsRead(comp, rest))
|
|
2702
|
+
return false;
|
|
2703
|
+
let other = false;
|
|
2704
|
+
const spreads = new Set();
|
|
2705
|
+
const visit = (value) => {
|
|
2706
|
+
if (other || !value || typeof value !== 'object')
|
|
2707
|
+
return;
|
|
2708
|
+
if (Array.isArray(value))
|
|
2709
|
+
return value.forEach(visit);
|
|
2710
|
+
if (t.isNode(value)) {
|
|
2711
|
+
t.traverseFast(value, (n) => {
|
|
2712
|
+
if (t.isIdentifier(n) && comp.refs.get(n) === rest && !spreads.has(n))
|
|
2713
|
+
other = true;
|
|
2714
|
+
});
|
|
2715
|
+
return;
|
|
2716
|
+
}
|
|
2717
|
+
if (Reflect.get(value, 'kind') === 'spread') {
|
|
2718
|
+
const expr = Reflect.get(value, 'expr');
|
|
2719
|
+
if (t.isNode(expr) && t.isIdentifier(expr) && comp.refs.get(expr) === rest)
|
|
2720
|
+
spreads.add(expr);
|
|
2721
|
+
}
|
|
2722
|
+
Object.values(value).forEach(visit);
|
|
2723
|
+
};
|
|
2724
|
+
visit(comp.template);
|
|
2725
|
+
visit(comp.fragments);
|
|
2726
|
+
return !other;
|
|
2727
|
+
}
|
|
2728
|
+
function propsDeclaration(comp, script) {
|
|
2729
|
+
const members = [];
|
|
2730
|
+
// a prop whose markup the component renders as a named slot (the prop its fallback): a caller converted to Vue hands
|
|
2731
|
+
// the markup as the slot, so the prop itself may be missing (its type holds undefined already)
|
|
2732
|
+
const slotProps = new Set();
|
|
2733
|
+
const findSlots = (n) => {
|
|
2734
|
+
if (n.type === 'slot')
|
|
2735
|
+
slotProps.add(n.prop);
|
|
2736
|
+
const kids = n.type === 'if' ? n.branches.flatMap((b) => b.children) : n.type === 'slot' ? n.fallback : 'children' in n ? n.children : [];
|
|
2737
|
+
kids.forEach(findSlots);
|
|
2738
|
+
if (n.type === 'element')
|
|
2739
|
+
for (const a of n.attrs)
|
|
2740
|
+
if (a.kind === 'slotProp')
|
|
2741
|
+
a.children.forEach(findSlots);
|
|
2742
|
+
};
|
|
2743
|
+
findSlots(comp.template);
|
|
2744
|
+
const add = (key, type, optional, doc) => {
|
|
2745
|
+
const sig = t.tsPropertySignature(/^[A-Za-z_$][\w$]*$/.test(key) ? t.identifier(key) : t.stringLiteral(key), t.tsTypeAnnotation(type ?? t.tsUnknownKeyword()));
|
|
2746
|
+
sig.optional = optional || (slotProps.has(key) && !!type && t.isTSUnionType(type) && type.types.some((x) => t.isTSUndefinedKeyword(x)));
|
|
2747
|
+
if (doc)
|
|
2748
|
+
t.addComment(sig, 'leading', doc.slice(2, -2), false);
|
|
2749
|
+
members.push(sig);
|
|
2750
|
+
};
|
|
2751
|
+
const seen = new Set();
|
|
2752
|
+
const destructured = new Map(comp.props.map((p) => [p.key, p]));
|
|
2753
|
+
for (const [key, m] of comp.declared) {
|
|
2754
|
+
if (key === 'children' || key === 'ref' || key === 'key')
|
|
2755
|
+
continue;
|
|
2756
|
+
seen.add(key);
|
|
2757
|
+
// a render prop is a scoped slot, not a prop
|
|
2758
|
+
if (renderSignature(m.type))
|
|
2759
|
+
continue;
|
|
2760
|
+
const kind = destructured.get(key)?.kind;
|
|
2761
|
+
const outKey = key === 'className' ? 'class' : key;
|
|
2762
|
+
const type = kind === 'node' && !m.type ? t.tsUnionType([t.tsStringKeyword(), t.tsNumberKeyword()]) : script.type(m.type);
|
|
2763
|
+
add(outKey, type, m.optional, null);
|
|
2764
|
+
}
|
|
2765
|
+
// props types from other files (an imported interface, Omit<...>): flattened, so Vue resolves them without help
|
|
2766
|
+
for (const h of comp.propsHeritage) {
|
|
2767
|
+
// a type from a package (`VariantProps<typeof variants>`): its members as React's checker lists them
|
|
2768
|
+
const checked = script.ctx.types.members(h, script.ctx.sourceFile) ? null : (script.ctx.oracle?.membersOfType(script.ctx.sourceFile, h.loc) ?? null);
|
|
2769
|
+
const resolved = checked ? new Map([...checked].map(([key, m]) => [key, { type: m.type, optional: m.optional, file: script.ctx.sourceFile }])) : script.ctx.types.members(h, script.ctx.sourceFile);
|
|
2770
|
+
if (!resolved) {
|
|
2771
|
+
// Vue cannot resolve it either: leave it out of the props type, declare what the component reads, warn
|
|
2772
|
+
script.warn('props-type-unresolved', 'Part of the props type cannot be resolved for Vue; the props the component reads are declared as unknown and the rest pass through as attributes.');
|
|
2773
|
+
continue;
|
|
2774
|
+
}
|
|
2775
|
+
for (const [key, m] of resolved) {
|
|
2776
|
+
if (seen.has(key) || key === 'children' || key === 'ref' || key === 'key')
|
|
2777
|
+
continue;
|
|
2778
|
+
seen.add(key);
|
|
2779
|
+
const kind = destructured.get(key)?.kind;
|
|
2780
|
+
let type = kind === 'node' && !m.type ? t.tsUnionType([t.tsStringKeyword(), t.tsNumberKeyword()]) : script.type(m.type);
|
|
2781
|
+
// React's types the declaring file imports from react (`header?: ReactNode` in types.ts) are mapped as that file
|
|
2782
|
+
// maps them, never imported from it (its module does not export React's names)
|
|
2783
|
+
const declaring = m.file !== script.ctx.sourceFile ? (script.ctx.moduleOf?.(m.file) ?? null) : null;
|
|
2784
|
+
if (type && declaring)
|
|
2785
|
+
type = mapReactTypes(type, 'vue', moduleFacts(declaring).reactNames, script.typeImports);
|
|
2786
|
+
if (type && m.file !== script.ctx.sourceFile)
|
|
2787
|
+
script.foreignTypes.push({ type, file: m.file });
|
|
2788
|
+
add(key === 'className' ? 'class' : key, type, m.optional, null);
|
|
2789
|
+
}
|
|
2790
|
+
}
|
|
2791
|
+
for (const p of comp.props) {
|
|
2792
|
+
if (seen.has(p.key) || p.key === 'children' || p.key === 'ref' || p.key === 'key')
|
|
2793
|
+
continue;
|
|
2794
|
+
const outKey = p.key === 'className' ? 'class' : p.key;
|
|
2795
|
+
// a React component's style is an object (its code spreads and reads it), never a string
|
|
2796
|
+
if (p.key === 'style') {
|
|
2797
|
+
script.typeImports.push({ source: 'vue', name: 'CSSProperties' });
|
|
2798
|
+
add('style', t.tsTypeReference(t.identifier('CSSProperties')), true, null);
|
|
2799
|
+
continue;
|
|
2800
|
+
}
|
|
2801
|
+
// an inherited HTML attribute: the type React's own attributes give it (`type` on a button is 'button' | 'submit' | …)
|
|
2802
|
+
const inferred = p.key === 'className' ? null : (script.ctx.oracle?.typeOf(script.ctx.sourceFile, comp.name, p.local) ?? null);
|
|
2803
|
+
add(outKey, (inferred && script.type(inferred)) ?? inheritedAttrType(p.key, p.defaultValue), true, null);
|
|
2804
|
+
}
|
|
2805
|
+
const statements = [];
|
|
2806
|
+
const literal = t.tsTypeLiteral(members);
|
|
2807
|
+
const propsType = literal;
|
|
2808
|
+
// the module's own code may declare a `Props` of its own (both script blocks share one scope): a free name then
|
|
2809
|
+
const propsName = script.alloc.alloc('Props');
|
|
2810
|
+
statements.push(t.tsTypeAliasDeclaration(t.identifier(propsName), null, propsType));
|
|
2811
|
+
const defineProps = t.callExpression(t.identifier('defineProps'), []);
|
|
2812
|
+
defineProps.typeParameters = t.tsTypeParameterInstantiation([t.tsTypeReference(t.identifier(propsName))]);
|
|
2813
|
+
// Vue turns an absent optional boolean prop into false, React leaves it undefined (`showTime ?? true` reads true):
|
|
2814
|
+
// a boolean without a default of its own gets `undefined` as its default, which Vue then keeps
|
|
2815
|
+
const booleans = new Set();
|
|
2816
|
+
for (const m of members) {
|
|
2817
|
+
const key = t.isIdentifier(m.key) ? m.key.name : t.isStringLiteral(m.key) ? m.key.value : null;
|
|
2818
|
+
const type = m.typeAnnotation?.typeAnnotation;
|
|
2819
|
+
const parts = type && t.isTSUnionType(type) ? type.types : type ? [type] : [];
|
|
2820
|
+
if (key && m.optional && parts.some((x) => t.isTSBooleanKeyword(x) || (t.isTSLiteralType(x) && t.isBooleanLiteral(x.literal))))
|
|
2821
|
+
booleans.add(key);
|
|
2822
|
+
}
|
|
2823
|
+
let restSpread = 'attrs';
|
|
2824
|
+
let restDeclaration = null;
|
|
2825
|
+
if (comp.propsStyle === 'object' && comp.propsObject) {
|
|
2826
|
+
const keep = [...booleans].map((key) => t.objectProperty(/^[A-Za-z_$][\w$]*$/.test(key) ? t.identifier(key) : t.stringLiteral(key), t.identifier('undefined')));
|
|
2827
|
+
const declared = keep.length ? t.callExpression(t.identifier('withDefaults'), [defineProps, t.objectExpression(keep)]) : defineProps;
|
|
2828
|
+
statements.push(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(comp.propsObject), declared)]));
|
|
2829
|
+
}
|
|
2830
|
+
else if (comp.propsStyle === 'destructured') {
|
|
2831
|
+
const props = [];
|
|
2832
|
+
for (const p of comp.props) {
|
|
2833
|
+
if (p.key === 'children' || p.key === 'ref' || p.key === 'key' || renderSignature(p.type ?? comp.declared.get(p.key)?.type))
|
|
2834
|
+
continue;
|
|
2835
|
+
const key = p.key === 'className' ? 'class' : p.key;
|
|
2836
|
+
const keyNode = /^[A-Za-z_$][\w$]*$/.test(key) ? t.identifier(key) : t.stringLiteral(key);
|
|
2837
|
+
const fallback = p.defaultValue ? t.cloneNode(p.defaultValue, true) : booleans.has(key) ? t.identifier('undefined') : null;
|
|
2838
|
+
const value = fallback ? t.assignmentPattern(t.identifier(p.local), fallback) : t.identifier(p.local);
|
|
2839
|
+
props.push(t.objectProperty(keyNode, value, false, t.isIdentifier(keyNode) && keyNode.name === p.local && !fallback));
|
|
2840
|
+
}
|
|
2841
|
+
// the rest is declared whenever the component has one: its own leftover props, and those of an imported props
|
|
2842
|
+
// type (flattened into Props above), are what its code reads through it
|
|
2843
|
+
// React's rest holds only the props a caller passed. Vue's lists every declared prop, the absent ones as undefined
|
|
2844
|
+
// (booleans as false), so `{ ...DEFAULTS, ...rest }` would lose its defaults: the declared rest is filtered into the
|
|
2845
|
+
// one the component reads. Booleans left in it are taken out with an `undefined` default first, so they stay absent.
|
|
2846
|
+
const restBooleans = [];
|
|
2847
|
+
let declaredRest = null;
|
|
2848
|
+
const named = new Set(comp.props.filter((p) => p.key !== 'children' && p.key !== 'ref' && p.key !== 'key').map((p) => (p.key === 'className' ? 'class' : p.key)));
|
|
2849
|
+
// every declared prop is destructured by name and the rest is only spread on markup: it holds attributes alone
|
|
2850
|
+
const memberKeys = members.map((m) => (t.isIdentifier(m.key) ? m.key.name : t.isStringLiteral(m.key) ? m.key.value : ''));
|
|
2851
|
+
const attrsOnly = !!comp.rest && memberKeys.every((k) => named.has(k)) && restOnlySpread(comp, comp.rest);
|
|
2852
|
+
if (comp.rest && !attrsOnly) {
|
|
2853
|
+
for (const key of booleans) {
|
|
2854
|
+
if (named.has(key) || !/^[A-Za-z_$][\w$]*$/.test(key))
|
|
2855
|
+
continue;
|
|
2856
|
+
const local = script.alloc.alloc(key);
|
|
2857
|
+
restBooleans.push([key, local]);
|
|
2858
|
+
props.push(t.objectProperty(t.identifier(key), t.assignmentPattern(t.identifier(local), t.identifier('undefined')), false, local === key));
|
|
2859
|
+
}
|
|
2860
|
+
declaredRest = script.alloc.alloc(`${comp.rest}Declared`);
|
|
2861
|
+
props.push(t.restElement(t.identifier(declaredRest)));
|
|
2862
|
+
// the rest keeps the name the component gave it (`...props`): its code reads it by that name
|
|
2863
|
+
restSpread = `{ ...${comp.rest}, ...attrs }`;
|
|
2864
|
+
const all = restBooleans.length
|
|
2865
|
+
? t.objectExpression([t.spreadElement(t.identifier(declaredRest)), ...restBooleans.map(([key, local]) => t.objectProperty(t.identifier(key), t.identifier(local), false, key === local))])
|
|
2866
|
+
: t.identifier(declaredRest);
|
|
2867
|
+
const entries = t.callExpression(t.memberExpression(t.identifier('Object'), t.identifier('entries')), [all]);
|
|
2868
|
+
const kept = t.callExpression(t.memberExpression(entries, t.identifier('filter')), [
|
|
2869
|
+
t.arrowFunctionExpression([t.arrayPattern([null, t.identifier('value')])], t.binaryExpression('!==', t.identifier('value'), t.identifier('undefined'))),
|
|
2870
|
+
]);
|
|
2871
|
+
const omitted = [...named];
|
|
2872
|
+
const restType = omitted.length
|
|
2873
|
+
? t.tsTypeReference(t.identifier('Omit'), t.tsTypeParameterInstantiation([t.tsTypeReference(t.identifier(propsName)), t.tsUnionType(omitted.map((k) => t.tsLiteralType(t.stringLiteral(k))))]))
|
|
2874
|
+
: t.tsTypeReference(t.identifier(propsName));
|
|
2875
|
+
const filtered = t.tsAsExpression(t.callExpression(t.memberExpression(t.identifier('Object'), t.identifier('fromEntries')), [kept]), restType);
|
|
2876
|
+
restDeclaration = t.variableDeclaration('const', [t.variableDeclarator(t.identifier(comp.rest), t.callExpression(t.identifier(script.api('computed')), [t.arrowFunctionExpression([], filtered)]))]);
|
|
2877
|
+
t.addComment(restDeclaration, 'leading', ' the props that were passed, as the React rest holds them', true);
|
|
2878
|
+
}
|
|
2879
|
+
if (props.length)
|
|
2880
|
+
statements.push(t.variableDeclaration('const', [t.variableDeclarator(t.objectPattern(props), defineProps)]));
|
|
2881
|
+
else
|
|
2882
|
+
statements.push(t.expressionStatement(defineProps));
|
|
2883
|
+
if (restDeclaration)
|
|
2884
|
+
statements.push(restDeclaration);
|
|
2885
|
+
}
|
|
2886
|
+
if (comp.rest) {
|
|
2887
|
+
statements.unshift(t.expressionStatement(t.callExpression(t.identifier('defineOptions'), [t.objectExpression([t.objectProperty(t.identifier('inheritAttrs'), t.booleanLiteral(false))])])));
|
|
2888
|
+
// what a parent set beyond the declared props: any attribute, whatever its value (the declared ones, `class`
|
|
2889
|
+
// among them, keep their own types)
|
|
2890
|
+
const attrs = t.identifier('attrs');
|
|
2891
|
+
attrs.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier('Record'), t.tsTypeParameterInstantiation([t.tsStringKeyword(), t.tsUnknownKeyword()])));
|
|
2892
|
+
statements.push(t.variableDeclaration('const', [t.variableDeclarator(attrs, t.callExpression(t.identifier(script.api('useAttrs')), []))]));
|
|
2893
|
+
script.alloc.reserve('attrs');
|
|
2894
|
+
}
|
|
2895
|
+
// a ref forwarded to nothing (handed to useImperativeHandle, or unused) needs nothing; one forwarded to an element is
|
|
2896
|
+
// exposed as `el` (see shared/handles)
|
|
2897
|
+
if (comp.forwardRef && forwardedElement(comp)?.node.component === false)
|
|
2898
|
+
script.warn('forward-ref', "A parent's template ref on this component reaches { el, focus, blur }: the forwarded element is `el`.", 'info');
|
|
2899
|
+
for (const w of propWrites(comp)) {
|
|
2900
|
+
script.warn('prop-write', `${comp.name} assigns to its prop "${w.name}", which React recomputes on every render; Vue props are read-only (a destructured prop cannot be assigned): not converted. Compute a new name from the prop instead (\`const shown = typeof ${w.name} === 'string' ? … : ${w.name}\`).`, 'error', w.line);
|
|
2901
|
+
}
|
|
2902
|
+
for (const p of comp.props) {
|
|
2903
|
+
if (p.kind !== 'children')
|
|
2904
|
+
continue;
|
|
2905
|
+
// a test of whether children were given reads the default slot (VueScript.slotReads); any other read sees nothing
|
|
2906
|
+
if (childrenReadAsValue(comp, p.local))
|
|
2907
|
+
script.warn('children-in-script', `"${p.local}" is read in script code; in Vue the children are a slot, so that code sees nothing.`);
|
|
2908
|
+
}
|
|
2909
|
+
// a markup prop the template renders as a slot (kind 'node': markup arrives as the slot, text as the prop), read in
|
|
2910
|
+
// script code (`header !== undefined ? 28 : 0`): given markup, that code sees undefined where React saw the element
|
|
2911
|
+
for (const p of comp.props) {
|
|
2912
|
+
// only where the template renders the slot: a prop never rendered as one gets markup as a value (or a caller error)
|
|
2913
|
+
if (p.kind !== 'node' || p.key === 'children' || !rendersSlot(comp, p.key))
|
|
2914
|
+
continue;
|
|
2915
|
+
const read = scriptReadOf(comp, p.local);
|
|
2916
|
+
if (read)
|
|
2917
|
+
script.warn('slot-in-script', `"${p.key}" is read in script code; in Vue markup passed for it arrives as a slot, which that code does not see (it sees undefined where React sees the element; text passed for it reads the same).`, 'warning', read.loc?.start.line);
|
|
2918
|
+
}
|
|
2919
|
+
return { statements, restSpread };
|
|
2920
|
+
}
|
|
2921
|
+
const NL = String.fromCharCode(10);
|
|
2922
|
+
/** Whether code awaits in its own body (an `await` inside a function it declares is that function's). */
|
|
2923
|
+
function awaitsInPlace(node) {
|
|
2924
|
+
let found = false;
|
|
2925
|
+
const visit = (n) => {
|
|
2926
|
+
if (found || t.isFunction(n) || t.isClass(n))
|
|
2927
|
+
return;
|
|
2928
|
+
if (t.isAwaitExpression(n) || (t.isForOfStatement(n) && n.await)) {
|
|
2929
|
+
found = true;
|
|
2930
|
+
return;
|
|
2931
|
+
}
|
|
2932
|
+
for (const key of t.VISITOR_KEYS[n.type] ?? []) {
|
|
2933
|
+
const child = Reflect.get(n, key);
|
|
2934
|
+
for (const c of Array.isArray(child) ? child : [child])
|
|
2935
|
+
if (t.isNode(c))
|
|
2936
|
+
visit(c);
|
|
2937
|
+
}
|
|
2938
|
+
};
|
|
2939
|
+
visit(node);
|
|
2940
|
+
return found;
|
|
2941
|
+
}
|
|
2942
|
+
/** React's element tools the render-function writer has a Vue form for (render-fn/h). */
|
|
2943
|
+
const ELEMENT_TOOLS = new Set(['Children', 'cloneElement', 'isValidElement']);
|
|
2944
|
+
const MUTATORS = new Set(['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'fill', 'copyWithin', 'set', 'add', 'delete', 'clear']);
|
|
2945
|
+
/**
|
|
2946
|
+
* Whether code writes to anything it does not declare itself: an assignment or update of an outer name or a member of
|
|
2947
|
+
* one (`ref.current = …`, `refs.current[i] = el`), or a mutating method called on one (`seen.add(x)`, `list.push(x)`).
|
|
2948
|
+
*/
|
|
2949
|
+
function writesOutside(block, ir) {
|
|
2950
|
+
const declared = new Set();
|
|
2951
|
+
t.traverseFast(block, (n) => {
|
|
2952
|
+
const ids = t.isVariableDeclarator(n) ? [n.id] : t.isFunction(n) ? [...n.params, ...(t.isFunctionDeclaration(n) && n.id ? [n.id] : [])] : t.isCatchClause(n) && n.param ? [n.param] : [];
|
|
2953
|
+
for (const id of ids)
|
|
2954
|
+
for (const b of Object.keys(t.getBindingIdentifiers(id)))
|
|
2955
|
+
declared.add(b);
|
|
2956
|
+
});
|
|
2957
|
+
const root = (e) => {
|
|
2958
|
+
let at = e;
|
|
2959
|
+
while (t.isMemberExpression(at) || t.isOptionalMemberExpression(at) || t.isTSNonNullExpression(at))
|
|
2960
|
+
at = t.isTSNonNullExpression(at) ? at.expression : at.object;
|
|
2961
|
+
return t.isIdentifier(at) ? at.name : null;
|
|
2962
|
+
};
|
|
2963
|
+
// a ref callback or an event handler runs after the render, when the element mounts or the event fires (as React
|
|
2964
|
+
// runs them): what it writes is no write of the render
|
|
2965
|
+
const later = new Set();
|
|
2966
|
+
t.traverseFast(block, (n) => {
|
|
2967
|
+
if (t.isJSXAttribute(n) && t.isJSXIdentifier(n.name) && (n.name.name === 'ref' || /^on[A-Z]/.test(n.name.name)) && t.isJSXExpressionContainer(n.value))
|
|
2968
|
+
later.add(n.value.expression);
|
|
2969
|
+
});
|
|
2970
|
+
let found = false;
|
|
2971
|
+
const check = (n) => {
|
|
2972
|
+
// a setter or dispatch called while rendering
|
|
2973
|
+
const callee = t.isCallExpression(n) && t.isIdentifier(n.callee) ? ir.bindings.get(ir.refs.get(n.callee) ?? '')?.kind : undefined;
|
|
2974
|
+
if (callee === 'setter' || callee === 'dispatch')
|
|
2975
|
+
found = true;
|
|
2976
|
+
const target = t.isAssignmentExpression(n) ? n.left : t.isUpdateExpression(n) ? n.argument : null;
|
|
2977
|
+
if (target) {
|
|
2978
|
+
const names = t.isIdentifier(target) || t.isMemberExpression(target) || t.isOptionalMemberExpression(target) ? [root(target)] : Object.keys(t.getBindingIdentifiers(target));
|
|
2979
|
+
if (names.some((name) => !name || !declared.has(name)))
|
|
2980
|
+
found = true;
|
|
2981
|
+
}
|
|
2982
|
+
if ((t.isCallExpression(n) || t.isOptionalCallExpression(n)) && (t.isMemberExpression(n.callee) || t.isOptionalMemberExpression(n.callee)) && t.isIdentifier(n.callee.property) && !n.callee.computed && MUTATORS.has(n.callee.property.name)) {
|
|
2983
|
+
const name = root(n.callee.object);
|
|
2984
|
+
if (!name || !declared.has(name))
|
|
2985
|
+
found = true;
|
|
2986
|
+
}
|
|
2987
|
+
};
|
|
2988
|
+
const visit = (n) => {
|
|
2989
|
+
if (later.has(n))
|
|
2990
|
+
return;
|
|
2991
|
+
check(n);
|
|
2992
|
+
for (const key of t.VISITOR_KEYS[n.type] ?? []) {
|
|
2993
|
+
const child = Reflect.get(n, key);
|
|
2994
|
+
for (const c of Array.isArray(child) ? child : [child])
|
|
2995
|
+
if (t.isNode(c))
|
|
2996
|
+
visit(c);
|
|
2997
|
+
}
|
|
2998
|
+
};
|
|
2999
|
+
visit(block);
|
|
3000
|
+
return found;
|
|
3001
|
+
}
|
|
3002
|
+
/** Whether code assigns to a prop of the component (reported as prop-write: a Vue prop is read-only). */
|
|
3003
|
+
function assignsProp(node, ir) {
|
|
3004
|
+
let found = false;
|
|
3005
|
+
t.traverseFast(node, (n) => {
|
|
3006
|
+
const target = t.isAssignmentExpression(n) ? n.left : t.isUpdateExpression(n) ? n.argument : null;
|
|
3007
|
+
const name = target && t.isIdentifier(target) ? ir.refs.get(target) : undefined;
|
|
3008
|
+
if (name && ir.bindings.get(name)?.kind === 'prop')
|
|
3009
|
+
found = true;
|
|
3010
|
+
});
|
|
3011
|
+
return found;
|
|
3012
|
+
}
|
|
3013
|
+
/** Type names that need no import. */
|
|
3014
|
+
/** Types the props of another file name that are Vue's own (React's style types, mapped): imported from 'vue'. */
|
|
3015
|
+
const VUE_TYPES = new Set(['CSSProperties', 'StyleValue']);
|
|
3016
|
+
const GLOBAL_TYPES = new Set(['Record', 'Partial', 'Required', 'Readonly', 'Pick', 'Omit', 'Array', 'ReadonlyArray', 'Promise', 'Map', 'Set', 'HTMLElement', 'MouseEvent', 'KeyboardEvent', 'PointerEvent', 'FocusEvent', 'Event', 'WheelEvent', 'TouchEvent', 'DragEvent', 'CSSProperties', 'StyleValue', 'Element', 'SVGElement', 'HTMLDivElement', 'HTMLButtonElement', 'HTMLInputElement', 'HTMLCanvasElement', 'HTMLImageElement', 'HTMLSpanElement', 'Date', 'RegExp', 'Function', 'ReturnType', 'Parameters', 'NonNullable', 'Exclude', 'Extract']);
|
|
3017
|
+
/**
|
|
3018
|
+
* A handler written in place on an element with an untyped event parameter (`onChange={(e) => set(e.target.checked)}`):
|
|
3019
|
+
* React typed the event by that element, so `e.currentTarget` (and, for onChange, React's ChangeEvent, `e.target`) is
|
|
3020
|
+
* the element. Vue types the parameter as the plain DOM event; those reads state the element React's type named.
|
|
3021
|
+
*/
|
|
3022
|
+
function elementEventReads(handler, event, tag, ir) {
|
|
3023
|
+
const fn = unwrap(handler);
|
|
3024
|
+
if (!(t.isArrowFunctionExpression(fn) || t.isFunctionExpression(fn)))
|
|
3025
|
+
return handler;
|
|
3026
|
+
const [param] = fn.params;
|
|
3027
|
+
if (!t.isIdentifier(param) || tag.startsWith('motion.') || !/^[a-z][a-z0-9]*$/.test(tag))
|
|
3028
|
+
return handler;
|
|
3029
|
+
const name = param.name;
|
|
3030
|
+
const members = new Set(event === 'change' || event === 'input' || event === 'onChange' ? ['currentTarget', 'target'] : ['currentTarget']);
|
|
3031
|
+
let shadowed = false;
|
|
3032
|
+
t.traverseFast(fn.body, (n) => {
|
|
3033
|
+
if ((t.isFunction(n) && n.params.some((p) => t.isIdentifier(p, { name }))) || (t.isVariableDeclarator(n) && t.isIdentifier(n.id, { name })))
|
|
3034
|
+
shadowed = true;
|
|
3035
|
+
});
|
|
3036
|
+
if (shadowed)
|
|
3037
|
+
return handler;
|
|
3038
|
+
let changed = false;
|
|
3039
|
+
const body = transform(cloneWithRefs(fn.body, ir), (n, parent) => {
|
|
3040
|
+
if (parent && t.isTSAsExpression(parent))
|
|
3041
|
+
return null;
|
|
3042
|
+
if (!(t.isMemberExpression(n) || t.isOptionalMemberExpression(n)) || n.computed || !t.isIdentifier(n.object, { name }) || !t.isIdentifier(n.property) || !members.has(n.property.name))
|
|
3043
|
+
return null;
|
|
3044
|
+
changed = true;
|
|
3045
|
+
const cast = t.tsAsExpression(t.memberExpression(t.identifier(name), t.identifier(n.property.name)), domElementType(tag));
|
|
3046
|
+
KEPT_CASTS.add(cast);
|
|
3047
|
+
return t.parenthesizedExpression(cast);
|
|
3048
|
+
});
|
|
3049
|
+
// React's `e.nativeEvent` is the DOM event Vue hands the handler
|
|
3050
|
+
t.traverseFast(body, (n) => {
|
|
3051
|
+
if ((t.isMemberExpression(n) || t.isOptionalMemberExpression(n)) && !n.computed && t.isIdentifier(n.object, { name }) && t.isIdentifier(n.property, { name: 'nativeEvent' }))
|
|
3052
|
+
changed = true;
|
|
3053
|
+
});
|
|
3054
|
+
if (!changed || !(t.isBlockStatement(body) || t.isExpression(body)))
|
|
3055
|
+
return handler;
|
|
3056
|
+
const native = nativeEventReads(body, name);
|
|
3057
|
+
if (!(t.isBlockStatement(native) || t.isExpression(native)))
|
|
3058
|
+
return handler;
|
|
3059
|
+
const out = t.isArrowFunctionExpression(fn) ? t.arrowFunctionExpression(fn.params, native, fn.async) : t.functionExpression(fn.id, fn.params, t.isBlockStatement(native) ? native : t.blockStatement([t.returnStatement(native)]), fn.generator, fn.async);
|
|
3060
|
+
out.loc = fn.loc;
|
|
3061
|
+
return out;
|
|
3062
|
+
}
|
|
3063
|
+
/** Whether a type the checker printed is React's ref object (`React.RefObject<…>`, `MutableRefObject<…>`, `| null` allowed). */
|
|
3064
|
+
function reactRefType(type) {
|
|
3065
|
+
if (!type)
|
|
3066
|
+
return false;
|
|
3067
|
+
const parts = t.isTSUnionType(type) ? type.types.filter((x) => !t.isTSNullKeyword(x) && !t.isTSUndefinedKeyword(x)) : [type];
|
|
3068
|
+
return parts.length > 0 && parts.every((p) => {
|
|
3069
|
+
if (!t.isTSTypeReference(p))
|
|
3070
|
+
return false;
|
|
3071
|
+
const name = t.isIdentifier(p.typeName) ? p.typeName.name : t.isIdentifier(p.typeName.right) ? p.typeName.right.name : '';
|
|
3072
|
+
return name === 'RefObject' || name === 'MutableRefObject';
|
|
3073
|
+
});
|
|
3074
|
+
}
|
|
3075
|
+
const DOM_EVENTS = new Set(['Event', 'UIEvent', 'MouseEvent', 'PointerEvent', 'KeyboardEvent', 'FocusEvent', 'WheelEvent', 'TouchEvent', 'DragEvent', 'InputEvent', 'CompositionEvent', 'AnimationEvent', 'TransitionEvent', 'ClipboardEvent', 'SubmitEvent', 'ToggleEvent']);
|
|
3076
|
+
/** Whether a parameter's type is the DOM's own event (or a union or intersection of them, `| undefined` allowed). */
|
|
3077
|
+
function domEventType(type) {
|
|
3078
|
+
if (t.isTSParenthesizedType(type))
|
|
3079
|
+
return domEventType(type.typeAnnotation);
|
|
3080
|
+
if (t.isTSUnionType(type))
|
|
3081
|
+
return type.types.some((x) => !t.isTSUndefinedKeyword(x) && !t.isTSNullKeyword(x)) && type.types.every((x) => t.isTSUndefinedKeyword(x) || t.isTSNullKeyword(x) || domEventType(x));
|
|
3082
|
+
if (t.isTSIntersectionType(type))
|
|
3083
|
+
return type.types.some(domEventType) && type.types.every((x) => domEventType(x) || t.isTSTypeLiteral(x));
|
|
3084
|
+
return t.isTSTypeReference(type) && t.isIdentifier(type.typeName) && DOM_EVENTS.has(type.typeName.name);
|
|
3085
|
+
}
|
|
3086
|
+
/** `e.nativeEvent` → `e` in a function body whose own parameter `e` is the DOM event (not where a nested function rebinds it). */
|
|
3087
|
+
function nativeEventReads(body, name) {
|
|
3088
|
+
const reads = new Set();
|
|
3089
|
+
t.traverse(body, (n, ancestors) => {
|
|
3090
|
+
if (!(t.isMemberExpression(n) || t.isOptionalMemberExpression(n)) || n.computed || !t.isIdentifier(n.object, { name }) || !t.isIdentifier(n.property, { name: 'nativeEvent' }))
|
|
3091
|
+
return;
|
|
3092
|
+
const shadowed = ancestors.some(({ node }) => t.isFunction(node) && node.params.some((p) => name in t.getBindingIdentifiers(p)));
|
|
3093
|
+
if (!shadowed)
|
|
3094
|
+
reads.add(n);
|
|
3095
|
+
});
|
|
3096
|
+
if (!reads.size)
|
|
3097
|
+
return body;
|
|
3098
|
+
return transform(body, (n) => (reads.has(n) ? t.identifier(name) : null));
|
|
3099
|
+
}
|
|
3100
|
+
/**
|
|
3101
|
+
* Whether a cast written in the source names only the DOM's own element, node and event types (`e.target as HTMLElement`,
|
|
3102
|
+
* `as Node | null`): lib.dom declares them in every output, so a Vue template of a `lang="ts"` component keeps the cast.
|
|
3103
|
+
*/
|
|
3104
|
+
function domTypeOnly(type, reactNames) {
|
|
3105
|
+
const parts = t.isTSUnionType(type) ? type.types : [type];
|
|
3106
|
+
return parts.every((p) => t.isTSNullKeyword(p) || (t.isTSTypeReference(p) && !p.typeParameters && t.isIdentifier(p.typeName) && !reactNames.has(p.typeName.name) && (/^(HTML[A-Za-z]*Element|SVG[A-Za-z]*Element|Element|Node|EventTarget|Text)$/.test(p.typeName.name) || DOM_EVENTS.has(p.typeName.name))));
|
|
3107
|
+
}
|
|
3108
|
+
function printStatements(stmts) {
|
|
3109
|
+
return printProgram(stmts);
|
|
3110
|
+
}
|
|
3111
|
+
/**
|
|
3112
|
+
* Emits one lowered module as Vue files. A file with components becomes one main SFC holding the file's own code
|
|
3113
|
+
* (types, constants, composables, canvas loops) in a `<script lang="ts">` block and its stylesheet in `<style>`;
|
|
3114
|
+
* small private components are written in place; only components that must stand alone get an SFC beside it.
|
|
3115
|
+
*/
|
|
3116
|
+
export function emitVue(mod, layout, ctx) {
|
|
3117
|
+
for (const [alias, name] of mod.aliases) {
|
|
3118
|
+
if (!mod.exportedNames.has(alias) || !layout.components.has(alias))
|
|
3119
|
+
continue;
|
|
3120
|
+
ctx.diagnostics.push({ code: 'component-alias', severity: 'info', message: `${alias} is another name for ${name}: a component file exports only its component, so ${alias} is ${name}'s file, imported under that name.`, file: ctx.sourceRel, target: ctx.target });
|
|
3121
|
+
}
|
|
3122
|
+
const facts = moduleFacts(mod);
|
|
3123
|
+
const files = [];
|
|
3124
|
+
const moduleTypeImports = [];
|
|
3125
|
+
// contexts: reads and providers linked to their declarations, each declaration an InjectionKey (see shared/context)
|
|
3126
|
+
linkContexts(mod, ctx);
|
|
3127
|
+
keepProvidersFiled(mod, layout, ctx.target);
|
|
3128
|
+
// Vue's Ref under another name where the file imports React's (which maps to a `{ current }` box)
|
|
3129
|
+
const vueRef = facts.reactNames.has('Ref') ? 'VueRef' : 'Ref';
|
|
3130
|
+
const contexts = contextModuleBody(mod, 'vue', vueRef);
|
|
3131
|
+
mod.moduleBody = contexts.body;
|
|
3132
|
+
for (const name of contexts.imports.types)
|
|
3133
|
+
moduleTypeImports.push(name === 'VueRef' ? { source: 'vue', name: 'Ref', local: 'VueRef' } : { source: 'vue', name });
|
|
3134
|
+
// a pure module function kept as code that returns markup (exported, or read by module code): it returns functional
|
|
3135
|
+
// components, Vue's markup held as a value, which templates render with `<component :is>` (see renderHelperValue)
|
|
3136
|
+
const elementValues = reactValues(mod);
|
|
3137
|
+
let renderHelpers = 0;
|
|
3138
|
+
// a module name `h` would hide Vue's
|
|
3139
|
+
const moduleH = mod.moduleBody.some((s) => 'h' in t.getOuterBindingIdentifiers(s)) || mod.imports.some((d) => d.specifiers.some((sp) => sp.local.name === 'h'));
|
|
3140
|
+
// only a pure one: a template may read its call more than once (ModuleIR.pureFunctions)
|
|
3141
|
+
const pureHelper = (s) => {
|
|
3142
|
+
const decl = t.isExportNamedDeclaration(s) ? s.declaration : s;
|
|
3143
|
+
const names = decl ? Object.keys(t.getOuterBindingIdentifiers(decl)) : [];
|
|
3144
|
+
return names.length === 1 && !!mod.pureFunctions?.has(names[0] ?? '');
|
|
3145
|
+
};
|
|
3146
|
+
mod.moduleBody = mod.moduleBody.map((s) => {
|
|
3147
|
+
const value = containsJSX(s) && !moduleH && pureHelper(s) ? renderHelperValue(s, (callee) => isElementTest(callee, elementValues)) : null;
|
|
3148
|
+
if (value)
|
|
3149
|
+
renderHelpers++;
|
|
3150
|
+
return value ?? s;
|
|
3151
|
+
});
|
|
3152
|
+
// module functions that build elements in statements, rendered only as a component's child: render-function code
|
|
3153
|
+
// (module-builders)
|
|
3154
|
+
const builders = layout.kind === 'module' ? null : planElementBuilders(mod, facts.reactNames, moduleLets(mod.moduleBody), moduleH, ctx.oracle, ctx.sourceFile);
|
|
3155
|
+
if (builders) {
|
|
3156
|
+
const taken = builders.statements;
|
|
3157
|
+
facts.moduleMarkup = (stmt) => taken.get(stmt) ?? null;
|
|
3158
|
+
renderHelpers += taken.size;
|
|
3159
|
+
for (const name of builders.types)
|
|
3160
|
+
moduleTypeImports.push({ source: 'vue', name });
|
|
3161
|
+
}
|
|
3162
|
+
// the file's own functions and types are handed to Vue's event props too (`@mousedown="stopEvent"`): see nativeEventParams
|
|
3163
|
+
const moduleStatements = nativeEventParams(transformModuleBody(mod.moduleBody, ctx, facts, moduleTypeImports));
|
|
3164
|
+
// every name the module body declares, its types too (Babel lists no binding for an interface or a type alias):
|
|
3165
|
+
// a component file of the module that reads one imports it from the main file, which exports it
|
|
3166
|
+
const moduleLocal = new Set(mod.moduleBody.flatMap((s) => {
|
|
3167
|
+
const decl = t.isExportNamedDeclaration(s) ? s.declaration : s;
|
|
3168
|
+
return t.isTSInterfaceDeclaration(decl) || t.isTSTypeAliasDeclaration(decl) || t.isTSEnumDeclaration(decl) ? [decl.id.name] : Object.keys(t.getOuterBindingIdentifiers(s));
|
|
3169
|
+
}));
|
|
3170
|
+
const mutableModuleNames = moduleLets(mod.moduleBody);
|
|
3171
|
+
// React's element test is the one the templates use (markup held as a value is a functional component, a function), and other React runtime values are reported
|
|
3172
|
+
const rv = reactValues(mod);
|
|
3173
|
+
// a component's function that runs React's element tools (Children, cloneElement, isValidElement) and nothing else of
|
|
3174
|
+
// React's: kept as React wrote it, before the element tests are rewritten for templates, so a template that renders
|
|
3175
|
+
// its call writes it as a render function (VueTemplate.toolHelper)
|
|
3176
|
+
const toolFns = new Map();
|
|
3177
|
+
for (const comp of mod.components) {
|
|
3178
|
+
for (const item of comp.items) {
|
|
3179
|
+
if (item.kind !== 'function')
|
|
3180
|
+
continue;
|
|
3181
|
+
const probe = { ...comp, items: [item], template: { type: 'fragment', children: [] }, fragments: [], props: [] };
|
|
3182
|
+
const reads = [...reactRuntimeReads(probe, rv).keys()];
|
|
3183
|
+
if (!reads.length || !reads.every((r) => ELEMENT_TOOLS.has(r)))
|
|
3184
|
+
continue;
|
|
3185
|
+
const own = toolFns.get(comp) ?? new Map();
|
|
3186
|
+
own.set(item.name, cloneWithRefs(item.node, comp));
|
|
3187
|
+
toolFns.set(comp, own);
|
|
3188
|
+
}
|
|
3189
|
+
}
|
|
3190
|
+
// each component's react-runtime errors, by the React name they report (withdrawn when no read is left)
|
|
3191
|
+
const runtimeErrors = new Map();
|
|
3192
|
+
for (const fn of [...mod.components, ...mod.hooks]) {
|
|
3193
|
+
replaceElementTests(fn, rv, (arg) => t.binaryExpression('===', t.unaryExpression('typeof', arg), t.stringLiteral('function')));
|
|
3194
|
+
const before = ctx.diagnostics.length;
|
|
3195
|
+
reportReactRuntime(fn, rv, ctx);
|
|
3196
|
+
const names = [...reactRuntimeReads(fn, rv).keys()];
|
|
3197
|
+
const pushed = ctx.diagnostics.slice(before);
|
|
3198
|
+
if (pushed.length === names.length) {
|
|
3199
|
+
runtimeErrors.set(fn, names.flatMap((name, i) => {
|
|
3200
|
+
const diagnostic = pushed[i];
|
|
3201
|
+
return diagnostic ? [[name, diagnostic]] : [];
|
|
3202
|
+
}));
|
|
3203
|
+
}
|
|
3204
|
+
}
|
|
3205
|
+
// interfaces and type aliases of the file: imported with `import type`
|
|
3206
|
+
const moduleTypes = new Set();
|
|
3207
|
+
for (const s of mod.moduleBody) {
|
|
3208
|
+
const decl = t.isExportNamedDeclaration(s) ? s.declaration : s;
|
|
3209
|
+
if (t.isTSInterfaceDeclaration(decl) || t.isTSTypeAliasDeclaration(decl))
|
|
3210
|
+
moduleTypes.add(decl.id.name);
|
|
3211
|
+
}
|
|
3212
|
+
for (const s of mod.moduleBody) {
|
|
3213
|
+
const decl = t.isExportNamedDeclaration(s) ? s.declaration : s;
|
|
3214
|
+
if (decl && !t.isTSInterfaceDeclaration(decl) && !t.isTSTypeAliasDeclaration(decl))
|
|
3215
|
+
for (const n of Object.keys(t.getOuterBindingIdentifiers(decl)))
|
|
3216
|
+
moduleTypes.delete(n);
|
|
3217
|
+
}
|
|
3218
|
+
const writtenModuleNames = new Set();
|
|
3219
|
+
for (const s of mod.moduleBody) {
|
|
3220
|
+
const decl = t.isExportNamedDeclaration(s) ? s.declaration : s;
|
|
3221
|
+
if (t.isTSInterfaceDeclaration(decl) || t.isTSTypeAliasDeclaration(decl) || t.isTSEnumDeclaration(decl))
|
|
3222
|
+
moduleLocal.add(decl.id.name);
|
|
3223
|
+
}
|
|
3224
|
+
const addTypeImports = (set, list) => {
|
|
3225
|
+
for (const ti of list)
|
|
3226
|
+
set.type(ti.source, ti.name, ti.local ?? ti.name);
|
|
3227
|
+
};
|
|
3228
|
+
const hookStatements = (exportNames) => {
|
|
3229
|
+
const statements = [];
|
|
3230
|
+
const sets = [];
|
|
3231
|
+
// every hook may name an API its own way (`vueRef` beside a `ref` parameter): each pair is imported
|
|
3232
|
+
const apis = [];
|
|
3233
|
+
const typeImports = [];
|
|
3234
|
+
for (const hook of mod.hooks) {
|
|
3235
|
+
// a Vue API keeps one local name across the file: the hooks avoid every name a component binds too
|
|
3236
|
+
const alloc = new NameAllocator([...hook.bindings.keys(), ...moduleLocal, ...mod.hooks.map((h) => h.name), ...mod.components.flatMap((c) => [...c.bindings.keys()])]);
|
|
3237
|
+
// a ref the hook returns may be put on an element by its caller (`ref="canvas"`): Vue fills only a real ref,
|
|
3238
|
+
// so it is one (`ref<El | null>(null)`, read through .value), not a { current } object
|
|
3239
|
+
// Only a ref returned as itself (`return ref`, `{ ref }`, `[ref, …]`) and starting empty, as element refs do: a
|
|
3240
|
+
// ref read inside a returned function, or one holding a value, stays what it is
|
|
3241
|
+
if (hook.returns) {
|
|
3242
|
+
const r = unwrap(hook.returns);
|
|
3243
|
+
const direct = t.isObjectExpression(r) ? r.properties.map((p) => (t.isObjectProperty(p) ? p.value : null)) : t.isArrayExpression(r) ? r.elements : [r];
|
|
3244
|
+
for (const n of direct) {
|
|
3245
|
+
const name = n && t.isIdentifier(n) ? hook.refs.get(n) : undefined;
|
|
3246
|
+
const b = name ? hook.bindings.get(name) : undefined;
|
|
3247
|
+
const item = hook.items.find((i) => i.kind === 'ref' && i.name === name);
|
|
3248
|
+
const empty = !item?.init || t.isNullLiteral(item.init) || t.isIdentifier(item.init, { name: 'undefined' });
|
|
3249
|
+
if (b?.kind === 'ref' && empty) {
|
|
3250
|
+
b.refKind = 'dom';
|
|
3251
|
+
b.escapes = false;
|
|
3252
|
+
}
|
|
3253
|
+
}
|
|
3254
|
+
}
|
|
3255
|
+
const script = new VueScript(hook, alloc, ctx, facts, layout.modulePath);
|
|
3256
|
+
// a type the checker wrote inline (`import('@/x/types').Point`) points at the output file
|
|
3257
|
+
const stmt = rewriteImportTypes(emitHook(hook, script), ctx);
|
|
3258
|
+
nativeEventParams([stmt]);
|
|
3259
|
+
statements.push(exportNames.has(hook.name) && !t.isExportNamedDeclaration(stmt) ? t.exportNamedDeclaration(stmt) : stmt);
|
|
3260
|
+
for (const pair of script.vue)
|
|
3261
|
+
apis.push(pair);
|
|
3262
|
+
typeImports.push(...script.typeImports);
|
|
3263
|
+
sets.push(script.imports);
|
|
3264
|
+
}
|
|
3265
|
+
return { statements, imports: apis, typeImports, sets };
|
|
3266
|
+
};
|
|
3267
|
+
const vueImport = (set, apis) => {
|
|
3268
|
+
for (const [api, local] of apis)
|
|
3269
|
+
set.named('vue', api, local);
|
|
3270
|
+
};
|
|
3271
|
+
if (layout.kind === 'module') {
|
|
3272
|
+
const hooks = hookStatements(new Set());
|
|
3273
|
+
const outPath = layout.modulePath;
|
|
3274
|
+
const set = new ImportSet();
|
|
3275
|
+
for (const decl of mod.imports)
|
|
3276
|
+
addOriginalImport(decl, set, outPath, ctx);
|
|
3277
|
+
for (const s of hooks.sets)
|
|
3278
|
+
for (const d of s.declarations())
|
|
3279
|
+
addDeclaration(set, d);
|
|
3280
|
+
if (renderHelpers)
|
|
3281
|
+
set.named('vue', 'h');
|
|
3282
|
+
vueImport(set, hooks.imports);
|
|
3283
|
+
addTypeImports(set, [...moduleTypeImports, ...hooks.typeImports]);
|
|
3284
|
+
const reexports = mod.reexports.flatMap((r) => rewriteReexport(r, outPath, ctx));
|
|
3285
|
+
const body = [...moduleStatements, ...hooks.statements, ...reexports];
|
|
3286
|
+
files.push({ path: outPath, contents: printStatements([...set.declarations(namesIn(body)), ...body]), kind: 'module' });
|
|
3287
|
+
return files;
|
|
3288
|
+
}
|
|
3289
|
+
const inlineComps = new Map(mod.components.filter((c) => layout.inlined.has(c.name)).map((c) => [c.name, c]));
|
|
3290
|
+
/** names the other component files read from the main file, which it therefore exports */
|
|
3291
|
+
const fromMain = new Set(layout.defaultValue ? [layout.defaultValue] : []);
|
|
3292
|
+
/** Imports of the original file needed at `outPath`, the other component files it renders, and (outside the main file) the main file's names. */
|
|
3293
|
+
const importsFor = (outPath, used, self, isMain) => {
|
|
3294
|
+
const set = new ImportSet();
|
|
3295
|
+
for (const decl of mod.imports)
|
|
3296
|
+
addOriginalImport(decl, set, outPath, ctx);
|
|
3297
|
+
for (const [name, file] of layout.components)
|
|
3298
|
+
if (name !== self && used.has(name))
|
|
3299
|
+
set.defaultImport(importPath(outPath, file), name);
|
|
3300
|
+
if (isMain)
|
|
3301
|
+
return set;
|
|
3302
|
+
const main = importPath(outPath, layout.modulePath);
|
|
3303
|
+
for (const name of moduleLocal) {
|
|
3304
|
+
if (!used.has(name))
|
|
3305
|
+
continue;
|
|
3306
|
+
fromMain.add(name);
|
|
3307
|
+
if (moduleTypes.has(name))
|
|
3308
|
+
set.type(main, name);
|
|
3309
|
+
else
|
|
3310
|
+
set.named(main, name);
|
|
3311
|
+
}
|
|
3312
|
+
for (const name of writtenModuleNames) {
|
|
3313
|
+
const setterName = `set${name.charAt(0).toUpperCase()}${name.slice(1)}`;
|
|
3314
|
+
if (!used.has(setterName))
|
|
3315
|
+
continue;
|
|
3316
|
+
fromMain.add(setterName);
|
|
3317
|
+
set.named(main, setterName);
|
|
3318
|
+
}
|
|
3319
|
+
for (const h of mod.hooks) {
|
|
3320
|
+
if (!used.has(h.name))
|
|
3321
|
+
continue;
|
|
3322
|
+
fromMain.add(h.name);
|
|
3323
|
+
set.named(main, h.name);
|
|
3324
|
+
}
|
|
3325
|
+
return set;
|
|
3326
|
+
};
|
|
3327
|
+
/** The main file's module script: the file's own code, exporting what the other component files read. */
|
|
3328
|
+
/** `const name: FunctionalComponent = () => h(…)` for each markup value the module's data holds (see vue/render-fn). */
|
|
3329
|
+
const markupValueStatements = () => (mod.markupValues ?? []).flatMap((v) => {
|
|
3330
|
+
const fn = renderFunction(v.template);
|
|
3331
|
+
if (!fn) {
|
|
3332
|
+
ctx.diagnostics.push({ code: 'module-jsx', severity: 'error', message: `The markup the file's data holds as ${v.name} has no render-function form here (a style number computed at run time, a ref, a slot or a motion element): not converted.`, file: ctx.sourceRel, target: 'vue' });
|
|
3333
|
+
return [];
|
|
3334
|
+
}
|
|
3335
|
+
const id = t.identifier(v.name);
|
|
3336
|
+
id.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier('FunctionalComponent')));
|
|
3337
|
+
return [t.variableDeclaration('const', [t.variableDeclarator(id, fn)])];
|
|
3338
|
+
});
|
|
3339
|
+
const mainModuleScript = (outPath) => {
|
|
3340
|
+
const listed = new Set();
|
|
3341
|
+
for (const s of moduleStatements) {
|
|
3342
|
+
if (t.isExportNamedDeclaration(s) && !s.declaration && !s.source)
|
|
3343
|
+
for (const sp of s.specifiers)
|
|
3344
|
+
if (t.isExportSpecifier(sp))
|
|
3345
|
+
listed.add(sp.local.name);
|
|
3346
|
+
}
|
|
3347
|
+
const statements = [];
|
|
3348
|
+
for (const s of moduleStatements) {
|
|
3349
|
+
// a component file's default export is the component: a plain default value is exported by name instead
|
|
3350
|
+
if (t.isExportDefaultDeclaration(s)) {
|
|
3351
|
+
if (t.isIdentifier(s.declaration))
|
|
3352
|
+
continue;
|
|
3353
|
+
if (t.isExpression(s.declaration) && layout.defaultValue) {
|
|
3354
|
+
statements.push(t.exportNamedDeclaration(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(layout.defaultValue), s.declaration)])));
|
|
3355
|
+
continue;
|
|
3356
|
+
}
|
|
3357
|
+
}
|
|
3358
|
+
// an interface or type alias binds no value, so Babel lists no names for it: its own name, for the type imports
|
|
3359
|
+
const names = t.isTSInterfaceDeclaration(s) || t.isTSTypeAliasDeclaration(s) || t.isTSEnumDeclaration(s) ? [s.id.name] : Object.keys(t.getOuterBindingIdentifiers(s));
|
|
3360
|
+
const exported = t.isExportNamedDeclaration(s) || names.some((n) => listed.has(n));
|
|
3361
|
+
statements.push(!exported && names.some((n) => fromMain.has(n)) ? exportIfLocal(s) : s);
|
|
3362
|
+
}
|
|
3363
|
+
const hooks = hookStatements(fromMain);
|
|
3364
|
+
statements.push(...hooks.statements, ...moduleSetters(writtenModuleNames), ...mod.reexports.flatMap((r) => rewriteReexport(r, outPath, ctx)));
|
|
3365
|
+
return { statements, apis: hooks.imports, typeImports: hooks.typeImports, sets: hooks.sets };
|
|
3366
|
+
};
|
|
3367
|
+
/** One SFC: the main file also carries the module's own code and the stylesheet. */
|
|
3368
|
+
const emitComponent = (comp, outPath, isMain) => {
|
|
3369
|
+
// the forwarded ref's own name never reaches the output unless script code reads it (it becomes `el`, or a handle)
|
|
3370
|
+
const forwardName = comp.forwardRef && !itemsRead(comp, comp.forwardRef) ? comp.forwardRef : null;
|
|
3371
|
+
const alloc = new NameAllocator([...[...comp.bindings.keys()].filter((n) => n !== forwardName), ...moduleLocal, ...mod.components.map((c) => c.name), ...mod.hooks.map((h) => h.name)]);
|
|
3372
|
+
const script = new VueScript(comp, alloc, ctx, facts, outPath);
|
|
3373
|
+
script.childOf = (tag) => childComponent(mod, tag, ctx);
|
|
3374
|
+
script.childOfAny = (parent, tag) => {
|
|
3375
|
+
const own = parent.file === ctx.sourceFile ? mod : (ctx.moduleOf?.(parent.file) ?? null);
|
|
3376
|
+
return own ? childComponent(own, tag, { ...ctx, sourceFile: parent.file }) : null;
|
|
3377
|
+
};
|
|
3378
|
+
const propsFrom = ctx.diagnostics.length;
|
|
3379
|
+
const props = propsDeclaration(comp, script);
|
|
3380
|
+
const propsProblems = ctx.diagnostics.slice(propsFrom);
|
|
3381
|
+
const items = script.items();
|
|
3382
|
+
if (cutLeftoverJsx(items))
|
|
3383
|
+
script.warn('jsx-in-script', `${comp.name} builds elements in script code, which have no form outside a template.`, 'error');
|
|
3384
|
+
// render helpers: each call written in place
|
|
3385
|
+
// M4: a tree's error, withdrawn when the template draws it with a render function (treeCall)
|
|
3386
|
+
const treeFailures = new Map();
|
|
3387
|
+
for (const f of writeFragmentsInPlace(comp)) {
|
|
3388
|
+
script.warn('jsx-in-script', f.reason, 'error');
|
|
3389
|
+
const d = ctx.diagnostics[ctx.diagnostics.length - 1];
|
|
3390
|
+
if (d && comp.fragments.some((x) => x.name === f.name))
|
|
3391
|
+
treeFailures.set(f.name, [...(treeFailures.get(f.name) ?? []), d]);
|
|
3392
|
+
}
|
|
3393
|
+
const inlineUsed = new Set();
|
|
3394
|
+
const template = new VueTemplate(comp, script, facts, props.restSpread, isMain ? null : { names: mutableModuleNames, written: writtenModuleNames }, { comps: inlineComps, used: inlineUsed });
|
|
3395
|
+
// M4: the tree errors treeCall withdraws
|
|
3396
|
+
template.treeFailures = treeFailures;
|
|
3397
|
+
template.toolFns = toolFns.get(comp) ?? new Map();
|
|
3398
|
+
const markup = template.root(comp.template, ' ', { rename: new Map(), loopNames: new Set(), depth: 0 });
|
|
3399
|
+
// M4: React's focus put back after an update that moved the focused element; helper errors of drawn helpers go
|
|
3400
|
+
template.restoreFocus();
|
|
3401
|
+
template.withdrawDrawnHelpers();
|
|
3402
|
+
if (template.dropped.size) {
|
|
3403
|
+
// the functions the template wrote as render functions: their React form leaves the setup, and a react-runtime
|
|
3404
|
+
// error whose React name no other code of the component reads is withdrawn (the render function wrote it)
|
|
3405
|
+
const declares = (s) => (t.isFunctionDeclaration(s) && s.id ? [s.id.name] : t.isVariableDeclaration(s) ? s.declarations.flatMap((d) => Object.keys(t.getBindingIdentifiers(d.id))) : []);
|
|
3406
|
+
const kept = items.filter((s) => !declares(s).some((n) => template.dropped.has(n)));
|
|
3407
|
+
items.splice(0, items.length, ...kept);
|
|
3408
|
+
const left = reactRuntimeReads({ ...comp, items: comp.items.filter((i) => !(i.kind === 'function' && template.dropped.has(i.name))) }, rv);
|
|
3409
|
+
for (const [name, diagnostic] of runtimeErrors.get(comp) ?? [])
|
|
3410
|
+
if (!left.has(name))
|
|
3411
|
+
withdraw(ctx.diagnostics, diagnostic);
|
|
3412
|
+
// children read only by those functions are read during render now, as the default slot's nodes
|
|
3413
|
+
const rest = { ...comp, items: comp.items.filter((i) => !(i.kind === 'function' && template.dropped.has(i.name))) };
|
|
3414
|
+
for (const p of comp.props) {
|
|
3415
|
+
if (p.kind !== 'children' || childrenReadAsValue(rest, p.local))
|
|
3416
|
+
continue;
|
|
3417
|
+
for (const d of propsProblems)
|
|
3418
|
+
if (d.code === 'children-in-script' && d.message.startsWith(`"${p.local}" `))
|
|
3419
|
+
withdraw(ctx.diagnostics, d);
|
|
3420
|
+
}
|
|
3421
|
+
}
|
|
3422
|
+
// render props are scoped slots: their props keep the types React gave the function's parameters
|
|
3423
|
+
const slots = slotsDeclaration(comp, script);
|
|
3424
|
+
if (slots)
|
|
3425
|
+
props.statements.push(slots);
|
|
3426
|
+
// markup a prop's data holds (ComponentIR.markupValues): functional components of the setup; each reads the
|
|
3427
|
+
// component's values where it renders, so it follows them as the template does
|
|
3428
|
+
const ownMarkup = [];
|
|
3429
|
+
for (const v of comp.markupValues ?? []) {
|
|
3430
|
+
const fn = renderFunction(v.template, (node) => cloneWithRefs(node, comp));
|
|
3431
|
+
const id = t.identifier(v.name);
|
|
3432
|
+
if (!fn) {
|
|
3433
|
+
script.warn('jsx-in-expression', `The markup ${comp.name} passes in a prop's data as ${v.name} has no render-function form here (a style number computed at run time, a ref, a slot or a motion element): not converted.`, 'error');
|
|
3434
|
+
ownMarkup.push(t.variableDeclaration('const', [t.variableDeclarator(id, t.nullLiteral())]));
|
|
3435
|
+
continue;
|
|
3436
|
+
}
|
|
3437
|
+
id.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier('FunctionalComponent')));
|
|
3438
|
+
script.imports.named('vue', 'h');
|
|
3439
|
+
script.typeImports.push({ source: 'vue', name: 'FunctionalComponent' });
|
|
3440
|
+
ownMarkup.push(t.variableDeclaration('const', [t.variableDeclarator(id, script.r(fn))]));
|
|
3441
|
+
}
|
|
3442
|
+
// a type the checker wrote inline (`import('@/x/types').Point`) points at the output file
|
|
3443
|
+
let body = nativeEventParams([...props.statements, ...script.helperStatements(), ...script.forwardStatements(), ...items, ...ownMarkup, ...script.provides(comp), ...template.hoisted.map((s) => mapReactTypes(s, 'vue', facts.reactNames, script.typeImports))].map((s) => rewriteImportTypes(s, ctx)));
|
|
3444
|
+
// another component file writes the main file's module variables through setters it exports
|
|
3445
|
+
if (!isMain)
|
|
3446
|
+
for (const name of routeModuleWrites(body, mutableModuleNames, new Set(comp.bindings.keys())))
|
|
3447
|
+
writtenModuleNames.add(name);
|
|
3448
|
+
const moduleScript = [];
|
|
3449
|
+
const extraTypes = [];
|
|
3450
|
+
let moduleApis = [];
|
|
3451
|
+
const moduleSets = [];
|
|
3452
|
+
if (isMain) {
|
|
3453
|
+
const main = mainModuleScript(outPath);
|
|
3454
|
+
// the module's markup values, functional components declared before the data that holds them
|
|
3455
|
+
const values = markupValueStatements();
|
|
3456
|
+
if (values.length || renderHelpers) {
|
|
3457
|
+
const set = new ImportSet();
|
|
3458
|
+
set.named('vue', 'h');
|
|
3459
|
+
moduleSets.push(set);
|
|
3460
|
+
// a render helper names the type only where its own types say so (mapReactTypes imports it then)
|
|
3461
|
+
if (values.length)
|
|
3462
|
+
extraTypes.push({ source: 'vue', name: 'FunctionalComponent' });
|
|
3463
|
+
}
|
|
3464
|
+
moduleScript.push(...values);
|
|
3465
|
+
moduleScript.push(...main.statements);
|
|
3466
|
+
moduleApis = main.apis;
|
|
3467
|
+
moduleSets.push(...main.sets);
|
|
3468
|
+
extraTypes.push(...moduleTypeImports, ...main.typeImports);
|
|
3469
|
+
}
|
|
3470
|
+
// canvas and animation loops, framework-free, at the top of the file that runs them
|
|
3471
|
+
for (const core of script.cores)
|
|
3472
|
+
moduleScript.push(...core.module.statements.map((st) => rewriteImportTypes(mapReactTypes(st, 'vue', facts.reactNames, extraTypes), ctx)));
|
|
3473
|
+
const generic = comp.typeParams ? ` generic="${genericsAttr(comp.typeParams)}"` : '';
|
|
3474
|
+
// nothing the file declares stays unless the script or the template reads it
|
|
3475
|
+
const templateNames = wordsIn(generic, markupNames(markup, 'vue'));
|
|
3476
|
+
const pureCalls = new Set([...script.vue].filter(([api]) => api === 'ref' || api === 'computed' || api === 'useId' || api === 'useAttrs' || api === 'reactive' || api === 'inject' || api === 'shallowRef').map(([, local]) => local));
|
|
3477
|
+
const [prunedModule = [], prunedBody = []] = pruneUnused([moduleScript, body], templateNames, { calls: pureCalls, props: { calls: new Set(['defineProps', 'withDefaults']), whenUnread: 'call' } });
|
|
3478
|
+
moduleScript.splice(0, moduleScript.length, ...prunedModule);
|
|
3479
|
+
body = prunedBody;
|
|
3480
|
+
// a name the component declares itself shadows the module's: never import it into the component
|
|
3481
|
+
const used = namesIn(body);
|
|
3482
|
+
for (const name of comp.bindings.keys())
|
|
3483
|
+
if (!comp.moduleNames.has(name) && name !== forwardName)
|
|
3484
|
+
used.delete(name);
|
|
3485
|
+
namesIn(moduleScript, used);
|
|
3486
|
+
// names only the markup reads (components, motion) appear in no script statement
|
|
3487
|
+
for (const name of templateNames)
|
|
3488
|
+
used.add(name);
|
|
3489
|
+
// one import set for the whole SFC: Vue merges both script blocks into one module, so nothing may be imported twice
|
|
3490
|
+
const imports = importsFor(outPath, used, comp.name, isMain);
|
|
3491
|
+
for (const d of script.imports.declarations())
|
|
3492
|
+
addDeclaration(imports, d);
|
|
3493
|
+
for (const set of moduleSets)
|
|
3494
|
+
for (const d of set.declarations())
|
|
3495
|
+
addDeclaration(imports, d);
|
|
3496
|
+
vueImport(imports, script.vue);
|
|
3497
|
+
vueImport(imports, moduleApis);
|
|
3498
|
+
addTypeImports(imports, [...script.typeImports, ...extraTypes]);
|
|
3499
|
+
// type names used by props flattened from another file come from that file's module
|
|
3500
|
+
for (const { type, file } of script.foreignTypes) {
|
|
3501
|
+
const layoutOfFile = ctx.layoutOf(file);
|
|
3502
|
+
if (!layoutOfFile)
|
|
3503
|
+
continue;
|
|
3504
|
+
t.traverseFast(type, (n) => {
|
|
3505
|
+
if (!t.isTSTypeReference(n) || !t.isIdentifier(n.typeName))
|
|
3506
|
+
return;
|
|
3507
|
+
const name = n.typeName.name;
|
|
3508
|
+
if (imports.locals().has(name) || moduleLocal.has(name) || comp.bindings.has(name))
|
|
3509
|
+
return;
|
|
3510
|
+
// React's style types under their Vue names are Vue's own, imported from 'vue' like any other Vue type
|
|
3511
|
+
if (VUE_TYPES.has(name)) {
|
|
3512
|
+
imports.type('vue', name);
|
|
3513
|
+
used.add(name);
|
|
3514
|
+
return;
|
|
3515
|
+
}
|
|
3516
|
+
if (GLOBAL_TYPES.has(name))
|
|
3517
|
+
return;
|
|
3518
|
+
// a name that file imports itself comes from where it imports it (that file's module does not export it)
|
|
3519
|
+
let from = importedThrough(file, name, ctx);
|
|
3520
|
+
for (let hop = 0, next = from; hop < 4 && next; hop++) {
|
|
3521
|
+
next = importedThrough(next.file, next.imported, ctx);
|
|
3522
|
+
if (next)
|
|
3523
|
+
from = next;
|
|
3524
|
+
}
|
|
3525
|
+
if (from) {
|
|
3526
|
+
const origin = ctx.layoutOf(from.file);
|
|
3527
|
+
if (!origin)
|
|
3528
|
+
return;
|
|
3529
|
+
imports.type(importPath(outPath, origin.modulePath), from.imported, name);
|
|
3530
|
+
used.add(name);
|
|
3531
|
+
return;
|
|
3532
|
+
}
|
|
3533
|
+
imports.type(importPath(outPath, layoutOfFile.modulePath), name);
|
|
3534
|
+
used.add(name);
|
|
3535
|
+
});
|
|
3536
|
+
}
|
|
3537
|
+
const declarations = imports.declarations(used);
|
|
3538
|
+
const parts = [];
|
|
3539
|
+
if (moduleScript.length) {
|
|
3540
|
+
parts.push(`<script lang="ts">${NL}${printStatements([...declarations, ...moduleScript])}${NL}</script>${NL}`);
|
|
3541
|
+
// the template sees the module script's names (its constants, the components it imports) only beside a setup
|
|
3542
|
+
// script: with nothing to set up, the setup script declares the component's name
|
|
3543
|
+
if (body.length)
|
|
3544
|
+
parts.push(`<script setup lang="ts"${generic}>${NL}${printStatements(body)}${NL}</script>${NL}`);
|
|
3545
|
+
else
|
|
3546
|
+
parts.push(`<script setup lang="ts"${generic}>${NL}defineOptions({ name: '${comp.name}' });${NL}</script>${NL}`);
|
|
3547
|
+
}
|
|
3548
|
+
else if (declarations.length || body.length)
|
|
3549
|
+
parts.push(`<script setup lang="ts"${generic}>${NL}${printStatements([...declarations, ...body])}${NL}</script>${NL}`);
|
|
3550
|
+
// a component with nothing to set up is a bare template, but Vue's tooling (compileScript, the bundler) wants a
|
|
3551
|
+
// script: its name is the one thing worth declaring there (devtools, KeepAlive's include)
|
|
3552
|
+
else
|
|
3553
|
+
parts.push(`<script setup lang="ts">${NL}defineOptions({ name: '${comp.name}' });${NL}</script>${NL}`);
|
|
3554
|
+
parts.push(`<template>${NL} ${markup}${NL}</template>${NL}`);
|
|
3555
|
+
if (isMain) {
|
|
3556
|
+
const style = componentStyle('vue', layout.styles);
|
|
3557
|
+
if (style)
|
|
3558
|
+
parts.push(style);
|
|
3559
|
+
}
|
|
3560
|
+
return { path: outPath, contents: parts.join(NL), kind: 'component' };
|
|
3561
|
+
};
|
|
3562
|
+
// the other component files first: the main file then knows which of its names they read
|
|
3563
|
+
const main = mod.components.find((c) => c.name === layout.mainComponent);
|
|
3564
|
+
for (const comp of mod.components) {
|
|
3565
|
+
const outPath = layout.components.get(comp.name);
|
|
3566
|
+
if (outPath && comp !== main)
|
|
3567
|
+
files.push(emitComponent(comp, outPath, false));
|
|
3568
|
+
}
|
|
3569
|
+
if (main)
|
|
3570
|
+
files.unshift(emitComponent(main, layout.modulePath, true));
|
|
3571
|
+
return files;
|
|
3572
|
+
}
|
|
3573
|
+
/** Exports a declaration that another component file of the same source imports. */
|
|
3574
|
+
function exportIfLocal(s) {
|
|
3575
|
+
if (t.isExportNamedDeclaration(s) || t.isExportDefaultDeclaration(s))
|
|
3576
|
+
return s;
|
|
3577
|
+
if (t.isVariableDeclaration(s) || t.isFunctionDeclaration(s) || t.isClassDeclaration(s) || t.isTSInterfaceDeclaration(s) || t.isTSTypeAliasDeclaration(s) || t.isTSEnumDeclaration(s)) {
|
|
3578
|
+
return t.exportNamedDeclaration(s);
|
|
3579
|
+
}
|
|
3580
|
+
return s;
|
|
3581
|
+
}
|
|
3582
|
+
function addDeclaration(set, d) {
|
|
3583
|
+
const source = d.source.value;
|
|
3584
|
+
if (!d.specifiers.length)
|
|
3585
|
+
set.side(source);
|
|
3586
|
+
for (const s of d.specifiers) {
|
|
3587
|
+
if (t.isImportDefaultSpecifier(s))
|
|
3588
|
+
set.defaultImport(source, s.local.name);
|
|
3589
|
+
else if (t.isImportNamespaceSpecifier(s))
|
|
3590
|
+
set.namespace(source, s.local.name);
|
|
3591
|
+
else {
|
|
3592
|
+
const imported = t.isIdentifier(s.imported) ? s.imported.name : s.imported.value;
|
|
3593
|
+
if (d.importKind === 'type' || s.importKind === 'type')
|
|
3594
|
+
set.type(source, imported, s.local.name);
|
|
3595
|
+
else
|
|
3596
|
+
set.named(source, imported, s.local.name);
|
|
3597
|
+
}
|
|
3598
|
+
}
|
|
3599
|
+
}
|
|
3600
|
+
/** A custom hook as a composable: same body rules as a component, returning refs as refs. */
|
|
3601
|
+
function emitHook(hook, script) {
|
|
3602
|
+
const items = script.items();
|
|
3603
|
+
const cut = cutLeftoverJsx(items);
|
|
3604
|
+
const params = hook.params.filter((p) => !t.isTSParameterProperty(p)).map((p) => script.r(mapReactTypes(t.cloneNode(p, true), 'vue', script.facts.reactNames, script.typeImports)));
|
|
3605
|
+
const body = [...items];
|
|
3606
|
+
if (hook.returns)
|
|
3607
|
+
body.push(t.returnStatement(composableReturn(hook, script, hook.returns)));
|
|
3608
|
+
if (cutLeftoverJsx(body) + cut)
|
|
3609
|
+
script.warn('jsx-in-script', `${hook.name} returns or builds elements, which have no form outside a template.`, 'error');
|
|
3610
|
+
const fn = t.functionDeclaration(t.identifier(hook.name), params, t.blockStatement(body));
|
|
3611
|
+
if (hook.typeParams)
|
|
3612
|
+
fn.typeParameters = t.cloneNode(hook.typeParams, true);
|
|
3613
|
+
return hook.exported ? t.exportNamedDeclaration(fn) : fn;
|
|
3614
|
+
}
|
|
3615
|
+
function composableReturn(hook, script, ret) {
|
|
3616
|
+
const value = (e) => {
|
|
3617
|
+
// a context the hook checked is there: returned as React's types see it after the check
|
|
3618
|
+
if (guardedContext(hook, e) && t.isIdentifier(e)) {
|
|
3619
|
+
const vueRef = script.facts.reactNames.has('Ref') ? 'VueRef' : 'Ref';
|
|
3620
|
+
script.typeImports.push(vueRef === 'Ref' ? { source: 'vue', name: 'Ref' } : { source: 'vue', name: 'Ref', local: 'VueRef' });
|
|
3621
|
+
const narrowed = t.tsTypeReference(t.identifier('NonNullable'), t.tsTypeParameterInstantiation([t.tsTypeQuery(t.tsQualifiedName(t.identifier(e.name), t.identifier('value')))]));
|
|
3622
|
+
return t.tsAsExpression(t.identifier(e.name), t.tsTypeReference(t.identifier('Readonly'), t.tsTypeParameterInstantiation([t.tsTypeReference(t.identifier(vueRef), t.tsTypeParameterInstantiation([narrowed]))])));
|
|
3623
|
+
}
|
|
3624
|
+
// a state setter returned by name (`set: setValue`) has no declaration in Vue: the function that sets the ref
|
|
3625
|
+
const setter = t.isIdentifier(e) && hook.bindings.get(hook.refs.get(e) ?? '')?.kind === 'setter';
|
|
3626
|
+
if (t.isIdentifier(e) && hook.refs.get(e) && !setter)
|
|
3627
|
+
return e;
|
|
3628
|
+
if (t.isFunction(e) || setter)
|
|
3629
|
+
return script.r(e);
|
|
3630
|
+
const reads = [...bindingsUsed(e, hook)].some((n) => {
|
|
3631
|
+
const b = hook.bindings.get(n);
|
|
3632
|
+
return b && (b.reactive || b.kind === 'state' || b.kind === 'reducer');
|
|
3633
|
+
});
|
|
3634
|
+
const rewritten = script.r(e);
|
|
3635
|
+
return reads ? t.callExpression(t.identifier(script.api('computed')), [t.arrowFunctionExpression([], rewritten)]) : rewritten;
|
|
3636
|
+
};
|
|
3637
|
+
const r = unwrap(ret);
|
|
3638
|
+
// a tuple computed in the script (`[value === undefined ? own : value, set] as const` reading a live argument): the
|
|
3639
|
+
// value is a computed of the whole tuple, which a caller cannot destructure; each member is returned on its own,
|
|
3640
|
+
// a reactive one as a computed of its place, so `const [page, setPage] = useValue(…)` works as in React
|
|
3641
|
+
const held = t.isIdentifier(r) ? hook.bindings.get(hook.refs.get(r) ?? '') : undefined;
|
|
3642
|
+
if (t.isIdentifier(r) && hook.returnShape.kind === 'array' && held?.reactive && held.kind !== 'function') {
|
|
3643
|
+
const at = (i) => t.memberExpression(t.memberExpression(t.identifier(r.name), t.identifier('value')), t.numericLiteral(i), true);
|
|
3644
|
+
const members = hook.returnShape.members.map((m, i) => (m.reactive ? t.callExpression(t.identifier(script.api('computed')), [t.arrowFunctionExpression([], at(i))]) : at(i)));
|
|
3645
|
+
return t.tsAsExpression(t.arrayExpression(members), t.tsTypeReference(t.identifier('const')));
|
|
3646
|
+
}
|
|
3647
|
+
if (t.isObjectExpression(r)) {
|
|
3648
|
+
for (const p of r.properties) {
|
|
3649
|
+
if (t.isObjectProperty(p) && t.isExpression(p.value)) {
|
|
3650
|
+
const v = value(p.value);
|
|
3651
|
+
if (v !== p.value)
|
|
3652
|
+
p.shorthand = false;
|
|
3653
|
+
p.value = v;
|
|
3654
|
+
}
|
|
3655
|
+
}
|
|
3656
|
+
return r;
|
|
3657
|
+
}
|
|
3658
|
+
if (t.isArrayExpression(r)) {
|
|
3659
|
+
r.elements = r.elements.map((el) => (el && t.isExpression(el) ? value(el) : el));
|
|
3660
|
+
// `[value, setValue] as const` stays a tuple, so a caller's destructured names keep their own types
|
|
3661
|
+
return t.isTSAsExpression(ret) && t.isTSTypeReference(ret.typeAnnotation) && t.isIdentifier(ret.typeAnnotation.typeName, { name: 'const' }) ? t.tsAsExpression(r, ret.typeAnnotation) : r;
|
|
3662
|
+
}
|
|
3663
|
+
return value(r);
|
|
3664
|
+
}
|
|
3665
|
+
/**
|
|
3666
|
+
* React types an event by the element it is bound on (`KeyboardEvent<HTMLDivElement>`: `currentTarget` is that div);
|
|
3667
|
+
* Vue's event props take the plain DOM event. Such a parameter is typed as the DOM event, and its `currentTarget` (and,
|
|
3668
|
+
* for change and input events, `target`) reads say which element it is, as React's type did.
|
|
3669
|
+
*/
|
|
3670
|
+
function nativeEventParams(statements) {
|
|
3671
|
+
// `Event & { currentTarget: El }`, or a union of such with the same element (`PointerEvent<El> | MouseEvent<El>` in
|
|
3672
|
+
// React): the DOM event (the union of them) and the element each target member names
|
|
3673
|
+
const split = (ann) => {
|
|
3674
|
+
const inner = t.isTSParenthesizedType(ann) ? ann.typeAnnotation : ann;
|
|
3675
|
+
if (t.isTSUnionType(inner)) {
|
|
3676
|
+
// an optional parameter's `| undefined` (or `| null`) stays as it is
|
|
3677
|
+
const isEmpty = (x) => t.isTSUndefinedKeyword(x) || t.isTSNullKeyword(x);
|
|
3678
|
+
const empty = inner.types.filter(isEmpty);
|
|
3679
|
+
const parts = inner.types.filter((x) => !isEmpty(x)).map(split);
|
|
3680
|
+
const [first] = parts;
|
|
3681
|
+
if (!first || !parts.every((x) => x !== null))
|
|
3682
|
+
return null;
|
|
3683
|
+
const key = (m) => [...m].map(([k, v]) => `${k}:${printExpr(t.tsAsExpression(t.identifier('x'), v))}`).sort().join(',');
|
|
3684
|
+
if (!parts.every((x) => key(x.targets) === key(first.targets)))
|
|
3685
|
+
return null;
|
|
3686
|
+
return { event: t.tsUnionType([...parts.map((x) => x.event), ...empty]), targets: first.targets };
|
|
3687
|
+
}
|
|
3688
|
+
if (!t.isTSIntersectionType(inner) || inner.types.length !== 2)
|
|
3689
|
+
return null;
|
|
3690
|
+
const [event, extra] = inner.types;
|
|
3691
|
+
if (!event || !t.isTSTypeReference(event) || !t.isTSTypeLiteral(extra))
|
|
3692
|
+
return null;
|
|
3693
|
+
const targets = new Map();
|
|
3694
|
+
for (const m of extra.members) {
|
|
3695
|
+
if (t.isTSPropertySignature(m) && t.isIdentifier(m.key) && (m.key.name === 'currentTarget' || m.key.name === 'target') && m.typeAnnotation)
|
|
3696
|
+
targets.set(m.key.name, m.typeAnnotation.typeAnnotation);
|
|
3697
|
+
}
|
|
3698
|
+
return targets.size && targets.size === extra.members.length ? { event, targets } : null;
|
|
3699
|
+
};
|
|
3700
|
+
const fix = (fn) => {
|
|
3701
|
+
for (const p of fn.params) {
|
|
3702
|
+
const ann = t.isIdentifier(p) && p.typeAnnotation && t.isTSTypeAnnotation(p.typeAnnotation) ? p.typeAnnotation.typeAnnotation : null;
|
|
3703
|
+
if (t.isIdentifier(p) && ann && domEventType(ann)) {
|
|
3704
|
+
// React's `e.nativeEvent` is the DOM event, which is what Vue hands the handler
|
|
3705
|
+
fn.body = nativeEventReads(fn.body, p.name);
|
|
3706
|
+
}
|
|
3707
|
+
const parts = ann ? split(ann) : null;
|
|
3708
|
+
if (!t.isIdentifier(p) || !parts)
|
|
3709
|
+
continue;
|
|
3710
|
+
const { event, targets } = parts;
|
|
3711
|
+
const name = p.name;
|
|
3712
|
+
// an optional event whose element is read (`e?.currentTarget.x`): a cast would cut the optional chain, so the
|
|
3713
|
+
// parameter keeps React's type
|
|
3714
|
+
if (t.isTSUnionType(event) && event.types.some((x) => t.isTSUndefinedKeyword(x) || t.isTSNullKeyword(x))) {
|
|
3715
|
+
let read = false;
|
|
3716
|
+
t.traverseFast(fn.body, (n) => {
|
|
3717
|
+
if ((t.isMemberExpression(n) || t.isOptionalMemberExpression(n)) && t.isIdentifier(n.object, { name }) && t.isIdentifier(n.property) && !n.computed && targets.has(n.property.name))
|
|
3718
|
+
read = true;
|
|
3719
|
+
});
|
|
3720
|
+
if (read)
|
|
3721
|
+
continue;
|
|
3722
|
+
}
|
|
3723
|
+
p.typeAnnotation = t.tsTypeAnnotation(event);
|
|
3724
|
+
t.traverseFast(fn.body, (n) => {
|
|
3725
|
+
// a read already cast (this pass put it there) stays as it is
|
|
3726
|
+
if (t.isTSAsExpression(n))
|
|
3727
|
+
return;
|
|
3728
|
+
for (const key of t.VISITOR_KEYS[n.type] ?? []) {
|
|
3729
|
+
const swap = (child) => {
|
|
3730
|
+
if (!t.isMemberExpression(child) && !t.isOptionalMemberExpression(child))
|
|
3731
|
+
return child;
|
|
3732
|
+
const m = child;
|
|
3733
|
+
if (m.computed || !t.isIdentifier(m.object, { name }) || !t.isIdentifier(m.property))
|
|
3734
|
+
return child;
|
|
3735
|
+
const type = targets.get(m.property.name);
|
|
3736
|
+
return type ? t.parenthesizedExpression(t.tsAsExpression(m, t.cloneNode(type, true))) : child;
|
|
3737
|
+
};
|
|
3738
|
+
const value = childAt(n, key);
|
|
3739
|
+
if (Array.isArray(value))
|
|
3740
|
+
setChildAt(n, key, value.map(swap));
|
|
3741
|
+
else
|
|
3742
|
+
setChildAt(n, key, swap(value));
|
|
3743
|
+
}
|
|
3744
|
+
});
|
|
3745
|
+
}
|
|
3746
|
+
};
|
|
3747
|
+
// a function type with such a parameter (`onClick?: (event: MouseEvent & { currentTarget: … }) => void`) takes the
|
|
3748
|
+
// plain DOM event too, as what Vue hands on
|
|
3749
|
+
const plain = (fn) => {
|
|
3750
|
+
for (const p of fn.parameters) {
|
|
3751
|
+
const ann = t.isIdentifier(p) && p.typeAnnotation && t.isTSTypeAnnotation(p.typeAnnotation) ? p.typeAnnotation.typeAnnotation : null;
|
|
3752
|
+
const parts = ann ? split(ann) : null;
|
|
3753
|
+
if (parts && t.isIdentifier(p))
|
|
3754
|
+
p.typeAnnotation = t.tsTypeAnnotation(parts.event);
|
|
3755
|
+
}
|
|
3756
|
+
};
|
|
3757
|
+
for (const s of statements) {
|
|
3758
|
+
t.traverseFast(s, (n) => {
|
|
3759
|
+
if (t.isFunction(n))
|
|
3760
|
+
fix(n);
|
|
3761
|
+
if (t.isTSFunctionType(n))
|
|
3762
|
+
plain(n);
|
|
3763
|
+
});
|
|
3764
|
+
}
|
|
3765
|
+
return statements;
|
|
3766
|
+
}
|
|
3767
|
+
/**
|
|
3768
|
+
* An effect's returned cleanup, handed to Vue's onCleanup. A function written in place goes as it is; anything else (a
|
|
3769
|
+
* core's return value, which may be nothing) goes only when it is a function.
|
|
3770
|
+
*/
|
|
3771
|
+
function cleanupWith(onCleanup, value, alloc) {
|
|
3772
|
+
if (t.isArrowFunctionExpression(value) || t.isFunctionExpression(value))
|
|
3773
|
+
return [t.expressionStatement(t.callExpression(t.cloneNode(onCleanup), [value]))];
|
|
3774
|
+
const stop = alloc.alloc('stop');
|
|
3775
|
+
return [
|
|
3776
|
+
t.variableDeclaration('const', [t.variableDeclarator(t.identifier(stop), value)]),
|
|
3777
|
+
t.ifStatement(t.binaryExpression('===', t.unaryExpression('typeof', t.identifier(stop)), t.stringLiteral('function')), t.expressionStatement(t.callExpression(t.cloneNode(onCleanup), [t.identifier(stop)]))),
|
|
3778
|
+
];
|
|
3779
|
+
}
|
|
3780
|
+
/** The members script code reads on a ref's element (`x.current.value`, `x.current?.focus()`). */
|
|
3781
|
+
function elementReads(comp, name) {
|
|
3782
|
+
const out = new Set();
|
|
3783
|
+
// the ref's box read as React wrote it (`ref.current`) or as the setup script already rewrote it (`ref.value`, a new
|
|
3784
|
+
// identifier of the same name that no longer maps to the binding)
|
|
3785
|
+
const boxRead = (p) => t.isIdentifier(p, { name: 'current' }) || t.isIdentifier(p, { name: 'value' });
|
|
3786
|
+
const isRef = (id) => (comp.refs.get(id) ?? id.name) === name;
|
|
3787
|
+
// local names a function body sets to the ref's value (`const el = ref.current`)
|
|
3788
|
+
const aliases = new Set();
|
|
3789
|
+
for (const item of comp.items) {
|
|
3790
|
+
for (const value of Object.values(item)) {
|
|
3791
|
+
if (!t.isNode(value))
|
|
3792
|
+
continue;
|
|
3793
|
+
t.traverseFast(value, (n) => {
|
|
3794
|
+
if (!t.isVariableDeclarator(n) || !t.isIdentifier(n.id) || !n.init)
|
|
3795
|
+
return;
|
|
3796
|
+
const init = n.init;
|
|
3797
|
+
if ((t.isMemberExpression(init) || t.isOptionalMemberExpression(init)) && !init.computed && boxRead(init.property) && t.isIdentifier(init.object) && isRef(init.object))
|
|
3798
|
+
aliases.add(n.id.name);
|
|
3799
|
+
});
|
|
3800
|
+
}
|
|
3801
|
+
}
|
|
3802
|
+
for (const item of comp.items) {
|
|
3803
|
+
for (const value of Object.values(item)) {
|
|
3804
|
+
if (!t.isNode(value))
|
|
3805
|
+
continue;
|
|
3806
|
+
t.traverseFast(value, (n) => {
|
|
3807
|
+
if (!(t.isMemberExpression(n) || t.isOptionalMemberExpression(n)) || n.computed || !t.isIdentifier(n.property))
|
|
3808
|
+
return;
|
|
3809
|
+
const inner = n.object;
|
|
3810
|
+
if ((t.isMemberExpression(inner) || t.isOptionalMemberExpression(inner)) && !inner.computed && boxRead(inner.property) && t.isIdentifier(inner.object) && isRef(inner.object))
|
|
3811
|
+
out.add(n.property.name);
|
|
3812
|
+
// through a name that holds it (`const stageEl = stageRef.current; stageEl.getBoundingClientRect()`)
|
|
3813
|
+
if (t.isIdentifier(inner) && aliases.has(inner.name))
|
|
3814
|
+
out.add(n.property.name);
|
|
3815
|
+
});
|
|
3816
|
+
}
|
|
3817
|
+
}
|
|
3818
|
+
return [...out];
|
|
3819
|
+
}
|
|
3820
|
+
/** The local name of a component's `children` prop, if it has one. */
|
|
3821
|
+
function childrenLocal(ir) {
|
|
3822
|
+
const isComponent = (x) => 'template' in x;
|
|
3823
|
+
return isComponent(ir) ? ir.props.find((p) => p.key === 'children')?.local : undefined;
|
|
3824
|
+
}
|
|
3825
|
+
/**
|
|
3826
|
+
* The places script code only tests whether children were given (`!children`, `children ? a : b`, `if (children)`,
|
|
3827
|
+
* `children || !errors?.length` as a test): where each such read sits, so it can be replaced.
|
|
3828
|
+
*/
|
|
3829
|
+
function childrenTests(root, ir, local) {
|
|
3830
|
+
const out = [];
|
|
3831
|
+
const visit = (n, truthy) => {
|
|
3832
|
+
for (const key of t.VISITOR_KEYS[n.type] ?? []) {
|
|
3833
|
+
const test = ((t.isIfStatement(n) || t.isConditionalExpression(n) || t.isWhileStatement(n) || t.isDoWhileStatement(n) || t.isForStatement(n)) && key === 'test') || t.isUnaryExpression(n, { operator: '!' });
|
|
3834
|
+
const inner = test || (t.isLogicalExpression(n) && (truthy || (n.operator === '&&' && key === 'left')));
|
|
3835
|
+
const held = childAt(n, key);
|
|
3836
|
+
const each = (child, index) => {
|
|
3837
|
+
if (!t.isNode(child))
|
|
3838
|
+
return;
|
|
3839
|
+
if (inner && t.isIdentifier(child) && ir.refs.get(child) === local)
|
|
3840
|
+
out.push({ holder: n, key, index });
|
|
3841
|
+
else
|
|
3842
|
+
visit(child, inner);
|
|
3843
|
+
};
|
|
3844
|
+
if (Array.isArray(held))
|
|
3845
|
+
held.forEach((c, i) => each(c, i));
|
|
3846
|
+
else
|
|
3847
|
+
each(held, null);
|
|
3848
|
+
}
|
|
3849
|
+
};
|
|
3850
|
+
visit(root, false);
|
|
3851
|
+
return out;
|
|
3852
|
+
}
|
|
3853
|
+
/** Whether script code reads the children as a value (not only tests whether they were given). */
|
|
3854
|
+
function childrenReadAsValue(comp, local) {
|
|
3855
|
+
let reads = 0;
|
|
3856
|
+
let tests = 0;
|
|
3857
|
+
for (const item of comp.items) {
|
|
3858
|
+
for (const value of Object.values(item)) {
|
|
3859
|
+
const roots = Array.isArray(value) ? value : [value];
|
|
3860
|
+
for (const root of roots) {
|
|
3861
|
+
if (!t.isNode(root))
|
|
3862
|
+
continue;
|
|
3863
|
+
t.traverseFast(root, (n) => void (t.isIdentifier(n) && comp.refs.get(n) === local && reads++));
|
|
3864
|
+
tests += childrenTests(root, comp, local).length;
|
|
3865
|
+
}
|
|
3866
|
+
}
|
|
3867
|
+
}
|
|
3868
|
+
return reads > tests;
|
|
3869
|
+
}
|
|
3870
|
+
/** Whether any script item reads a component binding. */
|
|
3871
|
+
function itemsRead(comp, name) {
|
|
3872
|
+
let found = false;
|
|
3873
|
+
const check = (node) => {
|
|
3874
|
+
if (!node || found)
|
|
3875
|
+
return;
|
|
3876
|
+
t.traverseFast(node, (n) => {
|
|
3877
|
+
if (t.isIdentifier(n) && comp.refs.get(n) === name)
|
|
3878
|
+
found = true;
|
|
3879
|
+
});
|
|
3880
|
+
};
|
|
3881
|
+
for (const item of comp.items) {
|
|
3882
|
+
if (item.kind === 'derived')
|
|
3883
|
+
check(item.init);
|
|
3884
|
+
else if (item.kind === 'block')
|
|
3885
|
+
item.statements.forEach(check);
|
|
3886
|
+
else if (item.kind === 'function')
|
|
3887
|
+
check(item.node);
|
|
3888
|
+
else if (item.kind === 'effect')
|
|
3889
|
+
check(item.body);
|
|
3890
|
+
else if (item.kind === 'hook')
|
|
3891
|
+
check(item.call);
|
|
3892
|
+
else if (item.kind === 'statement')
|
|
3893
|
+
check(item.node);
|
|
3894
|
+
else if (item.kind === 'state')
|
|
3895
|
+
check(item.init);
|
|
3896
|
+
}
|
|
3897
|
+
return found;
|
|
3898
|
+
}
|
|
3899
|
+
/**
|
|
3900
|
+
* Where a file of the conversion takes a name it imports by name (`import type { Layer } from './layer'`): the project
|
|
3901
|
+
* file and the name it exports there. Null when the file declares the name itself, or imports it from a package.
|
|
3902
|
+
*/
|
|
3903
|
+
function importedThrough(file, name, ctx) {
|
|
3904
|
+
const mod = ctx.moduleOf?.(file);
|
|
3905
|
+
if (!mod)
|
|
3906
|
+
return null;
|
|
3907
|
+
for (const decl of mod.imports) {
|
|
3908
|
+
for (const s of decl.specifiers) {
|
|
3909
|
+
if (s.local.name !== name || !t.isImportSpecifier(s))
|
|
3910
|
+
continue;
|
|
3911
|
+
const from = resolveLocal(file, decl.source.value, ctx.project);
|
|
3912
|
+
return from ? { file: from, imported: t.isIdentifier(s.imported) ? s.imported.name : s.imported.value } : null;
|
|
3913
|
+
}
|
|
3914
|
+
}
|
|
3915
|
+
return null;
|
|
3916
|
+
}
|
|
3917
|
+
/** The return statements of a function body that return from it (not from a function nested in it). */
|
|
3918
|
+
function ownReturns(body) {
|
|
3919
|
+
const out = [];
|
|
3920
|
+
const visit = (n) => {
|
|
3921
|
+
if (t.isFunction(n) || t.isClass(n))
|
|
3922
|
+
return;
|
|
3923
|
+
if (t.isReturnStatement(n))
|
|
3924
|
+
out.push(n);
|
|
3925
|
+
for (const key of t.VISITOR_KEYS[n.type] ?? []) {
|
|
3926
|
+
const child = Reflect.get(n, key);
|
|
3927
|
+
for (const c of Array.isArray(child) ? child : [child])
|
|
3928
|
+
if (t.isNode(c))
|
|
3929
|
+
visit(c);
|
|
3930
|
+
}
|
|
3931
|
+
};
|
|
3932
|
+
for (const s of body.body)
|
|
3933
|
+
visit(s);
|
|
3934
|
+
return out;
|
|
3935
|
+
}
|
|
3936
|
+
/** A test that only reads values (names, members, literals and operators, no call, assignment or update). */
|
|
3937
|
+
function plainTest(e) {
|
|
3938
|
+
let plain = true;
|
|
3939
|
+
t.traverseFast(e, (n) => {
|
|
3940
|
+
if (t.isCallExpression(n) || t.isOptionalCallExpression(n) || t.isNewExpression(n) || t.isAssignmentExpression(n) || t.isUpdateExpression(n) || t.isFunction(n) || t.isTaggedTemplateExpression(n) || t.isAwaitExpression(n) || t.isYieldExpression(n) || t.isJSX(n))
|
|
3941
|
+
plain = false;
|
|
3942
|
+
});
|
|
3943
|
+
return plain;
|
|
3944
|
+
}
|
|
3945
|
+
/** A test turned around, written as a person would (`a === b` for `!(a !== b)`, `x` for `!x`). */
|
|
3946
|
+
function negated(test) {
|
|
3947
|
+
const e = unwrap(test);
|
|
3948
|
+
if (t.isUnaryExpression(e, { operator: '!' }))
|
|
3949
|
+
return e.argument;
|
|
3950
|
+
const flip = { '===': '!==', '!==': '===', '==': '!=', '!=': '==' };
|
|
3951
|
+
const op = t.isBinaryExpression(e) ? flip[e.operator] : undefined;
|
|
3952
|
+
if (t.isBinaryExpression(e) && op && t.isExpression(e.left))
|
|
3953
|
+
return t.binaryExpression(op, e.left, e.right);
|
|
3954
|
+
return t.unaryExpression('!', t.isIdentifier(e) || t.isMemberExpression(e) ? e : t.parenthesizedExpression(e));
|
|
3955
|
+
}
|
|
3956
|
+
/** What the default slot renders: `slots.default?.()`. */
|
|
3957
|
+
function slotNodes(slots) {
|
|
3958
|
+
return t.optionalCallExpression(t.memberExpression(t.identifier(slots), t.identifier('default')), [], true);
|
|
3959
|
+
}
|
|
3960
|
+
/** The globals a Vue template reads directly (Vue's own list, `GLOBALS_ALLOWED` in @vue/shared); any other is the component's. */
|
|
3961
|
+
const VUE_TEMPLATE_GLOBALS = new Set('Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol'.split(','));
|
|
3962
|
+
/** Node's own globals a page does not have: never given to a template as the page's. */
|
|
3963
|
+
const NODE_ONLY = new Set(['process', 'Buffer', 'global', 'require', 'module', 'exports', '__dirname', '__filename']);
|
|
3964
|
+
/** Names the browser gives every page that Node's own global object does not have. */
|
|
3965
|
+
const BROWSER_GLOBALS = new Set(['window', 'document', 'navigator', 'location', 'history', 'localStorage', 'sessionStorage', 'getComputedStyle', 'matchMedia', 'requestAnimationFrame', 'cancelAnimationFrame', 'innerWidth', 'innerHeight', 'devicePixelRatio', 'HTMLElement', 'Element', 'Node', 'Event', 'CustomEvent', 'KeyboardEvent', 'MouseEvent', 'PointerEvent', 'ResizeObserver', 'IntersectionObserver', 'MutationObserver', 'Image', 'CSS']);
|
|
3966
|
+
/** Removes a diagnostic the output no longer earns (the same object lowering reported). */
|
|
3967
|
+
function withdraw(list, diagnostic) {
|
|
3968
|
+
const at = list.indexOf(diagnostic);
|
|
3969
|
+
if (at >= 0)
|
|
3970
|
+
list.splice(at, 1);
|
|
3971
|
+
}
|
|
3972
|
+
/** Calls `visit` on every expression a template holds (values, tests, attributes, loops), outermost first. */
|
|
3973
|
+
function walkTNodeExpressions(node, visit) {
|
|
3974
|
+
if (Array.isArray(node)) {
|
|
3975
|
+
for (const x of node)
|
|
3976
|
+
walkTNodeExpressions(x, visit);
|
|
3977
|
+
return;
|
|
3978
|
+
}
|
|
3979
|
+
if (!node || typeof node !== 'object')
|
|
3980
|
+
return;
|
|
3981
|
+
if (t.isNode(node)) {
|
|
3982
|
+
if (t.isExpression(node))
|
|
3983
|
+
visit(node);
|
|
3984
|
+
return;
|
|
3985
|
+
}
|
|
3986
|
+
for (const value of Object.values(node))
|
|
3987
|
+
walkTNodeExpressions(value, visit);
|
|
3988
|
+
}
|
|
3989
|
+
/**
|
|
3990
|
+
* The bare renders (`{header}`) of a component's prop `local`, when it reads it only where a functional component behaves as React's element does: a
|
|
3991
|
+
* bare render of it in its template (`{header}`), a test of whether it is there (`x !== undefined`, `x == null`, `!x`,
|
|
3992
|
+
* `x && …`, a condition or branch test) or a dependency list. Anything else (passed on, called, `typeof`, a member, kept
|
|
3993
|
+
* in another name) could tell the two apart. Returns the bare renders, or null when some other read exists.
|
|
3994
|
+
*/
|
|
3995
|
+
function markupRenders(comp, local) {
|
|
3996
|
+
let ok = true;
|
|
3997
|
+
const renders = [];
|
|
3998
|
+
const check = (root, key) => {
|
|
3999
|
+
if (!ok)
|
|
4000
|
+
return;
|
|
4001
|
+
if (t.isIdentifier(root, { name: local })) {
|
|
4002
|
+
if (key !== 'deps' && key !== 'test')
|
|
4003
|
+
ok = false;
|
|
4004
|
+
return;
|
|
4005
|
+
}
|
|
4006
|
+
t.traverse(root, (n, ancestors) => {
|
|
4007
|
+
if (!t.isIdentifier(n, { name: local }))
|
|
4008
|
+
return;
|
|
4009
|
+
const at = ancestors[ancestors.length - 1];
|
|
4010
|
+
const parent = at?.node;
|
|
4011
|
+
if (!parent)
|
|
4012
|
+
return;
|
|
4013
|
+
// a property's key or a member's name is not a read
|
|
4014
|
+
if ((t.isMemberExpression(parent) || t.isOptionalMemberExpression(parent) || t.isObjectProperty(parent)) && !parent.computed && (at.key === 'property' || at.key === 'key'))
|
|
4015
|
+
return;
|
|
4016
|
+
const nothing = (e) => t.isNullLiteral(e) || t.isIdentifier(e, { name: 'undefined' });
|
|
4017
|
+
if (t.isBinaryExpression(parent) && ['===', '!==', '==', '!='].includes(parent.operator) && nothing(at.key === 'left' ? parent.right : parent.left))
|
|
4018
|
+
return;
|
|
4019
|
+
if (t.isUnaryExpression(parent, { operator: '!' }))
|
|
4020
|
+
return;
|
|
4021
|
+
// `typeof x === 'number'` (React's falsy-number branch): an element and a function both answer false; only
|
|
4022
|
+
// 'object' and 'function' tell them apart
|
|
4023
|
+
const outer = ancestors[ancestors.length - 2]?.node;
|
|
4024
|
+
if (t.isUnaryExpression(parent, { operator: 'typeof' }) && t.isBinaryExpression(outer) && ['===', '!==', '==', '!='].includes(outer.operator)) {
|
|
4025
|
+
const other = outer.left === parent ? outer.right : outer.left;
|
|
4026
|
+
if (t.isStringLiteral(other) && other.value !== 'object' && other.value !== 'function')
|
|
4027
|
+
return;
|
|
4028
|
+
}
|
|
4029
|
+
if (t.isLogicalExpression(parent, { operator: '&&' }) && at.key === 'left')
|
|
4030
|
+
return;
|
|
4031
|
+
if ((t.isConditionalExpression(parent) || t.isIfStatement(parent)) && at.key === 'test')
|
|
4032
|
+
return;
|
|
4033
|
+
ok = false;
|
|
4034
|
+
});
|
|
4035
|
+
};
|
|
4036
|
+
const walk = (value, key, inTemplate) => {
|
|
4037
|
+
if (!ok || !value || typeof value !== 'object')
|
|
4038
|
+
return;
|
|
4039
|
+
if (Array.isArray(value)) {
|
|
4040
|
+
for (const x of value)
|
|
4041
|
+
walk(x, key, inTemplate);
|
|
4042
|
+
return;
|
|
4043
|
+
}
|
|
4044
|
+
if (t.isNode(value)) {
|
|
4045
|
+
check(value, key);
|
|
4046
|
+
return;
|
|
4047
|
+
}
|
|
4048
|
+
if (value instanceof Map || value instanceof Set || value instanceof WeakMap)
|
|
4049
|
+
return;
|
|
4050
|
+
// the template's bare render of it (`{header}`) is the render the receiver prints as markup
|
|
4051
|
+
const bare = inTemplate && Reflect.get(value, 'type') === 'expr' ? Reflect.get(value, 'expr') : null;
|
|
4052
|
+
if (t.isNode(bare) && t.isIdentifier(bare, { name: local })) {
|
|
4053
|
+
renders.push(bare);
|
|
4054
|
+
return;
|
|
4055
|
+
}
|
|
4056
|
+
for (const [k, v] of Object.entries(value))
|
|
4057
|
+
walk(v, k, inTemplate);
|
|
4058
|
+
};
|
|
4059
|
+
walk(comp.template, '', true);
|
|
4060
|
+
for (const f of comp.fragments)
|
|
4061
|
+
walk(f.template, '', true);
|
|
4062
|
+
for (const item of comp.items)
|
|
4063
|
+
walk(item, '', false);
|
|
4064
|
+
return ok ? renders : null;
|
|
4065
|
+
}
|
|
4066
|
+
/** The first read of a component's name `local` in its script code (its items), or null. */
|
|
4067
|
+
function scriptReadOf(comp, local) {
|
|
4068
|
+
let found = null;
|
|
4069
|
+
const walk = (value) => {
|
|
4070
|
+
if (found || !value || typeof value !== 'object')
|
|
4071
|
+
return;
|
|
4072
|
+
if (Array.isArray(value)) {
|
|
4073
|
+
for (const x of value)
|
|
4074
|
+
walk(x);
|
|
4075
|
+
return;
|
|
4076
|
+
}
|
|
4077
|
+
if (t.isNode(value)) {
|
|
4078
|
+
t.traverseFast(value, (n) => {
|
|
4079
|
+
if (!found && t.isIdentifier(n) && comp.refs.get(n) === local)
|
|
4080
|
+
found = n;
|
|
4081
|
+
});
|
|
4082
|
+
return;
|
|
4083
|
+
}
|
|
4084
|
+
if (value instanceof Map || value instanceof Set || value instanceof WeakMap)
|
|
4085
|
+
return;
|
|
4086
|
+
for (const v of Object.values(value))
|
|
4087
|
+
walk(v);
|
|
4088
|
+
};
|
|
4089
|
+
for (const item of comp.items)
|
|
4090
|
+
walk(item);
|
|
4091
|
+
return found;
|
|
4092
|
+
}
|