reveal.js-appearance 1.2.0 → 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,430 +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.0
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
- const assignAutoClass = (section, str, kind) => {
145
- let index = [...section.parentElement.children].filter(s => s.tagName == "SECTION").indexOf(section) + 1;
146
- 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}`;
147
- if (typeof str === "string") str = str.replace(/[“”]/g, '"').replace(/[‘’]/g, "'");
148
- 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, '"')}}`;
149
-
150
- if (!isJSON(strJSON)) {
151
- console.log(warning);
152
- } else {
153
- let elementsToAnimate = JSON.parse(strJSON);
154
-
155
- for (const [element, assignables] of Object.entries(elementsToAnimate)) {
156
- let elementsInSection = section.querySelectorAll(element);
157
- elementsInSection.forEach(elementInSection => {
158
- if (!elementInSection.classList.contains(baseclass) || elementInSection.dataset["autoappear"]) {
159
- elementInSection.dataset["autoappear"] = true;
160
- let newClasses = [],
161
- newDelay = null,
162
- speedClass = false;
163
-
164
- if (Array.isArray(assignables)) {
165
- newClasses = assignables[0].split(/[ ,]+/);
166
- newDelay = assignables[1];
167
- } else if (typeof assignables == "string") {
168
- newClasses = assignables.split(/[ ,]+/);
169
- }
170
-
171
- speedClasses.forEach(speed => {
172
- if (elementInSection.classList.contains(speed)) {
173
- speedClass = speed;
174
- }
175
- });
176
- let classesToRemove = [];
177
- elementInSection.classList.forEach(currentClass => {
178
- if (String(currentClass).includes("animate__")) {
179
- classesToRemove.push(currentClass);
180
- }
181
- });
182
- classesToRemove.forEach(currentClass => {
183
- elementInSection.classList.remove(currentClass);
184
- });
185
- newClasses.forEach(newClass => {
186
- if (speedClasses.includes(newClass)) {
187
- // There is a speed class from JSON to be assigned
188
- if (speedClass) {
189
- speedClass = newClass;
190
- }
191
- }
192
- });
193
- newClasses.forEach(newClass => {
194
- elementInSection.classList.add(newClass);
195
- });
196
-
197
- if (speedClass) {
198
- elementInSection.classList.add(speedClass);
199
- }
200
-
201
- if (newDelay) {
202
- elementInSection.dataset.delay = newDelay;
203
- }
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
+ };
204
212
 
205
- elementInSection.classList.add(baseclass);
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;
234
+ }
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(/[ ,]+/);
206
262
  }
207
- });
208
- }
209
- }
210
- };
211
-
212
- const findAppearancesIn = function (container, includeClass, excludeClass) {
213
- if (!isStack(container)) {
214
- let appearances = selectionArray(container, `:scope ${includeClass}`);
215
- appearances.forEach(appearance => {
216
- let convertListItem = appearance => {
217
- let from = appearance,
218
- to = appearance.parentNode;
219
- if (!to) return;
220
-
221
- for (let sibling of to.children) {
222
- if (sibling !== appearance) {
223
- if (sibling.dataset.appearParent) return;
263
+ if (assignables.speed) {
264
+ speedClass = String(assignables.speed);
265
+ if (!speedClass.includes("animate__")) {
266
+ speedClass = `animate__${speedClass}`;
224
267
  }
225
268
  }
226
-
227
- to.classList = from.classList;
228
- copyDataAttributes(from, to, "data-appear-parent");
229
- to.innerHTML = from.innerHTML;
230
- }; // Conversion of list items with Appearance classes to the parent, needs manual attribute
231
- // Relates to Quarto wrapping list content in a span.
232
-
233
-
234
- if (appearance.hasAttribute("data-appear-parent")) {
235
- convertListItem(appearance);
236
- } // Automatic conversion of list items which directly contain spans.
237
- // Relates to Quarto wrapping list content in a span.
238
-
239
-
240
- if (options.appearparents) {
241
- if (appearance.parentNode && appearance.parentNode.tagName) {
242
- if (appearance.tagName == "SPAN" && appearance.parentNode.tagName == "LI") {
243
- let spanLength = String(appearance.outerHTML).length;
244
- let liContentLength = String(appearance.parentNode.innerHTML).length;
245
-
246
- if (spanLength == liContentLength) {
247
- convertListItem(appearance);
248
- }
249
- }
269
+ if (assignables.delay) {
270
+ newDelay = String(assignables.delay);
250
271
  }
251
- }
252
- });
253
- appearances = selectionArray(container, `:scope ${includeClass}`);
254
- let excludes = selectionArray(container, `:scope ${excludeClass} ${includeClass}`);
255
- let delay = 0;
256
- appearances.filter(function (appearance, index) {
257
- if (!(excludes.indexOf(appearance) > -1)) {
258
- if (index == 0 && appearance.dataset.delay || index != 0) {
259
- let elementDelay = options.delay;
260
-
261
- if (appearance.dataset && appearance.dataset.delay) {
262
- elementDelay = parseInt(appearance.dataset.delay);
263
- }
264
-
265
- delay = delay + elementDelay; // Allow fragments to be Appearance items
266
-
267
- if (appearance.classList.contains("fragment")) {
268
- delay = 0;
269
-
270
- if (appearance.querySelectorAll(`.${baseclass}`)) {
271
- let firstNestedAppearance = appearance.querySelectorAll(`.${baseclass}`)[0];
272
-
273
- if (firstNestedAppearance) {
274
- let elementDelay = options.delay;
275
-
276
- if (firstNestedAppearance.dataset && firstNestedAppearance.dataset.delay) {
277
- elementDelay = parseInt(firstNestedAppearance.dataset.delay);
278
- }
279
-
280
- firstNestedAppearance.dataset.delay = elementDelay;
281
- }
282
- }
283
- }
284
-
285
- 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"]);
286
277
  }
287
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
+ }
288
292
  });
289
293
  }
290
- };
291
-
292
- const autoAdd = function () {
293
- regularSections.forEach(section => {
294
- if (section.hasAttribute("data-autoappear")) {
295
- let sectDataAppear = section.dataset.autoappear;
296
-
297
- if (sectDataAppear == "auto" || sectDataAppear == "" || sectDataAppear.length < 1 || sectDataAppear == "true") {
298
- // This section should get the global autoappear classes on its objects
299
- if (options.autoelements) {
300
- if (!options.autoelements) {
301
- return console.log(`Please add some elements in the option "autoelements"`);
302
- }
303
-
304
- assignAutoClass(section, options.autoelements, 'global');
305
- }
306
- } else if (sectDataAppear.length > 0) {
307
- // This section should get the local data-autoappear classes on its objects
308
- assignAutoClass(section, sectDataAppear, 'local'); //section.removeAttribute("data-autoappear");
309
- }
310
- } else {
311
- if (options.autoappear) {
312
- if (!options.autoelements) {
313
- return console.log(`Please add some elements in the option "autoelements"`);
314
- } // This section should get the global autoappear classes on its objects
294
+ });
295
+ }
296
+ };
315
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
+ };
316
315
 
317
- assignAutoClass(section, options.autoelements, 'global');
318
- }
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);
319
341
  }
320
- });
321
- };
322
-
323
- if (options.compatibility) {
324
- 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';
325
- baseclass = options.compatibilitybaseclass;
326
- }
327
-
328
- let allappearances = deck.getRevealElement().querySelectorAll(animatecss);
329
- allappearances.forEach(appearance => {
330
- if (!appearance.classList.contains(baseclass)) {
331
- appearance.classList.add(baseclass);
332
342
  }
333
- });
334
- autoAdd();
335
- sections.forEach(section => {
336
- findAppearancesIn(section, appearanceSelector, fragmentSelector);
337
- });
338
- fragments.forEach(fragment => {
339
- findAppearancesIn(fragment, appearanceSelector, fragmentSelector);
340
- });
343
+ }
344
+ }
345
+ };
341
346
 
342
- const fromTo = function (event) {
343
- let slides = {};
344
- slides.from = event.fromSlide ? event.fromSlide : event.previousSlide ? event.previousSlide : null;
345
- slides.to = event.toSlide ? event.toSlide : event.currentSlide ? event.currentSlide : null;
346
- return slides;
347
- };
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
+ };
348
366
 
349
- const showHideSlide = function (event) {
350
- 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
+ };
351
381
 
352
- let etype = event.type;
353
- let slides = fromTo(event);
354
- 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
+ };
355
423
 
356
- if (((_slides$to = slides.to) === null || _slides$to === void 0 ? void 0 : _slides$to.dataset.appearevent) == "auto") {
357
- 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";
358
440
  }
359
-
360
- if (options.appearevent == "auto") {
361
- options.appearevent = "autoanimate";
441
+ if (parent.dataset.delay && index !== 0) {
442
+ span.dataset.delay = parent.dataset.delay;
362
443
  }
363
-
364
- if (etype == "ready") {
365
- slides.to.dataset.appearanceCanStart = true;
444
+ if (parent.dataset.containerDelay && index === 0) {
445
+ span.dataset.delay = parent.dataset.containerDelay;
366
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
+ };
367
457
 
368
- if (slides.to) {
369
- let appearevent = slides.to.dataset.appearevent ? slides.to.dataset.appearevent : options.appearevent;
370
-
371
- if (etype == appearevent || etype == "slidetransitionend" && appearevent == "autoanimate") {
372
- slides.to.dataset.appearanceCanStart = true;
373
- }
374
-
375
- if (etype == "slidetransitionend") {
376
- if (options.hideagain) {
377
- if (slides.from) {
378
- if (slides.from.dataset.appearanceCanStart) {
379
- delete slides.from.dataset.appearanceCanStart;
380
- }
381
-
382
- 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
+ };
383
470
 
384
- if (fromFragments) {
385
- fromFragments.forEach(fragment => {
386
- fragment.classList.remove('visible');
387
- });
388
- }
389
- }
390
- }
391
- }
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
+ };
392
493
 
393
- if (event.type == 'slidechanged' && document.body.dataset.exitoverview) {
394
- if (options.hideagain) {
395
- 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
+ };
396
508
 
397
- (_slides$from = slides.from) === null || _slides$from === void 0 ? true : delete _slides$from.dataset.appearanceCanStart;
398
- }
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
+ };
399
531
 
400
- slides.to.dataset.appearanceCanStart = true;
401
- } else if (event.type == 'overviewhidden') {
402
- document.body.dataset.exitoverview = true;
403
- setTimeout(function () {
404
- document.body.removeAttribute('data-exitoverview');
405
- }, 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
+ }
406
550
 
407
- if (event.currentSlide) {
408
- if (options.hideagain) {
409
- 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);
410
555
 
411
- (_slides$from2 = slides.from) === null || _slides$from2 === void 0 ? true : delete _slides$from2.dataset.appearanceCanStart;
412
- }
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
+ };
413
580
 
414
- slides.to.dataset.appearanceCanStart = true;
415
- }
416
- }
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);
417
613
  }
418
- };
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
+ };
419
627
 
420
- const eventnames = ['ready', 'slidechanged', 'slidetransitionend', 'autoanimate', 'overviewhidden'];
421
- eventnames.forEach(eventname => deck.on(eventname, event => {
422
- 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);
423
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
+ });
424
673
  };
425
674
 
675
+ /**
676
+ * Initialize the plugin
677
+ * @param {object} deck - The deck object
678
+ */
426
679
  const init = function (deck) {
427
- let es5Filename = "appearance.js";
428
680
  let defaultOptions = {
429
681
  baseclass: 'animate__animated',
430
682
  hideagain: true,
@@ -442,47 +694,9 @@ const Plugin = () => {
442
694
  compatibility: false,
443
695
  compatibilitybaseclass: 'animated'
444
696
  };
445
-
446
- const defaults = function (options, defaultOptions) {
447
- for (let i in defaultOptions) {
448
- if (!options.hasOwnProperty(i)) {
449
- options[i] = defaultOptions[i];
450
- }
451
- }
452
- };
453
-
454
- let options = deck.getConfig().appearance || {};
455
- defaults(options, defaultOptions);
456
-
457
- function pluginPath() {
458
- let path;
459
- let pluginScript = document.querySelector(`script[src$="${es5Filename}"]`);
460
-
461
- if (pluginScript) {
462
- path = pluginScript.getAttribute("src").slice(0, -1 * es5Filename.length);
463
- } else {
464
- path = import.meta.url.slice(0, import.meta.url.lastIndexOf('/') + 1);
465
- }
466
-
467
- return path;
468
- }
469
-
470
- let AppearanceStylePath = options.csspath.appearance ? options.csspath.appearance : `${pluginPath()}appearance.css` || 'plugin/appearance/appearance.css';
471
- let AnimateCSSPath = !options.compatibility ? options.animatecsspath.link : options.animatecsspath.compat;
472
-
473
- if (options.debug) {
474
- console.log(`Plugin path = ${pluginPath()}`);
475
- console.log(`Compatibility mode: ${options.compatibility}`);
476
- console.log(`Appearance CSS path = ${AppearanceStylePath}`);
477
- console.log(`AnimateCSS CSS path = ${AnimateCSSPath}`);
478
- }
479
-
480
- loadStyle(AnimateCSSPath, 'stylesheet', function () {
481
- loadStyle(AppearanceStylePath, 'stylesheet');
482
- });
483
- appear(deck, options);
697
+ options = mergeDeep(defaultOptions, deck.getConfig().appearance || {});
698
+ return Appear(deck, options, "appearance.js");
484
699
  };
485
-
486
700
  return {
487
701
  id: 'appearance',
488
702
  init: init