-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathapp.js
75 lines (62 loc) · 1.95 KB
/
app.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
import { ContentfulLivePreview } from '@contentful/live-preview';
import { createClient } from 'contentful';
import dotenv from 'dotenv';
// Configuration object
const CONFIG = {
locale: 'en-US',
entryId: 'W9z8t0uXz3CMFjp4sw5zj',
fields: ['title'],
subscriptions: [],
debugMode: true,
};
document.addEventListener('DOMContentLoaded', initialize);
function initialize() {
dotenv.config();
const client = createClient({
space: process.env.CONTENTFUL_SPACE_ID,
accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
host: 'preview.contentful.com',
});
ContentfulLivePreview.init({ locale: CONFIG.locale });
client
.getEntry(CONFIG.entryId)
.then((entry) => {
CONFIG.fields.forEach((fieldId) => {
displayFieldData(entry, client, fieldId);
setupLivePreview(entry, fieldId);
});
})
.catch((err) => console.error(err));
}
function findElementByDataAttributes(entryId, fieldId) {
return document.querySelector(
`[data-contentful-entry-id="${entryId}"][data-contentful-field-id="${fieldId}"]`
);
}
function displayFieldData(entry, client, fieldId) {
const domElement = findElementByDataAttributes(CONFIG.entryId, fieldId);
if (!domElement) {
console.error(
`DOM element with entry ID "${CONFIG.entryId}" and field ID "${fieldId}" not found.`
);
return;
}
domElement.textContent = entry.fields[fieldId];
}
function setupLivePreview(entry, fieldId) {
const callback = (updatedData) => {
const domElement = findElementByDataAttributes(CONFIG.entryId, fieldId);
if (domElement && updatedData.fields && updatedData.fields[fieldId]) {
// Check if the content is text
if (typeof updatedData.fields[fieldId] === 'string') {
domElement.textContent = updatedData.fields[fieldId];
}
}
};
const unsubscribe = ContentfulLivePreview.subscribe({
data: entry,
locale: CONFIG.locale,
callback,
});
CONFIG.subscriptions.push(unsubscribe);
}