bind to dimensions

pull/1386/head
Rich Harris 7 years ago
parent f00d08427e
commit 541ec6c397

@ -6,6 +6,7 @@ import flattenReference from '../../utils/flattenReference';
import Compiler from '../Compiler'; import Compiler from '../Compiler';
import Block from '../dom/Block'; import Block from '../dom/Block';
import Expression from './shared/Expression'; import Expression from './shared/Expression';
import { dimensions } from '../../utils/patterns';
const readOnlyMediaAttributes = new Set([ const readOnlyMediaAttributes = new Set([
'duration', 'duration',
@ -62,7 +63,7 @@ export default class Binding extends Node {
const needsLock = node.name !== 'input' || !/radio|checkbox|range|color/.test(node.getStaticAttributeValue('type')); const needsLock = node.name !== 'input' || !/radio|checkbox|range|color/.test(node.getStaticAttributeValue('type'));
const isReadOnly = ( const isReadOnly = (
(node.isMediaNode() && readOnlyMediaAttributes.has(this.name)) || (node.isMediaNode() && readOnlyMediaAttributes.has(this.name)) ||
this.name === 'width' || this.name === 'height' dimensions.test(this.name)
); );
let updateCondition: string; let updateCondition: string;
@ -122,8 +123,8 @@ export default class Binding extends Node {
initialUpdate = null; initialUpdate = null;
} }
// bind:width and bind:height // bind:offsetWidth and bind:offsetHeight
if (this.name === 'width' || this.name === 'height') { if (dimensions.test(this.name)) {
initialUpdate = null; initialUpdate = null;
updateDom = null; updateDom = null;
} }

@ -17,6 +17,7 @@ import Action from './Action';
import Text from './Text'; import Text from './Text';
import * as namespaces from '../../utils/namespaces'; import * as namespaces from '../../utils/namespaces';
import mapChildren from './shared/mapChildren'; import mapChildren from './shared/mapChildren';
import { dimensions } from '../../utils/patterns';
// source: https://gist.github.com/ArjanSchouten/0b8574a6ad7f5065a5e7 // 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(' ')); 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(' '));
@ -489,6 +490,19 @@ export default class Element extends Node {
`); `);
group.events.forEach(name => { group.events.forEach(name => {
if (name === 'resize') {
// special case
const resize_listener = block.getUniqueName(`${this.var}_resize_listener`);
block.addVariable(resize_listener);
block.builders.mount.addLine(
`${resize_listener} = @addResizeListener(${this.var}, ${handler});`
);
block.builders.unmount.addLine(
`${resize_listener}.cancel();`
);
} else {
block.builders.hydrate.addLine( block.builders.hydrate.addLine(
`@addListener(${this.var}, "${name}", ${handler});` `@addListener(${this.var}, "${name}", ${handler});`
); );
@ -496,6 +510,7 @@ export default class Element extends Node {
block.builders.destroy.addLine( block.builders.destroy.addLine(
`@removeListener(${this.var}, "${name}", ${handler});` `@removeListener(${this.var}, "${name}", ${handler});`
); );
}
}); });
const allInitialStateIsDefined = group.bindings const allInitialStateIsDefined = group.bindings
@ -509,6 +524,14 @@ export default class Element extends Node {
`if (!(${allInitialStateIsDefined})) #component.root._beforecreate.push(${handler});` `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'); this.initialUpdate = mungedBindings.map(binding => binding.initialUpdate).filter(Boolean).join('\n');
@ -973,7 +996,7 @@ const events = [
{ {
eventNames: ['resize'], eventNames: ['resize'],
filter: (node: Element, name: string) => filter: (node: Element, name: string) =>
(name === 'width' || name === 'height') dimensions.test(name)
}, },
// media events // media events

@ -203,14 +203,18 @@ export function addResizeListener(element, fn) {
object.setAttribute('style', 'display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; pointer-events: none; z-index: -1;'); 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.type = 'text/html';
if (isIE) element.appendChild(object);
object.data = 'about:blank';
if (!isIE) element.appendChild(object);
object.onload = () => { object.onload = () => {
object.contentDocument.defaultView.addEventListener('resize', fn); 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 { return {
cancel: () => { cancel: () => {
object.contentDocument.defaultView.removeEventListener('resize', fn); object.contentDocument.defaultView.removeEventListener('resize', fn);

@ -1 +1,3 @@
export const whitespace = /[ \t\r\n]/; export const whitespace = /[ \t\r\n]/;
export const dimensions = /^(?:offset|client)(?:Width|Height)$/;

@ -2,6 +2,7 @@ import * as namespaces from '../../utils/namespaces';
import validateEventHandler from './validateEventHandler'; import validateEventHandler from './validateEventHandler';
import validate, { Validator } from '../index'; import validate, { Validator } from '../index';
import { Node } from '../../interfaces'; import { Node } from '../../interfaces';
import { dimensions } from '../../utils/patterns';
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)$/; 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)$/;
@ -157,7 +158,7 @@ export default function validateElement(
message: `'${name}' binding can only be used with <audio> or <video>` message: `'${name}' binding can only be used with <audio> or <video>`
}); });
} }
} else if (name !== 'width' && name !== 'height') { } else if (!dimensions.test(name)) {
validator.error(attribute, { validator.error(attribute, {
code: `invalid-binding`, code: `invalid-binding`,
message: `'${attribute.name}' is not a valid binding` message: `'${attribute.name}' is not a valid binding`

@ -1,3 +0,0 @@
<div bind:width=w bind:height=h>
some content
</div>

@ -17,6 +17,35 @@ function createElement(name) {
return document.createElement(name); return document.createElement(name);
} }
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';
if (/Trident/.test(navigator.userAgent)) {
element.appendChild(object);
object.data = 'about:blank';
} else {
object.data = 'about:blank';
element.appendChild(object);
}
object.onload = () => {
object.contentDocument.defaultView.addEventListener('resize', fn);
};
return {
cancel: () => {
object.contentDocument.defaultView.removeEventListener('resize', fn);
element.removeChild(object);
}
};
}
function blankObject() { function blankObject() {
return Object.create(null); return Object.create(null);
} }
@ -136,19 +165,26 @@ var proto = {
/* generated by Svelte vX.Y.Z */ /* generated by Svelte vX.Y.Z */
function create_main_fragment(component, ctx) { function create_main_fragment(component, ctx) {
var div; var div, div_resize_listener;
function div_resize_handler() {
component.set({ w: div.offsetWidth, h: div.offsetHeight });
}
return { return {
c: function create() { c: function create() {
div = createElement("div"); div = createElement("div");
div.textContent = "some content"; div.textContent = "some content";
this.h();
},
h: function hydrate() {
div_resize_listener = addResizeListener(div, div_resize_handler);
component.root._beforecreate.push(div_resize_handler);
}, },
m: function mount(target, anchor) { m: function mount(target, anchor) {
insertNode(div, target, anchor); insertNode(div, target, anchor);
div.width = ctx.width ;
div.height = ctx.height;
}, },
p: noop, p: noop,
@ -157,7 +193,9 @@ function create_main_fragment(component, ctx) {
detachNode(div); detachNode(div);
}, },
d: noop d: function destroy$$1() {
div_resize_listener.cancel();
}
}; };
} }

@ -5,18 +5,19 @@ function create_main_fragment(component, ctx) {
var div, div_resize_listener; var div, div_resize_listener;
function div_resize_handler() { function div_resize_handler() {
component.set({ w: div.offsetWidth, h: offsetHeight }); component.set({ w: div.offsetWidth, h: div.offsetHeight });
} }
return { return {
c: function create() { c: function create() {
div = createElement("div"); div = createElement("div");
div.textContent = "some content"; div.textContent = "some content";
this.h();
}, },
h: function hydrate() { h: function hydrate() {
div_resize_listener = addResizeListener(div, div_resize_handler); div_resize_listener = addResizeListener(div, div_resize_handler);
component._beforecreate.push(div_resize_handler); component.root._beforecreate.push(div_resize_handler);
}, },
m: function mount(target, anchor) { m: function mount(target, anchor) {
@ -26,11 +27,12 @@ function create_main_fragment(component, ctx) {
p: noop, p: noop,
u: function unmount() { u: function unmount() {
div_resize_listener.cancel();
detachNode(div); detachNode(div);
}, },
d: noop d: function destroy() {
div_resize_listener.cancel();
}
}; };
} }

@ -0,0 +1,3 @@
<div bind:offsetWidth=w bind:offsetHeight=h>
some content
</div>
Loading…
Cancel
Save