implement :shorthand attributes

pull/384/head
Rich Harris 8 years ago
parent ecf141346e
commit e6d088d753

@ -204,7 +204,7 @@ function readTagName ( parser ) {
function readAttribute ( parser, uniqueNames ) {
const start = parser.index;
const name = parser.readUntil( /(\s|=|\/|>)/ );
let name = parser.readUntil( /(\s|=|\/|>)/ );
if ( !name ) return null;
if ( uniqueNames.has( name ) ) {
parser.error( 'Attributes need to be unique', start );
@ -232,7 +232,15 @@ function readAttribute ( parser, uniqueNames ) {
};
}
const value = parser.eat( '=' ) ? readAttributeValue( parser ) : true;
let value;
// :foo is shorthand for foo='{{foo}}'
if ( /^:\w+$/.test( name ) ) {
name = name.slice( 1 );
value = getShorthandValue( start + 1, name );
} else {
value = parser.eat( '=' ) ? readAttributeValue( parser ) : true;
}
return {
start,
@ -312,3 +320,19 @@ function readAttributeValue ( parser ) {
parser.error( `Unexpected end of input` );
}
function getShorthandValue ( start, name ) {
const end = start + name.length;
return [{
type: 'AttributeShorthand',
start,
end,
expression: {
type: 'Identifier',
start,
end,
name
}
}];
}

@ -0,0 +1,10 @@
export default {
html: `<div id="foo"></div>`,
test ( assert, component, target ) {
component.set({ id: 'bar' });
assert.equal( target.innerHTML, `<div id="bar"></div>` );
component.teardown();
}
};

@ -0,0 +1,9 @@
<div :id/>
<script>
export default {
data: () => ({
id: 'foo'
})
};
</script>

@ -0,0 +1,17 @@
export default {
data: {
foo: 42
},
html: `<div><p>foo: 42</p></div>`,
test ( assert, component, target ) {
component.set({
foo: 99
});
assert.equal( target.innerHTML, `<div><p>foo: 99</p></div>` );
component.teardown();
}
};

@ -0,0 +1,11 @@
<div>
<Widget :foo/>
</div>
<script>
import Widget from './Widget.html';
export default {
components: { Widget }
};
</script>

@ -0,0 +1,40 @@
{
"hash": 4120363214,
"html": {
"start": 0,
"end": 10,
"type": "Fragment",
"children": [
{
"start": 0,
"end": 10,
"type": "Element",
"name": "div",
"attributes": [
{
"start": 5,
"end": 8,
"type": "Attribute",
"name": "id",
"value": [
{
"start": 6,
"end": 8,
"type": "AttributeShorthand",
"expression": {
"type": "Identifier",
"start": 6,
"end": 8,
"name": "id"
}
}
]
}
],
"children": []
}
]
},
"css": null,
"js": null
}
Loading…
Cancel
Save