feat: using construct-style-sheets-polyfill

This commit is contained in:
dntzhang 2021-06-23 15:58:28 +08:00
parent 5bfd68c361
commit e8d9766d7a
18 changed files with 5254 additions and 1012 deletions

View File

@ -1,5 +1,5 @@
/**
* Omi v6.19.5 http://omijs.org
* Omi v6.19.6 http://omijs.org
* Front End Cross-Frameworks Framework.
* By dntzhang https://github.com/dntzhang
* Github: https://github.com/Tencent/omi
@ -922,9 +922,11 @@
if (this.constructor.css) {
if (typeof this.constructor.css === 'string') {
console.log(1111);
this.styleSheet = new CSSStyleSheet();
this.styleSheet.replaceSync(this.constructor.css);
} else {
console.log(this.constructor.css);
this.styleSheet = this.constructor.css;
}
shadowRoot.adoptedStyleSheets = [this.styleSheet];
@ -1813,243 +1815,344 @@
var n=function(t,r,u,e){for(var p=1;p<r.length;p++){var s=r[p],h="number"==typeof s?u[s]:s,a=r[++p];1===a?e[0]=h:3===a?e[1]=Object.assign(e[1]||{},h):5===a?(e[1]=e[1]||{})[r[++p]]=h:6===a?e[1][r[++p]]+=h+"":e.push(a?t.apply(null,n(t,h,u,["",null])):h);}return e},t=function(n){for(var t,r,u=1,e="",p="",s=[0],h=function(n){1===u&&(n||(e=e.replace(/^\s*\n\s*|\s*\n\s*$/g,"")))?s.push(n||e,0):3===u&&(n||e)?(s.push(n||e,1), u=2):2===u&&"..."===e&&n?s.push(n,3):2===u&&e&&!n?s.push(!0,5,e):u>=5&&((e||!n&&5===u)&&(s.push(e,u,r), u=6), n&&(s.push(n,u,r), u=6)), e="";},a=0;a<n.length;a++){a&&(1===u&&h(), h(a));for(var f=0;f<n[a].length;f++)t=n[a][f], 1===u?"<"===t?(h(), s=[s], u=3):e+=t:4===u?"--"===e&&">"===t?(u=1, e=""):e=t+e[0]:p?t===p?p="":e+=t:'"'===t||"'"===t?p=t:">"===t?(h(), u=1):u&&("="===t?(u=5, r=e, e=""):"/"===t&&(u<5||">"===n[a][f+1])?(h(), 3===u&&(s=s[0]), u=s, (s=s[0]).push(u,2), u=0):" "===t||"\t"===t||"\n"===t||"\r"===t?(h(), u=2):e+=t), 3===u&&"!--"===e&&(u=4, s=s[0]);}return h(), s},r="function"==typeof Map,u=r?new Map:{},e=r?function(n){var r=u.get(n);return r||u.set(n,r=t(n)), r}:function(n){for(var r="",e=0;e<n.length;e++)r+=n[e].length+"-"+n[e];return u[r]||(u[r]=t(n))};function htm(t){var r=n(this,e(t),arguments,[]);return r.length>1?r:r[0]}
(function () {
try {
new window.CSSStyleSheet('a{}');
return;
} catch (e) {}
// TODO: this could really just by a dunderprop to keep the polyfill light.
var INTERNAL = typeof Symbol !== 'undefined' ? Symbol('__s') : '__s';
if ('adoptedStyleSheets' in document) { return; }
/**
* Problem 1:
* CSSStyleSheet is nonconfigurable.
* This means we're stuck with a ponyfill and not a "perfect" polyfill.
*/
// Object.defineProperty(window, 'CSSStyleSheet', {
// configurable: true,
// enumerable: true,
// get: () => CSSStyleSheet
// });
var hasShadyCss = 'ShadyCSS' in window && !ShadyCSS.nativeShadow;
var bootstrapper = document.implementation.createHTMLDocument('boot');
var closedShadowRootRegistry = new WeakMap();
var _DOMException = typeof DOMException === 'object' ? Error : DOMException;
var OriginalCSSStyleSheet = window.CSSStyleSheet;
window.CSSStyleSheet = CSSStyleSheet;
var DOC;
var counter = 0;
/**
* Problem #2:
* CSSStyleSheet is not instantiable.
* We can inherit from the real CSSStyleSheet in order to
*/
function CSSStyleSheet(options) {
if (!DOC) {
var frame = document.createElement('iframe');
frame.style.cssText = 'position:absolute;left:0;top:-9999px;width:1px;height:1px;';
document.body.appendChild(frame);
DOC = frame.contentWindow.document;
}
var style = DOC.createElement('style');
style.$id = ++counter;
style.childSheets = [];
style.appendChild(DOC.createTextNode(''));
DOC.body.appendChild(style);
// console.log(style, sheet);
Object.assign(style.sheet, options || {});
this[INTERNAL] = style;
}
// we can be nice and ensure that this holds:
// document.createElement('style').stylesheet instanceof CSSStyleSeetPolyfill
CSSStyleSheet.prototype = Object.create(OriginalCSSStyleSheet);
Object.defineProperty(CSSStyleSheet.prototype, 'cssRules', {
get: function get() {
return this[INTERNAL].sheet.cssRules;
}
});
CSSStyleSheet.prototype.replace = function (cssText) {
var style = this[INTERNAL];
return new Promise(function (resolve, reject) {
var l = DOC.createElement('link');
l.rel = 'preload';
l.as = 'style';
l.onload = function () {
// sheet.ownerNode.firstChild.textContent = cssText;
style.firstChild.data = cssText;
for (var i = 0; i < style.childSheets.length; i++) {
style.childSheets[i].firstChild.data = cssText;
var defineProperty = Object.defineProperty;
var forEach = Array.prototype.forEach;
var importPattern = /@import.+?;?$/gm;
function rejectImports(contents) {
var _contents = contents.replace(importPattern, '');
if (_contents !== contents) {
console.warn('@import rules are not allowed here. See https://github.com/WICG/construct-stylesheets/issues/119#issuecomment-588352418');
}
// if (sheet.cssRules[0]) sheet.deleteRule(0);
// sheet.insertRule(cssText);
l.remove();
resolve();
};
l.onerror = reject;
l.href = 'data:text/css;base64,' + btoa(cssText);
DOC.head.appendChild(l);
return _contents.trim();
}
function clearRules(sheet) {
for (var i = 0; i < sheet.cssRules.length; i++) {
sheet.deleteRule(0);
}
}
function insertAllRules(from, to) {
forEach.call(from.cssRules, function (rule, i) {
to.insertRule(rule.cssText, i);
});
}
function isElementConnected(element) {
return 'isConnected' in element
? element.isConnected
: document.contains(element);
}
function unique(arr) {
return arr.filter(function (value, index) { return arr.indexOf(value) === index; });
}
function diff(arr1, arr2) {
return arr1.filter(function (value) { return arr2.indexOf(value) === -1; });
}
function removeNode(node) {
node.parentNode.removeChild(node);
}
function getShadowRoot(element) {
return element.shadowRoot || closedShadowRootRegistry.get(element);
}
var cssStyleSheetMethods = [
'addImport',
'addPageRule',
'addRule',
'deleteRule',
'insertRule',
'removeImport',
'removeRule',
];
var NonConstructedStyleSheet = CSSStyleSheet;
var nonConstructedProto = NonConstructedStyleSheet.prototype;
nonConstructedProto.replace = function () {
return Promise.reject(new _DOMException("Can't call replace on non-constructed CSSStyleSheets."));
};
nonConstructedProto.replaceSync = function () {
throw new _DOMException("Failed to execute 'replaceSync' on 'CSSStyleSheet': Can't call replaceSync on non-constructed CSSStyleSheets.");
};
function isCSSStyleSheetInstance(instance) {
return typeof instance === 'object'
? proto$2.isPrototypeOf(instance) ||
nonConstructedProto.isPrototypeOf(instance)
: false;
}
function isNonConstructedStyleSheetInstance(instance) {
return typeof instance === 'object'
? nonConstructedProto.isPrototypeOf(instance)
: false;
}
var $basicStyleSheet = new WeakMap();
var $locations = new WeakMap();
var $adoptersByLocation = new WeakMap();
function addAdopterLocation(sheet, location) {
var adopter = document.createElement('style');
$adoptersByLocation.get(sheet).set(location, adopter);
$locations.get(sheet).push(location);
return adopter;
}
function getAdopterByLocation(sheet, location) {
return $adoptersByLocation.get(sheet).get(location);
}
function removeAdopterLocation(sheet, location) {
$adoptersByLocation.get(sheet).delete(location);
$locations.set(sheet, $locations.get(sheet).filter(function (_location) { return _location !== location; }));
}
function restyleAdopter(sheet, adopter) {
requestAnimationFrame(function () {
clearRules(adopter.sheet);
insertAllRules($basicStyleSheet.get(sheet), adopter.sheet);
});
}
function checkInvocationCorrectness(self) {
if (!$basicStyleSheet.has(self)) {
throw new TypeError('Illegal invocation');
}
}
function ConstructedStyleSheet() {
var self = this;
var style = document.createElement('style');
bootstrapper.body.appendChild(style);
$basicStyleSheet.set(self, style.sheet);
$locations.set(self, []);
$adoptersByLocation.set(self, new WeakMap());
}
var proto$2 = ConstructedStyleSheet.prototype;
proto$2.replace = function replace(contents) {
try {
this.replaceSync(contents);
return Promise.resolve(this);
}
catch (e) {
return Promise.reject(e);
}
};
proto$2.replaceSync = function replaceSync(contents) {
checkInvocationCorrectness(this);
if (typeof contents === 'string') {
var self_1 = this;
var style = $basicStyleSheet.get(self_1).ownerNode;
style.textContent = rejectImports(contents);
$basicStyleSheet.set(self_1, style.sheet);
$locations.get(self_1).forEach(function (location) {
if (location.isConnected()) {
restyleAdopter(self_1, getAdopterByLocation(self_1, location));
}
});
}
};
defineProperty(proto$2, 'cssRules', {
configurable: true,
enumerable: true,
get: function cssRules() {
checkInvocationCorrectness(this);
return $basicStyleSheet.get(this).cssRules;
},
});
};
CSSStyleSheet.prototype.replaceSync = function (cssText) {
var style = this[INTERNAL];
if (cssText.replace(/\/\*[\s\S]+?\*\//g, '').match(/@import\s*\(\s*(['"])[^\1]*?\1\s*\)/)) {
throw Error('no');
}
// if (sheet.cssRules[0]) sheet.deleteRule(0);
// sheet.insertRule(cssText);
// sheet.ownerNode.firstChild.textContent = cssText;
style.firstChild.data = cssText;
for (var i = 0; i < style.childSheets.length; i++) {
style.childSheets[i].firstChild.data = cssText;
}
};
var oldInnerHTML = Object.getOwnPropertyDescriptor(ShadowRoot.prototype, 'innerHTML');
var oldFirstChild = Object.getOwnPropertyDescriptor(Node.prototype, 'firstChild');
var oldLastChild = Object.getOwnPropertyDescriptor(Node.prototype, 'lastChild');
function getState(obj) {
return obj[INTERNAL] || (obj[INTERNAL] = {
adoptedStyleSheets: [],
sheets: [],
id: ++counter
cssStyleSheetMethods.forEach(function (method) {
proto$2[method] = function () {
var self = this;
checkInvocationCorrectness(self);
var args = arguments;
var basic = $basicStyleSheet.get(self);
var locations = $locations.get(self);
var result = basic[method].apply(basic, args);
locations.forEach(function (location) {
if (location.isConnected()) {
var sheet = getAdopterByLocation(self, location).sheet;
sheet[method].apply(sheet, args);
}
});
return result;
};
});
defineProperty(ConstructedStyleSheet, Symbol.hasInstance, {
configurable: true,
value: isCSSStyleSheetInstance,
});
}
Object.defineProperties(ShadowRoot.prototype, {
firstChild: {
get: function get() {
var child = oldFirstChild.get.call(this);
while (child) {
if (child[INTERNAL] == null) break;
child = child.nextSibling;
var defaultObserverOptions = {
childList: true,
subtree: true,
};
var locations = new WeakMap();
function getAssociatedLocation(element) {
var location = locations.get(element);
if (!location) {
location = new Location(element);
locations.set(element, location);
}
return child;
}
},
lastChild: {
get: function get() {
var child = oldLastChild.get.call(this);
while (child) {
if (child[INTERNAL] == null) break;
child = child.previousSibling;
return location;
}
function attachAdoptedStyleSheetProperty(constructor) {
defineProperty(constructor.prototype, 'adoptedStyleSheets', {
configurable: true,
enumerable: true,
get: function () {
return getAssociatedLocation(this).sheets;
},
set: function (sheets) {
getAssociatedLocation(this).update(sheets);
},
});
}
function traverseWebComponents(node, callback) {
var iter = document.createNodeIterator(node, NodeFilter.SHOW_ELEMENT, function (foundNode) {
return getShadowRoot(foundNode)
? NodeFilter.FILTER_ACCEPT
: NodeFilter.FILTER_REJECT;
},
null, false);
for (var next = void 0; (next = iter.nextNode());) {
callback(getShadowRoot(next));
}
return child;
}
},
// @TODO
// childNodes: {},
// children: {},
innerHTML: {
get: function get() {
var html = '';
var child = oldFirstChild.get.call(this);
while (child) {
if (!child[INTERNAL]) {
if (child.nodeType === 3) html += child.data;
html += child.outerHTML;
}
child = child.nextSibling;
}
return html;
// return old.get.call(this).replace(/</);
},
set: function set(html) {
var child = oldFirstChild.get.call(this);
var sheets = [];
while (child) {
if (child[INTERNAL]) sheets.push(child);
child = child.nextSibling;
}
oldInnerHTML.set.call(this, html);
child = oldFirstChild.get.call(this);
for (var i = 0; i < sheets.length; i++) {
this.insertBefore(sheets[i], child);
}
// this.insertAdjacentHTML(html, 'beforeend');
}
},
adoptedStyleSheets: {
get: function get() {
var state = getState(this);
return state.adoptedStyleSheets;
},
// @TODO:
// Chrome's implementation doesn't do any diffing, so the polyfill needn't either.
// Also, we should always clone the passed Array and freeze it if available.
set: function set(value) {
var state = getState(this);
var previous = state.adoptedStyleSheets.slice();
var indices = [];
if (!Array.isArray(value)) {
value = [].concat(value || []);
}
// this[INTERNAL] = value;
state.adoptedStyleSheets = value;
for (var i = 0; i < value.length; i++) {
var v = value[i];
var index = previous.indexOf(v);
if (index === -1) {
var style = v[INTERNAL];
var clone = style.cloneNode(true);
// clone.setAttribute('data-is-constructed', state.id);
clone[INTERNAL] = {};
// clone.$parent = style;
style.childSheets.push(clone);
// clone.textContent = style.textContent;
// clone.$id = style.$id;
// state.sheets.push(clone);
this.appendChild(clone);
// console.log(this, clone, this.childNodes);
// console.log(`found new sheet, adding.`, clone);
} else {
indices[index] = true;
// const style = v[INTERNAL];
}
}
for (var i = 0; i < previous.length; i++) {
if (indices[i] !== true) {
var prev = previous[i][INTERNAL];
// const style = prev.$parent;
for (var j = 0; j < prev.childSheets.length; j++) {
var sheet = prev.childSheets[j];
if (sheet.parentNode === this) {
this.removeChild(sheet);
prev.childSheets.splice(j, 1);
break;
}
}
var $element = new WeakMap();
var $uniqueSheets = new WeakMap();
var $observer = new WeakMap();
function isExistingAdopter(self, element) {
return (element instanceof HTMLStyleElement &&
$uniqueSheets.get(self).some(function (sheet) { return getAdopterByLocation(sheet, self); }));
}
function getAdopterContainer(self) {
var element = $element.get(self);
return element instanceof Document ? element.body : element;
}
function adopt(self) {
var styleList = document.createDocumentFragment();
var sheets = $uniqueSheets.get(self);
var observer = $observer.get(self);
var container = getAdopterContainer(self);
observer.disconnect();
sheets.forEach(function (sheet) {
styleList.appendChild(getAdopterByLocation(sheet, self) || addAdopterLocation(sheet, self));
});
container.insertBefore(styleList, null);
observer.observe(container, defaultObserverOptions);
sheets.forEach(function (sheet) {
restyleAdopter(sheet, getAdopterByLocation(sheet, self));
});
}
function Location(element) {
var self = this;
self.sheets = [];
$element.set(self, element);
$uniqueSheets.set(self, []);
$observer.set(self, new MutationObserver(function (mutations, observer) {
if (!document) {
observer.disconnect();
return;
}
// for (let j = 0; j < state.sheets.length; j++) {
// if (state.sheets[j].$id === prev.$id) {
// state.sheets[j].remove();
// break;
// }
// }
}
}
}
mutations.forEach(function (mutation) {
if (!hasShadyCss) {
forEach.call(mutation.addedNodes, function (node) {
if (!(node instanceof Element)) {
return;
}
traverseWebComponents(node, function (root) {
getAssociatedLocation(root).connect();
});
});
}
forEach.call(mutation.removedNodes, function (node) {
if (!(node instanceof Element)) {
return;
}
if (isExistingAdopter(self, node)) {
adopt(self);
}
if (!hasShadyCss) {
traverseWebComponents(node, function (root) {
getAssociatedLocation(root).disconnect();
});
}
});
});
}));
}
});
})();
var proto$1 = Location.prototype;
proto$1.isConnected = function isConnected() {
var element = $element.get(this);
return element instanceof Document
? element.readyState !== 'loading'
: isElementConnected(element.host);
};
proto$1.connect = function connect() {
var container = getAdopterContainer(this);
$observer.get(this).observe(container, defaultObserverOptions);
if ($uniqueSheets.get(this).length > 0) {
adopt(this);
}
traverseWebComponents(container, function (root) {
getAssociatedLocation(root).connect();
});
};
proto$1.disconnect = function disconnect() {
$observer.get(this).disconnect();
};
proto$1.update = function update(sheets) {
var self = this;
var locationType = $element.get(self) === document ? 'Document' : 'ShadowRoot';
if (!Array.isArray(sheets)) {
throw new TypeError("Failed to set the 'adoptedStyleSheets' property on " + locationType + ": Iterator getter is not callable.");
}
if (!sheets.every(isCSSStyleSheetInstance)) {
throw new TypeError("Failed to set the 'adoptedStyleSheets' property on " + locationType + ": Failed to convert value to 'CSSStyleSheet'");
}
if (sheets.some(isNonConstructedStyleSheetInstance)) {
throw new TypeError("Failed to set the 'adoptedStyleSheets' property on " + locationType + ": Can't adopt non-constructed stylesheets");
}
self.sheets = sheets;
var oldUniqueSheets = $uniqueSheets.get(self);
var uniqueSheets = unique(sheets);
var removedSheets = diff(oldUniqueSheets, uniqueSheets);
removedSheets.forEach(function (sheet) {
removeNode(getAdopterByLocation(sheet, self));
removeAdopterLocation(sheet, self);
});
$uniqueSheets.set(self, uniqueSheets);
if (self.isConnected() && uniqueSheets.length > 0) {
adopt(self);
}
};
window.CSSStyleSheet = ConstructedStyleSheet;
attachAdoptedStyleSheetProperty(Document);
if ('ShadowRoot' in window) {
attachAdoptedStyleSheetProperty(ShadowRoot);
var proto = Element.prototype;
var attach_1 = proto.attachShadow;
proto.attachShadow = function attachShadow(init) {
var root = attach_1.call(this, init);
if (init.mode === 'closed') {
closedShadowRootRegistry.set(this, root);
}
return root;
};
}
var documentLocation = getAssociatedLocation(document);
if (documentLocation.isConnected()) {
documentLocation.connect();
}
else {
document.addEventListener('DOMContentLoaded', documentLocation.connect.bind(documentLocation));
}
}());
h.f = Fragment;
var html = htm.bind(h);
function createRef() {
return {};
return {};
}
var $ = {};
@ -2058,32 +2161,32 @@
var elements = options.mapping;
var omi = {
tag: tag,
WeElement: WeElement,
Component: Component,
render: render,
h: h,
createElement: h,
options: options,
define: define,
cloneElement: cloneElement,
getHost: getHost,
rpx: rpx,
defineElement: defineElement,
classNames: classNames,
extractClass: extractClass,
createRef: createRef,
html: html,
htm: htm,
o: o,
elements: elements,
$: $,
extend: extend$1,
get: get,
set: set,
bind: bind,
unbind: unbind,
JSONProxy: JSONPatcherProxy
tag: tag,
WeElement: WeElement,
Component: Component,
render: render,
h: h,
createElement: h,
options: options,
define: define,
cloneElement: cloneElement,
getHost: getHost,
rpx: rpx,
defineElement: defineElement,
classNames: classNames,
extractClass: extractClass,
createRef: createRef,
html: html,
htm: htm,
o: o,
elements: elements,
$: $,
extend: extend$1,
get: get,
set: set,
bind: bind,
unbind: unbind,
JSONProxy: JSONPatcherProxy
};
options.root.Omi = omi;

File diff suppressed because one or more lines are too long

View File

@ -1,5 +1,5 @@
/**
* Omi v6.19.5 http://omijs.org
* Omi v6.19.6 http://omijs.org
* Front End Cross-Frameworks Framework.
* By dntzhang https://github.com/dntzhang
* Github: https://github.com/Tencent/omi
@ -919,9 +919,11 @@ var WeElement = function (_HTMLElement) {
if (this.constructor.css) {
if (typeof this.constructor.css === 'string') {
console.log(1111);
this.styleSheet = new CSSStyleSheet();
this.styleSheet.replaceSync(this.constructor.css);
} else {
console.log(this.constructor.css);
this.styleSheet = this.constructor.css;
}
shadowRoot.adoptedStyleSheets = [this.styleSheet];
@ -1810,243 +1812,344 @@ function o(obj) {
var n=function(t,r,u,e){for(var p=1;p<r.length;p++){var s=r[p],h="number"==typeof s?u[s]:s,a=r[++p];1===a?e[0]=h:3===a?e[1]=Object.assign(e[1]||{},h):5===a?(e[1]=e[1]||{})[r[++p]]=h:6===a?e[1][r[++p]]+=h+"":e.push(a?t.apply(null,n(t,h,u,["",null])):h);}return e},t=function(n){for(var t,r,u=1,e="",p="",s=[0],h=function(n){1===u&&(n||(e=e.replace(/^\s*\n\s*|\s*\n\s*$/g,"")))?s.push(n||e,0):3===u&&(n||e)?(s.push(n||e,1), u=2):2===u&&"..."===e&&n?s.push(n,3):2===u&&e&&!n?s.push(!0,5,e):u>=5&&((e||!n&&5===u)&&(s.push(e,u,r), u=6), n&&(s.push(n,u,r), u=6)), e="";},a=0;a<n.length;a++){a&&(1===u&&h(), h(a));for(var f=0;f<n[a].length;f++)t=n[a][f], 1===u?"<"===t?(h(), s=[s], u=3):e+=t:4===u?"--"===e&&">"===t?(u=1, e=""):e=t+e[0]:p?t===p?p="":e+=t:'"'===t||"'"===t?p=t:">"===t?(h(), u=1):u&&("="===t?(u=5, r=e, e=""):"/"===t&&(u<5||">"===n[a][f+1])?(h(), 3===u&&(s=s[0]), u=s, (s=s[0]).push(u,2), u=0):" "===t||"\t"===t||"\n"===t||"\r"===t?(h(), u=2):e+=t), 3===u&&"!--"===e&&(u=4, s=s[0]);}return h(), s},r="function"==typeof Map,u=r?new Map:{},e=r?function(n){var r=u.get(n);return r||u.set(n,r=t(n)), r}:function(n){for(var r="",e=0;e<n.length;e++)r+=n[e].length+"-"+n[e];return u[r]||(u[r]=t(n))};function htm(t){var r=n(this,e(t),arguments,[]);return r.length>1?r:r[0]}
(function () {
try {
new window.CSSStyleSheet('a{}');
return;
} catch (e) {}
// TODO: this could really just by a dunderprop to keep the polyfill light.
var INTERNAL = typeof Symbol !== 'undefined' ? Symbol('__s') : '__s';
if ('adoptedStyleSheets' in document) { return; }
/**
* Problem 1:
* CSSStyleSheet is nonconfigurable.
* This means we're stuck with a ponyfill and not a "perfect" polyfill.
*/
// Object.defineProperty(window, 'CSSStyleSheet', {
// configurable: true,
// enumerable: true,
// get: () => CSSStyleSheet
// });
var hasShadyCss = 'ShadyCSS' in window && !ShadyCSS.nativeShadow;
var bootstrapper = document.implementation.createHTMLDocument('boot');
var closedShadowRootRegistry = new WeakMap();
var _DOMException = typeof DOMException === 'object' ? Error : DOMException;
var OriginalCSSStyleSheet = window.CSSStyleSheet;
window.CSSStyleSheet = CSSStyleSheet;
var DOC;
var counter = 0;
/**
* Problem #2:
* CSSStyleSheet is not instantiable.
* We can inherit from the real CSSStyleSheet in order to
*/
function CSSStyleSheet(options) {
if (!DOC) {
var frame = document.createElement('iframe');
frame.style.cssText = 'position:absolute;left:0;top:-9999px;width:1px;height:1px;';
document.body.appendChild(frame);
DOC = frame.contentWindow.document;
}
var style = DOC.createElement('style');
style.$id = ++counter;
style.childSheets = [];
style.appendChild(DOC.createTextNode(''));
DOC.body.appendChild(style);
// console.log(style, sheet);
Object.assign(style.sheet, options || {});
this[INTERNAL] = style;
}
// we can be nice and ensure that this holds:
// document.createElement('style').stylesheet instanceof CSSStyleSeetPolyfill
CSSStyleSheet.prototype = Object.create(OriginalCSSStyleSheet);
Object.defineProperty(CSSStyleSheet.prototype, 'cssRules', {
get: function get() {
return this[INTERNAL].sheet.cssRules;
}
});
CSSStyleSheet.prototype.replace = function (cssText) {
var style = this[INTERNAL];
return new Promise(function (resolve, reject) {
var l = DOC.createElement('link');
l.rel = 'preload';
l.as = 'style';
l.onload = function () {
// sheet.ownerNode.firstChild.textContent = cssText;
style.firstChild.data = cssText;
for (var i = 0; i < style.childSheets.length; i++) {
style.childSheets[i].firstChild.data = cssText;
var defineProperty = Object.defineProperty;
var forEach = Array.prototype.forEach;
var importPattern = /@import.+?;?$/gm;
function rejectImports(contents) {
var _contents = contents.replace(importPattern, '');
if (_contents !== contents) {
console.warn('@import rules are not allowed here. See https://github.com/WICG/construct-stylesheets/issues/119#issuecomment-588352418');
}
// if (sheet.cssRules[0]) sheet.deleteRule(0);
// sheet.insertRule(cssText);
l.remove();
resolve();
};
l.onerror = reject;
l.href = 'data:text/css;base64,' + btoa(cssText);
DOC.head.appendChild(l);
return _contents.trim();
}
function clearRules(sheet) {
for (var i = 0; i < sheet.cssRules.length; i++) {
sheet.deleteRule(0);
}
}
function insertAllRules(from, to) {
forEach.call(from.cssRules, function (rule, i) {
to.insertRule(rule.cssText, i);
});
}
function isElementConnected(element) {
return 'isConnected' in element
? element.isConnected
: document.contains(element);
}
function unique(arr) {
return arr.filter(function (value, index) { return arr.indexOf(value) === index; });
}
function diff(arr1, arr2) {
return arr1.filter(function (value) { return arr2.indexOf(value) === -1; });
}
function removeNode(node) {
node.parentNode.removeChild(node);
}
function getShadowRoot(element) {
return element.shadowRoot || closedShadowRootRegistry.get(element);
}
var cssStyleSheetMethods = [
'addImport',
'addPageRule',
'addRule',
'deleteRule',
'insertRule',
'removeImport',
'removeRule',
];
var NonConstructedStyleSheet = CSSStyleSheet;
var nonConstructedProto = NonConstructedStyleSheet.prototype;
nonConstructedProto.replace = function () {
return Promise.reject(new _DOMException("Can't call replace on non-constructed CSSStyleSheets."));
};
nonConstructedProto.replaceSync = function () {
throw new _DOMException("Failed to execute 'replaceSync' on 'CSSStyleSheet': Can't call replaceSync on non-constructed CSSStyleSheets.");
};
function isCSSStyleSheetInstance(instance) {
return typeof instance === 'object'
? proto$2.isPrototypeOf(instance) ||
nonConstructedProto.isPrototypeOf(instance)
: false;
}
function isNonConstructedStyleSheetInstance(instance) {
return typeof instance === 'object'
? nonConstructedProto.isPrototypeOf(instance)
: false;
}
var $basicStyleSheet = new WeakMap();
var $locations = new WeakMap();
var $adoptersByLocation = new WeakMap();
function addAdopterLocation(sheet, location) {
var adopter = document.createElement('style');
$adoptersByLocation.get(sheet).set(location, adopter);
$locations.get(sheet).push(location);
return adopter;
}
function getAdopterByLocation(sheet, location) {
return $adoptersByLocation.get(sheet).get(location);
}
function removeAdopterLocation(sheet, location) {
$adoptersByLocation.get(sheet).delete(location);
$locations.set(sheet, $locations.get(sheet).filter(function (_location) { return _location !== location; }));
}
function restyleAdopter(sheet, adopter) {
requestAnimationFrame(function () {
clearRules(adopter.sheet);
insertAllRules($basicStyleSheet.get(sheet), adopter.sheet);
});
}
function checkInvocationCorrectness(self) {
if (!$basicStyleSheet.has(self)) {
throw new TypeError('Illegal invocation');
}
}
function ConstructedStyleSheet() {
var self = this;
var style = document.createElement('style');
bootstrapper.body.appendChild(style);
$basicStyleSheet.set(self, style.sheet);
$locations.set(self, []);
$adoptersByLocation.set(self, new WeakMap());
}
var proto$2 = ConstructedStyleSheet.prototype;
proto$2.replace = function replace(contents) {
try {
this.replaceSync(contents);
return Promise.resolve(this);
}
catch (e) {
return Promise.reject(e);
}
};
proto$2.replaceSync = function replaceSync(contents) {
checkInvocationCorrectness(this);
if (typeof contents === 'string') {
var self_1 = this;
var style = $basicStyleSheet.get(self_1).ownerNode;
style.textContent = rejectImports(contents);
$basicStyleSheet.set(self_1, style.sheet);
$locations.get(self_1).forEach(function (location) {
if (location.isConnected()) {
restyleAdopter(self_1, getAdopterByLocation(self_1, location));
}
});
}
};
defineProperty(proto$2, 'cssRules', {
configurable: true,
enumerable: true,
get: function cssRules() {
checkInvocationCorrectness(this);
return $basicStyleSheet.get(this).cssRules;
},
});
};
CSSStyleSheet.prototype.replaceSync = function (cssText) {
var style = this[INTERNAL];
if (cssText.replace(/\/\*[\s\S]+?\*\//g, '').match(/@import\s*\(\s*(['"])[^\1]*?\1\s*\)/)) {
throw Error('no');
}
// if (sheet.cssRules[0]) sheet.deleteRule(0);
// sheet.insertRule(cssText);
// sheet.ownerNode.firstChild.textContent = cssText;
style.firstChild.data = cssText;
for (var i = 0; i < style.childSheets.length; i++) {
style.childSheets[i].firstChild.data = cssText;
}
};
var oldInnerHTML = Object.getOwnPropertyDescriptor(ShadowRoot.prototype, 'innerHTML');
var oldFirstChild = Object.getOwnPropertyDescriptor(Node.prototype, 'firstChild');
var oldLastChild = Object.getOwnPropertyDescriptor(Node.prototype, 'lastChild');
function getState(obj) {
return obj[INTERNAL] || (obj[INTERNAL] = {
adoptedStyleSheets: [],
sheets: [],
id: ++counter
cssStyleSheetMethods.forEach(function (method) {
proto$2[method] = function () {
var self = this;
checkInvocationCorrectness(self);
var args = arguments;
var basic = $basicStyleSheet.get(self);
var locations = $locations.get(self);
var result = basic[method].apply(basic, args);
locations.forEach(function (location) {
if (location.isConnected()) {
var sheet = getAdopterByLocation(self, location).sheet;
sheet[method].apply(sheet, args);
}
});
return result;
};
});
defineProperty(ConstructedStyleSheet, Symbol.hasInstance, {
configurable: true,
value: isCSSStyleSheetInstance,
});
}
Object.defineProperties(ShadowRoot.prototype, {
firstChild: {
get: function get() {
var child = oldFirstChild.get.call(this);
while (child) {
if (child[INTERNAL] == null) break;
child = child.nextSibling;
var defaultObserverOptions = {
childList: true,
subtree: true,
};
var locations = new WeakMap();
function getAssociatedLocation(element) {
var location = locations.get(element);
if (!location) {
location = new Location(element);
locations.set(element, location);
}
return child;
}
},
lastChild: {
get: function get() {
var child = oldLastChild.get.call(this);
while (child) {
if (child[INTERNAL] == null) break;
child = child.previousSibling;
return location;
}
function attachAdoptedStyleSheetProperty(constructor) {
defineProperty(constructor.prototype, 'adoptedStyleSheets', {
configurable: true,
enumerable: true,
get: function () {
return getAssociatedLocation(this).sheets;
},
set: function (sheets) {
getAssociatedLocation(this).update(sheets);
},
});
}
function traverseWebComponents(node, callback) {
var iter = document.createNodeIterator(node, NodeFilter.SHOW_ELEMENT, function (foundNode) {
return getShadowRoot(foundNode)
? NodeFilter.FILTER_ACCEPT
: NodeFilter.FILTER_REJECT;
},
null, false);
for (var next = void 0; (next = iter.nextNode());) {
callback(getShadowRoot(next));
}
return child;
}
},
// @TODO
// childNodes: {},
// children: {},
innerHTML: {
get: function get() {
var html = '';
var child = oldFirstChild.get.call(this);
while (child) {
if (!child[INTERNAL]) {
if (child.nodeType === 3) html += child.data;
html += child.outerHTML;
}
child = child.nextSibling;
}
return html;
// return old.get.call(this).replace(/</);
},
set: function set(html) {
var child = oldFirstChild.get.call(this);
var sheets = [];
while (child) {
if (child[INTERNAL]) sheets.push(child);
child = child.nextSibling;
}
oldInnerHTML.set.call(this, html);
child = oldFirstChild.get.call(this);
for (var i = 0; i < sheets.length; i++) {
this.insertBefore(sheets[i], child);
}
// this.insertAdjacentHTML(html, 'beforeend');
}
},
adoptedStyleSheets: {
get: function get() {
var state = getState(this);
return state.adoptedStyleSheets;
},
// @TODO:
// Chrome's implementation doesn't do any diffing, so the polyfill needn't either.
// Also, we should always clone the passed Array and freeze it if available.
set: function set(value) {
var state = getState(this);
var previous = state.adoptedStyleSheets.slice();
var indices = [];
if (!Array.isArray(value)) {
value = [].concat(value || []);
}
// this[INTERNAL] = value;
state.adoptedStyleSheets = value;
for (var i = 0; i < value.length; i++) {
var v = value[i];
var index = previous.indexOf(v);
if (index === -1) {
var style = v[INTERNAL];
var clone = style.cloneNode(true);
// clone.setAttribute('data-is-constructed', state.id);
clone[INTERNAL] = {};
// clone.$parent = style;
style.childSheets.push(clone);
// clone.textContent = style.textContent;
// clone.$id = style.$id;
// state.sheets.push(clone);
this.appendChild(clone);
// console.log(this, clone, this.childNodes);
// console.log(`found new sheet, adding.`, clone);
} else {
indices[index] = true;
// const style = v[INTERNAL];
}
}
for (var i = 0; i < previous.length; i++) {
if (indices[i] !== true) {
var prev = previous[i][INTERNAL];
// const style = prev.$parent;
for (var j = 0; j < prev.childSheets.length; j++) {
var sheet = prev.childSheets[j];
if (sheet.parentNode === this) {
this.removeChild(sheet);
prev.childSheets.splice(j, 1);
break;
}
}
var $element = new WeakMap();
var $uniqueSheets = new WeakMap();
var $observer = new WeakMap();
function isExistingAdopter(self, element) {
return (element instanceof HTMLStyleElement &&
$uniqueSheets.get(self).some(function (sheet) { return getAdopterByLocation(sheet, self); }));
}
function getAdopterContainer(self) {
var element = $element.get(self);
return element instanceof Document ? element.body : element;
}
function adopt(self) {
var styleList = document.createDocumentFragment();
var sheets = $uniqueSheets.get(self);
var observer = $observer.get(self);
var container = getAdopterContainer(self);
observer.disconnect();
sheets.forEach(function (sheet) {
styleList.appendChild(getAdopterByLocation(sheet, self) || addAdopterLocation(sheet, self));
});
container.insertBefore(styleList, null);
observer.observe(container, defaultObserverOptions);
sheets.forEach(function (sheet) {
restyleAdopter(sheet, getAdopterByLocation(sheet, self));
});
}
function Location(element) {
var self = this;
self.sheets = [];
$element.set(self, element);
$uniqueSheets.set(self, []);
$observer.set(self, new MutationObserver(function (mutations, observer) {
if (!document) {
observer.disconnect();
return;
}
// for (let j = 0; j < state.sheets.length; j++) {
// if (state.sheets[j].$id === prev.$id) {
// state.sheets[j].remove();
// break;
// }
// }
}
}
}
mutations.forEach(function (mutation) {
if (!hasShadyCss) {
forEach.call(mutation.addedNodes, function (node) {
if (!(node instanceof Element)) {
return;
}
traverseWebComponents(node, function (root) {
getAssociatedLocation(root).connect();
});
});
}
forEach.call(mutation.removedNodes, function (node) {
if (!(node instanceof Element)) {
return;
}
if (isExistingAdopter(self, node)) {
adopt(self);
}
if (!hasShadyCss) {
traverseWebComponents(node, function (root) {
getAssociatedLocation(root).disconnect();
});
}
});
});
}));
}
});
})();
var proto$1 = Location.prototype;
proto$1.isConnected = function isConnected() {
var element = $element.get(this);
return element instanceof Document
? element.readyState !== 'loading'
: isElementConnected(element.host);
};
proto$1.connect = function connect() {
var container = getAdopterContainer(this);
$observer.get(this).observe(container, defaultObserverOptions);
if ($uniqueSheets.get(this).length > 0) {
adopt(this);
}
traverseWebComponents(container, function (root) {
getAssociatedLocation(root).connect();
});
};
proto$1.disconnect = function disconnect() {
$observer.get(this).disconnect();
};
proto$1.update = function update(sheets) {
var self = this;
var locationType = $element.get(self) === document ? 'Document' : 'ShadowRoot';
if (!Array.isArray(sheets)) {
throw new TypeError("Failed to set the 'adoptedStyleSheets' property on " + locationType + ": Iterator getter is not callable.");
}
if (!sheets.every(isCSSStyleSheetInstance)) {
throw new TypeError("Failed to set the 'adoptedStyleSheets' property on " + locationType + ": Failed to convert value to 'CSSStyleSheet'");
}
if (sheets.some(isNonConstructedStyleSheetInstance)) {
throw new TypeError("Failed to set the 'adoptedStyleSheets' property on " + locationType + ": Can't adopt non-constructed stylesheets");
}
self.sheets = sheets;
var oldUniqueSheets = $uniqueSheets.get(self);
var uniqueSheets = unique(sheets);
var removedSheets = diff(oldUniqueSheets, uniqueSheets);
removedSheets.forEach(function (sheet) {
removeNode(getAdopterByLocation(sheet, self));
removeAdopterLocation(sheet, self);
});
$uniqueSheets.set(self, uniqueSheets);
if (self.isConnected() && uniqueSheets.length > 0) {
adopt(self);
}
};
window.CSSStyleSheet = ConstructedStyleSheet;
attachAdoptedStyleSheetProperty(Document);
if ('ShadowRoot' in window) {
attachAdoptedStyleSheetProperty(ShadowRoot);
var proto = Element.prototype;
var attach_1 = proto.attachShadow;
proto.attachShadow = function attachShadow(init) {
var root = attach_1.call(this, init);
if (init.mode === 'closed') {
closedShadowRootRegistry.set(this, root);
}
return root;
};
}
var documentLocation = getAssociatedLocation(document);
if (documentLocation.isConnected()) {
documentLocation.connect();
}
else {
document.addEventListener('DOMContentLoaded', documentLocation.connect.bind(documentLocation));
}
}());
h.f = Fragment;
var html = htm.bind(h);
function createRef() {
return {};
return {};
}
var $ = {};
@ -2055,32 +2158,32 @@ var defineElement = define;
var elements = options.mapping;
var omi = {
tag: tag,
WeElement: WeElement,
Component: Component,
render: render,
h: h,
createElement: h,
options: options,
define: define,
cloneElement: cloneElement,
getHost: getHost,
rpx: rpx,
defineElement: defineElement,
classNames: classNames,
extractClass: extractClass,
createRef: createRef,
html: html,
htm: htm,
o: o,
elements: elements,
$: $,
extend: extend$1,
get: get,
set: set,
bind: bind,
unbind: unbind,
JSONProxy: JSONPatcherProxy
tag: tag,
WeElement: WeElement,
Component: Component,
render: render,
h: h,
createElement: h,
options: options,
define: define,
cloneElement: cloneElement,
getHost: getHost,
rpx: rpx,
defineElement: defineElement,
classNames: classNames,
extractClass: extractClass,
createRef: createRef,
html: html,
htm: htm,
o: o,
elements: elements,
$: $,
extend: extend$1,
get: get,
set: set,
bind: bind,
unbind: unbind,
JSONProxy: JSONPatcherProxy
};
options.root.Omi = omi;

File diff suppressed because one or more lines are too long

View File

@ -695,9 +695,13 @@
}
if (this.constructor.css) {
if ('string' == typeof this.constructor.css) {
console.log(1111);
this.styleSheet = new CSSStyleSheet();
this.styleSheet.replaceSync(this.constructor.css);
} else this.styleSheet = this.constructor.css;
} else {
console.log(this.constructor.css);
this.styleSheet = this.constructor.css;
}
shadowRoot.adoptedStyleSheets = [ this.styleSheet ];
}
if (this.css) shadowRoot.appendChild(cssToDom('function' == typeof this.css ? this.css() : this.css));
@ -1044,147 +1048,275 @@
return u[r] || (u[r] = t(n));
};
!function() {
function CSSStyleSheet(options) {
if (!DOC) {
var frame = document.createElement('iframe');
frame.style.cssText = 'position:absolute;left:0;top:-9999px;width:1px;height:1px;';
document.body.appendChild(frame);
DOC = frame.contentWindow.document;
}
var style = DOC.createElement('style');
style.$id = ++counter;
style.childSheets = [];
style.appendChild(DOC.createTextNode(''));
DOC.body.appendChild(style);
Object.assign(style.sheet, options || {});
this[INTERNAL] = style;
function rejectImports(contents) {
var _contents = contents.replace(importPattern, '');
if (_contents !== contents) console.warn('@import rules are not allowed here. See https://github.com/WICG/construct-stylesheets/issues/119#issuecomment-588352418');
return _contents.trim();
}
function getState(obj) {
return obj[INTERNAL] || (obj[INTERNAL] = {
adoptedStyleSheets: [],
sheets: [],
id: ++counter
function clearRules(sheet) {
for (var i = 0; i < sheet.cssRules.length; i++) sheet.deleteRule(0);
}
function insertAllRules(from, to) {
forEach.call(from.cssRules, function(rule, i) {
to.insertRule(rule.cssText, i);
});
}
try {
new window.CSSStyleSheet('a{}');
return;
} catch (e) {}
var INTERNAL = 'undefined' != typeof Symbol ? Symbol('__s') : '__s';
var OriginalCSSStyleSheet = window.CSSStyleSheet;
window.CSSStyleSheet = CSSStyleSheet;
var DOC;
var counter = 0;
CSSStyleSheet.prototype = Object.create(OriginalCSSStyleSheet);
CSSStyleSheet.prototype;
CSSStyleSheet.prototype.replace = function(cssText) {
var style = this[INTERNAL];
return new Promise(function(resolve, reject) {
var l = DOC.createElement('link');
l.rel = 'preload';
l.as = 'style';
l.onload = function() {
style.firstChild.data = cssText;
for (var i = 0; i < style.childSheets.length; i++) style.childSheets[i].firstChild.data = cssText;
l.remove();
resolve();
function isElementConnected(element) {
return 'isConnected' in element ? element.isConnected : document.contains(element);
}
function unique(arr) {
return arr.filter(function(value, index) {
return arr.indexOf(value) === index;
});
}
function diff(arr1, arr2) {
return arr1.filter(function(value) {
return -1 === arr2.indexOf(value);
});
}
function removeNode(node) {
node.parentNode.removeChild(node);
}
function getShadowRoot(element) {
return element.shadowRoot || closedShadowRootRegistry.get(element);
}
function isCSSStyleSheetInstance(instance) {
return 'object' == typeof instance ? proto$2.isPrototypeOf(instance) || nonConstructedProto.isPrototypeOf(instance) : !1;
}
function isNonConstructedStyleSheetInstance(instance) {
return 'object' == typeof instance ? nonConstructedProto.isPrototypeOf(instance) : !1;
}
function addAdopterLocation(sheet, location) {
var adopter = document.createElement('style');
$adoptersByLocation.get(sheet).set(location, adopter);
$locations.get(sheet).push(location);
return adopter;
}
function getAdopterByLocation(sheet, location) {
return $adoptersByLocation.get(sheet).get(location);
}
function removeAdopterLocation(sheet, location) {
$adoptersByLocation.get(sheet).delete(location);
$locations.set(sheet, $locations.get(sheet).filter(function(_location) {
return _location !== location;
}));
}
function restyleAdopter(sheet, adopter) {
requestAnimationFrame(function() {
clearRules(adopter.sheet);
insertAllRules($basicStyleSheet.get(sheet), adopter.sheet);
});
}
function checkInvocationCorrectness(self) {
if (!$basicStyleSheet.has(self)) throw new TypeError('Illegal invocation');
}
function ConstructedStyleSheet() {
var self = this;
var style = document.createElement('style');
bootstrapper.body.appendChild(style);
$basicStyleSheet.set(self, style.sheet);
$locations.set(self, []);
$adoptersByLocation.set(self, new WeakMap());
}
function getAssociatedLocation(element) {
var location = locations.get(element);
if (!location) {
location = new Location(element);
locations.set(element, location);
}
return location;
}
function attachAdoptedStyleSheetProperty(constructor) {
defineProperty(constructor.prototype, 'adoptedStyleSheets', {
configurable: !0,
enumerable: !0,
get: function() {
return getAssociatedLocation(this).sheets;
},
set: function(sheets) {
getAssociatedLocation(this).update(sheets);
}
});
}
function traverseWebComponents(node, callback) {
var iter = document.createNodeIterator(node, NodeFilter.SHOW_ELEMENT, function(foundNode) {
return getShadowRoot(foundNode) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
}, null, !1);
for (var next = void 0; next = iter.nextNode(); ) callback(getShadowRoot(next));
}
function isExistingAdopter(self, element) {
return element instanceof HTMLStyleElement && $uniqueSheets.get(self).some(function(sheet) {
return getAdopterByLocation(sheet, self);
});
}
function getAdopterContainer(self) {
var element = $element.get(self);
return element instanceof Document ? element.body : element;
}
function adopt(self) {
var styleList = document.createDocumentFragment();
var sheets = $uniqueSheets.get(self);
var observer = $observer.get(self);
var container = getAdopterContainer(self);
observer.disconnect();
sheets.forEach(function(sheet) {
styleList.appendChild(getAdopterByLocation(sheet, self) || addAdopterLocation(sheet, self));
});
container.insertBefore(styleList, null);
observer.observe(container, defaultObserverOptions);
sheets.forEach(function(sheet) {
restyleAdopter(sheet, getAdopterByLocation(sheet, self));
});
}
function Location(element) {
var self = this;
self.sheets = [];
$element.set(self, element);
$uniqueSheets.set(self, []);
$observer.set(self, new MutationObserver(function(mutations, observer) {
if (document) mutations.forEach(function(mutation) {
if (!hasShadyCss) forEach.call(mutation.addedNodes, function(node) {
if (node instanceof Element) traverseWebComponents(node, function(root) {
getAssociatedLocation(root).connect();
});
});
forEach.call(mutation.removedNodes, function(node) {
if (node instanceof Element) {
if (isExistingAdopter(self, node)) adopt(self);
if (!hasShadyCss) traverseWebComponents(node, function(root) {
getAssociatedLocation(root).disconnect();
});
}
});
}); else observer.disconnect();
}));
}
if (!('adoptedStyleSheets' in document)) {
var hasShadyCss = 'ShadyCSS' in window && !ShadyCSS.nativeShadow;
var bootstrapper = document.implementation.createHTMLDocument('boot');
var closedShadowRootRegistry = new WeakMap();
var _DOMException = 'object' == typeof DOMException ? Error : DOMException;
var defineProperty = Object.defineProperty;
var forEach = Array.prototype.forEach;
var importPattern = /@import.+?;?$/gm;
var cssStyleSheetMethods = [ 'addImport', 'addPageRule', 'addRule', 'deleteRule', 'insertRule', 'removeImport', 'removeRule' ];
var NonConstructedStyleSheet = CSSStyleSheet;
var nonConstructedProto = NonConstructedStyleSheet.prototype;
nonConstructedProto.replace = function() {
return Promise.reject(new _DOMException("Can't call replace on non-constructed CSSStyleSheets."));
};
nonConstructedProto.replaceSync = function() {
throw new _DOMException("Failed to execute 'replaceSync' on 'CSSStyleSheet': Can't call replaceSync on non-constructed CSSStyleSheets.");
};
var $basicStyleSheet = new WeakMap();
var $locations = new WeakMap();
var $adoptersByLocation = new WeakMap();
var proto$2 = ConstructedStyleSheet.prototype;
proto$2.replace = function(contents) {
try {
this.replaceSync(contents);
return Promise.resolve(this);
} catch (e) {
return Promise.reject(e);
}
};
proto$2.replaceSync = function(contents) {
checkInvocationCorrectness(this);
if ('string' == typeof contents) {
var self_1 = this;
var style = $basicStyleSheet.get(self_1).ownerNode;
style.textContent = rejectImports(contents);
$basicStyleSheet.set(self_1, style.sheet);
$locations.get(self_1).forEach(function(location) {
if (location.isConnected()) restyleAdopter(self_1, getAdopterByLocation(self_1, location));
});
}
};
defineProperty(proto$2, 'cssRules', {
configurable: !0,
enumerable: !0,
get: function() {
checkInvocationCorrectness(this);
return $basicStyleSheet.get(this).cssRules;
}
});
cssStyleSheetMethods.forEach(function(method) {
proto$2[method] = function() {
var self = this;
checkInvocationCorrectness(self);
var args = arguments;
var basic = $basicStyleSheet.get(self);
var locations = $locations.get(self);
var result = basic[method].apply(basic, args);
locations.forEach(function(location) {
if (location.isConnected()) {
var sheet = getAdopterByLocation(self, location).sheet;
sheet[method].apply(sheet, args);
}
});
return result;
};
l.onerror = reject;
l.href = 'data:text/css;base64,' + btoa(cssText);
DOC.head.appendChild(l);
});
};
CSSStyleSheet.prototype.replaceSync = function(cssText) {
var style = this[INTERNAL];
if (cssText.replace(/\/\*[\s\S]+?\*\//g, '').match(/@import\s*\(\s*(['"])[^\1]*?\1\s*\)/)) throw Error('no');
style.firstChild.data = cssText;
for (var i = 0; i < style.childSheets.length; i++) style.childSheets[i].firstChild.data = cssText;
};
var oldInnerHTML = Object.getOwnPropertyDescriptor(ShadowRoot.prototype, 'innerHTML');
var oldFirstChild = Object.getOwnPropertyDescriptor(Node.prototype, 'firstChild');
var oldLastChild = Object.getOwnPropertyDescriptor(Node.prototype, 'lastChild');
Object.defineProperties(ShadowRoot.prototype, {
firstChild: {
get: function() {
var child = oldFirstChild.get.call(this);
while (child) {
if (null == child[INTERNAL]) break;
child = child.nextSibling;
}
return child;
}
},
lastChild: {
get: function() {
var child = oldLastChild.get.call(this);
while (child) {
if (null == child[INTERNAL]) break;
child = child.previousSibling;
}
return child;
}
},
innerHTML: {
get: function() {
var html = '';
var child = oldFirstChild.get.call(this);
while (child) {
if (!child[INTERNAL]) {
if (3 === child.nodeType) html += child.data;
html += child.outerHTML;
}
child = child.nextSibling;
}
return html;
},
set: function(html) {
var child = oldFirstChild.get.call(this);
var sheets = [];
while (child) {
if (child[INTERNAL]) sheets.push(child);
child = child.nextSibling;
}
oldInnerHTML.set.call(this, html);
child = oldFirstChild.get.call(this);
for (var i = 0; i < sheets.length; i++) this.insertBefore(sheets[i], child);
}
},
adoptedStyleSheets: {
get: function() {
var state = getState(this);
return state.adoptedStyleSheets;
},
set: function(value) {
var state = getState(this);
var previous = state.adoptedStyleSheets.slice();
var indices = [];
if (!Array.isArray(value)) value = [].concat(value || []);
state.adoptedStyleSheets = value;
for (var i = 0; i < value.length; i++) {
var v = value[i];
var index = previous.indexOf(v);
if (-1 === index) {
var style = v[INTERNAL];
var clone = style.cloneNode(!0);
clone[INTERNAL] = {};
style.childSheets.push(clone);
this.appendChild(clone);
} else indices[index] = !0;
}
for (var i = 0; i < previous.length; i++) if (!0 !== indices[i]) {
var prev = previous[i][INTERNAL];
for (var j = 0; j < prev.childSheets.length; j++) {
var sheet = prev.childSheets[j];
if (sheet.parentNode === this) {
this.removeChild(sheet);
prev.childSheets.splice(j, 1);
break;
}
}
}
}
defineProperty(ConstructedStyleSheet, Symbol.hasInstance, {
configurable: !0,
value: isCSSStyleSheetInstance
});
var defaultObserverOptions = {
childList: !0,
subtree: !0
};
var locations = new WeakMap();
var $element = new WeakMap();
var $uniqueSheets = new WeakMap();
var $observer = new WeakMap();
var proto$1 = Location.prototype;
proto$1.isConnected = function() {
var element = $element.get(this);
return element instanceof Document ? 'loading' !== element.readyState : isElementConnected(element.host);
};
proto$1.connect = function() {
var container = getAdopterContainer(this);
$observer.get(this).observe(container, defaultObserverOptions);
if ($uniqueSheets.get(this).length > 0) adopt(this);
traverseWebComponents(container, function(root) {
getAssociatedLocation(root).connect();
});
};
proto$1.disconnect = function() {
$observer.get(this).disconnect();
};
proto$1.update = function(sheets) {
var self = this;
var locationType = $element.get(self) === document ? 'Document' : 'ShadowRoot';
if (!Array.isArray(sheets)) throw new TypeError("Failed to set the 'adoptedStyleSheets' property on " + locationType + ": Iterator getter is not callable.");
if (!sheets.every(isCSSStyleSheetInstance)) throw new TypeError("Failed to set the 'adoptedStyleSheets' property on " + locationType + ": Failed to convert value to 'CSSStyleSheet'");
if (sheets.some(isNonConstructedStyleSheetInstance)) throw new TypeError("Failed to set the 'adoptedStyleSheets' property on " + locationType + ": Can't adopt non-constructed stylesheets");
self.sheets = sheets;
var oldUniqueSheets = $uniqueSheets.get(self);
var uniqueSheets = unique(sheets);
var removedSheets = diff(oldUniqueSheets, uniqueSheets);
removedSheets.forEach(function(sheet) {
removeNode(getAdopterByLocation(sheet, self));
removeAdopterLocation(sheet, self);
});
$uniqueSheets.set(self, uniqueSheets);
if (self.isConnected() && uniqueSheets.length > 0) adopt(self);
};
window.CSSStyleSheet = ConstructedStyleSheet;
attachAdoptedStyleSheetProperty(Document);
if ('ShadowRoot' in window) {
attachAdoptedStyleSheetProperty(ShadowRoot);
var proto = Element.prototype;
var attach_1 = proto.attachShadow;
proto.attachShadow = function(init) {
var root = attach_1.call(this, init);
if ('closed' === init.mode) closedShadowRootRegistry.set(this, root);
return root;
};
}
});
var documentLocation = getAssociatedLocation(document);
if (documentLocation.isConnected()) documentLocation.connect(); else document.addEventListener('DOMContentLoaded', documentLocation.connect.bind(documentLocation));
}
}();
h.f = Fragment;
var html = htm.bind(h);

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -5,8 +5,7 @@
<body>
<script src="b.js"></script>
<my-counter count="4">
</my-component>
<my-counter count="4"></my-counter>
</body>
</html>

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,12 @@
<html>
<head></head>
<body>
<script src="b.js"></script>
<twind-button>
</twind-button>
</body>
</html>

View File

@ -0,0 +1,17 @@
import { define, WeElement } from '../../src/omi'
import { create, cssomSheet } from 'twind'
const sheet = cssomSheet({ target: new CSSStyleSheet() })
const { tw } = create({ sheet })
define('twind-button', class extends WeElement {
static css = sheet.target
render() {
return (
<button class={tw`bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded`} >twind button</button>
)
}
})

View File

@ -1,6 +1,6 @@
{
"name": "omi",
"version": "6.19.5",
"version": "6.19.6",
"description": "Front End Cross-Frameworks Framework.",
"main": "dist/omi.js",
"jsnext:main": "dist/omi.esm.js",
@ -123,6 +123,7 @@
"sinon": "^4.4.2",
"sinon-chai": "^3.0.0",
"to2to": "^1.0.2",
"twind": "^0.16.16",
"typescript": "^2.8.1",
"uglify-js": "^2.7.5",
"webpack": "^4.3.0"
@ -149,5 +150,7 @@
"tabWidth": 2,
"useTabs": false
},
"dependencies": {}
"dependencies": {
"construct-style-sheets-polyfill": "^3.0.0-0"
}
}

View File

@ -1,247 +0,0 @@
(function () {
try {
new window.CSSStyleSheet('a{}');
return;
} catch (e) { }
// TODO: this could really just by a dunderprop to keep the polyfill light.
const INTERNAL = typeof Symbol !== 'undefined' ? Symbol('__s') : '__s';
/**
* Problem 1:
* CSSStyleSheet is nonconfigurable.
* This means we're stuck with a ponyfill and not a "perfect" polyfill.
*/
// Object.defineProperty(window, 'CSSStyleSheet', {
// configurable: true,
// enumerable: true,
// get: () => CSSStyleSheet
// });
const OriginalCSSStyleSheet = window.CSSStyleSheet;
window.CSSStyleSheet = CSSStyleSheet;
let DOC;
let counter = 0;
/**
* Problem #2:
* CSSStyleSheet is not instantiable.
* We can inherit from the real CSSStyleSheet in order to
*/
function CSSStyleSheet(options) {
if (!DOC) {
const frame = document.createElement('iframe');
frame.style.cssText =
'position:absolute;left:0;top:-9999px;width:1px;height:1px;';
document.body.appendChild(frame);
DOC = frame.contentWindow.document;
}
const style = DOC.createElement('style');
style.$id = ++counter;
style.childSheets = [];
style.appendChild(DOC.createTextNode(''));
DOC.body.appendChild(style);
// console.log(style, sheet);
Object.assign(style.sheet, options || {});
this[INTERNAL] = style;
}
// we can be nice and ensure that this holds:
// document.createElement('style').stylesheet instanceof CSSStyleSeetPolyfill
CSSStyleSheet.prototype = Object.create(OriginalCSSStyleSheet);
Object.defineProperty(CSSStyleSheet.prototype, 'cssRules', {
get() {
return this[INTERNAL].sheet.cssRules;
}
});
CSSStyleSheet.prototype.replace = function (cssText) {
const style = this[INTERNAL];
return new Promise((resolve, reject) => {
const l = DOC.createElement('link');
l.rel = 'preload';
l.as = 'style';
l.onload = () => {
// sheet.ownerNode.firstChild.textContent = cssText;
style.firstChild.data = cssText;
for (let i = 0; i < style.childSheets.length; i++) {
style.childSheets[i].firstChild.data = cssText;
}
// if (sheet.cssRules[0]) sheet.deleteRule(0);
// sheet.insertRule(cssText);
l.remove();
resolve();
};
l.onerror = reject;
l.href = 'data:text/css;base64,' + btoa(cssText);
DOC.head.appendChild(l);
});
};
CSSStyleSheet.prototype.replaceSync = function (cssText) {
const style = this[INTERNAL];
if (
cssText
.replace(/\/\*[\s\S]+?\*\//g, '')
.match(/@import\s*\(\s*(['"])[^\1]*?\1\s*\)/)
) {
throw Error('no');
}
// if (sheet.cssRules[0]) sheet.deleteRule(0);
// sheet.insertRule(cssText);
// sheet.ownerNode.firstChild.textContent = cssText;
style.firstChild.data = cssText;
for (let i = 0; i < style.childSheets.length; i++) {
style.childSheets[i].firstChild.data = cssText;
}
};
const oldInnerHTML = Object.getOwnPropertyDescriptor(
ShadowRoot.prototype,
'innerHTML'
);
const oldFirstChild = Object.getOwnPropertyDescriptor(
Node.prototype,
'firstChild'
);
const oldLastChild = Object.getOwnPropertyDescriptor(
Node.prototype,
'lastChild'
);
function getState(obj) {
return (
obj[INTERNAL] ||
(obj[INTERNAL] = {
adoptedStyleSheets: [],
sheets: [],
id: ++counter
})
);
}
Object.defineProperties(ShadowRoot.prototype, {
firstChild: {
get() {
let child = oldFirstChild.get.call(this);
while (child) {
if (child[INTERNAL] == null) break;
child = child.nextSibling;
}
return child;
}
},
lastChild: {
get() {
let child = oldLastChild.get.call(this);
while (child) {
if (child[INTERNAL] == null) break;
child = child.previousSibling;
}
return child;
}
},
// @TODO
// childNodes: {},
// children: {},
innerHTML: {
get() {
let html = '';
let child = oldFirstChild.get.call(this);
while (child) {
if (!child[INTERNAL]) {
if (child.nodeType === 3) html += child.data;
html += child.outerHTML;
}
child = child.nextSibling;
}
return html;
// return old.get.call(this).replace(/</);
},
set(html) {
let child = oldFirstChild.get.call(this);
let sheets = [];
while (child) {
if (child[INTERNAL]) sheets.push(child);
child = child.nextSibling;
}
oldInnerHTML.set.call(this, html);
child = oldFirstChild.get.call(this);
for (let i = 0; i < sheets.length; i++) {
this.insertBefore(sheets[i], child);
}
// this.insertAdjacentHTML(html, 'beforeend');
}
},
adoptedStyleSheets: {
get() {
const state = getState(this);
return state.adoptedStyleSheets;
},
// @TODO:
// Chrome's implementation doesn't do any diffing, so the polyfill needn't either.
// Also, we should always clone the passed Array and freeze it if available.
set(value) {
const state = getState(this);
let previous = state.adoptedStyleSheets.slice();
const indices = [];
if (!Array.isArray(value)) {
value = [].concat(value || []);
}
// this[INTERNAL] = value;
state.adoptedStyleSheets = value;
for (let i = 0; i < value.length; i++) {
const v = value[i];
const index = previous.indexOf(v);
if (index === -1) {
const style = v[INTERNAL];
const clone = style.cloneNode(true);
// clone.setAttribute('data-is-constructed', state.id);
clone[INTERNAL] = {};
// clone.$parent = style;
style.childSheets.push(clone);
// clone.textContent = style.textContent;
// clone.$id = style.$id;
// state.sheets.push(clone);
this.appendChild(clone);
// console.log(this, clone, this.childNodes);
// console.log(`found new sheet, adding.`, clone);
} else {
indices[index] = true;
// const style = v[INTERNAL];
}
}
for (let i = 0; i < previous.length; i++) {
if (indices[i] !== true) {
const prev = previous[i][INTERNAL];
// const style = prev.$parent;
for (let j = 0; j < prev.childSheets.length; j++) {
const sheet = prev.childSheets[j];
if (sheet.parentNode === this) {
this.removeChild(sheet);
prev.childSheets.splice(j, 1);
break;
}
}
// for (let j = 0; j < state.sheets.length; j++) {
// if (state.sheets[j].$id === prev.$id) {
// state.sheets[j].remove();
// break;
// }
// }
}
}
}
}
});
}());

View File

@ -13,14 +13,14 @@ import htm from 'htm'
import { extend, get, set, bind, unbind } from './extend'
import JSONProxy from './proxy'
import { Fragment } from './util'
import './constructable-stylesheets-polyfill'
import 'construct-style-sheets-polyfill'
h.f = Fragment
const html = htm.bind(h)
function createRef() {
return {}
return {}
}
const $ = {}
@ -29,32 +29,32 @@ const defineElement = define
const elements = options.mapping
const omi = {
tag,
WeElement,
Component,
render,
h,
createElement,
options,
define,
cloneElement,
getHost,
rpx,
defineElement,
classNames,
extractClass,
createRef,
html,
htm,
o,
elements,
$,
extend,
get,
set,
bind,
unbind,
JSONProxy
tag,
WeElement,
Component,
render,
h,
createElement,
options,
define,
cloneElement,
getHost,
rpx,
defineElement,
classNames,
extractClass,
createRef,
html,
htm,
o,
elements,
$,
extend,
get,
set,
bind,
unbind,
JSONProxy
}
options.root.Omi = omi
@ -64,30 +64,30 @@ options.root.Omi.version = '6.19.3'
export default omi
export {
tag,
WeElement,
Component,
render,
h,
createElement,
options,
define,
cloneElement,
getHost,
rpx,
defineElement,
classNames,
extractClass,
createRef,
html,
htm,
o,
elements,
$,
extend,
get,
set,
bind,
unbind,
JSONProxy
tag,
WeElement,
Component,
render,
h,
createElement,
options,
define,
cloneElement,
getHost,
rpx,
defineElement,
classNames,
extractClass,
createRef,
html,
htm,
o,
elements,
$,
extend,
get,
set,
bind,
unbind,
JSONProxy
}

View File

@ -112,9 +112,11 @@ export default class WeElement extends HTMLElement {
if (this.constructor.css) {
if (typeof this.constructor.css === 'string') {
console.log(1111)
this.styleSheet = new CSSStyleSheet()
this.styleSheet.replaceSync(this.constructor.css)
} else {
console.log(this.constructor.css)
this.styleSheet = this.constructor.css
}
shadowRoot.adoptedStyleSheets = [this.styleSheet]

View File

@ -1,96 +1,96 @@
import {
define,
render,
WeElement
define,
render,
WeElement
} from '../../src/omi'
describe('css', () => {
let scratch
//const Empty = () => null
let scratch
//const Empty = () => null
before(() => {
scratch = document.createElement('div')
; (document.body || document.documentElement).appendChild(scratch)
})
before(() => {
scratch = document.createElement('div')
; (document.body || document.documentElement).appendChild(scratch)
})
beforeEach(() => {
//let c = scratch.firstElementChild;
//if (c) render(<Empty />, scratch, { merge: c })
scratch.innerHTML = ''
})
beforeEach(() => {
//let c = scratch.firstElementChild;
//if (c) render(<Empty />, scratch, { merge: c })
scratch.innerHTML = ''
})
after(() => {
scratch.parentNode.removeChild(scratch)
scratch = null
})
after(() => {
scratch.parentNode.removeChild(scratch)
scratch = null
})
define('hello-element', class extends WeElement {
static css = 'div{color:red;}'
define('hello-element', class extends WeElement {
static css = 'div{color:red;}'
render() {
return (
<div >
ABC
render() {
return (
<div >
ABC
</div>
)
}
})
)
}
})
it('base ', () => {
it('base ', () => {
define('my-app', class extends WeElement {
define('my-app', class extends WeElement {
myCSS = `
myCSS = `
div{
color:green !important;
}`
render(props, data) {
return (
<div >
<hello-element css={this.myCSS} />
</div>
)
}
})
render(<my-app />, scratch)
expect(getComputedStyle(scratch.firstChild.shadowRoot.firstChild.firstChild.shadowRoot.lastElementChild).color).to.equal('rgb(0, 128, 0)')
})
it('base2 ', () => {
var a
define('my-appx', class extends WeElement {
myCSS = `
div{
color:green;
}`
install() {
a = this
}
render(props, data) {
return (
<div >
<hello-element css={this.myCSS} />
</div>
)
}
})
render(<my-app />, scratch)
expect(getComputedStyle(scratch.firstChild.shadowRoot.firstChild.firstChild.shadowRoot.lastElementChild).color).to.equal('rgb(0, 128, 0)')
})
render(props, data) {
return (
<div onClick={this.onClick}>
<hello-element css={this.myCSS} />
</div>
)
}
})
it('base2 ', () => {
var a
define('my-appx', class extends WeElement {
myCSS = `
div{
color:green;
}`
install() {
a = this
}
render(props, data) {
return (
<div onClick={this.onClick}>
<hello-element css={this.myCSS} />
</div>
)
}
})
render(<my-appx />, scratch)
a.myCSS = `
render(<my-appx />, scratch)
a.myCSS = `
div{
color:blue;
color:blue !important;
}`
a.update()
a.update()
expect(getComputedStyle(scratch.firstChild.shadowRoot.firstChild.firstChild.shadowRoot.lastElementChild).color).to.equal('rgb(0, 0, 255)')
})
expect(getComputedStyle(scratch.firstChild.shadowRoot.firstChild.firstChild.shadowRoot.lastElementChild).color).to.equal('rgb(0, 0, 255)')
})
})