|
| 1 | +import map_children from './shared/map_children'; |
| 2 | +import Component from '../Component'; |
| 3 | +import TemplateScope from './shared/TemplateScope'; |
| 4 | +import Node from './shared/Node'; |
| 5 | +import Let from './Let'; |
| 6 | +import Attribute from './Attribute'; |
| 7 | +import { INode } from './interfaces'; |
| 8 | + |
| 9 | +export default class SlotTemplate extends Node { |
| 10 | + type: 'SlotTemplate'; |
| 11 | + scope: TemplateScope; |
| 12 | + children: INode[]; |
| 13 | + lets: Let[] = []; |
| 14 | + slot_attribute: Attribute; |
| 15 | + slot_name: string = 'default'; |
| 16 | + |
| 17 | + constructor(component: Component, parent: INode, scope: TemplateScope, info: any) { |
| 18 | + super(component, parent, scope, info); |
| 19 | + |
| 20 | + this.validate_slot_template_placement(); |
| 21 | + |
| 22 | + const has_let = info.attributes.some(node => node.type === 'Let'); |
| 23 | + if (has_let) { |
| 24 | + scope = scope.child(); |
| 25 | + } |
| 26 | + |
| 27 | + info.attributes.forEach(node => { |
| 28 | + switch (node.type) { |
| 29 | + case 'Let': { |
| 30 | + const l = new Let(component, this, scope, node); |
| 31 | + this.lets.push(l); |
| 32 | + const dependencies = new Set([l.name.name]); |
| 33 | + |
| 34 | + l.names.forEach(name => { |
| 35 | + scope.add(name, dependencies, this); |
| 36 | + }); |
| 37 | + break; |
| 38 | + } |
| 39 | + case 'Attribute': { |
| 40 | + if (node.name === 'slot') { |
| 41 | + this.slot_attribute = new Attribute(component, this, scope, node); |
| 42 | + if (!this.slot_attribute.is_static) { |
| 43 | + component.error(node, { |
| 44 | + code: `invalid-slot-attribute`, |
| 45 | + message: `slot attribute cannot have a dynamic value` |
| 46 | + }); |
| 47 | + } |
| 48 | + const value = this.slot_attribute.get_static_value(); |
| 49 | + if (typeof value === 'boolean') { |
| 50 | + component.error(node, { |
| 51 | + code: `invalid-slot-attribute`, |
| 52 | + message: `slot attribute value is missing` |
| 53 | + }); |
| 54 | + } |
| 55 | + this.slot_name = this.slot_attribute.get_static_value() as string; |
| 56 | + break; |
| 57 | + } |
| 58 | + throw new Error(`Invalid attribute "${node.name}" in <svelte:slot>`); |
| 59 | + } |
| 60 | + default: |
| 61 | + throw new Error(`Not implemented: ${node.type}`); |
| 62 | + } |
| 63 | + }); |
| 64 | + |
| 65 | + this.scope = scope; |
| 66 | + this.children = map_children(component, this, this.scope, info.children); |
| 67 | + } |
| 68 | + |
| 69 | + validate_slot_template_placement() { |
| 70 | + if (this.parent.type !== 'InlineComponent') { |
| 71 | + this.component.error(this, { |
| 72 | + code: `invalid-slotted-content`, |
| 73 | + message: `Element with a slot='...' attribute must be a child of a component` |
| 74 | + }); |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments