vue-meta.esm.browser.js 49 KB

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