/
vue-meta.esm-browser.js
808 lines (788 loc) · 26.4 KB
/
vue-meta.esm-browser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
/**
* vue-meta v3.0.0-alpha.1
* (c) 2021
* - Pim (@pimlie)
* - All the amazing contributors
* @license MIT
*/
import { markRaw, h, getCurrentInstance, inject, defineComponent, reactive, onUnmounted, Teleport, Comment } from 'vue';
const resolveOption = predicament => (options, contexts) => {
let resolvedIndex = -1;
contexts.reduce((acc, context, index) => {
const retval = predicament(acc, context);
if (retval !== acc) {
resolvedIndex = index;
return retval;
}
return acc;
}, undefined);
if (resolvedIndex > -1) {
return options[resolvedIndex];
}
};
function setup(context) {
let depth = 0;
if (context.vm) {
let { vm } = context;
do {
if (vm.parent) {
depth++;
vm = vm.parent;
}
} while (vm && vm.parent && vm !== vm.root);
}
context.depth = depth;
}
const resolve = resolveOption((acc, context) => {
const { depth } = context;
if (!acc || depth > acc) {
return acc;
}
});
var deepest = /*#__PURE__*/Object.freeze({
__proto__: null,
setup: setup,
resolve: resolve
});
const defaultConfig = {
body: {
tag: 'script',
to: 'body'
},
base: {
valueAttribute: 'href'
},
charset: {
tag: 'meta',
nameless: true,
valueAttribute: 'charset'
},
description: {
tag: 'meta'
},
og: {
group: true,
namespacedAttribute: true,
tag: 'meta',
keyAttribute: 'property'
},
twitter: {
group: true,
namespacedAttribute: true,
tag: 'meta'
},
htmlAttrs: {
attributesFor: 'html'
},
headAttrs: {
attributesFor: 'head'
},
bodyAttrs: {
attributesFor: 'body'
}
};
/*
* This is a fixed config for real HTML tags
*/
const tags = {
title: {
attributes: false
},
base: {
contentAsAttribute: true,
attributes: ['href', 'target']
},
meta: {
contentAsAttribute: true,
keyAttribute: 'name',
attributes: ['content', 'name', 'http-equiv', 'charset']
},
link: {
contentAsAttribute: true,
attributes: [
'href',
'crossorigin',
'rel',
'media',
'integrity',
'hreflang',
'type',
'referrerpolicy',
'sizes',
'imagesrcset',
'imagesizes',
'as',
'color'
]
},
style: {
attributes: ['media']
},
script: {
attributes: [
'src',
'type',
'nomodule',
'async',
'defer',
'crossorigin',
'integrity',
'referrerpolicy'
]
},
noscript: {
attributes: false
}
};
function getTagConfigItem(tagOrName, key) {
for (const name of tagOrName) {
const tag = tags[name];
if (name && tag) {
return tag[key];
}
}
}
/**
* Make a map and return a function for checking if a key
* is in that map.
* IMPORTANT: all calls of this function must be prefixed with
* \/\*#\_\_PURE\_\_\*\/
* So that rollup can tree-shake them if necessary.
*/
(process.env.NODE_ENV !== 'production')
? Object.freeze({})
: {};
(process.env.NODE_ENV !== 'production') ? Object.freeze([]) : [];
const isArray = Array.isArray;
const isFunction = (val) => typeof val === 'function';
const isString = (val) => typeof val === 'string';
const isObject = (val) => val !== null && typeof val === 'object';
const objectToString = Object.prototype.toString;
const toTypeString = (value) => objectToString.call(value);
const isPlainObject = (val) => toTypeString(val) === '[object Object]';
// https://github.com/microsoft/TypeScript/issues/1863
const IS_PROXY = Symbol('kIsProxy');
const PROXY_SOURCES = Symbol('kProxySources');
const PROXY_TARGET = Symbol('kProxyTarget');
const RESOLVE_CONTEXT = Symbol('kResolveContext');
// See: https://github.com/vuejs/vue-next/blob/08b4e8815da4e8911058ccbab986bea6365c3352/packages/compiler-ssr/src/transforms/ssrTransformComponent.ts
function clone(v) {
if (isArray(v)) {
return v.map(clone);
}
if (isObject(v)) {
const res = {};
for (const key in v) {
// never clone the context
if (key === 'context') {
res[key] = v[key];
}
else {
res[key] = clone(v[key]);
}
}
return res;
}
return v;
}
const pluck = (collection, key, callback) => {
const plucked = [];
for (const row of collection) {
if (key in row) {
plucked.push(row[key]);
if (callback) {
callback(row);
}
}
}
return plucked;
};
const allKeys = (source, ...sources) => {
const keys = source ? Object.keys(source) : [];
if (sources) {
for (const source of sources) {
if (!source || !isObject(source)) {
continue;
}
for (const key in source) {
if (!keys.includes(key)) {
keys.push(key);
}
}
}
}
// TODO: add check for consistent types for each key (dev only)
return keys;
};
const recompute = (context, sources, target, path = []) => {
if (!path.length) {
if (!target) {
target = context.active;
}
if (!sources) {
sources = context.sources;
}
}
if (!target || !sources) {
return;
}
const keys = allKeys(...sources);
// Clean up properties that dont exists anymore
const targetKeys = Object.keys(target);
for (const key of targetKeys) {
if (!keys.includes(key)) {
delete target[key];
}
}
for (const key of keys) {
// This assumes consistent types usages for keys across sources
if (isPlainObject(sources[0][key])) {
if (!target[key]) {
target[key] = {};
}
const keySources = [];
for (const source of sources) {
if (key in source) {
keySources.push(source[key]);
}
}
recompute(context, keySources, target[key], [...path, key]);
continue;
}
// Ensure the target is an array if source is an array and target is empty
if (!target[key] && isArray(sources[0][key])) {
target[key] = [];
}
const keyContexts = [];
const keySources = pluck(sources, key, source => keyContexts.push(source[RESOLVE_CONTEXT]));
let resolved = context.resolve(keySources, keyContexts, target[key], key, path);
if (isPlainObject(resolved)) {
resolved = clone(resolved);
}
// console.log('RESOLVED', key, resolved, 'was', target[key])
target[key] = resolved;
}
};
const createProxy = (context, target, resolveContext, pathSegments = []) => {
const handler = createHandler(context, resolveContext, pathSegments);
const proxy = markRaw(new Proxy(target, handler));
if (!pathSegments.length && context.sources) {
context.sources.push(proxy);
}
return proxy;
};
const createHandler = (context, resolveContext, pathSegments = []) => ({
get: (target, key, receiver) => {
if (key === IS_PROXY) {
return true;
}
if (key === PROXY_SOURCES) {
return context.sources;
}
if (key === PROXY_TARGET) {
return target;
}
if (key === RESOLVE_CONTEXT) {
return resolveContext;
}
let value = Reflect.get(target, key, receiver);
if (!isObject(value)) {
return value;
}
if (!value[IS_PROXY]) {
const keyPath = [...pathSegments, key];
value = createProxy(context, value, resolveContext, keyPath);
target[key] = value;
}
return value;
},
set: (target, key, value) => {
const success = Reflect.set(target, key, value);
// console.warn(success, 'PROXY SET\nkey:', key, '\npath:', pathSegments, '\ntarget:', isArray(target), target, '\ncontext:\n', context)
if (success) {
const isArrayItem = isArray(target);
let hasArrayParent = false;
let { sources: proxies, active } = context;
let activeSegmentKey;
let index = 0;
for (const segment of pathSegments) {
proxies = pluck(proxies, segment);
if (isArrayItem && index === pathSegments.length - 1) {
activeSegmentKey = segment;
break;
}
if (isArray(active)) {
hasArrayParent = true;
}
active = active[segment];
index++;
}
if (hasArrayParent) {
// TODO: fix that we dont have to recompute the full merged object
// we should only have to recompute the branch that has changed
// but there is an issue here with supporting both arrays of strings
// as collections (parent vs parent of parent we need to trigger the
// update from)
recompute(context);
return success;
}
let keyContexts = [];
let keySources;
if (isArrayItem) {
keySources = proxies;
keyContexts = proxies.map(proxy => proxy[RESOLVE_CONTEXT]);
}
else {
keySources = pluck(proxies, key, proxy => keyContexts.push(proxy[RESOLVE_CONTEXT]));
}
let resolved = context.resolve(keySources, keyContexts, active, key, pathSegments);
// Ensure to clone if value is an object, cause sources is an array of
// the sourceProxies not the sources so we could trigger an endless loop when
// updating a prop on an obj as the prop on the active object refers to
// a prop on a proxy
if (isPlainObject(resolved)) {
resolved = clone(resolved);
}
// console.log('SET VALUE', isArrayItem, key, '\nresolved:\n', resolved, '\nsources:\n', context.sources, '\nactive:\n', active, Object.keys(active))
if (isArrayItem && activeSegmentKey) {
active[activeSegmentKey] = resolved;
}
else {
active[key] = resolved;
}
}
// console.log('CONTEXT.ACTIVE', context.active, '\nparent:\n', target)
return success;
},
deleteProperty: (target, key) => {
const success = Reflect.deleteProperty(target, key);
// console.warn('PROXY DELETE\nkey:', key, '\npath:', pathSegments, '\nparent:', isArray(target), target)
if (success) {
const isArrayItem = isArray(target);
let activeSegmentKey;
let proxies = context.sources;
let active = context.active;
let index = 0;
for (const segment of pathSegments) {
proxies = proxies.map(proxy => proxy[segment]);
if (isArrayItem && index === pathSegments.length - 1) {
activeSegmentKey = segment;
break;
}
active = active[segment];
index++;
}
// Check if the key still exists in one of the sourceProxies,
// if so resolve the new value, if not remove the key
if (proxies.some(proxy => (key in proxy))) {
let keyContexts = [];
let keySources;
if (isArrayItem) {
keySources = proxies;
keyContexts = proxies.map(proxy => proxy[RESOLVE_CONTEXT]);
}
else {
keySources = pluck(proxies, key, proxy => keyContexts.push(proxy[RESOLVE_CONTEXT]));
}
let resolved = context.resolve(keySources, keyContexts, active, key, pathSegments);
if (isPlainObject(resolved)) {
resolved = clone(resolved);
}
// console.log('SET VALUE', resolved)
if (isArrayItem && activeSegmentKey) {
active[activeSegmentKey] = resolved;
}
else {
active[key] = resolved;
}
}
else {
delete active[key];
}
}
return success;
}
});
const createMergedObject = (resolve, active = {}) => {
const sources = [];
if (!active) {
active = {};
}
const context = {
active,
resolve,
sources
};
const compute = () => recompute(context);
return {
context,
compute,
addSource: (source, resolveContext, recompute = false) => {
const proxy = createProxy(context, source, resolveContext || {});
if (recompute) {
compute();
}
return proxy;
},
delSource: (sourceOrProxy, recompute = true) => {
const index = sources.findIndex(src => src === sourceOrProxy || src[PROXY_TARGET] === sourceOrProxy);
if (index > -1) {
sources.splice(index, 1);
if (recompute) {
compute();
}
return true;
}
return false;
}
};
};
const cachedElements = {};
function renderMeta(context, key, data, config) {
// console.info('renderMeta', key, data, config)
if ('attributesFor' in config) {
return renderAttributes(context, key, data, config);
}
if ('group' in config) {
return renderGroup(context, key, data, config);
}
return renderTag(context, key, data, config);
}
function renderGroup(context, key, data, config) {
// console.info('renderGroup', key, data, config)
if (isArray(data)) {
{
// eslint-disable-next-line no-console
console.warn('Specifying an array for group properties isnt supported');
}
// config.attributes = getConfigKey([key, config.tag], 'attributes', config)
return [];
}
return Object.keys(data)
.map((childKey) => {
const groupConfig = {
group: key,
data
};
if (config.namespaced) {
groupConfig.tagNamespace = config.namespaced === true ? key : config.namespaced;
}
else if (config.namespacedAttribute) {
const namespace = config.namespacedAttribute === true ? key : config.namespacedAttribute;
groupConfig.fullName = `${namespace}:${childKey}`;
groupConfig.slotName = `${namespace}(${childKey})`;
}
return renderTag(context, key, data[childKey], config, groupConfig);
})
.flat();
}
function renderTag(context, key, data, config = {}, groupConfig) {
// console.info('renderTag', key, data, config, groupConfig)
const contentAttributes = ['content', 'json', 'rawContent'];
const getTagConfig = (key) => getTagConfigItem([tag, config.tag], key);
if (isArray(data)) {
return data
.map((child) => {
return renderTag(context, key, child, config, groupConfig);
})
.flat();
}
const { tag = config.tag || key } = data;
let content = '';
let hasChilds = false;
let isRaw = false;
if (isString(data)) {
content = data;
}
else if (data.children && isArray(data.children)) {
hasChilds = true;
content = data.children.map((child) => {
const data = renderTag(context, key, child, config, groupConfig);
if (isArray(data)) {
return data.map(({ vnode }) => vnode);
}
return data.vnode;
});
}
else {
let i = 0;
for (const contentAttribute of contentAttributes) {
if (!content && data[contentAttribute]) {
if (i === 1) {
content = JSON.stringify(data[contentAttribute]);
}
else {
content = data[contentAttribute];
}
isRaw = i > 1;
break;
}
i++;
}
}
const fullName = (groupConfig && groupConfig.fullName) || key;
const slotName = (groupConfig && groupConfig.slotName) || key;
let { attrs: attributes } = data;
if (!attributes && typeof data === 'object') {
attributes = { ...data };
delete attributes.tag;
delete attributes.children;
delete attributes.to;
// cleanup all content attributes
for (const attr of contentAttributes) {
delete attributes[attr];
}
}
else if (!attributes) {
attributes = {};
}
if (hasChilds) {
content = getSlotContent(context, slotName, content, data);
}
else {
const contentAsAttribute = !!getTagConfig('contentAsAttribute');
let { valueAttribute } = config;
if (!valueAttribute && contentAsAttribute) {
const [tagAttribute] = getTagConfig('attributes');
valueAttribute = isString(contentAsAttribute) ? contentAsAttribute : tagAttribute;
}
if (!valueAttribute) {
content = getSlotContent(context, slotName, content, data);
}
else {
const { nameless, keyAttribute } = config;
if (!nameless) {
if (keyAttribute) {
attributes[keyAttribute] = fullName;
}
}
attributes[valueAttribute] = getSlotContent(context, slotName, attributes[valueAttribute] || content, groupConfig);
content = '';
}
}
const finalTag = groupConfig && groupConfig.tagNamespace
? `${groupConfig.tagNamespace}:${tag}`
: tag;
// console.info('FINAL TAG', finalTag)
// console.log(' ATTRIBUTES', attributes)
// console.log(' CONTENT', content)
// // console.log(data, attributes, config)
if (isRaw && content) {
attributes.innerHTML = content;
}
// Ignore empty string content
const vnode = h(finalTag, attributes, content || undefined);
return {
to: data.to,
vnode
};
}
function renderAttributes(context, key, data, config) {
// console.info('renderAttributes', key, data, config)
const { attributesFor } = config;
if (!attributesFor) {
return;
}
if (!cachedElements[attributesFor]) {
const [el, el2] = Array.from(document.querySelectorAll(attributesFor));
if ( !el) {
// eslint-disable-next-line no-console
console.error('Could not find element for selector', attributesFor, ', won\'t render attributes');
return;
}
if ( el2) {
// eslint-disable-next-line no-console
console.warn('Found multiple elements for selector', attributesFor);
}
cachedElements[attributesFor] = {
el,
attrs: []
};
}
const { el, attrs } = cachedElements[attributesFor];
for (const attr in data) {
const content = getSlotContent(context, `${key}(${attr})`, data[attr], data);
el.setAttribute(attr, content || '');
if (!attrs.includes(attr)) {
attrs.push(attr);
}
}
const attrsToRemove = attrs.filter(attr => !data[attr]);
for (const attr of attrsToRemove) {
el.removeAttribute(attr);
}
}
function getSlotContent({ metainfo, slots }, slotName, content, groupConfig) {
const slot = slots && slots[slotName];
if (!slot) {
return content;
}
const slotScopeProps = {
content,
metainfo
};
if (groupConfig && groupConfig.group) {
const { group, data } = groupConfig;
slotScopeProps[group] = data;
}
const slotContent = slot(slotScopeProps);
if (slotContent && slotContent.length) {
const { children } = slotContent[0];
return children ? children.toString() : '';
}
return content;
}
const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
const PolySymbol = (name) =>
// vm = vue meta
hasSymbol
? Symbol( '[vue-meta]: ' + name )
: ( '[vue-meta]: ' ) + name;
const metaActiveKey = /*#__PURE__*/ PolySymbol( 'active_meta' );
function getCurrentManager(vm) {
if (!vm) {
vm = getCurrentInstance() || undefined;
}
if (!vm) {
return undefined;
}
return vm.appContext.config.globalProperties.$metaManager;
}
function useMeta(source, manager) {
const vm = getCurrentInstance();
if (!manager && vm) {
manager = getCurrentManager(vm);
}
if (!manager) {
// oopsydoopsy
throw new Error('No manager or current instance');
}
return manager.addMeta(source, vm || undefined);
}
function useActiveMeta() {
return inject(metaActiveKey);
}
const MetainfoImpl = defineComponent({
name: 'Metainfo',
inheritAttrs: false,
setup(_, { slots }) {
return () => {
const manager = getCurrentManager();
if (!manager) {
return;
}
return manager.render({ slots });
};
}
});
const Metainfo = MetainfoImpl;
const ssrAttribute = 'data-vm-ssr';
const active = reactive({});
function addVnode(teleports, to, vnodes) {
const nodes = (isArray(vnodes) ? vnodes : [vnodes]);
{
// Comments shouldnt have any use on the client as they are not reactive anyway
nodes.forEach((vnode, idx) => {
if (vnode.type === Comment) {
nodes.splice(idx, 1);
}
});
// only add ssrAttribute's for real meta tags
}
if (!teleports[to]) {
teleports[to] = [];
}
teleports[to].push(...nodes);
}
function createMetaManager(config, resolver) {
let cleanedUpSsr = false;
const resolve = (options, contexts, active, key, pathSegments) => {
if (isFunction(resolver)) {
return resolver(options, contexts, active, key, pathSegments);
}
return resolver.resolve(options, contexts, active, key, pathSegments);
};
const { addSource, delSource } = createMergedObject(resolve, active);
// TODO: validate resolver
const manager = {
config,
install(app) {
app.component('Metainfo', Metainfo);
app.config.globalProperties.$metaManager = manager;
app.provide(metaActiveKey, active);
},
addMeta(metaObj, vm) {
if (!vm) {
vm = getCurrentInstance() || undefined;
}
const resolveContext = { vm };
if (resolver && 'setup' in resolver && isFunction(resolver.setup)) {
resolver.setup(resolveContext);
}
// TODO: optimize initial compute
const meta = addSource(metaObj, resolveContext, true);
const unmount = () => delSource(meta);
if (vm) {
onUnmounted(unmount);
}
return {
meta,
unmount
};
},
render({ slots } = {}) {
// cleanup ssr tags if not yet done
if ( !cleanedUpSsr) {
cleanedUpSsr = true;
// Listen for DOM loaded because tags in the body couldnt
// have loaded yet once the manager does it first render
// (preferable there should only be one meta render on hydration)
window.addEventListener('DOMContentLoaded', () => {
const ssrTags = document.querySelectorAll(`[${ssrAttribute}]`);
if (ssrTags && ssrTags.length) {
Array.from(ssrTags).forEach(el => el.parentNode && el.parentNode.removeChild(el));
}
});
}
const teleports = {};
for (const key in active) {
const config = this.config[key] || {};
let renderedNodes = renderMeta({ metainfo: active, slots }, key, active[key], config);
if (!renderedNodes) {
continue;
}
if (!isArray(renderedNodes)) {
renderedNodes = [renderedNodes];
}
let defaultTo = key !== 'base' && active[key].to;
if (!defaultTo && 'to' in config) {
defaultTo = config.to;
}
if (!defaultTo && 'attributesFor' in config) {
defaultTo = key;
}
for (const { to, vnode } of renderedNodes) {
addVnode(teleports, to || defaultTo || 'head', vnode);
}
}
if (slots) {
for (const slotName in slots) {
const tagName = slotName === 'default' ? 'head' : slotName;
// Only teleport the contents of head/body slots
if (tagName !== 'head' && tagName !== 'body') {
continue;
}
const slot = slots[slotName];
if (isFunction(slot)) {
addVnode(teleports, tagName, slot({ metainfo: active }));
}
}
}
return Object.keys(teleports).map((to) => {
return h(Teleport, { to }, teleports[to]);
});
}
};
return manager;
}
export { createMetaManager, deepest as deepestResolver, defaultConfig, getCurrentManager, resolveOption, useActiveMeta, useMeta };