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 Block from '../dom/Block';
import Expression from './shared/Expression';
import { dimensions } from '../../utils/patterns';
const readOnlyMediaAttributes = new Set([
'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 isReadOnly = (
(node.isMediaNode() && readOnlyMediaAttributes.has(this.name)) ||
this.name === 'width' || this.name === 'height'
dimensions.test(this.name)
);
let updateCondition: string;
@ -122,8 +123,8 @@ export default class Binding extends Node {
initialUpdate = null;
}
// bind:width and bind:height
if (this.name === 'width' || this.name === 'height') {
// bind:offsetWidth and bind:offsetHeight
if (dimensions.test(this.name)) {
initialUpdate = null;
updateDom = null;
}

@ -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(' '));
@ -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
@ -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');
@ -973,7 +996,7 @@ const events = [
{
eventNames: ['resize'],
filter: (node: Element, name: string) =>
(name === 'width' || name === 'height')
dimensions.test(name)
},
// 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.type = 'text/html';
if (isIE) element.appendChild(object);
object.data = 'about:blank';
if (!isIE) element.appendChild(object);
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);

@ -1 +1,3 @@
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 validate, { Validator } from '../index';
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)$/;
@ -157,7 +158,7 @@ export default function validateElement(
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, {
code: `invalid-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);
}
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() {
return Object.create(null);
}
@ -136,19 +165,26 @@ var proto = {
/* generated by Svelte vX.Y.Z */
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 {
c: function create() {
div = createElement("div");
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) {
insertNode(div, target, anchor);
div.width = ctx.width ;
div.height = ctx.height;
},
p: noop,
@ -157,7 +193,9 @@ function create_main_fragment(component, ctx) {
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;
function div_resize_handler() {
component.set({ w: div.offsetWidth, h: offsetHeight });
component.set({ w: div.offsetWidth, h: div.offsetHeight });
}
return {
c: function create() {
div = createElement("div");
div.textContent = "some content";
this.h();
},
h: function hydrate() {
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) {
@ -26,11 +27,12 @@ function create_main_fragment(component, ctx) {
p: noop,
u: function unmount() {
div_resize_listener.cancel();
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