validate props, auto-generate props if unspecified

pull/811/head
Rich Harris 7 years ago
parent afe3e2e669
commit 30e58c4a73

@ -577,8 +577,8 @@ export default class Generator {
}
if (templateProperties.props) {
// TODO
this.props = templateProperties.props.value;
this.props = templateProperties.props.value.elements.map((element: Node) => element.value);
removeObjectKey(this.code, defaultExport.declaration, 'props');
}
// now that we've analysed the default export, we can determine whether or not we need to keep it

@ -232,12 +232,32 @@ export default function dom(
`;
if (generator.customElement) {
const props = generator.props || Array.from(generator.expectedProperties);
builder.addBlock(deindent`
class ${name} extends HTMLElement {
constructor(options = {}) {
super();
${constructorBody}
}
static get observedAttributes() {
return ${JSON.stringify(props)};
}
${props.map(prop => deindent`
get ${prop}() {
return this.get('${prop}');
}
set ${prop}(value) {
this.set({ ${prop}: value });
}
`).join('\n\n')}
attributeChangedCallback ( attr, oldValue, newValue ) {
this.set({ [attr]: newValue });
}
}
customElements.define('${generator.tag}', ${name});

@ -9,6 +9,7 @@ import methods from './methods';
import components from './components';
import events from './events';
import namespace from './namespace';
import props from './props';
import tag from './tag';
import transitions from './transitions';
import setup from './setup';
@ -25,6 +26,7 @@ export default {
components,
events,
namespace,
props,
tag,
transitions,
setup,

@ -0,0 +1,20 @@
import { Validator } from '../../';
import { Node } from '../../../interfaces';
export default function props(validator: Validator, prop: Node) {
if (prop.value.type !== 'ArrayExpression') {
validator.error(
`'props' must be an array expression, if specified`,
prop.value.start
);
}
prop.value.elements.forEach((element: Node) => {
if (element.type !== 'Literal' || typeof element.value !== 'string') {
validator.error(
`'props' must be an array of string literals`,
element.start
);
}
});
}

@ -1,4 +1,3 @@
import usesThisOrArguments from '../utils/usesThisOrArguments';
import { Validator } from '../../';
import { Node } from '../../../interfaces';

Loading…
Cancel
Save