reveal.js-appearance 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,438 +1,682 @@
1
1
 
2
2
  /*****************************************************************
3
- * @author: Martijn De Jongh (Martino), martijn.de.jongh@gmail.com
4
- * https://github.com/Martinomagnifico
5
3
  *
6
- * Appearance.js for Reveal.js
7
- * Version 1.2.1
4
+ * Appearance for Reveal.js
5
+ * Version 1.3.0
8
6
  *
7
+ * @author: Martijn De Jongh (Martino), martijn.de.jongh@gmail.com
8
+ * https://github.com/martinomagnifico
9
+ *
9
10
  * @license
10
11
  * MIT licensed
12
+ *
13
+ * Copyright (C) 2023 Martijn De Jongh (Martino)
11
14
  *
12
- * Thanks to:
13
- * - Hakim El Hattab, Reveal.js
14
- * - Daniel Eden, Animate.css
15
15
  ******************************************************************/
16
16
 
17
-
18
-
19
- const Plugin = () => {
20
- // Scope support polyfill
17
+ /**
18
+ * Check if a given string is valid JSON.
19
+ * @param {string} str - The string to be checked.
20
+ * @returns {boolean} `true` if the string is valid JSON, otherwise `false`.
21
+ */
22
+ const isJSON = str => {
21
23
  try {
22
- document.querySelector(":scope *");
23
- } catch (t) {
24
- !function (t) {
25
- let e = /:scope(?![\w-])/gi,
26
- r = u(t.querySelector);
27
-
28
- t.querySelector = function (t) {
29
- return r.apply(this, arguments);
30
- };
31
-
32
- let c = u(t.querySelectorAll);
33
-
34
- if (t.querySelectorAll = function (t) {
35
- return c.apply(this, arguments);
36
- }, t.matches) {
37
- let n = u(t.matches);
38
-
39
- t.matches = function (t) {
40
- return n.apply(this, arguments);
41
- };
42
- }
43
-
44
- if (t.closest) {
45
- let o = u(t.closest);
46
-
47
- t.closest = function (t) {
48
- return o.apply(this, arguments);
49
- };
50
- }
51
-
52
- function u(t) {
53
- return function (r) {
54
- if (r && e.test(r)) {
55
- let c = "q" + Math.floor(9e6 * Math.random()) + 1e6;
56
- arguments[0] = r.replace(e, "[" + c + "]"), this.setAttribute(c, "");
57
- let n = t.apply(this, arguments);
58
- return this.removeAttribute(c), n;
59
- }
24
+ return JSON.parse(str) && !!str;
25
+ } catch (e) {
26
+ return false;
27
+ }
28
+ };
60
29
 
61
- return t.apply(this, arguments);
62
- };
63
- }
64
- }(Element.prototype);
30
+ /**
31
+ * Check if an element has child nodes that are `SECTION` elements.
32
+ * @param {Object} param0 - Object with childNodes property.
33
+ * @param {NodeListOf<ChildNode>} param0.childNodes - List of child nodes of the element.
34
+ * @returns {boolean} `true` if the element contains `SECTION` child nodes, otherwise `false`.
35
+ */
36
+ const isStack = _ref => {
37
+ let {
38
+ childNodes
39
+ } = _ref;
40
+ let isStack = false;
41
+ for (let i = 0; i < childNodes.length; i++) {
42
+ if (childNodes[i].tagName == "SECTION") {
43
+ isStack = true;
44
+ break;
45
+ }
65
46
  }
47
+ return isStack;
48
+ };
66
49
 
67
- const loadStyle = function (url, type, callback) {
68
- let head = document.querySelector('head');
69
- let style;
70
- style = document.createElement('link');
71
- style.rel = 'stylesheet';
72
- style.href = url;
73
-
74
- let finish = function () {
75
- if (typeof callback === 'function') {
76
- callback.call();
77
- callback = null;
78
- }
79
- };
50
+ /**
51
+ * Copy data attributes from a source element to a target element with an optional exception.
52
+ * @param {Object} param0 - Object with attributes property.
53
+ * @param {NamedNodeMap} param0.attributes - Map of attributes of the source element.
54
+ * @param {Element} target - Target element to copy attributes to.
55
+ * @param {string} [not] - Optional attribute name to exclude from copying.
56
+ */
57
+ const copyDataAttributes = (_ref2, target, not) => {
58
+ let {
59
+ attributes
60
+ } = _ref2;
61
+ [...attributes].filter(_ref3 => {
62
+ let {
63
+ nodeName
64
+ } = _ref3;
65
+ return nodeName.includes('data');
66
+ }).forEach(_ref4 => {
67
+ let {
68
+ nodeName,
69
+ nodeValue
70
+ } = _ref4;
71
+ if (not && nodeName !== not || !not) {
72
+ target.setAttribute(nodeName, nodeValue);
73
+ }
74
+ });
75
+ };
80
76
 
81
- style.onload = finish;
77
+ /**
78
+ * Check if the given item is an object and not an array.
79
+ * @param {*} item - The item to be checked.
80
+ * @returns {boolean} `true` if the item is an object and not an array, otherwise `false`.
81
+ */
82
+ const isObject = item => {
83
+ return item && typeof item === 'object' && !Array.isArray(item);
84
+ };
82
85
 
83
- style.onreadystatechange = function () {
84
- if (this.readyState === 'loaded') {
85
- finish();
86
+ /**
87
+ * Deep merge multiple objects into a target object.
88
+ * @param {Object} target - Target object to merge values into.
89
+ * @param {...Object} sources - Source objects to merge from.
90
+ * @returns {Object} The merged object.
91
+ */
92
+ const mergeDeep = function (target) {
93
+ for (var _len = arguments.length, sources = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
94
+ sources[_key - 1] = arguments[_key];
95
+ }
96
+ if (!sources.length) return target;
97
+ const source = sources.shift();
98
+ if (isObject(target) && isObject(source)) {
99
+ for (const key in source) {
100
+ if (isObject(source[key])) {
101
+ if (!target[key]) Object.assign(target, {
102
+ [key]: {}
103
+ });
104
+ mergeDeep(target[key], source[key]);
105
+ } else {
106
+ Object.assign(target, {
107
+ [key]: source[key]
108
+ });
86
109
  }
87
- };
110
+ }
111
+ }
112
+ return mergeDeep(target, ...sources);
113
+ };
88
114
 
89
- head.appendChild(style);
90
- };
115
+ /**
116
+ * Resolves the given Promise immediately using setTimeout.
117
+ * @param {Function} resolve - The resolve function of a Promise.
118
+ * @returns {number} The ID value of the timer that is set.
119
+ */
120
+ const doneLoading = resolve => {
121
+ return setTimeout(resolve, 0);
122
+ };
91
123
 
92
- const isJSON = str => {
93
- try {
94
- return JSON.parse(str) && !!str;
95
- } catch (e) {
96
- return false;
124
+ /**
125
+ * Converts a JavaScript object or a JSON-formatted string to a JSON string.
126
+ *
127
+ * @param {Object|string} str - The input string or object to be converted to a JSON string.
128
+ * @returns {string} The JSON string.
129
+ */
130
+ const toJSONString = str => {
131
+ let JSONString = '';
132
+ if (typeof str === "string") str = str.replace(/[“”]/g, '"').replace(/[‘’]/g, "'");
133
+ if (isJSON(str)) {
134
+ JSONString = str;
135
+ } else {
136
+ if (typeof str === "object") {
137
+ JSONString = JSON.stringify(str, null, 2);
138
+ } else {
139
+ JSONString = str.trim().replace(/'/g, '"').charAt(0) === "{" ? str.trim().replace(/'/g, '"') : `{${str.trim().replace(/'/g, '"')}}`;
97
140
  }
98
- };
141
+ }
142
+ return JSONString;
143
+ };
99
144
 
100
- const selectionArray = function (container, selectors) {
101
- let selections = container.querySelectorAll(selectors);
102
- let selectionarray = Array.prototype.slice.call(selections);
103
- return selectionarray;
145
+ /**
146
+ * Dynamically loads a stylesheet from the specified URL and calls a callback function when it's loaded.
147
+ *
148
+ * @param {string} url - The URL of the stylesheet to load.
149
+ * @param {Function} callback - A callback function to be called when the stylesheet is loaded.
150
+ */
151
+ const loadStyle = (url, callback) => {
152
+ const head = document.querySelector('head');
153
+ const style = document.createElement('link');
154
+ style.rel = 'stylesheet';
155
+ style.href = url;
156
+ style.onload = () => {
157
+ if (typeof callback === 'function') {
158
+ callback.call();
159
+ callback = null;
160
+ }
104
161
  };
105
-
106
- const isStack = function (section) {
107
- let isStack = false;
108
-
109
- for (let i = 0; i < section.childNodes.length; i++) {
110
- if (section.childNodes[i].tagName == "SECTION") {
111
- isStack = true;
112
- break;
113
- }
162
+ style.onreadystatechange = () => {
163
+ if (style.readyState === 'loaded') {
164
+ style.onload();
114
165
  }
115
-
116
- return isStack;
117
166
  };
167
+ head.appendChild(style);
168
+ };
118
169
 
119
- function copyDataAttributes(source, target, not) {
120
- [...source.attributes].filter(attr => attr.nodeName.indexOf('data') > -1).forEach(attr => {
121
- if (not && attr.nodeName !== not || !not) {
122
- target.setAttribute(attr.nodeName, attr.nodeValue);
123
- }
124
- });
170
+ /**
171
+ * Retrieves the path of a JavaScript file based on its filename.
172
+ *
173
+ * @param {string} fileName - The filename of the script.
174
+ * @returns {string} The path to the plugin's location.
175
+ */
176
+ const pluginPath = fileName => {
177
+ let path;
178
+ let pluginScript = document.querySelector(`script[src$="${fileName}"]`);
179
+ if (pluginScript) {
180
+ path = pluginScript.getAttribute("src").slice(0, -1 * fileName.length);
181
+ } else {
182
+ path = import.meta.url.slice(0, import.meta.url.lastIndexOf('/') + 1);
125
183
  }
184
+ return path;
185
+ };
186
+ const debugLog = (options, text) => {
187
+ if (options.debug) console.log(text);
188
+ };
126
189
 
127
- const appear = function (deck, options) {
128
- let baseclass = 'animate__animated';
129
- let viewport = deck.getRevealElement().tagName == "BODY" ? document : deck.getRevealElement();
130
- let appearanceSelector = options.compatibility ? `.${options.compatibilitybaseclass}` : `.${baseclass}`;
131
- let fragmentSelector = ".fragment";
132
- let speedClasses = ['slower', 'slow', 'fast', 'faster'];
133
- speedClasses.push(...speedClasses.map(speed => `animate__${speed}`));
134
- document.querySelector('[name=generator]');
135
- const sections = selectionArray(viewport, "section");
136
- const regularSections = sections.filter(section => !isStack(section) && section.dataset.visibility != "hidden");
137
- const fragments = deck.getRevealElement().querySelectorAll(fragmentSelector);
138
- let animatecss = '[class^="animate__"],[class*=" animate__"]';
139
-
140
- const debugLog = function (text) {
141
- if (options.debug) console.log(text);
142
- };
143
-
144
- let url = new URL(window.location);
145
- let urlparams = new URLSearchParams(url.search);
190
+ /**
191
+ * Retrieves and loads CSS stylesheets based on the provided options and ES5 filename.
192
+ *
193
+ * @param {Object} options - Configuration options for loading CSS.
194
+ * @param {string} fileName - The filename of the script.
195
+ */
196
+
197
+ const getAndLoadCSS = (options, fileName) => {
198
+ let thePath = pluginPath(fileName);
199
+ let pluginBaseName = fileName.replace(/\.[^/.]+$/, "");
200
+ let AppearanceStylePath = options.csspath.appearance ? options.csspath.appearance : `${thePath}${pluginBaseName}.css` || `plugin/${pluginBaseName}/${pluginBaseName}.css`;
201
+ let AnimateCSSPath = !options.compatibility ? options.animatecsspath.link : options.animatecsspath.compat;
202
+ if (options.debug) {
203
+ console.log(`Paths:`);
204
+ console.log(` - Plugin path = ${thePath}`);
205
+ console.log(` - Appearance CSS path = ${AppearanceStylePath}`);
206
+ console.log(` - AnimateCSS CSS path = ${AnimateCSSPath}`);
207
+ }
208
+ loadStyle(AnimateCSSPath, function () {
209
+ loadStyle(AppearanceStylePath);
210
+ });
211
+ };
146
212
 
147
- if (urlparams.has('receiver')) {
148
- viewport.classList.add('sv');
149
- console.log(viewport);
213
+ /**
214
+ * Adds automatic animations to elements within a section based on specified criteria.
215
+ *
216
+ * This function examines the provided section for attributes and options to determine
217
+ * which classes should be added to its elements to enable automatic animations.
218
+ *
219
+ * @param {HTMLElement} section - The section element to which automatic animations will be applied.
220
+ * @param {Object} options - The existing user options object
221
+ * @param {Object} vars - The existing vars object
222
+ * @returns {undefined}
223
+ */
224
+ const addAutoAnimation = (section, options, vars) => {
225
+ let sectionAutoSelectors = null;
226
+ if (section.hasAttribute("data-autoappear")) {
227
+ let sectDataAppear = section.dataset.autoappear;
228
+ if (sectDataAppear == "auto" || sectDataAppear == "" || sectDataAppear.length < 1 || sectDataAppear == "true") {
229
+ // This section should get the global autoappear classes on its objects
230
+ sectionAutoSelectors = options.autoelements ? options.autoelements : null;
231
+ } else {
232
+ // This section should get the local autoappear classes on its objects
233
+ sectionAutoSelectors = sectDataAppear;
150
234
  }
151
-
152
- const assignAutoClass = (section, str, kind) => {
153
- let index = [...section.parentElement.children].filter(s => s.tagName == "SECTION").indexOf(section) + 1;
154
- let warning = kind == 'global' ? `JSON Parse error, please try to correct the global "autoelements" option.` : `JSON Parse error, please try to correct the "data-autoappear" attribute on section ${index}`;
155
- if (typeof str === "string") str = str.replace(/[“”]/g, '"').replace(/[‘’]/g, "'");
156
- let strJSON = isJSON(str) ? str : typeof str === "object" ? JSON.stringify(str, null, 2) : str.trim().replace(/'/g, '"').charAt(0) === "{" ? str.trim().replace(/'/g, '"') : `{${str.trim().replace(/'/g, '"')}}`;
157
-
158
- if (!isJSON(strJSON)) {
159
- console.log(warning);
160
- } else {
161
- let elementsToAnimate = JSON.parse(strJSON);
162
-
163
- for (const [element, assignables] of Object.entries(elementsToAnimate)) {
164
- let elementsInSection = section.querySelectorAll(element);
165
- elementsInSection.forEach(elementInSection => {
166
- if (!elementInSection.classList.contains(baseclass) || elementInSection.dataset["autoappear"]) {
167
- elementInSection.dataset["autoappear"] = true;
168
- let newClasses = [],
169
- newDelay = null,
170
- speedClass = false;
171
-
172
- if (Array.isArray(assignables)) {
173
- newClasses = assignables[0].split(/[ ,]+/);
174
- newDelay = assignables[1];
175
- } else if (typeof assignables == "string") {
176
- newClasses = assignables.split(/[ ,]+/);
177
- }
178
-
179
- speedClasses.forEach(speed => {
180
- if (elementInSection.classList.contains(speed)) {
181
- speedClass = speed;
182
- }
183
- });
184
- let classesToRemove = [];
185
- elementInSection.classList.forEach(currentClass => {
186
- if (String(currentClass).includes("animate__")) {
187
- classesToRemove.push(currentClass);
188
- }
189
- });
190
- classesToRemove.forEach(currentClass => {
191
- elementInSection.classList.remove(currentClass);
192
- });
193
- newClasses.forEach(newClass => {
194
- if (speedClasses.includes(newClass)) {
195
- // There is a speed class from JSON to be assigned
196
- if (speedClass) {
197
- speedClass = newClass;
198
- }
199
- }
200
- });
201
- newClasses.forEach(newClass => {
202
- elementInSection.classList.add(newClass);
203
- });
204
-
205
- if (speedClass) {
206
- elementInSection.classList.add(speedClass);
207
- }
208
-
209
- if (newDelay) {
210
- elementInSection.dataset.delay = newDelay;
211
- }
212
-
213
- elementInSection.classList.add(baseclass);
235
+ } else if (options.autoappear && options.autoelements) {
236
+ // This section should get the global autoappear classes on its objects
237
+ sectionAutoSelectors = options.autoelements;
238
+ }
239
+ if (sectionAutoSelectors) {
240
+ let elementsToAnimate = JSON.parse(toJSONString(sectionAutoSelectors));
241
+ Object.entries(elementsToAnimate).forEach(_ref => {
242
+ let [selector, assignables] = _ref;
243
+ // Exclude the elements from vars.appearances
244
+ let elements = Array.from(section.querySelectorAll(selector)).filter(element => !vars.appearances.includes(element));
245
+ if (elements.length) {
246
+ elements.forEach(element => {
247
+ vars.appearances.push(element);
248
+ let newClasses = [],
249
+ newDelay = null,
250
+ speedClass = false,
251
+ elementSplit = null,
252
+ containerDelay = null;
253
+ if (Array.isArray(assignables)) {
254
+ newClasses = assignables[0].split(/[ ,]+/);
255
+ newDelay = assignables[1];
256
+ } else if (typeof assignables == "string") {
257
+ newClasses = assignables.split(/[ ,]+/);
258
+ } else if (assignables.constructor === Object) {
259
+ if (assignables.class || assignables.animation) {
260
+ let animationClass = assignables.animation ? assignables.animation : assignables.class;
261
+ newClasses = animationClass.split(/[ ,]+/);
214
262
  }
215
- });
216
- }
217
- }
218
- };
219
-
220
- const findAppearancesIn = function (container, includeClass, excludeClass) {
221
- if (!isStack(container)) {
222
- let appearances = selectionArray(container, `:scope ${includeClass}`);
223
- appearances.forEach(appearance => {
224
- let convertListItem = appearance => {
225
- let from = appearance,
226
- to = appearance.parentNode;
227
- if (!to) return;
228
-
229
- for (let sibling of to.children) {
230
- if (sibling !== appearance) {
231
- if (sibling.dataset.appearParent) return;
263
+ if (assignables.speed) {
264
+ speedClass = String(assignables.speed);
265
+ if (!speedClass.includes("animate__")) {
266
+ speedClass = `animate__${speedClass}`;
232
267
  }
233
268
  }
234
-
235
- to.classList = from.classList;
236
- copyDataAttributes(from, to, "data-appear-parent");
237
- to.innerHTML = from.innerHTML;
238
- }; // Conversion of list items with Appearance classes to the parent, needs manual attribute
239
- // Relates to Quarto wrapping list content in a span.
240
-
241
-
242
- if (appearance.hasAttribute("data-appear-parent")) {
243
- convertListItem(appearance);
244
- } // Automatic conversion of list items which directly contain spans.
245
- // Relates to Quarto wrapping list content in a span.
246
-
247
-
248
- if (options.appearparents) {
249
- if (appearance.parentNode && appearance.parentNode.tagName) {
250
- if (appearance.tagName == "SPAN" && appearance.parentNode.tagName == "LI") {
251
- let spanLength = String(appearance.outerHTML).length;
252
- let liContentLength = String(appearance.parentNode.innerHTML).length;
253
-
254
- if (spanLength == liContentLength) {
255
- convertListItem(appearance);
256
- }
257
- }
269
+ if (assignables.delay) {
270
+ newDelay = String(assignables.delay);
258
271
  }
259
- }
260
- });
261
- appearances = selectionArray(container, `:scope ${includeClass}`);
262
- let excludes = selectionArray(container, `:scope ${excludeClass} ${includeClass}`);
263
- let delay = 0;
264
- appearances.filter(function (appearance, index) {
265
- if (!(excludes.indexOf(appearance) > -1)) {
266
- if (index == 0 && appearance.dataset.delay || index != 0) {
267
- let elementDelay = options.delay;
268
-
269
- if (appearance.dataset && appearance.dataset.delay) {
270
- elementDelay = parseInt(appearance.dataset.delay);
271
- }
272
-
273
- delay = delay + elementDelay; // Allow fragments to be Appearance items
274
-
275
- if (appearance.classList.contains("fragment")) {
276
- delay = 0;
277
-
278
- if (appearance.querySelectorAll(`.${baseclass}`)) {
279
- let firstNestedAppearance = appearance.querySelectorAll(`.${baseclass}`)[0];
280
-
281
- if (firstNestedAppearance) {
282
- let elementDelay = options.delay;
283
-
284
- if (firstNestedAppearance.dataset && firstNestedAppearance.dataset.delay) {
285
- elementDelay = parseInt(firstNestedAppearance.dataset.delay);
286
- }
287
-
288
- firstNestedAppearance.dataset.delay = elementDelay;
289
- }
290
- }
291
- }
292
-
293
- appearance.style.setProperty('animation-delay', delay + "ms");
272
+ if (assignables.split) {
273
+ elementSplit = String(assignables.split);
274
+ }
275
+ if (assignables["container-delay"]) {
276
+ containerDelay = String(assignables["container-delay"]);
294
277
  }
295
278
  }
279
+ element.classList.add(...newClasses);
280
+ if (speedClass) {
281
+ element.classList.add(speedClass);
282
+ }
283
+ if (newDelay) {
284
+ element.dataset.delay = newDelay;
285
+ }
286
+ if (elementSplit) {
287
+ element.dataset.split = elementSplit;
288
+ }
289
+ if (containerDelay) {
290
+ element.dataset.containerDelay = containerDelay;
291
+ }
296
292
  });
297
293
  }
298
- };
299
-
300
- const autoAdd = function () {
301
- regularSections.forEach(section => {
302
- if (section.hasAttribute("data-autoappear")) {
303
- let sectDataAppear = section.dataset.autoappear;
304
-
305
- if (sectDataAppear == "auto" || sectDataAppear == "" || sectDataAppear.length < 1 || sectDataAppear == "true") {
306
- // This section should get the global autoappear classes on its objects
307
- if (options.autoelements) {
308
- if (!options.autoelements) {
309
- return console.log(`Please add some elements in the option "autoelements"`);
310
- }
311
-
312
- assignAutoClass(section, options.autoelements, 'global');
313
- }
314
- } else if (sectDataAppear.length > 0) {
315
- // This section should get the local data-autoappear classes on its objects
316
- assignAutoClass(section, sectDataAppear, 'local'); //section.removeAttribute("data-autoappear");
317
- }
318
- } else {
319
- if (options.autoappear) {
320
- if (!options.autoelements) {
321
- return console.log(`Please add some elements in the option "autoelements"`);
322
- } // This section should get the global autoappear classes on its objects
294
+ });
295
+ }
296
+ };
323
297
 
298
+ /**
299
+ * Hoist a list item's appearance to its parent element's appearance.
300
+ *
301
+ * @param {HTMLElement} from - The list item element.
302
+ * @returns {undefined}
303
+ */
304
+ const hoistAppearance = (from, baseclass) => {
305
+ let to = from.parentNode;
306
+ if (!to) return;
307
+ for (const sibling of to.children) {
308
+ if (sibling !== from && sibling.dataset.appearParent) return;
309
+ }
310
+ to.classList = from.classList;
311
+ copyDataAttributes(from, to, "data-appear-parent");
312
+ to.innerHTML = from.innerHTML;
313
+ to.classList.add(baseclass);
314
+ };
324
315
 
325
- assignAutoClass(section, options.autoelements, 'global');
326
- }
316
+ /**
317
+ * Fix list items that were changed by Quarto.
318
+ *
319
+ * This function is designed for use with Quarto and handles the conversion of list items
320
+ * with Appearance classes to their parent elements when a manual attribute is present.
321
+ * It also provides automatic conversion for list items that directly contain spans, which
322
+ * is related to Quarto's wrapping of list content in a span.
323
+ *
324
+ * @param {HTMLElement} appearance - The list item element whose appearance will be converted.
325
+ * @param {Object} options - An options object that controls the conversion behavior.
326
+ * @param {boolean} options.appearparents - If `true`, automatic conversion of list items with spans is enabled.
327
+ * @returns {undefined}
328
+ */
329
+ const fixListItem = (appearance, options, names) => {
330
+ let baseclass = names.baseclass;
331
+ if (appearance.hasAttribute("data-appear-parent")) {
332
+ hoistAppearance(appearance, baseclass);
333
+ }
334
+ if (options.appearparents) {
335
+ if (appearance.parentNode && appearance.parentNode.tagName) {
336
+ if (appearance.tagName == "SPAN" && appearance.parentNode.tagName == "LI") {
337
+ let spanLength = String(appearance.outerHTML).length;
338
+ let liContentLength = String(appearance.parentNode.innerHTML).length;
339
+ if (spanLength == liContentLength) {
340
+ hoistAppearance(appearance);
327
341
  }
328
- });
329
- };
330
-
331
- if (options.compatibility) {
332
- animatecss = '.backInDown, .backInLeft, .backInRight, .backInUp, .bounceIn, .bounceInDown, .bounceInLeft, .bounceInRight, .bounceInUp, .fadeIn, .fadeInDown, .fadeInDownBig, .fadeInLeft, .fadeInLeftBig, .fadeInRight, .fadeInRightBig, .fadeInUp, .fadeInUpBig, .fadeInTopLeft, .fadeInTopRight, .fadeInBottomLeft, .fadeInBottomRight, .flipInX, .flipInY, .lightSpeedInRight, .lightSpeedInLeft, .rotateIn, .rotateInDownLeft, .rotateInDownRight, .rotateInUpLeft, .rotateInUpRight, .jackInTheBox, .rollIn, .zoomIn, .zoomInDown, .zoomInLeft, .zoomInRight, .zoomInUp, .slideInDown, .slideInLeft, .slideInRight, .slideInUp, .skidLeft, .skidLeftBig, .skidRight, .skidRightBig, .shrinkIn, .shrinkInBlur';
333
- baseclass = options.compatibilitybaseclass;
334
- }
335
-
336
- let allappearances = deck.getRevealElement().querySelectorAll(animatecss);
337
- allappearances.forEach(appearance => {
338
- if (!appearance.classList.contains(baseclass)) {
339
- appearance.classList.add(baseclass);
340
342
  }
341
- });
342
- autoAdd();
343
- sections.forEach(section => {
344
- findAppearancesIn(section, appearanceSelector, fragmentSelector);
345
- });
346
- fragments.forEach(fragment => {
347
- findAppearancesIn(fragment, appearanceSelector, fragmentSelector);
348
- });
343
+ }
344
+ }
345
+ };
349
346
 
350
- const fromTo = function (event) {
351
- let slides = {};
352
- slides.from = event.fromSlide ? event.fromSlide : event.previousSlide ? event.previousSlide : null;
353
- slides.to = event.toSlide ? event.toSlide : event.currentSlide ? event.currentSlide : null;
354
- return slides;
355
- };
347
+ /**
348
+ * Adds a base class to an HTML element if it doesn't already have it.
349
+ *
350
+ * This function checks if the specified HTML element has the specified base class,
351
+ * and if not, it adds the base class to the element's class list.
352
+ *
353
+ * @param {HTMLElement} appearance - The HTML element to which the base class should be added.
354
+ * @param {Object} names - The existing 'names' object
355
+ * @returns {undefined}
356
+ */
357
+
358
+ const addBaseClass = (appearance, names) => {
359
+ if (!appearance.classList.contains(names.baseclass)) {
360
+ appearance.classList.add(names.baseclass);
361
+ }
362
+ if (appearance.classList.contains(names.fragmentClass)) {
363
+ appearance.classList.add('custom');
364
+ }
365
+ };
356
366
 
357
- const showHideSlide = function (event) {
358
- var _slides$to;
367
+ const addDelay = (appearanceArray, options, names) => {
368
+ let delay = 0;
369
+ appearanceArray.forEach((appearance, index) => {
370
+ if (index == 0 && appearance.dataset.delay || index != 0) {
371
+ let elementDelay = options.delay;
372
+ if (appearance.dataset && appearance.dataset.delay) {
373
+ elementDelay = parseInt(appearance.dataset.delay);
374
+ }
375
+ delay = delay + elementDelay;
376
+ appearance.style.setProperty('animation-delay', delay + "ms");
377
+ appearance.removeAttribute('data-delay');
378
+ }
379
+ });
380
+ };
359
381
 
360
- let etype = event.type;
361
- let slides = fromTo(event);
362
- debugLog(etype);
382
+ /**
383
+ * Selects elements with a specified class that are not nested inside an element with another specified class.
384
+ * @param {string} targetClass - The class name to select elements.
385
+ * @param {string} excludeClass - The class name to exclude elements nested inside it.
386
+ * @param {Element} el - The element to find the target elements in.
387
+ * @returns {Element[]} - Array of selected elements.
388
+ */
389
+ const elemsNotInClass = (targetClass, excludeClass, el) => Array.from(el.querySelectorAll(`.${targetClass}`)).filter(s => !s.closest(`.${excludeClass}`));
390
+
391
+ /**
392
+ * Selects elements with a specified class that are nested inside an element with another specified class.
393
+ * @param {string} targetClass - The class name to select elements.
394
+ * @param {string} parentClass - The class name of the parent to find elements in.
395
+ * @param {Element} el - The element to find the target elements in.
396
+ * @returns {Element[]} - Array of selected elements.
397
+ */
398
+ const elemsInClass = (targetClass, parentClass, el) => Array.from(el.querySelectorAll(`.${targetClass}`)).filter(s => s.closest(`.${parentClass}`) === el);
399
+
400
+ /**
401
+ * Extracts groups of elements with a specified class from the provided section element.
402
+ * Groups are formed based on nesting inside elements with another specified class.
403
+ * @param {Element} section - The section to extract data from.
404
+ * @returns {Element[][]} - Nested arrays of selected elements.
405
+ */
406
+
407
+ /**
408
+ * Extracts groups of elements with a specified class from the provided section element.
409
+ * Groups are formed based on nesting inside elements with another specified class.
410
+ * @param {Element} section - The section to extract data from.
411
+ * @param {string} targetClass - The class name to select elements.
412
+ * @param {string} groupClass - The class name of the parent to find elements in.
413
+ * @returns {Element[][]} - Nested arrays of selected elements.
414
+ */
415
+ const getAppearanceArrays = (section, targetClass, groupClass) => {
416
+ const result = [elemsNotInClass(targetClass, groupClass, section), ...Array.from(section.querySelectorAll(`.${groupClass}`)).map(frag => elemsInClass(targetClass, groupClass, frag))];
417
+ if (result.some(group => group.length > 0)) {
418
+ return result;
419
+ } else {
420
+ return false;
421
+ }
422
+ };
363
423
 
364
- if (((_slides$to = slides.to) === null || _slides$to === void 0 ? void 0 : _slides$to.dataset.appearevent) == "auto") {
365
- slides.to.dataset.appearevent = "autoanimate";
424
+ const convertToSpans = (parent, kind) => {
425
+ let splitElements = false;
426
+ let joinChar = ' ';
427
+ if (kind == "words") {
428
+ splitElements = parent.textContent.trim().split(/\s+/);
429
+ } else if (kind == "letters") {
430
+ splitElements = parent.textContent.trim().split('');
431
+ joinChar = '';
432
+ }
433
+ if (splitElements) {
434
+ const parentAnimateClasses = Array.from(parent.classList).filter(className => className.startsWith('animate__'));
435
+ const newHtml = splitElements.map((element, index) => {
436
+ const span = document.createElement('span');
437
+ span.textContent = element;
438
+ if (element == " ") {
439
+ span.textContent = "\u00A0";
366
440
  }
367
-
368
- if (options.appearevent == "auto") {
369
- options.appearevent = "autoanimate";
441
+ if (parent.dataset.delay && index !== 0) {
442
+ span.dataset.delay = parent.dataset.delay;
370
443
  }
371
-
372
- if (etype == "ready") {
373
- slides.to.dataset.appearanceCanStart = true;
444
+ if (parent.dataset.containerDelay && index === 0) {
445
+ span.dataset.delay = parent.dataset.containerDelay;
374
446
  }
447
+ parent.classList.forEach(className => className.startsWith('animate__') && span.classList.add(className));
448
+ return span.outerHTML;
449
+ }).join(joinChar);
450
+ parentAnimateClasses.forEach(className => parent.classList.remove(className));
451
+ parent.removeAttribute('data-delay');
452
+ parent.removeAttribute('data-split');
453
+ parent.removeAttribute('data-container-delay');
454
+ parent.innerHTML = newHtml;
455
+ }
456
+ };
375
457
 
376
- if (slides.to) {
377
- let appearevent = slides.to.dataset.appearevent ? slides.to.dataset.appearevent : options.appearevent;
378
-
379
- if (etype == appearevent || etype == "slidetransitionend" && appearevent == "autoanimate") {
380
- slides.to.dataset.appearanceCanStart = true;
381
- }
382
-
383
- if (etype == "slidetransitionend") {
384
- if (options.hideagain) {
385
- if (slides.from) {
386
- if (slides.from.dataset.appearanceCanStart) {
387
- delete slides.from.dataset.appearanceCanStart;
388
- }
389
-
390
- let fromFragments = slides.from.querySelectorAll(`.fragment.visible`);
458
+ /**
459
+ * Derives slide from and to from the event object.
460
+ *
461
+ * @param {Object} event - The event object containing slide transition details.
462
+ * @returns {Object} - An object containing references to the "from" and "to" slides.
463
+ */
464
+ const fromTo = event => {
465
+ let slides = {};
466
+ slides.from = event.fromSlide || event.previousSlide || null;
467
+ slides.to = event.toSlide || event.currentSlide || null;
468
+ return slides;
469
+ };
391
470
 
392
- if (fromFragments) {
393
- fromFragments.forEach(fragment => {
394
- fragment.classList.remove('visible');
395
- });
396
- }
397
- }
398
- }
399
- }
471
+ /**
472
+ * A function that determines the appearance event for a given slide.
473
+ *
474
+ * This function checks the `data-appearevent` attribute of the slide and the `options.appearevent` parameter.
475
+ * If `data-appearevent` is set to "auto", it is converted to "autoanimate". If `options.appearevent` is "auto", it is also converted to "autoanimate".
476
+ * The function returns the appearance event, prioritizing `data-appearevent` over `options.appearevent`.
477
+ *
478
+ * @param {HTMLElement} toSlide - The slide for which the appearance event is determined.
479
+ * @param {Object} options - An object containing options for the appearance event.
480
+ * @param {string} options.appearevent - The appearance event option provided in the `options` object.
481
+ *
482
+ * @returns {string} - The determined appearance event for the slide, either from `data-appearevent` or `options.appearevent`.
483
+ */
484
+ const slideAppearevent = (toSlide, options) => {
485
+ if (toSlide.dataset.appearevent && toSlide.dataset.appearevent === "auto") {
486
+ toSlide.dataset.appearevent = "autoanimate";
487
+ }
488
+ if (options.appearevent == "auto") {
489
+ options.appearevent = "autoanimate";
490
+ }
491
+ return toSlide.dataset.appearevent ? toSlide.dataset.appearevent : options.appearevent;
492
+ };
400
493
 
401
- if (event.type == 'slidechanged' && document.body.dataset.exitoverview) {
402
- if (options.hideagain) {
403
- var _slides$from;
494
+ /**
495
+ * Remove the 'data-appearance-can-start' attribute from the 'from' slide if the 'hideagain' option is enabled.
496
+ *
497
+ * @param {HTMLElement} slides - The container element for the slides.
498
+ * @param {Object} options - An object containing configuration options.
499
+ * @param {boolean} options.hideagain - A flag indicating whether to remove the attribute when 'hideagain' is true.
500
+ */
501
+ const removeStartAttribute = (slides, options) => {
502
+ if (options.hideagain) {
503
+ if (slides.from && slides.from.dataset.appearanceCanStart) {
504
+ slides.from.removeAttribute('data-appearance-can-start');
505
+ }
506
+ }
507
+ };
404
508
 
405
- (_slides$from = slides.from) === null || _slides$from === void 0 ? true : delete _slides$from.dataset.appearanceCanStart;
406
- }
509
+ /**
510
+ * Turn off slide appearances when transitioning from one slide to another if the 'hideagain' option is enabled.
511
+ *
512
+ * @param {HTMLElement} slides - The container element for the slides.
513
+ * @param {Object} options - An object containing configuration options.
514
+ * @param {string} names.animatecss - The CSS selector for animated elements.
515
+ */
516
+ const turnOffSlideAppearances = (slides, options, names) => {
517
+ if (options.hideagain) {
518
+ let fromAppearances = slides.from.querySelectorAll(names.animatecss);
519
+ fromAppearances.forEach(appearance => {
520
+ appearance.classList.remove('animationended');
521
+ });
522
+ // Remove visible class from fragments when moving away from that slide
523
+ let fromFragments = slides.from.querySelectorAll(`.fragment.visible`);
524
+ if (fromFragments) {
525
+ fromFragments.forEach(fragment => {
526
+ fragment.classList.remove('visible');
527
+ });
528
+ }
529
+ }
530
+ };
407
531
 
408
- slides.to.dataset.appearanceCanStart = true;
409
- } else if (event.type == 'overviewhidden') {
410
- document.body.dataset.exitoverview = true;
411
- setTimeout(function () {
412
- document.body.removeAttribute('data-exitoverview');
413
- }, 500);
532
+ /**
533
+ * Handles the showing and hiding of slides based on the provided event and options.
534
+ *
535
+ * @param {Object} event - The event object containing slide transition details.
536
+ * @param {Object} options - An object containing configurations for slide appearance management.
537
+ */
538
+ const showHideSlide = (event, options, names, vars) => {
539
+ let view = vars.deck.getConfig().view;
540
+ let etype = event.type;
541
+ let slides = fromTo(event);
542
+ if (slides.to) {
543
+ if (etype == "ready") {
544
+ slides.to.dataset.appearanceCanStart = true;
545
+ }
546
+ let appearevent = slideAppearevent(slides.to, options);
547
+ if (etype == appearevent || etype == "slidetransitionend" && appearevent == "autoanimate") {
548
+ slides.to.dataset.appearanceCanStart = true;
549
+ }
414
550
 
415
- if (event.currentSlide) {
416
- if (options.hideagain) {
417
- var _slides$from2;
551
+ // Add experimental Reader mode compatibility, does not have a slidetransitionend event yet
552
+ if (view == "scroll" && etype == 'slidechanged') {
553
+ removeStartAttribute(slides, options);
554
+ turnOffSlideAppearances(slides, options, names);
418
555
 
419
- (_slides$from2 = slides.from) === null || _slides$from2 === void 0 ? true : delete _slides$from2.dataset.appearanceCanStart;
420
- }
556
+ // Add delay to allow for scroll animation to finish
557
+ setTimeout(() => {
558
+ slides.to.dataset.appearanceCanStart = true;
559
+ }, options.delay);
560
+ }
561
+ if (etype == "slidetransitionend") {
562
+ removeStartAttribute(slides, options);
563
+ turnOffSlideAppearances(slides, options, names);
564
+ }
565
+ if (etype == 'slidechanged' && document.body.dataset.exitoverview) {
566
+ removeStartAttribute(slides, options);
567
+ slides.to.dataset.appearanceCanStart = true;
568
+ } else if (etype == 'overviewhidden') {
569
+ document.body.dataset.exitoverview = true;
570
+ setTimeout(() => {
571
+ document.body.removeAttribute('data-exitoverview');
572
+ }, 500);
573
+ if (event.currentSlide) {
574
+ removeStartAttribute(slides, options);
575
+ slides.to.dataset.appearanceCanStart = true;
576
+ }
577
+ }
578
+ }
579
+ };
421
580
 
422
- slides.to.dataset.appearanceCanStart = true;
423
- }
424
- }
581
+ const Plugin = () => {
582
+ const vars = {};
583
+ vars.names = {};
584
+ let options = {};
585
+
586
+ /**
587
+ * Prepare the plugin to find Appearance elements
588
+ * @param {Object} vars - The variables to be prepared.
589
+ * @param {Object} names - The names to be prepared.
590
+ * @param {Function} resolve - The callback function to be called when preparation is complete.
591
+ * @throws {Error} Throws an error if the 'options' object is not defined.
592
+ */
593
+ const prepare = (options, vars, resolve) => {
594
+ debugLog(options, "------------- Preloading -------------");
595
+ let names = vars.names;
596
+ getAndLoadCSS(options, names.es5Filename);
597
+ if (options.compatibility) {
598
+ names.animatecss = '.backInDown, .backInLeft, .backInRight, .backInUp, .bounceIn, .bounceInDown, .bounceInLeft, .bounceInRight, .bounceInUp, .fadeIn, .fadeInDown, .fadeInDownBig, .fadeInLeft, .fadeInLeftBig, .fadeInRight, .fadeInRightBig, .fadeInUp, .fadeInUpBig, .fadeInTopLeft, .fadeInTopRight, .fadeInBottomLeft, .fadeInBottomRight, .flipInX, .flipInY, .lightSpeedInRight, .lightSpeedInLeft, .rotateIn, .rotateInDownLeft, .rotateInDownRight, .rotateInUpLeft, .rotateInUpRight, .jackInTheBox, .rollIn, .zoomIn, .zoomInDown, .zoomInLeft, .zoomInRight, .zoomInUp, .slideInDown, .slideInLeft, .slideInRight, .slideInUp, .skidLeft, .skidLeftBig, .skidRight, .skidRightBig, .shrinkIn, .shrinkInBlur';
599
+ names.baseclass = options.compatibilitybaseclass;
600
+ }
601
+ vars.appearances = Array.from(vars.slides.querySelectorAll(names.animatecss));
602
+
603
+ // Go through each section to see if there are any (auto) selectors that need animation classes
604
+ vars.regularSections.forEach(theSection => addAutoAnimation(theSection, options, vars));
605
+ vars.appearances.forEach((theAppearance, index) => {
606
+ // Fix any list item where the Appearance classes were moved to the span (Quarto does this)
607
+ fixListItem(theAppearance, options, names);
608
+
609
+ // Go through each appearance element and add the baseclass if it doesn't have it
610
+ addBaseClass(theAppearance, names);
611
+ if (theAppearance.hasAttribute('data-split')) {
612
+ convertToSpans(theAppearance, theAppearance.dataset.split);
425
613
  }
426
- };
614
+ });
615
+ vars.regularSections.forEach((theSection, index) => {
616
+ // Get all the Appearances in the section as separate arrays per delay loop
617
+ let appearanceArrays = getAppearanceArrays(theSection, names.baseclass, names.fragmentClass);
618
+ if (appearanceArrays) {
619
+ appearanceArrays.forEach(appearanceArray => {
620
+ // Add the delays to each appearance in the array
621
+ addDelay(appearanceArray, options);
622
+ });
623
+ }
624
+ });
625
+ doneLoading(resolve);
626
+ };
427
627
 
428
- const eventnames = ['ready', 'slidechanged', 'slidetransitionend', 'autoanimate', 'overviewhidden'];
429
- eventnames.forEach(eventname => deck.on(eventname, event => {
430
- showHideSlide(event);
628
+ /**
629
+ * The main function of the plugin
630
+ * @param {object} deck - The deck object
631
+ * @param {object} options - The options object
632
+ * @param {string} es5Filename - The name of the file that will be used
633
+ */
634
+ const Appear = function (deck, options, es5Filename) {
635
+ let names = vars.names;
636
+
637
+ // Set up names
638
+ names.baseclass = options.baseclass;
639
+ names.compatibilitybaseclass = options.compatibilitybaseclass;
640
+ names.fragmentSelector = ".fragment";
641
+ names.fragmentClass = "fragment";
642
+ names.speedClasses = ['slower', 'slow', 'fast', 'faster'];
643
+ names.speedClasses.push(...names.speedClasses.map(speed => `animate__${speed}`));
644
+ names.animatecss = '[class^="animate__"],[class*=" animate__"]';
645
+ names.es5Filename = es5Filename;
646
+ names.eventnames = ['ready', 'slidechanged', 'slidetransitionend', 'autoanimate', 'overviewhidden', 'scrolle'];
647
+
648
+ // Set up variables
649
+ vars.deck = deck;
650
+ vars.dom = deck.getRevealElement();
651
+ vars.viewport = deck.getViewportElement();
652
+ vars.slides = deck.getSlidesElement();
653
+ vars.sections = vars.slides.querySelectorAll('section');
654
+ vars.fragments = vars.slides.querySelectorAll(names.fragmentSelector);
655
+ vars.regularSections = Array.from(vars.sections).filter(section => !isStack(section));
656
+ if (/receiver/i.test(window.location.search)) vars.viewport.classList.add('sv');
657
+ names.eventnames.forEach(eventname => deck.on(eventname, event => {
658
+ showHideSlide(event, options, names, vars);
431
659
  }));
660
+ vars.viewport.addEventListener("animationend", event => {
661
+ event.target.classList.add('animationended');
662
+ });
663
+ vars.viewport.addEventListener("fragmenthidden", event => {
664
+ event.fragment.classList.remove('animationended');
665
+ event.fragment.querySelectorAll('.animationended').forEach(el => {
666
+ el.classList.remove('animationended');
667
+ });
668
+ });
669
+ return new Promise(resolve => {
670
+ prepare(options, vars, resolve);
671
+ debugLog(options, "---------- Done preloading ----------");
672
+ });
432
673
  };
433
674
 
675
+ /**
676
+ * Initialize the plugin
677
+ * @param {object} deck - The deck object
678
+ */
434
679
  const init = function (deck) {
435
- let es5Filename = "appearance.js";
436
680
  let defaultOptions = {
437
681
  baseclass: 'animate__animated',
438
682
  hideagain: true,
@@ -450,47 +694,9 @@ const Plugin = () => {
450
694
  compatibility: false,
451
695
  compatibilitybaseclass: 'animated'
452
696
  };
453
-
454
- const defaults = function (options, defaultOptions) {
455
- for (let i in defaultOptions) {
456
- if (!options.hasOwnProperty(i)) {
457
- options[i] = defaultOptions[i];
458
- }
459
- }
460
- };
461
-
462
- let options = deck.getConfig().appearance || {};
463
- defaults(options, defaultOptions);
464
-
465
- function pluginPath() {
466
- let path;
467
- let pluginScript = document.querySelector(`script[src$="${es5Filename}"]`);
468
-
469
- if (pluginScript) {
470
- path = pluginScript.getAttribute("src").slice(0, -1 * es5Filename.length);
471
- } else {
472
- path = import.meta.url.slice(0, import.meta.url.lastIndexOf('/') + 1);
473
- }
474
-
475
- return path;
476
- }
477
-
478
- let AppearanceStylePath = options.csspath.appearance ? options.csspath.appearance : `${pluginPath()}appearance.css` || 'plugin/appearance/appearance.css';
479
- let AnimateCSSPath = !options.compatibility ? options.animatecsspath.link : options.animatecsspath.compat;
480
-
481
- if (options.debug) {
482
- console.log(`Plugin path = ${pluginPath()}`);
483
- console.log(`Compatibility mode: ${options.compatibility}`);
484
- console.log(`Appearance CSS path = ${AppearanceStylePath}`);
485
- console.log(`AnimateCSS CSS path = ${AnimateCSSPath}`);
486
- }
487
-
488
- loadStyle(AnimateCSSPath, 'stylesheet', function () {
489
- loadStyle(AppearanceStylePath, 'stylesheet');
490
- });
491
- appear(deck, options);
697
+ options = mergeDeep(defaultOptions, deck.getConfig().appearance || {});
698
+ return Appear(deck, options, "appearance.js");
492
699
  };
493
-
494
700
  return {
495
701
  id: 'appearance',
496
702
  init: init