vue-wc-wrapper.global.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. var wrapVueWebComponent = (function () {
  2. 'use strict';
  3. const camelizeRE = /-(\w)/g;
  4. const camelize = str => {
  5. return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
  6. };
  7. const hyphenateRE = /\B([A-Z])/g;
  8. const hyphenate = str => {
  9. return str.replace(hyphenateRE, '-$1').toLowerCase()
  10. };
  11. function getInitialProps (propsList) {
  12. const res = {};
  13. propsList.forEach(key => {
  14. res[key] = undefined;
  15. });
  16. return res
  17. }
  18. function injectHook (options, key, hook) {
  19. options[key] = [].concat(options[key] || []);
  20. options[key].unshift(hook);
  21. }
  22. function callHooks (vm, hook) {
  23. if (vm) {
  24. const hooks = vm.$options[hook] || [];
  25. hooks.forEach(hook => {
  26. hook.call(vm);
  27. });
  28. }
  29. }
  30. function createCustomEvent (name, args) {
  31. return new CustomEvent(name, {
  32. bubbles: false,
  33. cancelable: false,
  34. detail: args
  35. })
  36. }
  37. const isBoolean = val => /function Boolean/.test(String(val));
  38. const isNumber = val => /function Number/.test(String(val));
  39. function convertAttributeValue (value, name, { type } = {}) {
  40. if (isBoolean(type)) {
  41. if (value === 'true' || value === 'false') {
  42. return value === 'true'
  43. }
  44. if (value === '' || value === name || value != null) {
  45. return true
  46. }
  47. return value
  48. } else if (isNumber(type)) {
  49. const parsed = parseFloat(value, 10);
  50. return isNaN(parsed) ? value : parsed
  51. } else {
  52. return value
  53. }
  54. }
  55. function toVNodes (h, children) {
  56. const res = [];
  57. for (let i = 0, l = children.length; i < l; i++) {
  58. res.push(toVNode(h, children[i]));
  59. }
  60. return res
  61. }
  62. function toVNode (h, node) {
  63. if (node.nodeType === 3) {
  64. return node.data.trim() ? node.data : null
  65. } else if (node.nodeType === 1) {
  66. const data = {
  67. attrs: getAttributes(node),
  68. domProps: {
  69. innerHTML: node.innerHTML
  70. }
  71. };
  72. if (data.attrs.slot) {
  73. data.slot = data.attrs.slot;
  74. delete data.attrs.slot;
  75. }
  76. return h(node.tagName, data)
  77. } else {
  78. return null
  79. }
  80. }
  81. function getAttributes (node) {
  82. const res = {};
  83. for (let i = 0, l = node.attributes.length; i < l; i++) {
  84. const attr = node.attributes[i];
  85. res[attr.nodeName] = attr.nodeValue;
  86. }
  87. return res
  88. }
  89. function wrap (Vue, Component) {
  90. const isAsync = typeof Component === 'function' && !Component.cid;
  91. let isInitialized = false;
  92. let hyphenatedPropsList;
  93. let camelizedPropsList;
  94. let camelizedPropsMap;
  95. function initialize (Component) {
  96. if (isInitialized) return
  97. const options = typeof Component === 'function'
  98. ? Component.options
  99. : Component;
  100. // extract props info
  101. const propsList = Array.isArray(options.props)
  102. ? options.props
  103. : Object.keys(options.props || {});
  104. hyphenatedPropsList = propsList.map(hyphenate);
  105. camelizedPropsList = propsList.map(camelize);
  106. const originalPropsAsObject = Array.isArray(options.props) ? {} : options.props || {};
  107. camelizedPropsMap = camelizedPropsList.reduce((map, key, i) => {
  108. map[key] = originalPropsAsObject[propsList[i]];
  109. return map
  110. }, {});
  111. // proxy $emit to native DOM events
  112. injectHook(options, 'beforeCreate', function () {
  113. const emit = this.$emit;
  114. this.$emit = (name, ...args) => {
  115. this.$root.$options.customElement.dispatchEvent(createCustomEvent(name, args));
  116. return emit.call(this, name, ...args)
  117. };
  118. });
  119. injectHook(options, 'created', function () {
  120. // sync default props values to wrapper on created
  121. camelizedPropsList.forEach(key => {
  122. this.$root.props[key] = this[key];
  123. });
  124. });
  125. // proxy props as Element properties
  126. camelizedPropsList.forEach(key => {
  127. Object.defineProperty(CustomElement.prototype, key, {
  128. get () {
  129. return this._wrapper.props[key]
  130. },
  131. set (newVal) {
  132. this._wrapper.props[key] = newVal;
  133. },
  134. enumerable: false,
  135. configurable: true
  136. });
  137. });
  138. isInitialized = true;
  139. }
  140. function syncAttribute (el, key) {
  141. const camelized = camelize(key);
  142. const value = el.hasAttribute(key) ? el.getAttribute(key) : undefined;
  143. el._wrapper.props[camelized] = convertAttributeValue(
  144. value,
  145. key,
  146. camelizedPropsMap[camelized]
  147. );
  148. }
  149. class CustomElement extends HTMLElement {
  150. constructor () {
  151. const self = super();
  152. self.attachShadow({ mode: 'open' });
  153. const wrapper = self._wrapper = new Vue({
  154. name: 'shadow-root',
  155. customElement: self,
  156. shadowRoot: self.shadowRoot,
  157. data () {
  158. return {
  159. props: {},
  160. slotChildren: []
  161. }
  162. },
  163. render (h) {
  164. return h(Component, {
  165. ref: 'inner',
  166. props: this.props
  167. }, this.slotChildren)
  168. }
  169. });
  170. // Use MutationObserver to react to future attribute & slot content change
  171. const observer = new MutationObserver(mutations => {
  172. let hasChildrenChange = false;
  173. for (let i = 0; i < mutations.length; i++) {
  174. const m = mutations[i];
  175. if (isInitialized && m.type === 'attributes' && m.target === self) {
  176. syncAttribute(self, m.attributeName);
  177. } else {
  178. hasChildrenChange = true;
  179. }
  180. }
  181. if (hasChildrenChange) {
  182. wrapper.slotChildren = Object.freeze(toVNodes(
  183. wrapper.$createElement,
  184. self.childNodes
  185. ));
  186. }
  187. });
  188. observer.observe(self, {
  189. childList: true,
  190. subtree: true,
  191. characterData: true,
  192. attributes: true
  193. });
  194. }
  195. get vueComponent () {
  196. return this._wrapper.$refs.inner
  197. }
  198. connectedCallback () {
  199. const wrapper = this._wrapper;
  200. if (!wrapper._isMounted) {
  201. // initialize attributes
  202. const syncInitialAttributes = () => {
  203. wrapper.props = getInitialProps(camelizedPropsList);
  204. hyphenatedPropsList.forEach(key => {
  205. syncAttribute(this, key);
  206. });
  207. };
  208. if (isInitialized) {
  209. syncInitialAttributes();
  210. } else {
  211. // async & unresolved
  212. Component().then(resolved => {
  213. if (resolved.__esModule || resolved[Symbol.toStringTag] === 'Module') {
  214. resolved = resolved.default;
  215. }
  216. initialize(resolved);
  217. syncInitialAttributes();
  218. });
  219. }
  220. // initialize children
  221. wrapper.slotChildren = Object.freeze(toVNodes(
  222. wrapper.$createElement,
  223. this.childNodes
  224. ));
  225. wrapper.$mount();
  226. this.shadowRoot.appendChild(wrapper.$el);
  227. } else {
  228. callHooks(this.vueComponent, 'activated');
  229. }
  230. }
  231. disconnectedCallback () {
  232. callHooks(this.vueComponent, 'deactivated');
  233. }
  234. }
  235. if (!isAsync) {
  236. initialize(Component);
  237. }
  238. return CustomElement
  239. }
  240. return wrap;
  241. }());