vue-meta.js 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737
  1. /**
  2. * vue-meta v2.4.0
  3. * (c) 2020
  4. * - Declan de Wet
  5. * - Sébastien Chopin (@Atinux)
  6. * - Pim (@pimlie)
  7. * - All the amazing contributors
  8. * @license MIT
  9. */
  10. (function (global, factory) {
  11. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  12. typeof define === 'function' && define.amd ? define(factory) :
  13. (global = global || self, global.VueMeta = factory());
  14. }(this, (function () { 'use strict';
  15. var version = "2.4.0";
  16. function _typeof(obj) {
  17. "@babel/helpers - typeof";
  18. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  19. _typeof = function (obj) {
  20. return typeof obj;
  21. };
  22. } else {
  23. _typeof = function (obj) {
  24. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  25. };
  26. }
  27. return _typeof(obj);
  28. }
  29. function _unsupportedIterableToArray(o, minLen) {
  30. if (!o) return;
  31. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  32. var n = Object.prototype.toString.call(o).slice(8, -1);
  33. if (n === "Object" && o.constructor) n = o.constructor.name;
  34. if (n === "Map" || n === "Set") return Array.from(o);
  35. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  36. }
  37. function _arrayLikeToArray(arr, len) {
  38. if (len == null || len > arr.length) len = arr.length;
  39. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  40. return arr2;
  41. }
  42. function _createForOfIteratorHelper(o, allowArrayLike) {
  43. var it;
  44. if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
  45. if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
  46. if (it) o = it;
  47. var i = 0;
  48. var F = function () {};
  49. return {
  50. s: F,
  51. n: function () {
  52. if (i >= o.length) return {
  53. done: true
  54. };
  55. return {
  56. done: false,
  57. value: o[i++]
  58. };
  59. },
  60. e: function (e) {
  61. throw e;
  62. },
  63. f: F
  64. };
  65. }
  66. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  67. }
  68. var normalCompletion = true,
  69. didErr = false,
  70. err;
  71. return {
  72. s: function () {
  73. it = o[Symbol.iterator]();
  74. },
  75. n: function () {
  76. var step = it.next();
  77. normalCompletion = step.done;
  78. return step;
  79. },
  80. e: function (e) {
  81. didErr = true;
  82. err = e;
  83. },
  84. f: function () {
  85. try {
  86. if (!normalCompletion && it.return != null) it.return();
  87. } finally {
  88. if (didErr) throw err;
  89. }
  90. }
  91. };
  92. }
  93. /**
  94. * checks if passed argument is an array
  95. * @param {any} arg - the object to check
  96. * @return {Boolean} - true if `arg` is an array
  97. */
  98. function isArray(arg) {
  99. return Array.isArray(arg);
  100. }
  101. function isUndefined(arg) {
  102. return typeof arg === 'undefined';
  103. }
  104. function isObject(arg) {
  105. return _typeof(arg) === 'object';
  106. }
  107. function isPureObject(arg) {
  108. return _typeof(arg) === 'object' && arg !== null;
  109. }
  110. function isFunction(arg) {
  111. return typeof arg === 'function';
  112. }
  113. function isString(arg) {
  114. return typeof arg === 'string';
  115. }
  116. function hasGlobalWindowFn() {
  117. try {
  118. return !isUndefined(window);
  119. } catch (e) {
  120. return false;
  121. }
  122. }
  123. var hasGlobalWindow = hasGlobalWindowFn();
  124. var _global = hasGlobalWindow ? window : global;
  125. var console = _global.console || {};
  126. function warn(str) {
  127. /* istanbul ignore next */
  128. if (!console || !console.warn) {
  129. return;
  130. }
  131. console.warn(str);
  132. }
  133. var showWarningNotSupportedInBrowserBundle = function showWarningNotSupportedInBrowserBundle(method) {
  134. return warn("".concat(method, " is not supported in browser builds"));
  135. };
  136. var showWarningNotSupported = function showWarningNotSupported() {
  137. return warn('This vue app/component has no vue-meta configuration');
  138. };
  139. /**
  140. * These are constant variables used throughout the application.
  141. */
  142. // set some sane defaults
  143. var defaultInfo = {
  144. title: undefined,
  145. titleChunk: '',
  146. titleTemplate: '%s',
  147. htmlAttrs: {},
  148. bodyAttrs: {},
  149. headAttrs: {},
  150. base: [],
  151. link: [],
  152. meta: [],
  153. style: [],
  154. script: [],
  155. noscript: [],
  156. __dangerouslyDisableSanitizers: [],
  157. __dangerouslyDisableSanitizersByTagID: {}
  158. };
  159. var rootConfigKey = '_vueMeta'; // This is the name of the component option that contains all the information that
  160. // gets converted to the various meta tags & attributes for the page.
  161. var keyName = 'metaInfo'; // This is the attribute vue-meta arguments on elements to know which it should
  162. // manage and which it should ignore.
  163. var attribute = 'data-vue-meta'; // This is the attribute that goes on the `html` tag to inform `vue-meta`
  164. // that the server has already generated the meta tags for the initial render.
  165. var ssrAttribute = 'data-vue-meta-server-rendered'; // This is the property that tells vue-meta to overwrite (instead of append)
  166. // an item in a tag list. For example, if you have two `meta` tag list items
  167. // that both have `vmid` of "description", then vue-meta will overwrite the
  168. // shallowest one with the deepest one.
  169. var tagIDKeyName = 'vmid'; // This is the key name for possible meta templates
  170. var metaTemplateKeyName = 'template'; // This is the key name for the content-holding property
  171. var contentKeyName = 'content'; // The id used for the ssr app
  172. var ssrAppId = 'ssr'; // How long meta update
  173. var debounceWait = 10; // How long meta update
  174. var waitOnDestroyed = true;
  175. var defaultOptions = {
  176. keyName: keyName,
  177. attribute: attribute,
  178. ssrAttribute: ssrAttribute,
  179. tagIDKeyName: tagIDKeyName,
  180. contentKeyName: contentKeyName,
  181. metaTemplateKeyName: metaTemplateKeyName,
  182. waitOnDestroyed: waitOnDestroyed,
  183. debounceWait: debounceWait,
  184. ssrAppId: ssrAppId
  185. }; // might be a bit ugly, but minimizes the browser bundles a bit
  186. var defaultInfoKeys = Object.keys(defaultInfo); // The metaInfo property keys which are used to disable escaping
  187. var disableOptionKeys = [defaultInfoKeys[12], defaultInfoKeys[13]]; // List of metaInfo property keys which are configuration options (and dont generate html)
  188. var metaInfoOptionKeys = [defaultInfoKeys[1], defaultInfoKeys[2], 'changed'].concat(disableOptionKeys); // List of metaInfo property keys which only generates attributes and no tags
  189. var metaInfoAttributeKeys = [defaultInfoKeys[3], defaultInfoKeys[4], defaultInfoKeys[5]]; // HTML elements which support the onload event
  190. var tagsSupportingOnload = ['link', 'style', 'script']; // HTML elements which dont have a head tag (shortened to our needs)
  191. var tagProperties = ['once', 'skip', 'template']; // Attributes which should be added with data- prefix
  192. var commonDataAttributes = ['body', 'pbody']; // from: https://github.com/kangax/html-minifier/blob/gh-pages/src/htmlminifier.js#L202
  193. var booleanHtmlAttributes = ['allowfullscreen', 'amp', 'amp-boilerplate', 'async', 'autofocus', 'autoplay', 'checked', 'compact', 'controls', 'declare', 'default', 'defaultchecked', 'defaultmuted', 'defaultselected', 'defer', 'disabled', 'enabled', 'formnovalidate', 'hidden', 'indeterminate', 'inert', 'ismap', 'itemscope', 'loop', 'multiple', 'muted', 'nohref', 'noresize', 'noshade', 'novalidate', 'nowrap', 'open', 'pauseonexit', 'readonly', 'required', 'reversed', 'scoped', 'seamless', 'selected', 'sortable', 'truespeed', 'typemustmatch', 'visible'];
  194. var batchId = null;
  195. function triggerUpdate(_ref, rootVm, hookName) {
  196. var debounceWait = _ref.debounceWait;
  197. // if an update was triggered during initialization or when an update was triggered by the
  198. // metaInfo watcher, set initialized to null
  199. // then we keep falsy value but know we need to run a triggerUpdate after initialization
  200. if (!rootVm[rootConfigKey].initialized && (rootVm[rootConfigKey].initializing || hookName === 'watcher')) {
  201. rootVm[rootConfigKey].initialized = null;
  202. }
  203. if (rootVm[rootConfigKey].initialized && !rootVm[rootConfigKey].pausing) {
  204. // batch potential DOM updates to prevent extraneous re-rendering
  205. // eslint-disable-next-line no-void
  206. batchUpdate(function () {
  207. return void rootVm.$meta().refresh();
  208. }, debounceWait);
  209. }
  210. }
  211. /**
  212. * Performs a batched update.
  213. *
  214. * @param {(null|Number)} id - the ID of this update
  215. * @param {Function} callback - the update to perform
  216. * @return {Number} id - a new ID
  217. */
  218. function batchUpdate(callback, timeout) {
  219. timeout = timeout === undefined ? 10 : timeout;
  220. if (!timeout) {
  221. callback();
  222. return;
  223. }
  224. clearTimeout(batchId);
  225. batchId = setTimeout(function () {
  226. callback();
  227. }, timeout);
  228. return batchId;
  229. }
  230. /*
  231. * To reduce build size, this file provides simple polyfills without
  232. * overly excessive type checking and without modifying
  233. * the global Array.prototype
  234. * The polyfills are automatically removed in the commonjs build
  235. * Also, only files in client/ & shared/ should use these functions
  236. * files in server/ still use normal js function
  237. */
  238. function find(array, predicate, thisArg) {
  239. if ( !Array.prototype.find) {
  240. // idx needs to be a Number, for..in returns string
  241. for (var idx = 0; idx < array.length; idx++) {
  242. if (predicate.call(thisArg, array[idx], idx, array)) {
  243. return array[idx];
  244. }
  245. }
  246. return;
  247. }
  248. return array.find(predicate, thisArg);
  249. }
  250. function findIndex(array, predicate, thisArg) {
  251. if ( !Array.prototype.findIndex) {
  252. // idx needs to be a Number, for..in returns string
  253. for (var idx = 0; idx < array.length; idx++) {
  254. if (predicate.call(thisArg, array[idx], idx, array)) {
  255. return idx;
  256. }
  257. }
  258. return -1;
  259. }
  260. return array.findIndex(predicate, thisArg);
  261. }
  262. function toArray(arg) {
  263. if ( !Array.from) {
  264. return Array.prototype.slice.call(arg);
  265. }
  266. return Array.from(arg);
  267. }
  268. function includes(array, value) {
  269. if ( !Array.prototype.includes) {
  270. for (var idx in array) {
  271. if (array[idx] === value) {
  272. return true;
  273. }
  274. }
  275. return false;
  276. }
  277. return array.includes(value);
  278. }
  279. var querySelector = function querySelector(arg, el) {
  280. return (el || document).querySelectorAll(arg);
  281. };
  282. function getTag(tags, tag) {
  283. if (!tags[tag]) {
  284. tags[tag] = document.getElementsByTagName(tag)[0];
  285. }
  286. return tags[tag];
  287. }
  288. function getElementsKey(_ref) {
  289. var body = _ref.body,
  290. pbody = _ref.pbody;
  291. return body ? 'body' : pbody ? 'pbody' : 'head';
  292. }
  293. function queryElements(parentNode, _ref2, attributes) {
  294. var appId = _ref2.appId,
  295. attribute = _ref2.attribute,
  296. type = _ref2.type,
  297. tagIDKeyName = _ref2.tagIDKeyName;
  298. attributes = attributes || {};
  299. var queries = ["".concat(type, "[").concat(attribute, "=\"").concat(appId, "\"]"), "".concat(type, "[data-").concat(tagIDKeyName, "]")].map(function (query) {
  300. for (var key in attributes) {
  301. var val = attributes[key];
  302. var attributeValue = val && val !== true ? "=\"".concat(val, "\"") : '';
  303. query += "[data-".concat(key).concat(attributeValue, "]");
  304. }
  305. return query;
  306. });
  307. return toArray(querySelector(queries.join(', '), parentNode));
  308. }
  309. function removeElementsByAppId(_ref3, appId) {
  310. var attribute = _ref3.attribute;
  311. toArray(querySelector("[".concat(attribute, "=\"").concat(appId, "\"]"))).map(function (el) {
  312. return el.remove();
  313. });
  314. }
  315. function removeAttribute(el, attributeName) {
  316. el.removeAttribute(attributeName);
  317. }
  318. function hasMetaInfo(vm) {
  319. vm = vm || this;
  320. return vm && (vm[rootConfigKey] === true || isObject(vm[rootConfigKey]));
  321. } // a component is in a metaInfo branch when itself has meta info or one of its (grand-)children has
  322. function inMetaInfoBranch(vm) {
  323. vm = vm || this;
  324. return vm && !isUndefined(vm[rootConfigKey]);
  325. }
  326. function pause(rootVm, refresh) {
  327. rootVm[rootConfigKey].pausing = true;
  328. return function () {
  329. return resume(rootVm, refresh);
  330. };
  331. }
  332. function resume(rootVm, refresh) {
  333. rootVm[rootConfigKey].pausing = false;
  334. if (refresh || refresh === undefined) {
  335. return rootVm.$meta().refresh();
  336. }
  337. }
  338. function addNavGuards(rootVm) {
  339. var router = rootVm.$router; // return when nav guards already added or no router exists
  340. if (rootVm[rootConfigKey].navGuards || !router) {
  341. /* istanbul ignore next */
  342. return;
  343. }
  344. rootVm[rootConfigKey].navGuards = true;
  345. router.beforeEach(function (to, from, next) {
  346. pause(rootVm);
  347. next();
  348. });
  349. router.afterEach(function () {
  350. rootVm.$nextTick(function () {
  351. var _resume = resume(rootVm),
  352. metaInfo = _resume.metaInfo;
  353. if (metaInfo && isFunction(metaInfo.afterNavigation)) {
  354. metaInfo.afterNavigation(metaInfo);
  355. }
  356. });
  357. });
  358. }
  359. var appId = 1;
  360. function createMixin(Vue, options) {
  361. // for which Vue lifecycle hooks should the metaInfo be refreshed
  362. var updateOnLifecycleHook = ['activated', 'deactivated', 'beforeMount'];
  363. var wasServerRendered = false; // watch for client side component updates
  364. return {
  365. beforeCreate: function beforeCreate() {
  366. var _this2 = this;
  367. var rootKey = '$root';
  368. var $root = this[rootKey];
  369. var $options = this.$options;
  370. var devtoolsEnabled = Vue.config.devtools;
  371. Object.defineProperty(this, '_hasMetaInfo', {
  372. configurable: true,
  373. get: function get() {
  374. // Show deprecation warning once when devtools enabled
  375. if (devtoolsEnabled && !$root[rootConfigKey].deprecationWarningShown) {
  376. warn('VueMeta DeprecationWarning: _hasMetaInfo has been deprecated and will be removed in a future version. Please use hasMetaInfo(vm) instead');
  377. $root[rootConfigKey].deprecationWarningShown = true;
  378. }
  379. return hasMetaInfo(this);
  380. }
  381. });
  382. if (this === $root) {
  383. $root.$once('hook:beforeMount', function () {
  384. wasServerRendered = this.$el && this.$el.nodeType === 1 && this.$el.hasAttribute('data-server-rendered'); // In most cases when you have a SSR app it will be the first app thats gonna be
  385. // initiated, if we cant detect the data-server-rendered attribute from Vue but we
  386. // do see our own ssrAttribute then _assume_ the Vue app with appId 1 is the ssr app
  387. // attempted fix for #404 & #562, but we rly need to refactor how we pass appIds from
  388. // ssr to the client
  389. if (!wasServerRendered && $root[rootConfigKey] && $root[rootConfigKey].appId === 1) {
  390. var htmlTag = getTag({}, 'html');
  391. wasServerRendered = htmlTag && htmlTag.hasAttribute(options.ssrAttribute);
  392. }
  393. });
  394. } // Add a marker to know if it uses metaInfo
  395. // _vnode is used to know that it's attached to a real component
  396. // useful if we use some mixin to add some meta tags (like nuxt-i18n)
  397. if (isUndefined($options[options.keyName]) || $options[options.keyName] === null) {
  398. return;
  399. }
  400. if (!$root[rootConfigKey]) {
  401. $root[rootConfigKey] = {
  402. appId: appId
  403. };
  404. appId++;
  405. if (devtoolsEnabled && $root.$options[options.keyName]) {
  406. // use nextTick so the children should be added to $root
  407. this.$nextTick(function () {
  408. // find the first child that lists fnOptions
  409. var child = find($root.$children, function (c) {
  410. return c.$vnode && c.$vnode.fnOptions;
  411. });
  412. if (child && child.$vnode.fnOptions[options.keyName]) {
  413. warn("VueMeta has detected a possible global mixin which adds a ".concat(options.keyName, " property to all Vue components on the page. This could cause severe performance issues. If possible, use $meta().addApp to add meta information instead"));
  414. }
  415. });
  416. }
  417. } // to speed up updates we keep track of branches which have a component with vue-meta info defined
  418. // if _vueMeta = true it has info, if _vueMeta = false a child has info
  419. if (!this[rootConfigKey]) {
  420. this[rootConfigKey] = true;
  421. var parent = this.$parent;
  422. while (parent && parent !== $root) {
  423. if (isUndefined(parent[rootConfigKey])) {
  424. parent[rootConfigKey] = false;
  425. }
  426. parent = parent.$parent;
  427. }
  428. } // coerce function-style metaInfo to a computed prop so we can observe
  429. // it on creation
  430. if (isFunction($options[options.keyName])) {
  431. $options.computed = $options.computed || {};
  432. $options.computed.$metaInfo = $options[options.keyName];
  433. if (!this.$isServer) {
  434. // if computed $metaInfo exists, watch it for updates & trigger a refresh
  435. // when it changes (i.e. automatically handle async actions that affect metaInfo)
  436. // credit for this suggestion goes to [Sébastien Chopin](https://github.com/Atinux)
  437. this.$on('hook:created', function () {
  438. this.$watch('$metaInfo', function () {
  439. triggerUpdate(options, this[rootKey], 'watcher');
  440. });
  441. });
  442. }
  443. } // force an initial refresh on page load and prevent other lifecycleHooks
  444. // to triggerUpdate until this initial refresh is finished
  445. // this is to make sure that when a page is opened in an inactive tab which
  446. // has throttled rAF/timers we still immediately set the page title
  447. if (isUndefined($root[rootConfigKey].initialized)) {
  448. $root[rootConfigKey].initialized = this.$isServer;
  449. if (!$root[rootConfigKey].initialized) {
  450. if (!$root[rootConfigKey].initializedSsr) {
  451. $root[rootConfigKey].initializedSsr = true;
  452. this.$on('hook:beforeMount', function () {
  453. var $root = this[rootKey]; // if this Vue-app was server rendered, set the appId to 'ssr'
  454. // only one SSR app per page is supported
  455. if (wasServerRendered) {
  456. $root[rootConfigKey].appId = options.ssrAppId;
  457. }
  458. });
  459. } // we use the mounted hook here as on page load
  460. this.$on('hook:mounted', function () {
  461. var $root = this[rootKey];
  462. if ($root[rootConfigKey].initialized) {
  463. return;
  464. } // used in triggerUpdate to check if a change was triggered
  465. // during initialization
  466. $root[rootConfigKey].initializing = true; // refresh meta in nextTick so all child components have loaded
  467. this.$nextTick(function () {
  468. var _$root$$meta$refresh = $root.$meta().refresh(),
  469. tags = _$root$$meta$refresh.tags,
  470. metaInfo = _$root$$meta$refresh.metaInfo; // After ssr hydration (identifier by tags === false) check
  471. // if initialized was set to null in triggerUpdate. That'd mean
  472. // that during initilazation changes where triggered which need
  473. // to be applied OR a metaInfo watcher was triggered before the
  474. // current hook was called
  475. // (during initialization all changes are blocked)
  476. if (tags === false && $root[rootConfigKey].initialized === null) {
  477. this.$nextTick(function () {
  478. return triggerUpdate(options, $root, 'init');
  479. });
  480. }
  481. $root[rootConfigKey].initialized = true;
  482. delete $root[rootConfigKey].initializing; // add the navigation guards if they havent been added yet
  483. // they are needed for the afterNavigation callback
  484. if (!options.refreshOnceOnNavigation && metaInfo.afterNavigation) {
  485. addNavGuards($root);
  486. }
  487. });
  488. }); // add the navigation guards if requested
  489. if (options.refreshOnceOnNavigation) {
  490. addNavGuards($root);
  491. }
  492. }
  493. }
  494. this.$on('hook:destroyed', function () {
  495. var _this = this;
  496. // do not trigger refresh:
  497. // - when user configured to not wait for transitions on destroyed
  498. // - when the component doesnt have a parent
  499. // - doesnt have metaInfo defined
  500. if (!this.$parent || !hasMetaInfo(this)) {
  501. return;
  502. }
  503. delete this._hasMetaInfo;
  504. this.$nextTick(function () {
  505. if (!options.waitOnDestroyed || !_this.$el || !_this.$el.offsetParent) {
  506. triggerUpdate(options, _this.$root, 'destroyed');
  507. return;
  508. } // Wait that element is hidden before refreshing meta tags (to support animations)
  509. var interval = setInterval(function () {
  510. if (_this.$el && _this.$el.offsetParent !== null) {
  511. /* istanbul ignore next line */
  512. return;
  513. }
  514. clearInterval(interval);
  515. triggerUpdate(options, _this.$root, 'destroyed');
  516. }, 50);
  517. });
  518. }); // do not trigger refresh on the server side
  519. if (this.$isServer) {
  520. /* istanbul ignore next */
  521. return;
  522. } // no need to add this hooks on server side
  523. updateOnLifecycleHook.forEach(function (lifecycleHook) {
  524. _this2.$on("hook:".concat(lifecycleHook), function () {
  525. triggerUpdate(options, this[rootKey], lifecycleHook);
  526. });
  527. });
  528. }
  529. };
  530. }
  531. function setOptions(options) {
  532. // combine options
  533. options = isObject(options) ? options : {}; // The options are set like this so they can
  534. // be minified by terser while keeping the
  535. // user api intact
  536. // terser --mangle-properties keep_quoted=strict
  537. /* eslint-disable dot-notation */
  538. return {
  539. keyName: options['keyName'] || defaultOptions.keyName,
  540. attribute: options['attribute'] || defaultOptions.attribute,
  541. ssrAttribute: options['ssrAttribute'] || defaultOptions.ssrAttribute,
  542. tagIDKeyName: options['tagIDKeyName'] || defaultOptions.tagIDKeyName,
  543. contentKeyName: options['contentKeyName'] || defaultOptions.contentKeyName,
  544. metaTemplateKeyName: options['metaTemplateKeyName'] || defaultOptions.metaTemplateKeyName,
  545. debounceWait: isUndefined(options['debounceWait']) ? defaultOptions.debounceWait : options['debounceWait'],
  546. waitOnDestroyed: isUndefined(options['waitOnDestroyed']) ? defaultOptions.waitOnDestroyed : options['waitOnDestroyed'],
  547. ssrAppId: options['ssrAppId'] || defaultOptions.ssrAppId,
  548. refreshOnceOnNavigation: !!options['refreshOnceOnNavigation']
  549. };
  550. /* eslint-enable dot-notation */
  551. }
  552. function getOptions(options) {
  553. var optionsCopy = {};
  554. for (var key in options) {
  555. optionsCopy[key] = options[key];
  556. }
  557. return optionsCopy;
  558. }
  559. function ensureIsArray(arg, key) {
  560. if (!key || !isObject(arg)) {
  561. return isArray(arg) ? arg : [];
  562. }
  563. if (!isArray(arg[key])) {
  564. arg[key] = [];
  565. }
  566. return arg;
  567. }
  568. var clientSequences = [[/&/g, "&"], [/</g, "<"], [/>/g, ">"], [/"/g, "\""], [/'/g, "'"]]; // sanitizes potentially dangerous characters
  569. function escape(info, options, escapeOptions, escapeKeys) {
  570. var tagIDKeyName = options.tagIDKeyName;
  571. var _escapeOptions$doEsca = escapeOptions.doEscape,
  572. doEscape = _escapeOptions$doEsca === void 0 ? function (v) {
  573. return v;
  574. } : _escapeOptions$doEsca;
  575. var escaped = {};
  576. for (var key in info) {
  577. var value = info[key]; // no need to escape configuration options
  578. if (includes(metaInfoOptionKeys, key)) {
  579. escaped[key] = value;
  580. continue;
  581. } // do not use destructuring for disableOptionKeys, it increases transpiled size
  582. // due to var checks while we are guaranteed the structure of the cb
  583. var disableKey = disableOptionKeys[0];
  584. if (escapeOptions[disableKey] && includes(escapeOptions[disableKey], key)) {
  585. // this info[key] doesnt need to escaped if the option is listed in __dangerouslyDisableSanitizers
  586. escaped[key] = value;
  587. continue;
  588. }
  589. var tagId = info[tagIDKeyName];
  590. if (tagId) {
  591. disableKey = disableOptionKeys[1]; // keys which are listed in __dangerouslyDisableSanitizersByTagID for the current vmid do not need to be escaped
  592. if (escapeOptions[disableKey] && escapeOptions[disableKey][tagId] && includes(escapeOptions[disableKey][tagId], key)) {
  593. escaped[key] = value;
  594. continue;
  595. }
  596. }
  597. if (isString(value)) {
  598. escaped[key] = doEscape(value);
  599. } else if (isArray(value)) {
  600. escaped[key] = value.map(function (v) {
  601. if (isPureObject(v)) {
  602. return escape(v, options, escapeOptions, true);
  603. }
  604. return doEscape(v);
  605. });
  606. } else if (isPureObject(value)) {
  607. escaped[key] = escape(value, options, escapeOptions, true);
  608. } else {
  609. escaped[key] = value;
  610. }
  611. if (escapeKeys) {
  612. var escapedKey = doEscape(key);
  613. if (key !== escapedKey) {
  614. escaped[escapedKey] = escaped[key];
  615. delete escaped[key];
  616. }
  617. }
  618. }
  619. return escaped;
  620. }
  621. function escapeMetaInfo(options, info, escapeSequences) {
  622. escapeSequences = escapeSequences || []; // do not use destructuring for seq, it increases transpiled size
  623. // due to var checks while we are guaranteed the structure of the cb
  624. var escapeOptions = {
  625. doEscape: function doEscape(value) {
  626. return escapeSequences.reduce(function (val, seq) {
  627. return val.replace(seq[0], seq[1]);
  628. }, value);
  629. }
  630. };
  631. disableOptionKeys.forEach(function (disableKey, index) {
  632. if (index === 0) {
  633. ensureIsArray(info, disableKey);
  634. } else if (index === 1) {
  635. for (var key in info[disableKey]) {
  636. ensureIsArray(info[disableKey], key);
  637. }
  638. }
  639. escapeOptions[disableKey] = info[disableKey];
  640. }); // begin sanitization
  641. return escape(info, options, escapeOptions);
  642. }
  643. var isMergeableObject = function isMergeableObject(value) {
  644. return isNonNullObject(value) && !isSpecial(value);
  645. };
  646. function isNonNullObject(value) {
  647. return !!value && _typeof(value) === 'object';
  648. }
  649. function isSpecial(value) {
  650. var stringValue = Object.prototype.toString.call(value);
  651. return stringValue === '[object RegExp]' || stringValue === '[object Date]' || false;
  652. } // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  653. function cloneUnlessOtherwiseSpecified(value, options) {
  654. return value;
  655. }
  656. function getMergeFunction(key, options) {
  657. {
  658. return deepmerge;
  659. }
  660. }
  661. function getKeys(target) {
  662. return Object.keys(target);
  663. }
  664. function propertyIsOnObject(object, property) {
  665. try {
  666. return property in object;
  667. } catch (_) {
  668. return false;
  669. }
  670. } // Protects from prototype poisoning and unexpected merging up the prototype chain.
  671. function propertyIsUnsafe(target, key) {
  672. return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet,
  673. && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain,
  674. && Object.propertyIsEnumerable.call(target, key)); // and also unsafe if they're nonenumerable.
  675. }
  676. function mergeObject(target, source, options) {
  677. var destination = {};
  678. if (options.isMergeableObject(target)) {
  679. getKeys(target).forEach(function (key) {
  680. destination[key] = cloneUnlessOtherwiseSpecified(target[key]);
  681. });
  682. }
  683. getKeys(source).forEach(function (key) {
  684. if (propertyIsUnsafe(target, key)) {
  685. return;
  686. }
  687. if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {
  688. destination[key] = getMergeFunction()(target[key], source[key], options);
  689. } else {
  690. destination[key] = cloneUnlessOtherwiseSpecified(source[key]);
  691. }
  692. });
  693. return destination;
  694. }
  695. function deepmerge(target, source, options) {
  696. options = options || {};
  697. options.arrayMerge = options.arrayMerge;
  698. options.isMergeableObject = options.isMergeableObject || isMergeableObject; // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge()
  699. // implementations can use it. The caller may not replace it.
  700. options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
  701. var sourceIsArray = Array.isArray(source);
  702. var targetIsArray = Array.isArray(target);
  703. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  704. if (!sourceAndTargetTypesMatch) {
  705. return cloneUnlessOtherwiseSpecified(source);
  706. } else if (sourceIsArray) {
  707. return options.arrayMerge(target, source, options);
  708. } else {
  709. return mergeObject(target, source, options);
  710. }
  711. }
  712. var deepmerge_1 = deepmerge;
  713. var cjs = deepmerge_1;
  714. function applyTemplate(_ref, headObject, template, chunk) {
  715. var component = _ref.component,
  716. metaTemplateKeyName = _ref.metaTemplateKeyName,
  717. contentKeyName = _ref.contentKeyName;
  718. if (template === true || headObject[metaTemplateKeyName] === true) {
  719. // abort, template was already applied
  720. return false;
  721. }
  722. if (isUndefined(template) && headObject[metaTemplateKeyName]) {
  723. template = headObject[metaTemplateKeyName];
  724. headObject[metaTemplateKeyName] = true;
  725. } // return early if no template defined
  726. if (!template) {
  727. // cleanup faulty template properties
  728. delete headObject[metaTemplateKeyName];
  729. return false;
  730. }
  731. if (isUndefined(chunk)) {
  732. chunk = headObject[contentKeyName];
  733. }
  734. headObject[contentKeyName] = isFunction(template) ? template.call(component, chunk) : template.replace(/%s/g, chunk);
  735. return true;
  736. }
  737. function _arrayMerge(_ref, target, source) {
  738. var component = _ref.component,
  739. tagIDKeyName = _ref.tagIDKeyName,
  740. metaTemplateKeyName = _ref.metaTemplateKeyName,
  741. contentKeyName = _ref.contentKeyName;
  742. // we concat the arrays without merging objects contained in,
  743. // but we check for a `vmid` property on each object in the array
  744. // using an O(1) lookup associative array exploit
  745. var destination = [];
  746. if (!target.length && !source.length) {
  747. return destination;
  748. }
  749. target.forEach(function (targetItem, targetIndex) {
  750. // no tagID so no need to check for duplicity
  751. if (!targetItem[tagIDKeyName]) {
  752. destination.push(targetItem);
  753. return;
  754. }
  755. var sourceIndex = findIndex(source, function (item) {
  756. return item[tagIDKeyName] === targetItem[tagIDKeyName];
  757. });
  758. var sourceItem = source[sourceIndex]; // source doesnt contain any duplicate vmid's, we can keep targetItem
  759. if (sourceIndex === -1) {
  760. destination.push(targetItem);
  761. return;
  762. } // when sourceItem explictly defines contentKeyName or innerHTML as undefined, its
  763. // an indication that we need to skip the default behaviour or child has preference over parent
  764. // which means we keep the targetItem and ignore/remove the sourceItem
  765. if (contentKeyName in sourceItem && sourceItem[contentKeyName] === undefined || 'innerHTML' in sourceItem && sourceItem.innerHTML === undefined) {
  766. destination.push(targetItem); // remove current index from source array so its not concatenated to destination below
  767. source.splice(sourceIndex, 1);
  768. return;
  769. } // we now know that targetItem is a duplicate and we should ignore it in favor of sourceItem
  770. // if source specifies null as content then ignore both the target as the source
  771. if (sourceItem[contentKeyName] === null || sourceItem.innerHTML === null) {
  772. // remove current index from source array so its not concatenated to destination below
  773. source.splice(sourceIndex, 1);
  774. return;
  775. } // now we only need to check if the target has a template to combine it with the source
  776. var targetTemplate = targetItem[metaTemplateKeyName];
  777. if (!targetTemplate) {
  778. return;
  779. }
  780. var sourceTemplate = sourceItem[metaTemplateKeyName];
  781. if (!sourceTemplate) {
  782. // use parent template and child content
  783. applyTemplate({
  784. component: component,
  785. metaTemplateKeyName: metaTemplateKeyName,
  786. contentKeyName: contentKeyName
  787. }, sourceItem, targetTemplate); // set template to true to indicate template was already applied
  788. sourceItem.template = true;
  789. return;
  790. }
  791. if (!sourceItem[contentKeyName]) {
  792. // use parent content and child template
  793. applyTemplate({
  794. component: component,
  795. metaTemplateKeyName: metaTemplateKeyName,
  796. contentKeyName: contentKeyName
  797. }, sourceItem, undefined, targetItem[contentKeyName]);
  798. }
  799. });
  800. return destination.concat(source);
  801. }
  802. var warningShown = false;
  803. function merge(target, source, options) {
  804. options = options || {}; // remove properties explicitly set to false so child components can
  805. // optionally _not_ overwrite the parents content
  806. // (for array properties this is checked in arrayMerge)
  807. if (source.title === undefined) {
  808. delete source.title;
  809. }
  810. metaInfoAttributeKeys.forEach(function (attrKey) {
  811. if (!source[attrKey]) {
  812. return;
  813. }
  814. for (var key in source[attrKey]) {
  815. if (key in source[attrKey] && source[attrKey][key] === undefined) {
  816. if (includes(booleanHtmlAttributes, key) && !warningShown) {
  817. warn('VueMeta: Please note that since v2 the value undefined is not used to indicate boolean attributes anymore, see migration guide for details');
  818. warningShown = true;
  819. }
  820. delete source[attrKey][key];
  821. }
  822. }
  823. });
  824. return cjs(target, source, {
  825. arrayMerge: function arrayMerge(t, s) {
  826. return _arrayMerge(options, t, s);
  827. }
  828. });
  829. }
  830. function getComponentMetaInfo(options, component) {
  831. return getComponentOption(options || {}, component, defaultInfo);
  832. }
  833. /**
  834. * Returns the `opts.option` $option value of the given `opts.component`.
  835. * If methods are encountered, they will be bound to the component context.
  836. * If `opts.deep` is true, will recursively merge all child component
  837. * `opts.option` $option values into the returned result.
  838. *
  839. * @param {Object} opts - options
  840. * @param {Object} opts.component - Vue component to fetch option data from
  841. * @param {Boolean} opts.deep - look for data in child components as well?
  842. * @param {Function} opts.arrayMerge - how should arrays be merged?
  843. * @param {String} opts.keyName - the name of the option to look for
  844. * @param {Object} [result={}] - result so far
  845. * @return {Object} result - final aggregated result
  846. */
  847. function getComponentOption(options, component, result) {
  848. result = result || {};
  849. if (component._inactive) {
  850. return result;
  851. }
  852. options = options || {};
  853. var _options = options,
  854. keyName = _options.keyName;
  855. var $metaInfo = component.$metaInfo,
  856. $options = component.$options,
  857. $children = component.$children; // only collect option data if it exists
  858. if ($options[keyName]) {
  859. // if $metaInfo exists then [keyName] was defined as a function
  860. // and set to the computed prop $metaInfo in the mixin
  861. // using the computed prop should be a small performance increase
  862. // because Vue caches those internally
  863. var data = $metaInfo || $options[keyName]; // only merge data with result when its an object
  864. // eg it could be a function when metaInfo() returns undefined
  865. // dueo to the or statement above
  866. if (isObject(data)) {
  867. result = merge(result, data, options);
  868. }
  869. } // collect & aggregate child options if deep = true
  870. if ($children.length) {
  871. $children.forEach(function (childComponent) {
  872. // check if the childComponent is in a branch
  873. // return otherwise so we dont walk all component branches unnecessarily
  874. if (!inMetaInfoBranch(childComponent)) {
  875. return;
  876. }
  877. result = getComponentOption(options, childComponent, result);
  878. });
  879. }
  880. return result;
  881. }
  882. var callbacks = [];
  883. function isDOMComplete(d) {
  884. return (d || document).readyState === 'complete';
  885. }
  886. function addCallback(query, callback) {
  887. if (arguments.length === 1) {
  888. callback = query;
  889. query = '';
  890. }
  891. callbacks.push([query, callback]);
  892. }
  893. function addCallbacks(_ref, type, tags, autoAddListeners) {
  894. var tagIDKeyName = _ref.tagIDKeyName;
  895. var hasAsyncCallback = false;
  896. tags.forEach(function (tag) {
  897. if (!tag[tagIDKeyName] || !tag.callback) {
  898. return;
  899. }
  900. hasAsyncCallback = true;
  901. addCallback("".concat(type, "[data-").concat(tagIDKeyName, "=\"").concat(tag[tagIDKeyName], "\"]"), tag.callback);
  902. });
  903. if (!autoAddListeners || !hasAsyncCallback) {
  904. return hasAsyncCallback;
  905. }
  906. return addListeners();
  907. }
  908. function addListeners() {
  909. if (isDOMComplete()) {
  910. applyCallbacks();
  911. return;
  912. } // Instead of using a MutationObserver, we just apply
  913. /* istanbul ignore next */
  914. document.onreadystatechange = function () {
  915. applyCallbacks();
  916. };
  917. }
  918. function applyCallbacks(matchElement) {
  919. callbacks.forEach(function (args) {
  920. // do not use destructuring for args, it increases transpiled size
  921. // due to var checks while we are guaranteed the structure of the cb
  922. var query = args[0];
  923. var callback = args[1];
  924. var selector = "".concat(query, "[onload=\"this.__vm_l=1\"]");
  925. var elements = [];
  926. if (!matchElement) {
  927. elements = toArray(querySelector(selector));
  928. }
  929. if (matchElement && matchElement.matches(selector)) {
  930. elements = [matchElement];
  931. }
  932. elements.forEach(function (element) {
  933. /* __vm_cb: whether the load callback has been called
  934. * __vm_l: set by onload attribute, whether the element was loaded
  935. * __vm_ev: whether the event listener was added or not
  936. */
  937. if (element.__vm_cb) {
  938. return;
  939. }
  940. var onload = function onload() {
  941. /* Mark that the callback for this element has already been called,
  942. * this prevents the callback to run twice in some (rare) conditions
  943. */
  944. element.__vm_cb = true;
  945. /* onload needs to be removed because we only need the
  946. * attribute after ssr and if we dont remove it the node
  947. * will fail isEqualNode on the client
  948. */
  949. removeAttribute(element, 'onload');
  950. callback(element);
  951. };
  952. /* IE9 doesnt seem to load scripts synchronously,
  953. * causing a script sometimes/often already to be loaded
  954. * when we add the event listener below (thus adding an onload event
  955. * listener has no use because it will never be triggered).
  956. * Therefore we add the onload attribute during ssr, and
  957. * check here if it was already loaded or not
  958. */
  959. if (element.__vm_l) {
  960. onload();
  961. return;
  962. }
  963. if (!element.__vm_ev) {
  964. element.__vm_ev = true;
  965. element.addEventListener('load', onload);
  966. }
  967. });
  968. });
  969. }
  970. // instead of adding it to the html
  971. var attributeMap = {};
  972. /**
  973. * Updates the document's html tag attributes
  974. *
  975. * @param {Object} attrs - the new document html attributes
  976. * @param {HTMLElement} tag - the HTMLElement tag to update with new attrs
  977. */
  978. function updateAttribute(appId, options, type, attrs, tag) {
  979. var _ref = options || {},
  980. attribute = _ref.attribute;
  981. var vueMetaAttrString = tag.getAttribute(attribute);
  982. if (vueMetaAttrString) {
  983. attributeMap[type] = JSON.parse(decodeURI(vueMetaAttrString));
  984. removeAttribute(tag, attribute);
  985. }
  986. var data = attributeMap[type] || {};
  987. var toUpdate = []; // remove attributes from the map
  988. // which have been removed for this appId
  989. for (var attr in data) {
  990. if (data[attr] !== undefined && appId in data[attr]) {
  991. toUpdate.push(attr);
  992. if (!attrs[attr]) {
  993. delete data[attr][appId];
  994. }
  995. }
  996. }
  997. for (var _attr in attrs) {
  998. var attrData = data[_attr];
  999. if (!attrData || attrData[appId] !== attrs[_attr]) {
  1000. toUpdate.push(_attr);
  1001. if (attrs[_attr] !== undefined) {
  1002. data[_attr] = data[_attr] || {};
  1003. data[_attr][appId] = attrs[_attr];
  1004. }
  1005. }
  1006. }
  1007. for (var _i = 0, _toUpdate = toUpdate; _i < _toUpdate.length; _i++) {
  1008. var _attr2 = _toUpdate[_i];
  1009. var _attrData = data[_attr2];
  1010. var attrValues = [];
  1011. for (var _appId in _attrData) {
  1012. Array.prototype.push.apply(attrValues, [].concat(_attrData[_appId]));
  1013. }
  1014. if (attrValues.length) {
  1015. var attrValue = includes(booleanHtmlAttributes, _attr2) && attrValues.some(Boolean) ? '' : attrValues.filter(function (v) {
  1016. return v !== undefined;
  1017. }).join(' ');
  1018. tag.setAttribute(_attr2, attrValue);
  1019. } else {
  1020. removeAttribute(tag, _attr2);
  1021. }
  1022. }
  1023. attributeMap[type] = data;
  1024. }
  1025. /**
  1026. * Updates the document title
  1027. *
  1028. * @param {String} title - the new title of the document
  1029. */
  1030. function updateTitle(title) {
  1031. if (!title && title !== '') {
  1032. return;
  1033. }
  1034. document.title = title;
  1035. }
  1036. /**
  1037. * Updates meta tags inside <head> and <body> on the client. Borrowed from `react-helmet`:
  1038. * https://github.com/nfl/react-helmet/blob/004d448f8de5f823d10f838b02317521180f34da/src/Helmet.js#L195-L245
  1039. *
  1040. * @param {('meta'|'base'|'link'|'style'|'script'|'noscript')} type - the name of the tag
  1041. * @param {(Array<Object>|Object)} tags - an array of tag objects or a single object in case of base
  1042. * @return {Object} - a representation of what tags changed
  1043. */
  1044. function updateTag(appId, options, type, tags, head, body) {
  1045. var _ref = options || {},
  1046. attribute = _ref.attribute,
  1047. tagIDKeyName = _ref.tagIDKeyName;
  1048. var dataAttributes = commonDataAttributes.slice();
  1049. dataAttributes.push(tagIDKeyName);
  1050. var newElements = [];
  1051. var queryOptions = {
  1052. appId: appId,
  1053. attribute: attribute,
  1054. type: type,
  1055. tagIDKeyName: tagIDKeyName
  1056. };
  1057. var currentElements = {
  1058. head: queryElements(head, queryOptions),
  1059. pbody: queryElements(body, queryOptions, {
  1060. pbody: true
  1061. }),
  1062. body: queryElements(body, queryOptions, {
  1063. body: true
  1064. })
  1065. };
  1066. if (tags.length > 1) {
  1067. // remove duplicates that could have been found by merging tags
  1068. // which include a mixin with metaInfo and that mixin is used
  1069. // by multiple components on the same page
  1070. var found = [];
  1071. tags = tags.filter(function (x) {
  1072. var k = JSON.stringify(x);
  1073. var res = !includes(found, k);
  1074. found.push(k);
  1075. return res;
  1076. });
  1077. }
  1078. tags.forEach(function (tag) {
  1079. if (tag.skip) {
  1080. return;
  1081. }
  1082. var newElement = document.createElement(type);
  1083. if (!tag.once) {
  1084. newElement.setAttribute(attribute, appId);
  1085. }
  1086. Object.keys(tag).forEach(function (attr) {
  1087. /* istanbul ignore next */
  1088. if (includes(tagProperties, attr)) {
  1089. return;
  1090. }
  1091. if (attr === 'innerHTML') {
  1092. newElement.innerHTML = tag.innerHTML;
  1093. return;
  1094. }
  1095. if (attr === 'json') {
  1096. newElement.innerHTML = JSON.stringify(tag.json);
  1097. return;
  1098. }
  1099. if (attr === 'cssText') {
  1100. if (newElement.styleSheet) {
  1101. /* istanbul ignore next */
  1102. newElement.styleSheet.cssText = tag.cssText;
  1103. } else {
  1104. newElement.appendChild(document.createTextNode(tag.cssText));
  1105. }
  1106. return;
  1107. }
  1108. if (attr === 'callback') {
  1109. newElement.onload = function () {
  1110. return tag[attr](newElement);
  1111. };
  1112. return;
  1113. }
  1114. var _attr = includes(dataAttributes, attr) ? "data-".concat(attr) : attr;
  1115. var isBooleanAttribute = includes(booleanHtmlAttributes, attr);
  1116. if (isBooleanAttribute && !tag[attr]) {
  1117. return;
  1118. }
  1119. var value = isBooleanAttribute ? '' : tag[attr];
  1120. newElement.setAttribute(_attr, value);
  1121. });
  1122. var oldElements = currentElements[getElementsKey(tag)]; // Remove a duplicate tag from domTagstoRemove, so it isn't cleared.
  1123. var indexToDelete;
  1124. var hasEqualElement = oldElements.some(function (existingTag, index) {
  1125. indexToDelete = index;
  1126. return newElement.isEqualNode(existingTag);
  1127. });
  1128. if (hasEqualElement && (indexToDelete || indexToDelete === 0)) {
  1129. oldElements.splice(indexToDelete, 1);
  1130. } else {
  1131. newElements.push(newElement);
  1132. }
  1133. });
  1134. var oldElements = [];
  1135. for (var _type in currentElements) {
  1136. Array.prototype.push.apply(oldElements, currentElements[_type]);
  1137. } // remove old elements
  1138. oldElements.forEach(function (element) {
  1139. element.parentNode.removeChild(element);
  1140. }); // insert new elements
  1141. newElements.forEach(function (element) {
  1142. if (element.hasAttribute('data-body')) {
  1143. body.appendChild(element);
  1144. return;
  1145. }
  1146. if (element.hasAttribute('data-pbody')) {
  1147. body.insertBefore(element, body.firstChild);
  1148. return;
  1149. }
  1150. head.appendChild(element);
  1151. });
  1152. return {
  1153. oldTags: oldElements,
  1154. newTags: newElements
  1155. };
  1156. }
  1157. /**
  1158. * Performs client-side updates when new meta info is received
  1159. *
  1160. * @param {Object} newInfo - the meta info to update to
  1161. */
  1162. function updateClientMetaInfo(appId, options, newInfo) {
  1163. options = options || {};
  1164. var _options = options,
  1165. ssrAttribute = _options.ssrAttribute,
  1166. ssrAppId = _options.ssrAppId; // only cache tags for current update
  1167. var tags = {};
  1168. var htmlTag = getTag(tags, 'html'); // if this is a server render, then dont update
  1169. if (appId === ssrAppId && htmlTag.hasAttribute(ssrAttribute)) {
  1170. // remove the server render attribute so we can update on (next) changes
  1171. removeAttribute(htmlTag, ssrAttribute); // add load callbacks if the
  1172. var addLoadListeners = false;
  1173. tagsSupportingOnload.forEach(function (type) {
  1174. if (newInfo[type] && addCallbacks(options, type, newInfo[type])) {
  1175. addLoadListeners = true;
  1176. }
  1177. });
  1178. if (addLoadListeners) {
  1179. addListeners();
  1180. }
  1181. return false;
  1182. } // initialize tracked changes
  1183. var tagsAdded = {};
  1184. var tagsRemoved = {};
  1185. for (var type in newInfo) {
  1186. // ignore these
  1187. if (includes(metaInfoOptionKeys, type)) {
  1188. continue;
  1189. }
  1190. if (type === 'title') {
  1191. // update the title
  1192. updateTitle(newInfo.title);
  1193. continue;
  1194. }
  1195. if (includes(metaInfoAttributeKeys, type)) {
  1196. var tagName = type.substr(0, 4);
  1197. updateAttribute(appId, options, type, newInfo[type], getTag(tags, tagName));
  1198. continue;
  1199. } // tags should always be an array, ignore if it isnt
  1200. if (!isArray(newInfo[type])) {
  1201. continue;
  1202. }
  1203. var _updateTag = updateTag(appId, options, type, newInfo[type], getTag(tags, 'head'), getTag(tags, 'body')),
  1204. oldTags = _updateTag.oldTags,
  1205. newTags = _updateTag.newTags;
  1206. if (newTags.length) {
  1207. tagsAdded[type] = newTags;
  1208. tagsRemoved[type] = oldTags;
  1209. }
  1210. }
  1211. return {
  1212. tagsAdded: tagsAdded,
  1213. tagsRemoved: tagsRemoved
  1214. };
  1215. }
  1216. var appsMetaInfo;
  1217. function addApp(rootVm, appId, options) {
  1218. return {
  1219. set: function set(metaInfo) {
  1220. return setMetaInfo(rootVm, appId, options, metaInfo);
  1221. },
  1222. remove: function remove() {
  1223. return removeMetaInfo(rootVm, appId, options);
  1224. }
  1225. };
  1226. }
  1227. function setMetaInfo(rootVm, appId, options, metaInfo) {
  1228. // if a vm exists _and_ its mounted then immediately update
  1229. if (rootVm && rootVm.$el) {
  1230. return updateClientMetaInfo(appId, options, metaInfo);
  1231. } // store for later, the info
  1232. // will be set on the first refresh
  1233. appsMetaInfo = appsMetaInfo || {};
  1234. appsMetaInfo[appId] = metaInfo;
  1235. }
  1236. function removeMetaInfo(rootVm, appId, options) {
  1237. if (rootVm && rootVm.$el) {
  1238. var tags = {};
  1239. var _iterator = _createForOfIteratorHelper(metaInfoAttributeKeys),
  1240. _step;
  1241. try {
  1242. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  1243. var type = _step.value;
  1244. var tagName = type.substr(0, 4);
  1245. updateAttribute(appId, options, type, {}, getTag(tags, tagName));
  1246. }
  1247. } catch (err) {
  1248. _iterator.e(err);
  1249. } finally {
  1250. _iterator.f();
  1251. }
  1252. return removeElementsByAppId(options, appId);
  1253. }
  1254. if (appsMetaInfo[appId]) {
  1255. delete appsMetaInfo[appId];
  1256. clearAppsMetaInfo();
  1257. }
  1258. }
  1259. function getAppsMetaInfo() {
  1260. return appsMetaInfo;
  1261. }
  1262. function clearAppsMetaInfo(force) {
  1263. if (force || !Object.keys(appsMetaInfo).length) {
  1264. appsMetaInfo = undefined;
  1265. }
  1266. }
  1267. /**
  1268. * Returns the correct meta info for the given component
  1269. * (child components will overwrite parent meta info)
  1270. *
  1271. * @param {Object} component - the Vue instance to get meta info from
  1272. * @return {Object} - returned meta info
  1273. */
  1274. function getMetaInfo(options, info, escapeSequences, component) {
  1275. options = options || {};
  1276. escapeSequences = escapeSequences || [];
  1277. var _options = options,
  1278. tagIDKeyName = _options.tagIDKeyName; // Remove all "template" tags from meta
  1279. // backup the title chunk in case user wants access to it
  1280. if (info.title) {
  1281. info.titleChunk = info.title;
  1282. } // replace title with populated template
  1283. if (info.titleTemplate && info.titleTemplate !== '%s') {
  1284. applyTemplate({
  1285. component: component,
  1286. contentKeyName: 'title'
  1287. }, info, info.titleTemplate, info.titleChunk || '');
  1288. } // convert base tag to an array so it can be handled the same way
  1289. // as the other tags
  1290. if (info.base) {
  1291. info.base = Object.keys(info.base).length ? [info.base] : [];
  1292. }
  1293. if (info.meta) {
  1294. // remove meta items with duplicate vmid's
  1295. info.meta = info.meta.filter(function (metaItem, index, arr) {
  1296. var hasVmid = !!metaItem[tagIDKeyName];
  1297. if (!hasVmid) {
  1298. return true;
  1299. }
  1300. var isFirstItemForVmid = index === findIndex(arr, function (item) {
  1301. return item[tagIDKeyName] === metaItem[tagIDKeyName];
  1302. });
  1303. return isFirstItemForVmid;
  1304. }); // apply templates if needed
  1305. info.meta.forEach(function (metaObject) {
  1306. return applyTemplate(options, metaObject);
  1307. });
  1308. }
  1309. return escapeMetaInfo(options, info, escapeSequences);
  1310. }
  1311. /**
  1312. * When called, will update the current meta info with new meta info.
  1313. * Useful when updating meta info as the result of an asynchronous
  1314. * action that resolves after the initial render takes place.
  1315. *
  1316. * Credit to [Sébastien Chopin](https://github.com/Atinux) for the suggestion
  1317. * to implement this method.
  1318. *
  1319. * @return {Object} - new meta info
  1320. */
  1321. function refresh(rootVm, options) {
  1322. options = options || {}; // make sure vue-meta was initiated
  1323. if (!rootVm[rootConfigKey]) {
  1324. showWarningNotSupported();
  1325. return {};
  1326. } // collect & aggregate all metaInfo $options
  1327. var rawInfo = getComponentMetaInfo(options, rootVm);
  1328. var metaInfo = getMetaInfo(options, rawInfo, clientSequences, rootVm);
  1329. var appId = rootVm[rootConfigKey].appId;
  1330. var tags = updateClientMetaInfo(appId, options, metaInfo); // emit "event" with new info
  1331. if (tags && isFunction(metaInfo.changed)) {
  1332. metaInfo.changed(metaInfo, tags.tagsAdded, tags.tagsRemoved);
  1333. tags = {
  1334. addedTags: tags.tagsAdded,
  1335. removedTags: tags.tagsRemoved
  1336. };
  1337. }
  1338. var appsMetaInfo = getAppsMetaInfo();
  1339. if (appsMetaInfo) {
  1340. for (var additionalAppId in appsMetaInfo) {
  1341. updateClientMetaInfo(additionalAppId, options, appsMetaInfo[additionalAppId]);
  1342. delete appsMetaInfo[additionalAppId];
  1343. }
  1344. clearAppsMetaInfo(true);
  1345. }
  1346. return {
  1347. vm: rootVm,
  1348. metaInfo: metaInfo,
  1349. // eslint-disable-line object-shorthand
  1350. tags: tags
  1351. };
  1352. }
  1353. function $meta(options) {
  1354. options = options || {};
  1355. /**
  1356. * Returns an injector for server-side rendering.
  1357. * @this {Object} - the Vue instance (a root component)
  1358. * @return {Object} - injector
  1359. */
  1360. var $root = this.$root;
  1361. return {
  1362. getOptions: function getOptions$1() {
  1363. return getOptions(options);
  1364. },
  1365. setOptions: function setOptions(newOptions) {
  1366. var refreshNavKey = 'refreshOnceOnNavigation';
  1367. if (newOptions && newOptions[refreshNavKey]) {
  1368. options.refreshOnceOnNavigation = !!newOptions[refreshNavKey];
  1369. addNavGuards($root);
  1370. }
  1371. var debounceWaitKey = 'debounceWait';
  1372. if (newOptions && debounceWaitKey in newOptions) {
  1373. var debounceWait = parseInt(newOptions[debounceWaitKey]);
  1374. if (!isNaN(debounceWait)) {
  1375. options.debounceWait = debounceWait;
  1376. }
  1377. }
  1378. var waitOnDestroyedKey = 'waitOnDestroyed';
  1379. if (newOptions && waitOnDestroyedKey in newOptions) {
  1380. options.waitOnDestroyed = !!newOptions[waitOnDestroyedKey];
  1381. }
  1382. },
  1383. refresh: function refresh$1() {
  1384. return refresh($root, options);
  1385. },
  1386. inject: function inject(injectOptions) {
  1387. return showWarningNotSupportedInBrowserBundle('inject');
  1388. },
  1389. pause: function pause$1() {
  1390. return pause($root);
  1391. },
  1392. resume: function resume$1() {
  1393. return resume($root);
  1394. },
  1395. addApp: function addApp$1(appId) {
  1396. return addApp($root, appId, options);
  1397. }
  1398. };
  1399. }
  1400. /**
  1401. * Plugin install function.
  1402. * @param {Function} Vue - the Vue constructor.
  1403. */
  1404. function install(Vue, options) {
  1405. if (Vue.__vuemeta_installed) {
  1406. return;
  1407. }
  1408. Vue.__vuemeta_installed = true;
  1409. options = setOptions(options);
  1410. Vue.prototype.$meta = function () {
  1411. return $meta.call(this, options);
  1412. };
  1413. Vue.mixin(createMixin(Vue, options));
  1414. }
  1415. {
  1416. // automatic install
  1417. if (!isUndefined(window) && !isUndefined(window.Vue)) {
  1418. /* istanbul ignore next */
  1419. install(window.Vue);
  1420. }
  1421. }
  1422. var index = {
  1423. version: version,
  1424. install: install,
  1425. generate: function generate(metaInfo, options) {
  1426. return showWarningNotSupportedInBrowserBundle('generate');
  1427. },
  1428. hasMetaInfo: hasMetaInfo
  1429. };
  1430. return index;
  1431. })));