Skip to content

Commit

Permalink
Merge pull request #1386 from sveltejs/gh-984
Browse files Browse the repository at this point in the history
width and height bindings
  • Loading branch information
Rich-Harris authored Apr 30, 2018
2 parents 4dcde4b + 8f8b130 commit 14f84a3
Show file tree
Hide file tree
Showing 14 changed files with 426 additions and 11 deletions.
18 changes: 15 additions & 3 deletions src/compile/nodes/Binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import flattenReference from '../../utils/flattenReference';
import Compiler from '../Compiler';
import Block from '../dom/Block';
import Expression from './shared/Expression';
import { dimensions } from '../../utils/patterns';

const readOnlyMediaAttributes = new Set([
'duration',
Expand All @@ -14,6 +15,9 @@ const readOnlyMediaAttributes = new Set([
'played'
]);

// TODO a lot of this element-specific stuff should live in Element —
// Binding should ideally be agnostic between Element and Component

export default class Binding extends Node {
name: string;
value: Expression;
Expand Down Expand Up @@ -57,7 +61,10 @@ export default class Binding extends Node {
const node: Element = this.parent;

const needsLock = node.name !== 'input' || !/radio|checkbox|range|color/.test(node.getStaticAttributeValue('type'));
const isReadOnly = node.isMediaNode() && readOnlyMediaAttributes.has(this.name);
const isReadOnly = (
(node.isMediaNode() && readOnlyMediaAttributes.has(this.name)) ||
dimensions.test(this.name)
);

let updateCondition: string;

Expand Down Expand Up @@ -103,8 +110,7 @@ export default class Binding extends Node {
if (this.name === 'currentTime' || this.name === 'volume') {
updateCondition = `!isNaN(${snippet})`;

if (this.name === 'currentTime')
initialUpdate = null;
if (this.name === 'currentTime') initialUpdate = null;
}

if (this.name === 'paused') {
Expand All @@ -117,6 +123,12 @@ export default class Binding extends Node {
initialUpdate = null;
}

// bind:offsetWidth and bind:offsetHeight
if (dimensions.test(this.name)) {
initialUpdate = null;
updateDom = null;
}

return {
name: this.name,
object: name,
Expand Down
44 changes: 36 additions & 8 deletions src/compile/nodes/Element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import Action from './Action';
import Text from './Text';
import * as namespaces from '../../utils/namespaces';
import mapChildren from './shared/mapChildren';
import { dimensions } from '../../utils/patterns';

// source: https://gist.github.com/ArjanSchouten/0b8574a6ad7f5065a5e7
const booleanAttributes = new Set('async autocomplete autofocus autoplay border challenge checked compact contenteditable controls default defer disabled formnovalidate frameborder hidden indeterminate ismap loop multiple muted nohref noresize noshade novalidate nowrap open readonly required reversed scoped scrolling seamless selected sortable spellcheck translate'.split(' '));
Expand Down Expand Up @@ -262,7 +263,7 @@ export default class Element extends Node {
parentNode;

block.addVariable(name);
const renderStatement = getRenderStatement(this.compiler, this.namespace, this.name);
const renderStatement = getRenderStatement(this.namespace, this.name);
block.builders.create.addLine(
`${name} = ${renderStatement};`
);
Expand Down Expand Up @@ -489,13 +490,27 @@ export default class Element extends Node {
`);

group.events.forEach(name => {
block.builders.hydrate.addLine(
`@addListener(${this.var}, "${name}", ${handler});`
);
if (name === 'resize') {
// special case
const resize_listener = block.getUniqueName(`${this.var}_resize_listener`);
block.addVariable(resize_listener);

block.builders.destroy.addLine(
`@removeListener(${this.var}, "${name}", ${handler});`
);
block.builders.mount.addLine(
`${resize_listener} = @addResizeListener(${this.var}, ${handler});`
);

block.builders.unmount.addLine(
`${resize_listener}.cancel();`
);
} else {
block.builders.hydrate.addLine(
`@addListener(${this.var}, "${name}", ${handler});`
);

block.builders.destroy.addLine(
`@removeListener(${this.var}, "${name}", ${handler});`
);
}
});

const allInitialStateIsDefined = group.bindings
Expand All @@ -509,6 +524,14 @@ export default class Element extends Node {
`if (!(${allInitialStateIsDefined})) #component.root._beforecreate.push(${handler});`
);
}

if (group.events[0] === 'resize') {
this.compiler.target.hasComplexBindings = true;

block.builders.hydrate.addLine(
`#component.root._beforecreate.push(${handler});`
);
}
});

this.initialUpdate = mungedBindings.map(binding => binding.initialUpdate).filter(Boolean).join('\n');
Expand Down Expand Up @@ -916,7 +939,6 @@ export default class Element extends Node {
}

function getRenderStatement(
compiler: Compiler,
namespace: string,
name: string
) {
Expand Down Expand Up @@ -971,6 +993,12 @@ const events = [
node.name === 'input' && /radio|checkbox|range/.test(node.getStaticAttributeValue('type'))
},

{
eventNames: ['resize'],
filter: (node: Element, name: string) =>
dimensions.test(name)
},

// media events
{
eventNames: ['timeupdate'],
Expand Down
29 changes: 29 additions & 0 deletions src/shared/dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,3 +193,32 @@ export function selectMultipleValue(select) {
return option.__value;
});
}

export function addResizeListener(element, fn) {
if (getComputedStyle(element).position === 'static') {
element.style.position = 'relative';
}

const object = document.createElement('object');
object.setAttribute('style', 'display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; pointer-events: none; z-index: -1;');
object.type = 'text/html';

object.onload = () => {
object.contentDocument.defaultView.addEventListener('resize', fn);
};

if (/Trident/.test(navigator.userAgent)) {
element.appendChild(object);
object.data = 'about:blank';
} else {
object.data = 'about:blank';
element.appendChild(object);
}

return {
cancel: () => {
object.contentDocument.defaultView.removeEventListener('resize', fn);
element.removeChild(object);
}
};
}
2 changes: 2 additions & 0 deletions src/utils/patterns.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export const whitespace = /[ \t\r\n]/;

export const dimensions = /^(?:offset|client)(?:Width|Height)$/;
19 changes: 19 additions & 0 deletions src/validate/html/validateElement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import * as namespaces from '../../utils/namespaces';
import validateEventHandler from './validateEventHandler';
import validate, { Validator } from '../index';
import { Node } from '../../interfaces';
import { dimensions } from '../../utils/patterns';
import isVoidElementName from '../../utils/isVoidElementName';

const svg = /^(?:altGlyph|altGlyphDef|altGlyphItem|animate|animateColor|animateMotion|animateTransform|circle|clipPath|color-profile|cursor|defs|desc|discard|ellipse|feBlend|feColorMatrix|feComponentTransfer|feComposite|feConvolveMatrix|feDiffuseLighting|feDisplacementMap|feDistantLight|feDropShadow|feFlood|feFuncA|feFuncB|feFuncG|feFuncR|feGaussianBlur|feImage|feMerge|feMergeNode|feMorphology|feOffset|fePointLight|feSpecularLighting|feSpotLight|feTile|feTurbulence|filter|font|font-face|font-face-format|font-face-name|font-face-src|font-face-uri|foreignObject|g|glyph|glyphRef|hatch|hatchpath|hkern|image|line|linearGradient|marker|mask|mesh|meshgradient|meshpatch|meshrow|metadata|missing-glyph|mpath|path|pattern|polygon|polyline|radialGradient|rect|set|solidcolor|stop|switch|symbol|text|textPath|tref|tspan|unknown|use|view|vkern)$/;

Expand Down Expand Up @@ -157,6 +159,23 @@ export default function validateElement(
message: `'${name}' binding can only be used with <audio> or <video>`
});
}
} else if (dimensions.test(name)) {
if (node.name === 'svg' && (name === 'offsetWidth' || name === 'offsetHeight')) {
validator.error(attribute, {
code: 'invalid-binding',
message: `'${attribute.name}' is not a valid binding on <svg>. Use '${name.replace('offset', 'client')}' instead`
});
} else if (svg.test(node.name)) {
validator.error(attribute, {
code: 'invalid-binding',
message: `'${attribute.name}' is not a valid binding on SVG elements`
});
} else if (isVoidElementName(node.name)) {
validator.error(attribute, {
code: 'invalid-binding',
message: `'${attribute.name}' is not a valid binding on void elements like <${node.name}>. Use a wrapper element instead`
});
}
} else {
validator.error(attribute, {
code: `invalid-binding`,
Expand Down
Loading

0 comments on commit 14f84a3

Please sign in to comment.