diff --git a/docs/adr/0009-migrate-patterns-to-basepattern.md b/docs/adr/0009-migrate-patterns-to-basepattern.md new file mode 100644 index 000000000..f35e7ee1e --- /dev/null +++ b/docs/adr/0009-migrate-patterns-to-basepattern.md @@ -0,0 +1,65 @@ +# 0009 Migrate patterns to BasePattern + +Status: Accepted (2026-11-29) + +## Context + +Most patterns were still based on the legacy `Base.extend` or were plain +objects with an `init($el)` function. Only part of them used the class based +`BasePattern`, which provides per-element instances, options parsing via a +static parser, instance scoped event listeners and automatic destroy when the +element is removed from the document (ADR 0001, 0004). + +Legacy patterns never cleaned up: listeners on `document`/`window`, +observers, timers and third party instances (Pikaday, Select2, Slick, +Masonry, ...) stayed alive after their element was removed. + +A class based implementation is also a precondition for loading pattern +implementations lazily, because a placeholder can then instantiate the real +class after loading it. + +## Decision + +Migrate all patterns of Patternslib and of the add-ons pat-shopping-cart, +pat-upload, pat-doclock and pat-tinymce to `BasePattern`, one commit per +pattern, following the pat-equaliser migration (3b43307e0): + +- Options come from the static parser. +- Global listeners are instance scoped, third party instances, observers and + timers are cleaned up in `destroy()`. +- `destroy()` does not undo DOM changes (deferred). +- jQuery listeners are kept where events are triggered via jQuery + (`patterns-injected`, `pat-update`, ...), because native listeners don't + receive them. They use a per-instance namespace and are removed on destroy. +- The HTML API stays the same. The JavaScript API changes: the default export + is the class, the jQuery plugins and static `init` methods are gone. In + Patternslib the commits are marked `tech`, because the pattern integration + contract for designers is unchanged; the JavaScript API change is described + in each commit message. In the add-ons they are marked `breaking`. + +Not migrated: + +- **pat-inject**: it is a shared service as well as a pattern (`execute`, + `submitSubform`, `registerTypeHandler`, `init` are called by other + patterns), has module level side effects which must run on page load + (history handling, the `patterns-injected` rescan listener) and relies on a + timing contract with pat-validation. +- **pat-ajax**: the transport service of pat-inject and pat-subform. +- **pat-focus, pat-legend**: transform-only patterns without per-element + instances. +- **pat-grid**: CSS only. + +## Consequences + +- Patterns are destroyed when their element is removed and stop reacting to + global events. Several leaks and long standing bugs found during the + migration are fixed, as separate `fix` commits where they were separable. +- All patterns initialize asynchronously, one tick later than legacy + patterns did. JavaScript code must wait with + `events.await_pattern_init(instance)`. +- JavaScript users of the legacy APIs need to migrate to `new Pattern(el)` + and instance methods. pat-modal: closing is now `close()`, `destroy()` only + cleans up. +- The add-ons depend on @patternslib/patternslib 9.11.1, whose `BasePattern` + has neither instance scoped listeners nor automatic destroy. They use + `core/events` directly and benefit from automatic destroy once they update. diff --git a/docs/adr/0010-lazily-loaded-pattern-implementations.md b/docs/adr/0010-lazily-loaded-pattern-implementations.md new file mode 100644 index 000000000..be128ba1a --- /dev/null +++ b/docs/adr/0010-lazily-loaded-pattern-implementations.md @@ -0,0 +1,108 @@ +# 0010 Lazily loaded pattern implementations + +Status: Accepted (2026-11-29) + +## Context + +All patterns imported in `src/patterns.js` end up in one eagerly loaded +patterns chunk, which every page loads. Before this change it was about +201 KB minified, of which about 148 KB was pattern code and about 10 KB were +lookup maps of dynamic import contexts (ADR 0007). Heavy third party +libraries were already imported dynamically, but the pattern code itself +was not, even on pages which don't use the pattern. + +Mockup already splits patterns into a thin registration module and a lazily +imported `--implementation` module. The convention started there with the +controlpanel patterns (Mockup commit fe0380c46, 2021-11-25) and is used for +several patterns since (e.g. Mockup's `pat/modal/modal.js`). Mockup's +patterns are `Base` patterns though, while the patterns split here are class +based (ADR 0009). See "Alternatives considered". + +Other code instantiates patterns from the registry directly, e.g. +`new registry.patterns.markdown(el)` in pat-tooltip or +`await new registry.patterns[name](el)` in Mockup. Registry code of other +Module Federation bundles also instantiates registry entries with `new`. + +## Decision + +- `core/lazy-pattern.js` provides `create_lazy_pattern({name, trigger, + order, load})`. It returns a small placeholder class which is registered + instead of the real class. Instantiating it loads the implementation and + returns a Promise of the real pattern instance. A class constructor may + return an object, so the registry and other code using `new` keep working + unchanged. Once loaded, the registry entry is replaced by the real class. +- `events.await_pattern_init` also accepts such a Promise, so + `await events.await_pattern_init(new Pattern(el))` keeps working. +- A split pattern `pat/NAME/NAME.js` only contains the registration and + module level code which must run on page load. The class lives in + `pat/NAME/NAME--implementation.js`, which still registers itself, so + importing it directly gives an eagerly registered pattern. Code which needs + the class or the parser imports the `--implementation` module. +- Split are patterns where it makes a difference (roughly 2 KB minified or + more, including dynamic import lookup maps): calendar, navigation, + scroll-marker, auto-suggest, date-picker, datetime-picker, display-time, + sortable, modal, notification, bumper, image-crop, clone, masonry, + gallery, carousel, auto-submit, markdown and syntax-highlight. +- Kept eager, because lazy loading would break them or change what users + see: + - pat-inject and pat-ajax: shared services, used by many patterns and on + almost every page anyway (ADR 0009). + - pat-validation: must register its submit handlers before pat-inject. + - pat-tooltip: imported as class and parser by Mockup and pat-tiptap. + - pat-depends, pat-collapsible, pat-stacks, pat-toggle: they hide or show + content on initialization. Loading them later would flash content in the + wrong state. + - pat-bind: renders bound values on initialization. + - pat-tabs, pat-auto-scale, pat-equaliser: they adjust the layout on + initialization. + - Transform-only patterns (pat-legend, pat-focus) and small patterns, for + which the registration module would eat most of the gain. + +## Alternatives considered + +- **Grafting the implementation's prototype onto the registration pattern** + (Mockup's current approach, e.g. `pat/modal/modal.js`): the registration + module is a `Base` pattern whose `init()` imports the implementation and + copies its prototype onto the running instance with `$.extend`. This + relies on `Base` specifics and does not work for `BasePattern` classes: + class methods are not enumerable and are not copied, class fields are + created by the implementation's constructor which never runs, private + fields throw when accessed on an object not constructed by their class, + and `BasePattern` parses the options with the implementation's static + parser before `init()` runs. +- **Wrapping a separate implementation instance** (Mockup's pat-tinymce + since 2022): the registration pattern creates an implementation object in + its `init()` and keeps it as `this.instance`. With a `BasePattern` class + as implementation, there are two pattern instances per element. The + registration pattern has already stored itself as `el["pattern-NAME"]`, so + the real pattern refuses to initialize as already initialized. Destroying, + lifecycle tracking and init events would have to be forwarded between the + two instances. +- **A placeholder which constructs the real pattern** (chosen): the real + class is instantiated with its own constructor, so fields, private fields, + the static parser, the initialization order and the re-initialization + guard work unchanged, and the implementation modules are ordinary + `BasePattern` classes. The logic lives in one helper, so each registration + module is a few lines of configuration. + +## Consequences + +- The eagerly loaded patterns chunk went from 206.9 KB to 129.1 KB minified + (60.7 KB to 38.8 KB gzipped), measured with production builds before and + after splitting. The split pattern implementations and their dynamic + import lookup maps are no longer part of it. The entry points grow by about + 0.5 KB for the additional chunk map entries. +- Instantiating a registration module's class with `new` returns a Promise + of the pattern instance, not the instance. Code which uses the result + directly has to `await new Pattern(el)`. + `events.await_pattern_init(new Pattern(el))` accepts the Promise. Code + which only registers patterns or lets the registry instantiate them is not + affected. +- A split pattern initializes after its implementation chunk is loaded, + i.e. one network round trip later on first use. Patterns which already + load a library dynamically now load two chunks in sequence. +- Breaking change for JavaScript users of split patterns: the default export + of `NAME.js` is the placeholder class and `parser` is no longer exported + there. Import `NAME--implementation.js` instead. +- Bundles importing `NAME.js` for registration (e.g. Mockup's + `patterns.js`) get the lazy loading without changes. diff --git a/src/core/events.js b/src/core/events.js index 309d0b2eb..40b1e5f86 100644 --- a/src/core/events.js +++ b/src/core/events.js @@ -281,12 +281,26 @@ const await_event = (el, event_name) => { * Usage: * await events.await_pattern_init(PATTERN); * - * @param {Pattern instance} pattern - The pattern instance. + * @param {Pattern instance} pattern - The pattern instance, or a Promise of + * it as returned when instantiating a lazily loaded pattern. * * @returns {Promise} - Returns a Promise which can be used for ``await`` and which will be resolved when the event is throwm. * */ const await_pattern_init = (pattern) => { + if (typeof pattern?.then === "function") { + // Lazily loaded patterns (see core/lazy-pattern.js) return a Promise + // of the pattern instance when instantiated. The instance is created + // synchronously when the Promise resolves while BasePattern + // initializes in a later tick, so the listeners below are still + // registered in time. + return pattern.then((instance) => { + if (!instance) { + throw new Error("The pattern could not be loaded."); + } + return await_pattern_init(instance); + }); + } // See: https://stackoverflow.com/a/44746691/1337474 return new Promise((resolve, reject) => { // Case initialized diff --git a/src/core/lazy-pattern.js b/src/core/lazy-pattern.js new file mode 100644 index 000000000..b0d747df1 --- /dev/null +++ b/src/core/lazy-pattern.js @@ -0,0 +1,83 @@ +/** + * Lazily loaded patterns. + * + * Create a lightweight placeholder pattern class, which is registered in the + * patterns registry instead of the real pattern class. The real pattern + * implementation is only loaded when the pattern is used for the first time. + * This keeps the pattern implementation out of the eagerly loaded bundle. + * + * Usage - in ``example.js``: + * + * import registry from "../../core/registry"; + * import create_lazy_pattern from "../../core/lazy-pattern"; + * + * const Pattern = create_lazy_pattern({ + * name: "example", + * trigger: ".pat-example", + * load: () => import("./example--implementation"), + * }); + * registry.register(Pattern); + * export default Pattern; + * + * The implementation module ``example--implementation.js`` contains the + * BasePattern based class as its default export. + * + * Instantiating the placeholder class returns a Promise, which resolves to the + * instance of the real pattern class. So the registry and code doing + * ``await new registry.patterns.example(el)`` keep working. + * + * After the implementation was loaded, the registry entry is replaced with + * the real pattern class. + */ +import logging from "./logging"; +import registry from "./registry"; + +const log = logging.getLogger("lazy-pattern"); + +export function create_lazy_pattern({ name, trigger, order, load }) { + let loading = null; + + class LazyPattern { + static name = name; + static trigger = trigger; + static order = order; + static lazy = true; + + static async load() { + if (!loading) { + loading = load() + .then((module) => { + const Pattern = module.default; + if (registry.patterns[name] === LazyPattern) { + // Swap the placeholder for the real pattern, so + // that further instantiations are done directly. + registry.patterns[name] = Pattern; + } + return Pattern; + }) + .catch((error) => { + // Allow to retry loading. + loading = null; + throw error; + }); + } + return await loading; + } + + constructor(el, options, trigger) { + // Return a Promise instead of the instance. This is allowed for + // classes which do not extend another class. + return LazyPattern.load().then( + (Pattern) => new Pattern(el, options, trigger), + (error) => { + log.error(`Could not load the pattern ${name}.`, error); + return null; + }, + ); + } + } + + return LazyPattern; +} + +export default create_lazy_pattern; diff --git a/src/core/lazy-pattern.test.js b/src/core/lazy-pattern.test.js new file mode 100644 index 000000000..bafdbcd13 --- /dev/null +++ b/src/core/lazy-pattern.test.js @@ -0,0 +1,121 @@ +import { BasePattern } from "./basepattern"; +import create_lazy_pattern from "./lazy-pattern"; +import events from "./events"; +import registry from "./registry"; + +class RealPattern extends BasePattern { + static name = "lazy-example"; + static trigger = ".pat-lazy-example"; + + init() { + this.el.textContent = "initialized"; + } +} + +describe("core.lazy-pattern", function () { + let load; + let LazyPattern; + + beforeEach(function () { + registry.clear(); + load = jest.fn(async () => ({ default: RealPattern })); + LazyPattern = create_lazy_pattern({ + name: "lazy-example", + trigger: ".pat-lazy-example", + order: 500, + load: load, + }); + }); + + afterEach(function () { + registry.clear(); + document.body.innerHTML = ""; + }); + + it("1 - provides the registry metadata.", function () { + expect(LazyPattern.name).toBe("lazy-example"); + expect(LazyPattern.trigger).toBe(".pat-lazy-example"); + expect(LazyPattern.order).toBe(500); + expect(LazyPattern.lazy).toBe(true); + }); + + it("2 - does not load the implementation before it is needed.", function () { + registry.register(LazyPattern); + registry.scan(document.body); + expect(load).not.toHaveBeenCalled(); + }); + + it("3 - resolves to an instance of the real pattern.", async function () { + document.body.innerHTML = `
`; + const el = document.querySelector(".pat-lazy-example"); + + const instance = await new LazyPattern(el); + await events.await_pattern_init(instance); + + expect(instance).toBeInstanceOf(RealPattern); + expect(el["pattern-lazy-example"]).toBe(instance); + expect(el.textContent).toBe("initialized"); + }); + + it("4 - initializes the real pattern when scanned by the registry.", async function () { + document.body.innerHTML = ` +
+
+ `; + registry.register(LazyPattern); + registry.scan(document.body); + + await LazyPattern.load(); + await events.await_event(document.querySelector("#one"), "init.lazy-example.patterns"); + + expect(load).toHaveBeenCalledTimes(1); + expect(document.querySelector("#one").textContent).toBe("initialized"); + expect(document.querySelector("#two").textContent).toBe("initialized"); + }); + + it("5 - replaces itself in the registry with the real pattern.", async function () { + registry.register(LazyPattern); + expect(registry.patterns["lazy-example"]).toBe(LazyPattern); + + await LazyPattern.load(); + expect(registry.patterns["lazy-example"]).toBe(RealPattern); + }); + + it("6 - does not replace another pattern registered under the same name.", async function () { + registry.register(RealPattern); + await LazyPattern.load(); + expect(registry.patterns["lazy-example"]).toBe(RealPattern); + }); + + it("7 - can be awaited with events.await_pattern_init.", async function () { + const el = document.createElement("div"); + document.body.appendChild(el); + + await events.await_pattern_init(new LazyPattern(el)); + + expect(el["pattern-lazy-example"]).toBeInstanceOf(RealPattern); + expect(el.textContent).toBe("initialized"); + }); + + it("8 - events.await_pattern_init rejects if loading failed.", async function () { + load.mockImplementationOnce(async () => { + throw new Error("Network error"); + }); + const el = document.createElement("div"); + + await expect(events.await_pattern_init(new LazyPattern(el))).rejects.toThrow( + "The pattern could not be loaded." + ); + }); + + it("9 - resolves to null and allows to retry when loading fails.", async function () { + load.mockImplementationOnce(async () => { + throw new Error("Network error"); + }); + const el = document.createElement("div"); + + expect(await new LazyPattern(el)).toBe(null); + expect(await new LazyPattern(el)).toBeInstanceOf(RealPattern); + expect(load).toHaveBeenCalledTimes(2); + }); +}); diff --git a/src/pat/auto-scale/auto-scale.js b/src/pat/auto-scale/auto-scale.js index 773470878..d9bcae8bd 100644 --- a/src/pat/auto-scale/auto-scale.js +++ b/src/pat/auto-scale/auto-scale.js @@ -6,8 +6,9 @@ */ import $ from "jquery"; -import Base from "../../core/base"; +import { BasePattern } from "../../core/basepattern"; import Parser from "../../core/parser"; +import registry from "../../core/registry"; import utils from "../../core/utils"; export const parser = new Parser("auto-scale"); @@ -18,32 +19,52 @@ parser.addArgument("max-width", 1000000); parser.addArgument("min-height", 0); parser.addArgument("max-height", 1000000); -export default Base.extend({ - name: "autoscale", - trigger: ".pat-auto-scale", - force_method: null, +class Pattern extends BasePattern { + static name = "autoscale"; + static trigger = ".pat-auto-scale"; + static parser = parser; - init: function ($el, opts) { - this.options = parser.parse(this.$el, opts); + force_method = null; + + init() { + this.$el = $(this.el); + this._setup(); if (this.force_method !== null) { this.options.method = this.force_method; } - this._setup().scale(); - return this.$el; - }, + this.scale(); + } + + get event_namespace() { + return `pat-autoscale--${this.uuid}`; + } - _setup: function () { + _setup() { if (!utils.checkCSSFeature("zoom")) { // See https://bugzilla.mozilla.org/show_bug.cgi?id=390936 this.force_method = "scale"; } - var scaler = utils.debounce(this.scale.bind(this), 250); - $(window).on("resize.autoscale", scaler); - $(document).on("pat-update.autoscale", scaler); + const scaler = utils.debounce(() => { + if (!this.destroyed) { + this.scale(); + } + }, 250); + this.add_event_listener(window, "resize", "scale-on-resize", scaler); + // ``pat-update`` is also triggered via jQuery, so we need to listen + // via jQuery. + $(document).on(`pat-update.${this.event_namespace}`, scaler); return this; - }, + } - scale: function () { + destroy() { + if (this.destroyed) { + return; + } + $(document).off(`.${this.event_namespace}`); + super.destroy(); + } + + scale() { var available_space, scale, scaled_height, scaled_width, container; if (this.$el[0].tagName === "BODY") { @@ -70,11 +91,11 @@ export default Base.extend({ available_space.width = Math.max(available_space.width, this.options.min.width); available_space.height = Math.min( available_space.height, - this.options.max.height + this.options.max.height, ); available_space.height = Math.max( available_space.height, - this.options.min.height + this.options.min.height, ); switch (this.options.size) { case "width": @@ -87,14 +108,14 @@ export default Base.extend({ // Fit entire content on area, allowing for extra space scale = Math.min( available_space.width / this.$el.outerWidth(), - available_space.height / this.$el.outerHeight() + available_space.height / this.$el.outerHeight(), ); break; case "cover": // Covert entire area, possible clipping scale = Math.max( available_space.width / this.$el.outerWidth(), - available_space.height / this.$el.outerHeight() + available_space.height / this.$el.outerHeight(), ); break; default: @@ -112,7 +133,7 @@ export default Base.extend({ (this.$el.parent().attr("class") != undefined && $.inArray( "auto-scale-wrapper", - this.$el.parent().attr("class").split(/\s+/) + this.$el.parent().attr("class").split(/\s+/), ) === -1) ) { this.$el.wrap("
"); @@ -125,5 +146,9 @@ export default Base.extend({ } this.$el.addClass("scaled"); return this; - }, -}); + } +} + +registry.register(Pattern); +export default Pattern; +export { Pattern }; diff --git a/src/pat/auto-scale/auto-scale.test.js b/src/pat/auto-scale/auto-scale.test.js new file mode 100644 index 000000000..9e4307cc9 --- /dev/null +++ b/src/pat/auto-scale/auto-scale.test.js @@ -0,0 +1,133 @@ +import $ from "jquery"; +import Pattern from "./auto-scale"; +import events from "../../core/events"; +import utils from "../../core/utils"; +import { jest } from "@jest/globals"; + +describe("pat-auto-scale", function () { + beforeEach(function () { + // jsdom has no layout. Mock the element size. + jest.spyOn($.fn, "outerWidth").mockReturnValue(100); + jest.spyOn($.fn, "outerHeight").mockReturnValue(50); + }); + + afterEach(function () { + document.body.innerHTML = ""; + jest.restoreAllMocks(); + }); + + it("Scales the element to the width of the container.", async function () { + document.body.innerHTML = ` +
+
+
+ `; + const el = document.querySelector(".pat-auto-scale"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + expect(el["pattern-autoscale"]).toBe(instance); + expect(el.style.transform).toBe("scale(2)"); + expect(el.classList.contains("scaled")).toBe(true); + const wrapper = el.parentElement; + expect(wrapper.classList.contains("auto-scale-wrapper")).toBe(true); + expect(wrapper.style.width).toBe("200px"); + expect(wrapper.style.height).toBe("100px"); + }); + + it("Respects the size and max-width options.", async function () { + document.body.innerHTML = ` +
+
+
+ `; + const el = document.querySelector(".pat-auto-scale"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + // available height 400 limited to 100, element height 50. + expect(el.style.transform).toBe("scale(2)"); + }); + + it("Forces the scale method if zoom is not supported.", async function () { + jest.spyOn(utils, "checkCSSFeature").mockReturnValue(false); + document.body.innerHTML = ` +
+
+
+ `; + const el = document.querySelector(".pat-auto-scale"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + expect(instance.options.method).toBe("scale"); + expect(el.style.transform).toBe("scale(2)"); + }); + + it("Uses the zoom method if supported.", async function () { + jest.spyOn(utils, "checkCSSFeature").mockReturnValue(true); + document.body.innerHTML = ` +
+
+
+ `; + const el = document.querySelector(".pat-auto-scale"); + const spy_css = jest.spyOn($.fn, "css"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + expect(instance.options.method).toBe("zoom"); + expect(spy_css).toHaveBeenCalledWith("zoom", 2); + expect(el.parentElement.classList.contains("auto-scale-wrapper")).toBe(false); + }); + + it("Rescales on window resize and pat-update events.", async function () { + document.body.innerHTML = ` +
+
+
+ `; + const el = document.querySelector(".pat-auto-scale"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + const spy_scale = jest.spyOn(instance, "scale"); + + window.dispatchEvent(new Event("resize")); + await utils.timeout(260); // debounce + expect(spy_scale).toHaveBeenCalledTimes(1); + + $(document.body).trigger("pat-update"); + await utils.timeout(260); // debounce + expect(spy_scale).toHaveBeenCalledTimes(2); + + document.body.dispatchEvent(events.update_event({})); + await utils.timeout(260); // debounce + expect(spy_scale).toHaveBeenCalledTimes(3); + }); + + it("Does not rescale anymore after destroy.", async function () { + document.body.innerHTML = ` +
+
+
+ `; + const el = document.querySelector(".pat-auto-scale"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + const spy_scale = jest.spyOn(instance, "scale"); + + // Trigger a debounced rescale before destroying. + window.dispatchEvent(new Event("resize")); + + document.querySelector(".container").remove(); + await utils.timeout(1); // wait for the automatic destroy. + expect(instance.destroyed).toBe(true); + expect(el["pattern-autoscale"]).toBeUndefined(); + + window.dispatchEvent(new Event("resize")); + $(document).trigger("pat-update"); + await utils.timeout(260); // debounce + expect(spy_scale).not.toHaveBeenCalled(); + }); +}); diff --git a/src/pat/auto-submit/auto-submit--implementation.js b/src/pat/auto-submit/auto-submit--implementation.js new file mode 100644 index 000000000..8ce995920 --- /dev/null +++ b/src/pat/auto-submit/auto-submit--implementation.js @@ -0,0 +1,153 @@ +import "../../core/jquery-ext"; +import $ from "jquery"; +import { BasePattern } from "../../core/basepattern"; +import dom from "../../core/dom"; +import events from "../../core/events"; +import input_change_events from "../../lib/input-change-events"; +import logging from "../../core/logging"; +import Parser from "../../core/parser"; +import registry from "../../core/registry"; +import utils from "../../core/utils"; + +const log = logging.getLogger("autosubmit"); + +export const parser = new Parser("autosubmit"); +// - 400ms -> 400 +// - 400 -> 400 +// - defocus +parser.addArgument("delay", "400ms"); + +class Pattern extends BasePattern { + static name = "autosubmit"; + static trigger = ".pat-autosubmit, .pat-auto-submit"; + static parser = parser; + + // Timer of the debounced input-change handler. + debounce_timer = { timer: null }; + + init() { + this.$el = $(this.el); + if (this.options.delay !== "defocus") { + this.options.delay = parseInt(this.options.delay.replace(/[^\d]*/g, ""), 10); + } + + input_change_events.setup(this.$el, "autosubmit"); + this.registerListeners(); + this.registerTriggers(); + } + + destroy() { + if (this.destroyed) { + return; + } + clearTimeout(this.debounce_timer.timer); + if (this.$el) { + // Only clean up, if the pattern was initialized. + input_change_events.remove(this.$el, "autosubmit"); + this.$el.off(".pat-autosubmit"); + } + super.destroy(); + } + + registerListeners() { + this.add_event_listener( + this.el, + "input-change-delayed", + "input-change-delayed", + (e) => this.onInputChange(e) + ); + this.registerSubformListeners(); + this.$el.on("patterns-injected.pat-autosubmit", (e, cfg, el, injected) => + this.refreshListeners(e, cfg, el, injected) + ); + this.$el.on("pat-update.pat-autosubmit", (e, data) => { + // Refresh on some pat-update events. + if ( + (data?.pattern === "clone" && data?.action === "removed") || + data?.pattern === "sortable" + ) { + // Directly submit when removing a clone or changing the sorting. + dom.find_form(this.el).dispatchEvent(events.submit_event()); + log.debug( + `triggered by pat-update, pattern: ${data.pattern}, action: ${data.action}` + ); + } else if (data?.pattern === "clone") { + // Refresh listeners on cloning. + this.refreshListeners(e, null, null, data.dom); + } + }); + } + + registerSubformListeners() { + /* If there are subforms, we need to listen on them as well, so + * that only the subform gets submitted if an element inside it + * changes. + */ + + // get all subforms whice are not yet auto submit forms. + const subforms = this.el.querySelectorAll( + ".pat-subform:not(.pat-autosubmit):not(.pat-auto-submit)" + ); + for (const subform of subforms) { + // register autosubmit on subform + this.add_event_listener( + subform, + "input-change-delayed", + "input-change-delayed--subform", + (e) => this.onInputChange(e) + ); + } + } + + refreshListeners(ev, cfg, el, injected) { + this.registerSubformListeners(); + // Register change event handlers for new inputs injected into this form + input_change_events.setup($(injected), "autosubmit"); + } + + registerTriggers() { + const isText = this.$el.is("input:text, input[type=search], textarea"); + if (this.options.delay === "defocus" && !isText) { + log.error( + "The defocus delay value makes only sense on text input elements." + ); + return; + } + + const trigger_event = (ev) => { + if (ev.target.closest(this.trigger) !== this.el) { + // Let a nested auto-submit element handle the event. + return; + } + ev.target.dispatchEvent(events.generic_event("input-change-delayed")); + }; + if (this.options.delay === "defocus") { + this.$el.on("input-defocus.pat-autosubmit", trigger_event); + } else if (this.options.delay > 0) { + this.$el.on( + "input-change.pat-autosubmit", + utils.debounce(trigger_event, this.options.delay, this.debounce_timer) + ); + } else { + this.$el.on("input-change.pat-autosubmit", trigger_event); + } + } + + onInputChange(e) { + // Stop the event here, so that it is not handled by a parent + // auto-submit element or by a second listener on the same subform. + e.stopImmediatePropagation(); + dom.find_form(e.target).dispatchEvent( + events.submit_event({ submitter: e.target }) + ); + log.debug( + `submit event triggered by event ${e.type} by submitter (1) on (2)`, + e.target, + this.el + ); + } +} + +registry.register(Pattern); +export default Pattern; +export { Pattern }; diff --git a/src/pat/auto-submit/auto-submit--implementation.test.js b/src/pat/auto-submit/auto-submit--implementation.test.js new file mode 100644 index 000000000..6779b8aad --- /dev/null +++ b/src/pat/auto-submit/auto-submit--implementation.test.js @@ -0,0 +1,416 @@ +import $ from "jquery"; +import Pattern from "./auto-submit--implementation"; +import events from "../../core/events"; +import registry from "../../core/registry"; +import utils from "../../core/utils"; +import { jest } from "@jest/globals"; + +describe("pat-autosubmit", function () { + afterEach(function () { + document.body.innerHTML = ""; + }); + + describe("1 - Triggering of the pattern", function () { + it("1.1 - happens when a form has the pat-autosubmit class", async function () { + document.body.innerHTML = ` +
+
+ + +
+
+ `; + const spy_init = jest.spyOn(Pattern.prototype, "init"); + registry.scan(document.body); + await utils.timeout(1); + expect(spy_init).toHaveBeenCalled(); + }); + + it("1.2 - when a grouping of inputs has the pat-autosubmit class", async function () { + document.body.innerHTML = ` +
+
+ + +
+
+ `; + const spy_init = jest.spyOn(Pattern.prototype, "init"); + registry.scan(document.body); + await utils.timeout(1); + expect(spy_init).toHaveBeenCalled(); + }); + + it("1.3 - when a single input has the pat-autosubmit class", async function () { + document.body.innerHTML = ` +
+ +
+ `; + const spy_init = jest.spyOn(Pattern.prototype, "init"); + registry.scan(document.body); + await utils.timeout(1); + expect(spy_init).toHaveBeenCalled(); + }); + + it("1.4 - calls refreshListeners when pat-clone adds an element", async function () { + document.body.innerHTML = ` +
+
+ `; + const el = document.querySelector(".pat-autosubmit"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + const spy = jest.spyOn(instance, "refreshListeners"); + $(el).trigger("pat-update", { pattern: "clone" }); + expect(spy).toHaveBeenCalled(); + }); + }); + + describe("2 - Trigger a submit", function () { + it("2.1 - when a change on a single input happens", async function () { + document.body.innerHTML = ` +
+ +
+ `; + const input = document.querySelector(".pat-autosubmit"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + let submit_form_dispatched = false; + document.querySelector("form").addEventListener("submit", () => { + submit_form_dispatched = true; + }); + input.dispatchEvent(events.input_event()); + await utils.timeout(1); + expect(submit_form_dispatched).toBe(true); + }); + + it("2.2 - when pat-clone'd input is changed", async function () { + const pattern_clone = (await import("../clone/clone--implementation")).default; + document.body.innerHTML = ` +
+ +
+ + `; + const el = document.querySelector(".pat-autosubmit"); + const el_clone = document.querySelector(".pat-clone"); + const button_clone = document.querySelector(".add-clone"); + + let submit_dispatched = false; + el.addEventListener("submit", () => { + submit_dispatched = true; + }); + + const instance = new Pattern(el); + await events.await_pattern_init(instance); + new pattern_clone(el_clone); + await utils.timeout(1); + + button_clone.click(); + + document.querySelector("form input").dispatchEvent(events.input_event()); + + await utils.timeout(1); + expect(submit_dispatched).toBe(true); + }); + + it("2.3 - when pat-clone removes an element", async function () { + document.body.innerHTML = ` +
+
+ `; + const el = document.querySelector(".pat-autosubmit"); + + let submit_dispatched = false; + el.addEventListener("submit", () => { + submit_dispatched = true; + }); + + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + $(el).trigger("pat-update", { pattern: "clone", action: "removed" }); + + expect(submit_dispatched).toBe(true); + }); + + it("2.4 - when pat-sortable changes the sorting", async function () { + document.body.innerHTML = ` +
+
+ `; + const el = document.querySelector(".pat-autosubmit"); + + let submit_dispatched = false; + el.addEventListener("submit", () => { + submit_dispatched = true; + }); + + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + $(el).trigger("pat-update", { pattern: "sortable" }); + + expect(submit_dispatched).toBe(true); + }); + + it("2.5 - when a change on a single input happens with delay option", async function () { + document.body.innerHTML = ` +
+ +
+ `; + const input = document.querySelector(".pat-autosubmit"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + let submit_form_dispatched = false; + document.querySelector("form").addEventListener("submit", () => { + submit_form_dispatched = true; + }); + input.dispatchEvent(events.input_event()); + await utils.timeout(1); + expect(submit_form_dispatched).toBe(false); + await utils.timeout(9); + expect(submit_form_dispatched).toBe(false); + await utils.timeout(10); + expect(submit_form_dispatched).toBe(true); + }); + + it("2.6 - when pat-autosubmit is defined not on a form element", async function () { + document.body.innerHTML = ` +
+
+ +
+
+ `; + const input = document.querySelector("input"); + const autosubmit = document.querySelector(".pat-autosubmit"); + const instance = new Pattern(autosubmit); + await events.await_pattern_init(instance); + + let submit_form_dispatched = false; + document.querySelector("form").addEventListener("submit", () => { + submit_form_dispatched = true; + }); + + input.dispatchEvent(events.input_event()); + await utils.timeout(1); + expect(submit_form_dispatched).toBe(true); + }); + + it("2.7 - directly on a pat-subform", async function () { + document.body.innerHTML = ` +
+
+ +
+
+ `; + const input = document.querySelector("input"); + const subform = document.querySelector(".pat-subform"); + const autosubmit = document.querySelector(".pat-autosubmit"); + const instance = new Pattern(autosubmit); + await events.await_pattern_init(instance); + + // The submit event should be invoked on the subform. + let submit_subform_dispatched = false; + subform.addEventListener("submit", () => { + submit_subform_dispatched = true; + }); + + // The submit event should also bubble up to the form. + let submit_form_dispatched = false; + document.querySelector("form").addEventListener("submit", () => { + submit_form_dispatched = true; + }); + + input.dispatchEvent(events.input_event()); + await utils.timeout(1); + expect(submit_subform_dispatched).toBe(true); + expect(submit_form_dispatched).toBe(true); + }); + }); + + describe("3 - Parsing of the delay option", function () { + const parse_delay = async (value) => { + const el = document.createElement("input"); + el.setAttribute("data-pat-autosubmit", value); + document.body.append(el); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + return instance.options.delay; + }; + + it("3.1 - can be done in shorthand notation", async function () { + expect(await parse_delay("500ms")).toBe(500); + expect(await parse_delay("500")).toBe(500); + expect(await parse_delay("defocus")).toBe("defocus"); + }); + + it("3.2 - can be done in longhand notation", async function () { + expect(await parse_delay("delay: 500ms")).toBe(500); + expect(await parse_delay("delay: 500")).toBe(500); + expect(await parse_delay("delay: defocus")).toBe("defocus"); + }); + }); + + describe("4 - The .pat-auto-submit trigger", function () { + it("4.1 - triggers a submit", async function () { + document.body.innerHTML = ` +
+
+ +
+
+ `; + const input = document.querySelector("input"); + const pattern_el = document.querySelector(".pat-auto-submit"); + const instance = new Pattern(pattern_el); + await events.await_pattern_init(instance); + + let submit_form_dispatched = false; + document.querySelector("form").addEventListener("submit", () => { + submit_form_dispatched = true; + }); + + input.dispatchEvent(events.input_event()); + await utils.timeout(1); + expect(submit_form_dispatched).toBe(true); + }); + }); + + describe("5 - Nesting", function () { + it("5.1 - submits a subform only once with nested auto-submit elements", async function () { + document.body.innerHTML = ` +
+
+
+ +
+
+
+ `; + const form = document.querySelector("form"); + const fieldset = document.querySelector("fieldset"); + const subform = document.querySelector(".pat-subform"); + const input = document.querySelector("input"); + + const instance_form = new Pattern(form); + await events.await_pattern_init(instance_form); + const instance_fieldset = new Pattern(fieldset); + await events.await_pattern_init(instance_fieldset); + + let submit_count = 0; + subform.addEventListener("submit", () => { + submit_count++; + }); + + // Both auto-submit instances listen on the subform. Only one of + // them may submit it. + input.dispatchEvent(events.generic_event("input-change-delayed")); + expect(submit_count).toBe(1); + }); + }); + + describe("6 - Destroy", function () { + it("6.1 - does not submit after being destroyed", async function () { + document.body.innerHTML = ` +
+
+ +
+ +
+ `; + const form = document.querySelector("form"); + const subform = document.querySelector(".pat-subform"); + const instance = new Pattern(form); + await events.await_pattern_init(instance); + + let submit_dispatched = false; + form.addEventListener("submit", () => { + submit_dispatched = true; + }); + + instance.destroy(); + expect(form["pattern-autosubmit"]).toBeUndefined(); + + form.querySelector("[name=q]").dispatchEvent(events.input_event()); + form.querySelector("[name=r]").dispatchEvent(events.input_event()); + $(form).trigger("pat-update", { pattern: "sortable" }); + await utils.timeout(1); + expect(submit_dispatched).toBe(false); + + // Also the listeners on the subform are removed. + subform.dispatchEvent(events.generic_event("input-change-delayed")); + expect(submit_dispatched).toBe(false); + }); + + it("6.2 - cancels a pending delayed submit when being destroyed", async function () { + document.body.innerHTML = ` +
+ +
+ `; + const form = document.querySelector("form"); + const instance = new Pattern(form); + await events.await_pattern_init(instance); + + let submit_dispatched = false; + form.addEventListener("submit", () => { + submit_dispatched = true; + }); + + form.querySelector("input").dispatchEvent(events.input_event()); + instance.destroy(); + await utils.timeout(20); + expect(submit_dispatched).toBe(false); + }); + + it("6.3 - is destroyed when the element is removed from the DOM", async function () { + document.body.innerHTML = ` +
+ +
+ `; + const form = document.querySelector("form"); + const instance = new Pattern(form); + await events.await_pattern_init(instance); + + form.remove(); + await utils.timeout(1); + expect(instance.destroyed).toBe(true); + }); + }); +}); diff --git a/src/pat/auto-submit/auto-submit.js b/src/pat/auto-submit/auto-submit.js index 7d0cbc41c..13bfb6475 100644 --- a/src/pat/auto-submit/auto-submit.js +++ b/src/pat/auto-submit/auto-submit.js @@ -1,141 +1,20 @@ -import "../../core/jquery-ext"; -import $ from "jquery"; -import Base from "../../core/base"; -import dom from "../../core/dom"; -import events from "../../core/events"; -import input_change_events from "../../lib/input-change-events"; -import logging from "../../core/logging"; -import Parser from "../../core/parser"; -import utils from "../../core/utils"; - -const log = logging.getLogger("autosubmit"); - -export const parser = new Parser("autosubmit"); -// - 400ms -> 400 -// - 400 -> 400 -// - defocus -parser.addArgument("delay", "400ms"); - -export default Base.extend({ +/** + * pat-auto-submit registration module. + * + * The pattern implementation is loaded lazily when the pattern is used for + * the first time. Import the implementation module to use the pattern class + * or its parser directly: + * ./auto-submit--implementation.js + */ +import create_lazy_pattern from "../../core/lazy-pattern"; +import registry from "../../core/registry"; + +const Pattern = create_lazy_pattern({ name: "autosubmit", trigger: ".pat-autosubmit, .pat-auto-submit", - - init() { - this.options = parser.parse(this.el, this.options); - if (this.options.delay !== "defocus") { - this.options.delay = parseInt(this.options.delay.replace(/[^\d]*/g, ""), 10); - } - - input_change_events.setup(this.$el, "autosubmit"); - this.registerListeners(); - this.registerTriggers(); - }, - - registerListeners() { - events.add_event_listener( - this.el, - "input-change-delayed", - "pat-autosubmit--input-change-delayed", - this.onInputChange.bind(this) - ); - this.registerSubformListeners(); - this.$el.on("patterns-injected", this.refreshListeners.bind(this)); - this.$el.on("pat-update", (e, data) => { - // Refresh on some pat-update events. - if ( - (data?.pattern === "clone" && data?.action === "removed") || - data?.pattern === "sortable" - ) { - // Directly submit when removing a clone or changing the sorting. - dom.find_form(this.el).dispatchEvent(events.submit_event()); - log.debug( - `triggered by pat-update, pattern: ${data.pattern}, action: ${data.action}` - ); - } else if (data?.pattern === "clone") { - // Refresh listeners on cloning. - this.refreshListeners(e, null, null, data.dom); - } - }); - }, - - registerSubformListeners(ev) { - /* If there are subforms, we need to listen on them as well, so - * that only the subform gets submitted if an element inside it - * changes. - */ - const el = typeof ev !== "undefined" ? ev.target : this.el; - - // get all subforms whice are not yet auto submit forms. - const subforms = el.querySelectorAll( - ".pat-subform:not(.pat-autosubmit):not(.pat-auto-submit)" - ); - for (const subform of subforms) { - // register autosubmit on subform - events.add_event_listener( - subform, - "input-change-delayed", - "pat-autosubmit--input-change-delayed", - this.onInputChange.bind(this) - ); - } - }, - - refreshListeners(ev, cfg, el, injected) { - this.registerSubformListeners(); - // Register change event handlers for new inputs injected into this form - input_change_events.setup($(injected), "autosubmit"); - }, - - registerTriggers() { - const isText = this.$el.is("input:text, input[type=search], textarea"); - if (this.options.delay === "defocus" && !isText) { - log.error( - "The defocus delay value makes only sense on text input elements." - ); - return this.$el; - } - - function trigger_event(ev) { - if (ev.target.closest(".pat-autosubmit") !== this) { - return; - } - ev.target.dispatchEvent(events.generic_event("input-change-delayed")); - } - if (this.options.delay === "defocus") { - this.$el.on("input-defocus.pat-autosubmit", trigger_event); - } else if (this.options.delay > 0) { - this.$el.on( - "input-change.pat-autosubmit", - utils.debounce(trigger_event, this.options.delay) - ); - } else { - this.$el.on("input-change.pat-autosubmit", trigger_event); - } - }, - - destroy($el) { - input_change_events.remove($el, "autosubmit"); - if (this.$el.is("form")) { - this.$el - .find(".pat-subform") - .addBack(this.$el) - .each((idx, el) => { - $(el).off(".pat-autosubmit"); - }); - } else { - $el.off(".pat-autosubmit"); - } - }, - - onInputChange(e) { - e.stopPropagation(); - dom.find_form(e.target).dispatchEvent( - events.submit_event({ submitter: e.target }) - ); - log.debug( - `submit event triggered by event ${e.type} by submitter (1) on (2)`, - e.target, - this.el - ); - }, + load: () => import("./auto-submit--implementation"), }); + +registry.register(Pattern); +export default Pattern; +export { Pattern }; diff --git a/src/pat/auto-submit/auto-submit.test.js b/src/pat/auto-submit/auto-submit.test.js index 941512b22..4492852e2 100644 --- a/src/pat/auto-submit/auto-submit.test.js +++ b/src/pat/auto-submit/auto-submit.test.js @@ -1,269 +1,15 @@ -import $ from "jquery"; import Pattern from "./auto-submit"; -import events from "../../core/events"; -import registry from "../../core/registry"; -import utils from "../../core/utils"; -import { jest } from "@jest/globals"; +import Implementation from "./auto-submit--implementation"; -describe("pat-autosubmit", function () { - afterEach(function () { - document.body.innerHTML = ""; +describe("pat-auto-submit registration module", function () { + it("registers a lazily loaded pattern with the implementation's metadata.", function () { + expect(Pattern.lazy).toBe(true); + expect(Pattern.name).toBe(Implementation.name); + expect(Pattern.trigger).toBe(Implementation.trigger); + expect(Pattern.order ?? 1000).toBe(Implementation.order ?? 1000); }); - describe("1 - Triggering of the pattern", function () { - it("1.1 - happens when a form has the pat-autosubmit class", function () { - document.body.innerHTML = ` -
-
- - -
-
- `; - var spy_init = jest.spyOn(Pattern, "init"); - registry.scan(document.body); - expect(spy_init).toHaveBeenCalled(); - }); - - it("1.2 - when a grouping of inputs has the pat-autosubmit class", function () { - document.body.innerHTML = ` -
-
- - -
-
- `; - var spy_init = jest.spyOn(Pattern, "init"); - registry.scan(document.body); - expect(spy_init).toHaveBeenCalled(); - }); - - it("1.3 - when a single input has the pat-autosubmit class", function () { - document.body.innerHTML = ` -
- -
- `; - var spy_init = jest.spyOn(Pattern, "init"); - registry.scan(document.body); - expect(spy_init).toHaveBeenCalled(); - }); - - it("1.4 - calls refreshListeners when pat-clone adds an element", function () { - document.body.innerHTML = ` -
-
- `; - const el = document.querySelector(".pat-autosubmit"); - const instance = new Pattern(el); - const spy = jest.spyOn(instance, "refreshListeners"); - $(el).trigger("pat-update", { pattern: "clone" }); - expect(spy).toHaveBeenCalled(); - }); - }); - - describe("2 - Trigger a submit", function () { - it("2.1 - when a change on a single input happens", async function () { - document.body.innerHTML = ` -
- -
- `; - const input = document.querySelector(".pat-autosubmit"); - new Pattern(input); - let submit_form_dispatched = false; - document.querySelector("form").addEventListener("submit", () => { - submit_form_dispatched = true; - }); - input.dispatchEvent(events.input_event()); - await utils.timeout(1); - expect(submit_form_dispatched).toBe(true); - }); - - it("2.2 - when pat-clone'd input is changed", async function () { - const pattern_clone = (await import("../clone/clone")).default; - document.body.innerHTML = ` -
- -
- - `; - const el = document.querySelector(".pat-autosubmit"); - const el_clone = document.querySelector(".pat-clone"); - const button_clone = document.querySelector(".add-clone"); - - let submit_dispatched = false; - el.addEventListener("submit", () => { - submit_dispatched = true; - }); - - new Pattern(el); - new pattern_clone(el_clone); - - button_clone.click(); - - document.querySelector("form input").dispatchEvent(events.input_event()); - - await utils.timeout(1); - expect(submit_dispatched).toBe(true); - }); - - it("2.3 - when pat-clone removes an element", function () { - document.body.innerHTML = ` -
-
- `; - const el = document.querySelector(".pat-autosubmit"); - - let submit_dispatched = false; - el.addEventListener("submit", () => { - submit_dispatched = true; - }); - - new Pattern(el); - - $(el).trigger("pat-update", { pattern: "clone", action: "removed" }); - - expect(submit_dispatched).toBe(true); - }); - - it("2.4 - when pat-sortable changes the sorting", function () { - document.body.innerHTML = ` -
-
- `; - const el = document.querySelector(".pat-autosubmit"); - - let submit_dispatched = false; - el.addEventListener("submit", () => { - submit_dispatched = true; - }); - - new Pattern(el); - - $(el).trigger("pat-update", { pattern: "sortable" }); - - expect(submit_dispatched).toBe(true); - }); - - it("2.5 - when a change on a single input happens with delay option", async function () { - document.body.innerHTML = ` -
- -
- `; - const input = document.querySelector(".pat-autosubmit"); - new Pattern(input); - let submit_form_dispatched = false; - document.querySelector("form").addEventListener("submit", () => { - submit_form_dispatched = true; - }); - input.dispatchEvent(events.input_event()); - await utils.timeout(1); - expect(submit_form_dispatched).toBe(false); - await utils.timeout(9); - expect(submit_form_dispatched).toBe(false); - await utils.timeout(10); - expect(submit_form_dispatched).toBe(true); - }); - - it("2.6 - when pat-autosubmit is defined not on a form element", async function () { - document.body.innerHTML = ` -
-
- -
-
- `; - const input = document.querySelector("input"); - const autosubmit = document.querySelector(".pat-autosubmit"); - new Pattern(autosubmit); - - let submit_form_dispatched = false; - document.querySelector("form").addEventListener("submit", () => { - submit_form_dispatched = true; - }); - - input.dispatchEvent(events.input_event()); - await utils.timeout(1); - expect(submit_form_dispatched).toBe(true); - }); - - it("2.7 - directly on a pat-subform", async function () { - document.body.innerHTML = ` -
-
- -
-
- `; - const input = document.querySelector("input"); - const subform = document.querySelector(".pat-subform"); - const autosubmit = document.querySelector(".pat-autosubmit"); - new Pattern(autosubmit); - - // The submit event should be invoked on the subform. - let submit_subform_dispatched = false; - subform.addEventListener("submit", () => { - submit_subform_dispatched = true; - }); - - // The submit event should also bubble up to the form. - let submit_form_dispatched = false; - document.querySelector("form").addEventListener("submit", () => { - submit_form_dispatched = true; - }); - - input.dispatchEvent(events.input_event()); - await utils.timeout(1); - expect(submit_subform_dispatched).toBe(true); - expect(submit_form_dispatched).toBe(true); - }); - }); - - describe("3 - Parsing of the delay option", function () { - it("3.1 - can be done in shorthand notation", function () { - let pat = new Pattern(``); - expect(pat.options.delay).toBe(500); - pat = new Pattern(``); - expect(pat.options.delay).toBe(500); - pat = new Pattern(``); - expect(pat.options.delay).toBe("defocus"); - }); - - it("3.2 - can be done in longhand notation", function () { - let pat = new Pattern(``); - expect(pat.options.delay).toBe(500); - pat = new Pattern(``); - expect(pat.options.delay).toBe(500); - pat = new Pattern(``); - expect(pat.options.delay).toBe("defocus"); - }); + it("loads the implementation.", async function () { + expect(await Pattern.load()).toBe(Implementation); }); }); diff --git a/src/pat/auto-suggest/auto-suggest--implementation.js b/src/pat/auto-suggest/auto-suggest--implementation.js new file mode 100644 index 000000000..c505c88bb --- /dev/null +++ b/src/pat/auto-suggest/auto-suggest--implementation.js @@ -0,0 +1,368 @@ +import "../../core/jquery-ext"; +import $ from "jquery"; +import { BasePattern } from "../../core/basepattern"; +import logging from "../../core/logging"; +import Parser from "../../core/parser"; +import dom from "../../core/dom"; +import events from "../../core/events"; +import registry from "../../core/registry"; + +const log = logging.getLogger("autosuggest"); + +export const parser = new Parser("autosuggest"); +parser.addArgument("ajax-data-type", "JSON"); +parser.addArgument("ajax-search-index", ""); +parser.addArgument("ajax-timeout", 400); +parser.addArgument("ajax-url", ""); +parser.addArgument("max-initial-size", 10); // AJAX search results limit for the first page. +parser.addArgument("ajax-batch-size", 0); // AJAX search results limit for subsequent pages. +parser.addArgument("allow-new-words", true); // Should custom tags be allowed? +parser.addArgument("max-selection-size", 0); +parser.addArgument("minimum-input-length"); // Don't restrict by default so that all results show +parser.addArgument("placeholder", function ($el) { + return $el.attr("placeholder") || undefined; +}); +parser.addArgument("prefill", function ($el) { + return $el.val(); +}); +parser.addArgument("prefill-json", ""); // JSON format for pre-filling +parser.addArgument("words", ""); +parser.addArgument("words-json"); +parser.addArgument("value-separator", ","); // Separator for multiple values + +// "selection-classes" allows you to add custom CSS classes to currently +// selected elements. +// The value passed in must be an object with each id being the text inside +// a selection and value being a list of classes to be added to the +// selection. +// e.g. {'BMW': ['selected', 'car'], 'BMX': ['selected', 'bicycle']} +parser.addArgument("selection-classes", ""); + +parser.addAlias("maximum-selection-size", "max-selection-size"); +parser.addAlias("data", "prefill-json"); +parser.addAlias("pre-fill", "prefill"); + +class Pattern extends BasePattern { + static name = "autosuggest"; + static trigger = ".pat-autosuggest,.pat-auto-suggest"; + static parser = parser; + + $pat_depends = null; + select2_initialized = false; + + async init() { + this.$el = $(this.el); + + if (window.__patternslib_import_styles) { + import("select2/select2.css"); + } + await import("select2"); + if (this.destroyed) { + return; + } + + let config = { + separator: this.options.valueSeparator, + tokenSeparators: [","], + openOnEnter: false, + maximumSelectionSize: this.options.max["selection-size"], + minimumInputLength: this.options.minimumInputLength, + allowClear: + this.options.max["selection-size"] === 1 && + !this.el.hasAttribute("required"), + }; + if (this.el.hasAttribute("readonly")) { + config.placeholder = ""; + } else if (this.options.placeholder) { + config.placeholder = this.options.placeholder; + } + + if (this.options.selectionClasses) { + // We need to customize the formatting/markup of the selection + config.formatSelection = (obj, container) => { + let selectionClasses = null; + try { + selectionClasses = JSON.parse(this.options.selectionClasses)[ + obj.text + ]; + } catch (e) { + if (e instanceof SyntaxError) { + log.error( + "SyntaxError: non-JSON data given to pat-autosuggest (selection-classes)" + ); + } else { + throw e; + } + } + if (selectionClasses) { + // According to Cornelis the classes need to be applied on + // the
  • , which is the container's parent + container.parent().addClass(selectionClasses.join(" ")); + } + return obj.text; + }; + } + + if (this.el.tagName === "INPUT") { + config = this.create_input_config(config); + } + const $sel2 = this.$el.select2(config); + this.select2_initialized = true; + + dom.hide(this.el); // hide input, but keep active (e.g. for validation) + + // Handle case of pat-depends, where select2 might not be visible initially + const pat_depends = this.el.closest(".pat-depends"); + if (pat_depends) { + this.$pat_depends = $(pat_depends); + this.$pat_depends.on(`pat-update.${this.event_namespace}`, (e, data) => { + if (data?.pattern === "depends") { + if (data?.enabled === true) { + this.$el.select2("enable", true); + } else if (data?.enabled === false) { + this.$el.select2("disable", true); + } + } + }); + } + + // Allow pat-validate to check for validity when select2 was interacted + // with but no value selected. + const initiate_empty_check = () => { + const val = $sel2.select2("val"); + if (val?.length === 0) { + // catches "" and [] + // focus-out the input field so that pat-validate can kick in + // when nothing was selected. + this.el.dispatchEvent(events.focusout_event()); + } + }; + this.$el.on(`select2-close.${this.event_namespace}`, initiate_empty_check); + this.$el.on(`select2-blur.${this.event_namespace}`, initiate_empty_check); + + this.$el.on(`change.${this.event_namespace}`, () => { + // The jQuery "change" event isn't caught by normal JavaScript + // event listeners, e.g. in pat-validation. + // Let's re-trigger as input-event, so that pat-validation but also + // ``input-change-events`` can pick it up. + this.el.dispatchEvent(events.input_event()); + }); + + // Clear values on reset. + this.add_event_listener(this.el.closest("form"), "reset", "clear-on-reset", () => + this.$el.select2("val", ""), + ); + } + + get event_namespace() { + // Instance specific jQuery event namespace. + return `pat-autosuggest-${this.uuid}`; + } + + create_input_config(config) { + let words = []; + + config.createSearchChoice = (term, data) => { + if (this.options.allowNewWords) { + if ( + data.filter((el) => el.text.localeCompare(term) === 0).length === 0 + ) { + return { id: term, text: term }; + } + } else { + return null; + } + }; + + if (this.options.wordsJson?.length) { + try { + words = JSON.parse(this.options.wordsJson); + } catch (e) { + if (e instanceof SyntaxError) { + words = []; + log.error("SyntaxError: non-JSON data given to pat-autosuggest"); + } else { + throw e; + } + } + if (!Array.isArray(words)) { + words = words.map((v, k) => { + return { id: k, text: v }; + }); + } + } + if (this.options.words) { + words = this.options.words.split(/\s*,\s*/); + words = words.map((v) => { + return { id: v, text: v }; + }); + } + + // Per Cornelis, if our max lenght is 1, we want select style. If it is larger, we want tag style + // Now this is somewhat fishy because so far, we always configured tag style by setting config.tags = words. + // Even if words was [], we would get a tag stylee select + // That was then properly working with ajax if configured. + + if (this.options.max["selection-size"] === 1) { + config.data = words; + // We allow exactly one value, use dropdown styles. How do we feed in words? + } else { + // We allow multiple values, use the pill style - called tags in select 2 speech + config.tags = words; + } + + if (this.options.prefill?.length) { + this.el.value = this.options.prefill + .split(",") + .map((it) => it.trim()) + .join(this.options.valueSeparator); + config.initSelection = (element, callback) => { + let data = []; + const values = element[0].value.split(this.options.valueSeparator); + for (const value of values) { + data.push({ id: value, text: value }); + } + if (this.options.max["selection-size"] === 1) { + data = data[0]; + } + callback(data); + }; + } + + if (this.options.prefillJson.length) { + /* We support two types of JSON data for prefill data: + * {"john-snow": "John Snow", "tywin-lannister": "Tywin Lannister"} + * or + * [ + * {"id": "john-snow", "text": "John Snow"}, + * {"id": "tywin-lannister", "text":"Tywin Lannister"} + * ] + */ + try { + const data = JSON.parse(this.options.prefillJson); + let ids = []; + for (const d in data) { + if (typeof d === "object") { + ids.push(d.id); + } else { + ids.push(d); + } + } + this.el.value = ids.join(this.options.valueSeparator); + config.initSelection = (element, callback) => { + let _data = []; + for (const d in data) { + if (typeof d === "object") { + _data.push({ id: d.id, text: d.text }); + } else { + _data.push({ id: d, text: data[d] }); + } + } + if (this.options.max["selection-size"] === 1) { + _data = _data[0]; + } + callback(_data); + }; + } catch (e) { + if (e instanceof SyntaxError) { + log.error("SyntaxError: non-JSON data given to pat-autosuggest"); + } else { + throw e; + } + } + } + + if (this.options.ajax?.url) { + config = $.extend( + true, + { + minimumInputLength: this.options.minimumInputLength, + ajax: { + url: this.options.ajax.url, + dataType: this.options.ajax["data-type"], + type: "GET", + quietMillis: this.options.ajax.timeout, + cache: true, + data: (term, page) => { + const request_data = { + q: term, // search term + page: page, + }; + + const index = this.options.ajax["search-index"]; + if (index) { + request_data.index = index; + } + + const page_limit = this.page_limit(page); + if (page_limit > 0) { + request_data.page_limit = page_limit; + } + + return request_data; + }, + results: (data, page) => { + // Parse the results into the format expected by Select2. + // data must be a list of objects with keys "id" and "text" + + // Check whether there are more results to come. + // There are maybe more results if the number of + // items is the same as the batch-size. + // We expect the backend to return an empty list if + // a batch page is requested where there are no + // more results. + const page_limit = this.page_limit(page); + const load_more = page_limit > 0 && + data && + Object.keys(data).length >= page_limit; + return { results: data, page: page, more: load_more }; + }, + }, + }, + config + ); + } + return config; + } + + page_limit(page) { + /* Return the page limit based on the current page. + * + * If no `ajax-batch-size` is set, batching is disabled but we can + * still define the number of items to be shown on the first page with + * `max-initial-size`. + * + * @param {number} page - The current page number. + * @returns {number} - The page limit. + */ + + // Page limit for the first page of a batch. + const initial_size = this.options.max["initial-size"] || 0; + + // Page limit for subsequent pages. + const batch_size = this.options.ajax["batch-size"] || 0; + + return page === 1 ? initial_size : batch_size; + } + + destroy() { + this.$el?.off(`.${this.event_namespace}`); + this.$pat_depends?.off(`.${this.event_namespace}`); + if (this.select2_initialized) { + const select2 = this.$el.data("select2"); + if (select2) { + // Select2 does not cancel pending (debounced AJAX) search + // requests on destroy and would fail on its removed DOM when + // the response arrives. Let it ignore any pending response. + select2.queryCount++; + } + this.$el.select2("destroy"); + this.select2_initialized = false; + } + super.destroy(); + } +} + +registry.register(Pattern); +export default Pattern; +export { Pattern }; diff --git a/src/pat/auto-suggest/auto-suggest--implementation.test.js b/src/pat/auto-suggest/auto-suggest--implementation.test.js new file mode 100644 index 000000000..bc17ce262 --- /dev/null +++ b/src/pat/auto-suggest/auto-suggest--implementation.test.js @@ -0,0 +1,901 @@ +import $ from "jquery"; +import events from "../../core/events"; +import Pattern from "./auto-suggest--implementation"; +import utils from "../../core/utils"; +import registry from "../../core/registry"; +import { jest } from "@jest/globals"; + +// Need to import for the ajax mock to work. +import "select2"; + +const mock_fetch_ajax = (...data) => { + // Data format: [{id: str, text: str}, ... ], ... + // first batch ^ ^ second batch + + // NOTE: You need to add a trailing comma if you add only one argument to + // make the multi-argument dereferencing work. + + // Mock Select2 + $.fn.select2.ajaxDefaults.transport = jest.fn().mockImplementation((opts) => { + // Get the batch page + const page = opts.data.page - 1; + + // Return the data for the batch + return opts.success(data[page]); + }); +}; + +var testutils = { + createInputElement: function (c) { + var cfg = c || {}; + return $("", { + "id": cfg.id || "select2", + "data-pat-autosuggest": cfg.data, + "class": "pat-autosuggest", + "type": "text", + }).appendTo($("div#lab")); + }, + + createSelectElement: function (c) { + var cfg = c || {}; + return $(" element gets converted into a select2 widget", async function () { + testutils.createInputElement(); + var $el = $("input.pat-autosuggest"); + + expect($(".select2-container").length).toBe(0); + expect($el.hasClass("select2-offscreen")).toBeFalsy(); + + registry.scan(document.body); + await utils.timeout(1); // wait a tick for async to settle. + + $el = $("input.pat-autosuggest"); // element was replaced - re-get it. + expect($el.hasClass("select2-offscreen")).toBeTruthy(); + expect($(".select2-container").length).toBe(1); + testutils.removeSelect2(); + + expect($el[0].getAttribute("type")).toBe("text"); + expect($el[0].style.display).toBe("none"); + }); + + it("1.1 - An element with an ajax option keeps the ajax option when turning into a select2 widget", async function () { + testutils.createInputElement({ + data: "ajax-url: http://test.org/test", + }); + var $el = $("input.pat-autosuggest"); + + const instance = new Pattern($el); + await events.await_pattern_init(instance); + expect($el.data("select2").opts.ajax).toBeDefined(); + testutils.removeSelect2(); + }); + + it("1.3 - A + `; + + const input = document.querySelector("input"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + $(".select2-input").click(); + $(document.querySelector(".select2-result")).mouseup(); + + const selected = document.querySelectorAll(".select2-search-choice"); + expect(selected.length).toBe(1); + expect(selected[0].textContent.trim()).toBe("apple"); + expect(input.value).toBe("apple"); + }); + + it("2.4 - select multiple items from a word list.", async function () { + document.body.innerHTML = ` + + `; + + const input = document.querySelector("input"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + $(".select2-input").click(); + $(document.querySelector(".select2-result")).mouseup(); + $(".select2-input").click(); + $(document.querySelector(".select2-result")).mouseup(); + + const selected = document.querySelectorAll(".select2-search-choice"); + expect(selected.length).toBe(2); + expect(selected[0].textContent.trim()).toBe("apple"); + expect(selected[1].textContent.trim()).toBe("orange"); + expect(input.value).toBe("apple,orange"); + }); + + it("2.5 - items can be pre-filled with json.", async function () { + // Check if json pre-filled fields do work as expected. + // Version 7.0 introduced a problem where at json pre-filled fields + // no items could be deleted or added. + // Version 7.11 fixes that problem. + + document.body.innerHTML = ` + + `; + + const input = document.querySelector("input"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + + let selected = document.querySelectorAll(".select2-search-choice"); + expect(selected.length).toBe(2); + expect(selected[0].textContent.trim()).toBe("Orange"); + expect(selected[1].textContent.trim()).toBe("Lemon"); + expect(input.value).toBe("id-orange,id-lemon"); + + // NOTE: the keyboard event init key ``which`` is deprecated, + // but that's what select2 3.5.1 is expecting. + document + .querySelector(".select2-input") + .dispatchEvent(new KeyboardEvent("keydown", { which: 8 })); + // Need to send two times. + document + .querySelector(".select2-input") + .dispatchEvent(new KeyboardEvent("keydown", { which: 8 })); + + selected = document.querySelectorAll(".select2-search-choice"); + expect(selected.length).toBe(1); + expect(selected[0].textContent.trim()).toBe("Orange"); + + document.querySelector(".select2-input").click(); + document.querySelector(".select2-result").dispatchEvent(events.mouseup_event()); // prettier-ignore + document.querySelector(".select2-input").click(); + document.querySelector(".select2-result").dispatchEvent(events.mouseup_event()); // prettier-ignore + + selected = document.querySelectorAll(".select2-search-choice"); + expect(selected.length).toBe(3); + expect(selected[0].textContent.trim()).toBe("Orange"); + expect(selected[1].textContent.trim()).toBe("Apple"); + expect(selected[2].textContent.trim()).toBe("Lemon"); + expect(input.value).toBe("id-orange,id-apple,id-lemon"); + }); + + it("2.6 - items can be pre-filled without json.", async function () { + document.body.innerHTML = ` + + `; + + const input = document.querySelector("input"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + + let selected = document.querySelectorAll(".select2-search-choice"); + expect(selected.length).toBe(2); + expect(selected[0].textContent.trim()).toBe("id-orange"); + expect(selected[1].textContent.trim()).toBe("id-lemon"); + expect(input.value).toBe("id-orange,id-lemon"); + }); + + it("2.7.1 - use a custom separator for multiple items.", async function () { + document.body.innerHTML = ` + + " /> + `; + + const input = document.querySelector("input"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + $(".select2-input").click(); + $(document.querySelector(".select2-result")).mouseup(); + $(".select2-input").click(); + $(document.querySelector(".select2-result")).mouseup(); + + const selected = document.querySelectorAll(".select2-search-choice"); + expect(selected.length).toBe(2); + expect(selected[0].textContent.trim()).toBe("apple"); + expect(selected[1].textContent.trim()).toBe("orange"); + expect(input.value).toBe("apple|orange"); + }); + + it("2.7.2 - use another custom separator for multiple items.", async function () { + document.body.innerHTML = ` + + " /> + `; + + const input = document.querySelector("input"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + $(".select2-input").click(); + $(document.querySelector(".select2-result")).mouseup(); + $(".select2-input").click(); + $(document.querySelector(".select2-result")).mouseup(); + + const selected = document.querySelectorAll(".select2-search-choice"); + expect(selected.length).toBe(2); + expect(selected[0].textContent.trim()).toBe("apple"); + expect(selected[1].textContent.trim()).toBe("orange"); + expect(input.value).toBe("apple;orange"); + }); + + it("2.7.3 - use a custom separator and pre-fill with json.", async function () { + document.body.innerHTML = ` + + `; + + const input = document.querySelector("input"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + + let selected = document.querySelectorAll(".select2-search-choice"); + expect(selected.length).toBe(2); + expect(selected[0].textContent.trim()).toBe("Orange"); + expect(selected[1].textContent.trim()).toBe("Lemon"); + expect(input.value).toBe("id-orange;id-lemon"); + }); + + it("2.7.4 - use a custom separator and pre-fill.", async function () { + document.body.innerHTML = ` + + `; + + const input = document.querySelector("input"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + + let selected = document.querySelectorAll(".select2-search-choice"); + expect(selected.length).toBe(2); + expect(selected[0].textContent.trim()).toBe("id-orange"); + expect(selected[1].textContent.trim()).toBe("id-lemon"); + expect(input.value).toBe("id-orange;id-lemon"); + }); + + it("2.7.5 - use a custom separator and pre-fill with the value attribute.", async function () { + document.body.innerHTML = ` + + `; + + const input = document.querySelector("input"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + + let selected = document.querySelectorAll(".select2-search-choice"); + expect(selected.length).toBe(2); + expect(selected[0].textContent.trim()).toBe("id-orange"); + expect(selected[1].textContent.trim()).toBe("id-lemon"); + expect(input.value).toBe("id-orange;id-lemon"); + }); + }); + + describe("3 - Placeholder tests", function () { + it("3.1 - A placeholder on the original element is reused on the auto-suggest element", async function () { + var placeholder = "Test placeholder"; + + $("", { + id: "select2", + class: "pat-autosuggest", + placeholder: "Test placeholder", + }).appendTo($("div#lab")); + + var $el = $("input.pat-autosuggest"); + + expect($el.prop("placeholder")).toBe(placeholder); + const instance = new Pattern($el); + await events.await_pattern_init(instance); + // XXX Placeholder is used as value of the input field. + // Change this as soon Select2 changes this odd behavior. + expect($(".select2-input").val()).toBe(placeholder); + testutils.removeSelect2(); + }); + + it("3.2 - No placeholder doesn't create an automatic one.", async function () { + $("", { + id: "select2", + class: "pat-autosuggest", + }).appendTo($("div#lab")); + + var $el = $("input.pat-autosuggest"); + + expect($el.prop("placeholder")).toBe(""); + const instance = new Pattern($el); + await events.await_pattern_init(instance); + // XXX Placeholder is used as value of the input field. + // Change this as soon Select2 changes this odd behavior. + expect($(".select2-input").val()).toBe(""); + testutils.removeSelect2(); + }); + }); + + describe("4 - Integration...", function () { + it("4.1 - Works with pat-auto-submit", async function () { + document.body.innerHTML = ` +
    + +
    + `; + + const pattern_autosubmit = (await import("../auto-submit/auto-submit--implementation")).default; // prettier-ignore + const input = document.querySelector("input"); + + let submit_dispatched = false; + document.querySelector("form").addEventListener("submit", () => { + submit_dispatched = true; + }); + + const instance = new Pattern(input); + const instance_autosubmit = new pattern_autosubmit(input); + await events.await_pattern_init(instance); + await events.await_pattern_init(instance_autosubmit); + + $(".select2-input").click(); + $(document.querySelector(".select2-result")).mouseup(); + + expect(submit_dispatched).toBe(true); + }); + + it("4.2 - Works with pat-validate on an empty selection.", async function () { + const pattern_validation = (await import("../validation/validation")).default; // prettier-ignore + + document.body.innerHTML = ` +
    + +
    + `; + + const form = document.querySelector("form"); + const input = document.querySelector("input"); + + const instance_validation = new pattern_validation(form); + await events.await_pattern_init(instance_validation); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + + // Open the select2 dropdown + $(".select2-input").click(); + await utils.timeout(1); // wait a tick for async to settle. + + // Close it without selecting something. + $(input).select2("close"); + + await utils.timeout(1); // wait a tick for async to settle. + + // There should be a error message from pat-validation. + expect(form.querySelectorAll("em.warning").length).toBe(1); + }); + + it("4.3 - Works with pat-validate when empty and focus moves away.", async function () { + const pattern_validation = (await import("../validation/validation")).default; // prettier-ignore + + document.body.innerHTML = ` +
    + +
    + `; + + const form = document.querySelector("form"); + const input = document.querySelector("input"); + + const instance_validation = new pattern_validation(form); + await events.await_pattern_init(instance_validation); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + + // Move focus away from select2 + $(".select2-input")[0].dispatchEvent(events.blur_event()); + await utils.timeout(1); // wait a tick for async to settle. + + // There should be a error message from pat-validation. + expect(form.querySelectorAll("em.warning").length).toBe(1); + }); + }); + + describe("5 - Pittfalls...", function () { + it("5.1 - BEWARE! JSON structures must be valid JSON!", async function () { + // The following contains invalid JSON. Note the comma after the last prefill item. + document.body.innerHTML = ` + + `; + + const input = document.querySelector("input"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + + let selected = document.querySelectorAll(".select2-search-choice"); + + // INVALID JSON! No prefilling should happen. + expect(selected.length).toBe(0); + }); + }); + + describe("6 - AJAX tests", function () { + it("6.1 - AJAX works with a simple data structure.", async function () { + mock_fetch_ajax( + [ + { id: "1", text: "apple" }, + { id: "2", text: "orange" }, + ] // Note the trailing comma to make the multi-argument dereferencing work. + ); + + document.body.innerHTML = ` + + `; + + const input = document.querySelector("input"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + + $(".select2-input").click(); + await utils.timeout(1); // wait for ajax to finish. + + const results = $(document.querySelectorAll(".select2-results li")); + expect(results.length).toBe(2); + + $(results[0]).mouseup(); + + const selected = document.querySelectorAll(".select2-search-choice"); + expect(selected.length).toBe(1); + expect(selected[0].textContent.trim()).toBe("apple"); + expect(input.value).toBe("1"); + }); + + // This test is so flaky, just skip it if it fails. + it.skip.failing("6.2 - AJAX works with batches.", async function () { + mock_fetch_ajax( + [ + { id: "1", text: "one" }, + { id: "2", text: "two" }, + { id: "3", text: "three" }, + { id: "4", text: "four" }, + ], + [ + { id: "5", text: "five" }, + { id: "6", text: "six" }, + ], + [{ id: "7", text: "seven" }] + ); + + document.body.innerHTML = ` + + `; + + const input = document.querySelector("input"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + + // Load batch 1 with batch size 4 + $(".select2-input").click(); + await utils.timeout(1); // wait for ajax to finish. + + const results_1 = $( + document.querySelectorAll(".select2-results .select2-result") + ); + expect(results_1.length).toBe(4); + + const load_more_1 = $( + document.querySelectorAll(".select2-results .select2-more-results") + ); + expect(load_more_1.length).toBe(1); + + // Load batch 2 with batch size 2 + $(load_more_1[0]).mouseup(); + // NOTE: Flaky behavior needs multiple timeouts 👌 + await utils.timeout(1); // wait for ajax to finish. + await utils.timeout(1); // wait for ajax to finish. + await utils.timeout(1); // wait for ajax to finish. + await utils.timeout(1); // wait for ajax to finish. + + const results_2 = $( + document.querySelectorAll(".select2-results .select2-result") + ); + expect(results_2.length).toBe(6); + + const load_more_2 = $( + document.querySelectorAll(".select2-results .select2-more-results") + ); + expect(load_more_2.length).toBe(1); + + // Load final batch 2 + $(load_more_2[0]).mouseup(); + // NOTE: Flaky behavior needs multiple timeouts 🤘 + await utils.timeout(1); // wait for ajax to finish. + await utils.timeout(1); // wait for ajax to finish. + await utils.timeout(1); // wait for ajax to finish. + await utils.timeout(1); // wait for ajax to finish. + + const results_3 = $( + document.querySelectorAll(".select2-results .select2-result") + ); + expect(results_3.length).toBe(7); + + const load_more_3 = $( + document.querySelectorAll(".select2-results .select2-more-results") + ); + expect(load_more_3.length).toBe(0); + }); + + describe("6.3 - Test the page_limit logic.", function () { + + it("6.3.1 - page_limit set only by ajax-batch-size.", async function () { + document.body.innerHTML = ` + + `; + + const input = document.querySelector("input"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + + expect(instance.page_limit(1)).toBe(10); + expect(instance.page_limit(2)).toBe(2); + }); + + it("6.3.2 - page_limit set by ajax-batch-size and max-initial-size.", async function () { + document.body.innerHTML = ` + + `; + + const input = document.querySelector("input"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + + expect(instance.page_limit(1)).toBe(4); + expect(instance.page_limit(2)).toBe(2); + }); + + it("6.3.3 - page_limit set only by max-initial-size and batching not activated.", async function () { + document.body.innerHTML = ` + + `; + + const input = document.querySelector("input"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + + expect(instance.page_limit(1)).toBe(4); + expect(instance.page_limit(2)).toBe(0); + }); + + }); + }); + + describe("7 - Form reset", function () { + it("7.1 - Clears all auto-suggest inputs of a form on reset.", async function () { + document.body.innerHTML = ` +
    + + +
    + `; + const form = document.querySelector("form"); + const input_1 = document.querySelector("[name=one]"); + const input_2 = document.querySelector("[name=two]"); + const instance_1 = new Pattern(input_1); + const instance_2 = new Pattern(input_2); + await events.await_pattern_init(instance_1); + await events.await_pattern_init(instance_2); + + expect(input_1.value).toBe("apple"); + expect(input_2.value).toBe("pear"); + + form.dispatchEvent(new Event("reset")); + + expect(input_1.value).toBe(""); + expect(input_2.value).toBe(""); + }); + }); + + describe("8 - destroy", function () { + it("8.1 - Removes select2 and the event listeners on destroy.", async function () { + document.body.innerHTML = ` +
    + +
    + `; + const form = document.querySelector("form"); + const input = document.querySelector("input"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + + expect(input["pattern-autosuggest"]).toBe(instance); + expect(document.querySelectorAll(".select2-container").length).toBe(1); + + const input_handler = jest.fn(); + input.addEventListener("input", input_handler); + + instance.destroy(); + + expect(instance.destroyed).toBe(true); + expect(input["pattern-autosuggest"]).toBe(undefined); + expect($(input).data("select2")).toBe(undefined); + expect(document.querySelectorAll(".select2-container").length).toBe(0); + + // The jQuery change event is not re-dispatched as input event anymore. + $(input).trigger("change"); + expect(input_handler).not.toHaveBeenCalled(); + + // The value is not cleared on form reset anymore. + form.dispatchEvent(new Event("reset")); + expect(input.value).toBe("apple"); + }); + + it("8.2 - Is destroyed when the element is removed from the DOM.", async function () { + document.body.innerHTML = ` +
    + +
    + `; + const input = document.querySelector("input"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + + document.querySelector(".wrapper").remove(); + await utils.timeout(1); + + expect(instance.destroyed).toBe(true); + expect($(input).data("select2")).toBe(undefined); + }); + + it("8.3 - Stops listening to pat-depends updates on destroy.", async function () { + document.body.innerHTML = ` +
    + +
    + `; + const depends = document.querySelector(".pat-depends"); + const input = document.querySelector("input"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + + const spy_select2 = jest.spyOn($.fn, "select2"); + $(depends).trigger("pat-update", { pattern: "depends", enabled: false }); + expect(spy_select2).toHaveBeenCalledWith("disable", true); + + instance.destroy(); + spy_select2.mockClear(); + + $(depends).trigger("pat-update", { pattern: "depends", enabled: true }); + expect(spy_select2).not.toHaveBeenCalled(); + }); + + it("8.4 - Ignores a pending AJAX response after destroy.", async function () { + let pending_request; + $.fn.select2.ajaxDefaults.transport = jest.fn().mockImplementation((opts) => { + pending_request = opts; + }); + + document.body.innerHTML = ` + + `; + const input = document.querySelector("input"); + const instance = new Pattern(input); + await events.await_pattern_init(instance); + + $(".select2-input").click(); + await utils.timeout(10); // wait for the debounced AJAX request. + expect(pending_request).toBeTruthy(); + + instance.destroy(); + + // The response arrives after destroy. + expect(() => { + pending_request.success([{ id: "1", text: "apple" }]); + }).not.toThrow(); + }); + }); +}); diff --git a/src/pat/auto-suggest/auto-suggest.js b/src/pat/auto-suggest/auto-suggest.js index 1a484cea5..3e61bd964 100644 --- a/src/pat/auto-suggest/auto-suggest.js +++ b/src/pat/auto-suggest/auto-suggest.js @@ -1,340 +1,20 @@ -import "../../core/jquery-ext"; -import $ from "jquery"; -import Base from "../../core/base"; -import logging from "../../core/logging"; -import Parser from "../../core/parser"; -import dom from "../../core/dom"; -import events from "../../core/events"; - -const log = logging.getLogger("autosuggest"); - -export const parser = new Parser("autosuggest"); -parser.addArgument("ajax-data-type", "JSON"); -parser.addArgument("ajax-search-index", ""); -parser.addArgument("ajax-timeout", 400); -parser.addArgument("ajax-url", ""); -parser.addArgument("max-initial-size", 10); // AJAX search results limit for the first page. -parser.addArgument("ajax-batch-size", 0); // AJAX search results limit for subsequent pages. -parser.addArgument("allow-new-words", true); // Should custom tags be allowed? -parser.addArgument("max-selection-size", 0); -parser.addArgument("minimum-input-length"); // Don't restrict by default so that all results show -parser.addArgument("placeholder", function ($el) { - return $el.attr("placeholder") || undefined; -}); -parser.addArgument("prefill", function ($el) { - return $el.val(); -}); -parser.addArgument("prefill-json", ""); // JSON format for pre-filling -parser.addArgument("words", ""); -parser.addArgument("words-json"); -parser.addArgument("value-separator", ","); // Separator for multiple values - -// "selection-classes" allows you to add custom CSS classes to currently -// selected elements. -// The value passed in must be an object with each id being the text inside -// a selection and value being a list of classes to be added to the -// selection. -// e.g. {'BMW': ['selected', 'car'], 'BMX': ['selected', 'bicycle']} -parser.addArgument("selection-classes", ""); - -parser.addAlias("maximum-selection-size", "max-selection-size"); -parser.addAlias("data", "prefill-json"); -parser.addAlias("pre-fill", "prefill"); - -export default Base.extend({ +/** + * pat-auto-suggest registration module. + * + * The pattern implementation is loaded lazily when the pattern is used for + * the first time. Import the implementation module to use the pattern class + * or its parser directly: + * ./auto-suggest--implementation.js + */ +import create_lazy_pattern from "../../core/lazy-pattern"; +import registry from "../../core/registry"; + +const Pattern = create_lazy_pattern({ name: "autosuggest", trigger: ".pat-autosuggest,.pat-auto-suggest", - - async init() { - if (window.__patternslib_import_styles) { - import("select2/select2.css"); - } - await import("select2"); - - this.options = parser.parse(this.el, this.options); - - let config = { - separator: this.options.valueSeparator, - tokenSeparators: [","], - openOnEnter: false, - maximumSelectionSize: this.options.max["selection-size"], - minimumInputLength: this.options.minimumInputLength, - allowClear: - this.options.max["selection-size"] === 1 && - !this.el.hasAttribute("required"), - }; - if (this.el.hasAttribute("readonly")) { - config.placeholder = ""; - } else if (this.options.placeholder) { - config.placeholder = this.options.placeholder; - } - - if (this.options.selectionClasses) { - // We need to customize the formatting/markup of the selection - config.formatSelection = (obj, container) => { - let selectionClasses = null; - try { - selectionClasses = JSON.parse(this.options.selectionClasses)[ - obj.text - ]; - } catch (e) { - if (e instanceof SyntaxError) { - log.error( - "SyntaxError: non-JSON data given to pat-autosuggest (selection-classes)" - ); - } else { - throw e; - } - } - if (selectionClasses) { - // According to Cornelis the classes need to be applied on - // the
  • , which is the container's parent - container.parent().addClass(selectionClasses.join(" ")); - } - return obj.text; - }; - } - - if (this.el.tagName === "INPUT") { - config = this.create_input_config(config); - } - const $sel2 = this.$el.select2(config); - - dom.hide(this.el); // hide input, but keep active (e.g. for validation) - - // Handle case of pat-depends, where select2 might not be visible initially - const pat_depends = this.el.closest(".pat-depends"); - if (pat_depends) { - $(pat_depends).on("pat-update", (e, data) => { - if (data?.pattern === "depends") { - if (data?.enabled === true) { - this.$el.select2("enable", true); - } else if (data?.enabled === false) { - this.$el.select2("disable", true); - } - } - }); - } - - // Allow pat-validate to check for validity when select2 was interacted - // with but no value selected. - const initiate_empty_check = () => { - const val = $sel2.select2("val"); - if (val?.length === 0) { - // catches "" and [] - // focus-out the input field so that pat-validate can kick in - // when nothing was selected. - this.el.dispatchEvent(events.focusout_event()); - } - }; - this.$el.on("select2-close", initiate_empty_check.bind(this)); - this.$el.on("select2-blur", initiate_empty_check.bind(this)); - - this.$el.on("change", () => { - // The jQuery "change" event isn't caught by normal JavaScript - // event listeners, e.g. in pat-validation. - // Let's re-trigger as input-event, so that pat-validation but also - // ``input-change-events`` can pick it up. - this.el.dispatchEvent(events.input_event()); - }); - - // Clear values on reset. - events.add_event_listener( - this.el.closest("form"), - "reset", - "pat-auto-suggest--reset", - () => this.$el.select2("val", "") - ); - }, - - create_input_config(config) { - let words = []; - - config.createSearchChoice = (term, data) => { - if (this.options.allowNewWords) { - if ( - data.filter((el) => el.text.localeCompare(term) === 0).length === 0 - ) { - return { id: term, text: term }; - } - } else { - return null; - } - }; - - if (this.options.wordsJson?.length) { - try { - words = JSON.parse(this.options.wordsJson); - } catch (e) { - if (e instanceof SyntaxError) { - words = []; - log.error("SyntaxError: non-JSON data given to pat-autosuggest"); - } else { - throw e; - } - } - if (!Array.isArray(words)) { - words = words.map((v, k) => { - return { id: k, text: v }; - }); - } - } - if (this.options.words) { - words = this.options.words.split(/\s*,\s*/); - words = words.map((v) => { - return { id: v, text: v }; - }); - } - - // Per Cornelis, if our max lenght is 1, we want select style. If it is larger, we want tag style - // Now this is somewhat fishy because so far, we always configured tag style by setting config.tags = words. - // Even if words was [], we would get a tag stylee select - // That was then properly working with ajax if configured. - - if (this.options.max["selection-size"] === 1) { - config.data = words; - // We allow exactly one value, use dropdown styles. How do we feed in words? - } else { - // We allow multiple values, use the pill style - called tags in select 2 speech - config.tags = words; - } - - if (this.options.prefill?.length) { - this.el.value = this.options.prefill - .split(",") - .map((it) => it.trim()) - .join(this.options.valueSeparator); - config.initSelection = (element, callback) => { - let data = []; - const values = element[0].value.split(this.options.valueSeparator); - for (const value of values) { - data.push({ id: value, text: value }); - } - if (this.options.max["selection-size"] === 1) { - data = data[0]; - } - callback(data); - }; - } - - if (this.options.prefillJson.length) { - /* We support two types of JSON data for prefill data: - * {"john-snow": "John Snow", "tywin-lannister": "Tywin Lannister"} - * or - * [ - * {"id": "john-snow", "text": "John Snow"}, - * {"id": "tywin-lannister", "text":"Tywin Lannister"} - * ] - */ - try { - const data = JSON.parse(this.options.prefillJson); - let ids = []; - for (const d in data) { - if (typeof d === "object") { - ids.push(d.id); - } else { - ids.push(d); - } - } - this.el.value = ids.join(this.options.valueSeparator); - config.initSelection = (element, callback) => { - let _data = []; - for (const d in data) { - if (typeof d === "object") { - _data.push({ id: d.id, text: d.text }); - } else { - _data.push({ id: d, text: data[d] }); - } - } - if (this.options.max["selection-size"] === 1) { - _data = _data[0]; - } - callback(_data); - }; - } catch (e) { - if (e instanceof SyntaxError) { - log.error("SyntaxError: non-JSON data given to pat-autosuggest"); - } else { - throw e; - } - } - } - - if (this.options.ajax?.url) { - config = $.extend( - true, - { - minimumInputLength: this.options.minimumInputLength, - ajax: { - url: this.options.ajax.url, - dataType: this.options.ajax["data-type"], - type: "GET", - quietMillis: this.options.ajax.timeout, - cache: true, - data: (term, page) => { - const request_data = { - q: term, // search term - page: page, - }; - - const index = this.options.ajax["search-index"]; - if (index) { - request_data.index = index; - } - - const page_limit = this.page_limit(page); - if (page_limit > 0) { - request_data.page_limit = page_limit; - } - - return request_data; - }, - results: (data, page) => { - // Parse the results into the format expected by Select2. - // data must be a list of objects with keys "id" and "text" - - // Check whether there are more results to come. - // There are maybe more results if the number of - // items is the same as the batch-size. - // We expect the backend to return an empty list if - // a batch page is requested where there are no - // more results. - const page_limit = this.page_limit(page); - const load_more = page_limit > 0 && - data && - Object.keys(data).length >= page_limit; - return { results: data, page: page, more: load_more }; - }, - }, - }, - config - ); - } - return config; - }, - - page_limit(page) { - /* Return the page limit based on the current page. - * - * If no `ajax-batch-size` is set, batching is disabled but we can - * still define the number of items to be shown on the first page with - * `max-initial-size`. - * - * @param {number} page - The current page number. - * @returns {number} - The page limit. - */ - - // Page limit for the first page of a batch. - const initial_size = this.options.max["initial-size"] || 0; - - // Page limit for subsequent pages. - const batch_size = this.options.ajax["batch-size"] || 0; - - return page === 1 ? initial_size : batch_size; - }, - - destroy($el) { - $el.off(".pat-autosuggest"); - $el.select2("destroy"); - }, + load: () => import("./auto-suggest--implementation"), }); + +registry.register(Pattern); +export default Pattern; +export { Pattern }; diff --git a/src/pat/auto-suggest/auto-suggest.test.js b/src/pat/auto-suggest/auto-suggest.test.js index a958c483a..f66ef2e1f 100644 --- a/src/pat/auto-suggest/auto-suggest.test.js +++ b/src/pat/auto-suggest/auto-suggest.test.js @@ -1,751 +1,15 @@ -import $ from "jquery"; -import events from "../../core/events"; -import pattern from "./auto-suggest"; -import utils from "../../core/utils"; -import registry from "../../core/registry"; -import { jest } from "@jest/globals"; +import Pattern from "./auto-suggest"; +import Implementation from "./auto-suggest--implementation"; -// Need to import for the ajax mock to work. -import "select2"; - -const mock_fetch_ajax = (...data) => { - // Data format: [{id: str, text: str}, ... ], ... - // first batch ^ ^ second batch - - // NOTE: You need to add a trailing comma if you add only one argument to - // make the multi-argument dereferencing work. - - // Mock Select2 - $.fn.select2.ajaxDefaults.transport = jest.fn().mockImplementation((opts) => { - // Get the batch page - const page = opts.data.page - 1; - - // Return the data for the batch - return opts.success(data[page]); - }); -}; - -var testutils = { - createInputElement: function (c) { - var cfg = c || {}; - return $("", { - "id": cfg.id || "select2", - "data-pat-autosuggest": cfg.data, - "class": "pat-autosuggest", - "type": "text", - }).appendTo($("div#lab")); - }, - - createSelectElement: function (c) { - var cfg = c || {}; - return $(" element gets converted into a select2 widget", async function () { - testutils.createInputElement(); - var $el = $("input.pat-autosuggest"); - - expect($(".select2-container").length).toBe(0); - expect($el.hasClass("select2-offscreen")).toBeFalsy(); - - registry.scan(document.body); - await utils.timeout(1); // wait a tick for async to settle. - - $el = $("input.pat-autosuggest"); // element was replaced - re-get it. - expect($el.hasClass("select2-offscreen")).toBeTruthy(); - expect($(".select2-container").length).toBe(1); - testutils.removeSelect2(); - - expect($el[0].getAttribute("type")).toBe("text"); - expect($el[0].style.display).toBe("none"); - }); - - it("1.1 - An element with an ajax option keeps the ajax option when turning into a select2 widget", async function () { - testutils.createInputElement({ - data: "ajax-url: http://test.org/test", - }); - var $el = $("input.pat-autosuggest"); - jest.spyOn($el, "select2"); - - pattern.init($el); - await utils.timeout(1); // wait a tick for async to settle. - expect($el.select2.mock.calls.pop()[0].ajax).toBeDefined(); - testutils.removeSelect2(); - }); - - it("1.3 - A - `; - - const input = document.querySelector("input"); - new pattern(input); - await utils.timeout(1); // wait a tick for async to settle. - $(".select2-input").click(); - $(document.querySelector(".select2-result")).mouseup(); - - const selected = document.querySelectorAll(".select2-search-choice"); - expect(selected.length).toBe(1); - expect(selected[0].textContent.trim()).toBe("apple"); - expect(input.value).toBe("apple"); - }); - - it("2.4 - select multiple items from a word list.", async function () { - document.body.innerHTML = ` - - `; - - const input = document.querySelector("input"); - new pattern(input); - await utils.timeout(1); // wait a tick for async to settle. - $(".select2-input").click(); - $(document.querySelector(".select2-result")).mouseup(); - $(".select2-input").click(); - $(document.querySelector(".select2-result")).mouseup(); - - const selected = document.querySelectorAll(".select2-search-choice"); - expect(selected.length).toBe(2); - expect(selected[0].textContent.trim()).toBe("apple"); - expect(selected[1].textContent.trim()).toBe("orange"); - expect(input.value).toBe("apple,orange"); - }); - - it("2.5 - items can be pre-filled with json.", async function () { - // Check if json pre-filled fields do work as expected. - // Version 7.0 introduced a problem where at json pre-filled fields - // no items could be deleted or added. - // Version 7.11 fixes that problem. - - document.body.innerHTML = ` - - `; - - const input = document.querySelector("input"); - new pattern(input); - await utils.timeout(1); // wait a tick for async to settle. - - let selected = document.querySelectorAll(".select2-search-choice"); - expect(selected.length).toBe(2); - expect(selected[0].textContent.trim()).toBe("Orange"); - expect(selected[1].textContent.trim()).toBe("Lemon"); - expect(input.value).toBe("id-orange,id-lemon"); - - // NOTE: the keyboard event init key ``which`` is deprecated, - // but that's what select2 3.5.1 is expecting. - document - .querySelector(".select2-input") - .dispatchEvent(new KeyboardEvent("keydown", { which: 8 })); - // Need to send two times. - document - .querySelector(".select2-input") - .dispatchEvent(new KeyboardEvent("keydown", { which: 8 })); - - selected = document.querySelectorAll(".select2-search-choice"); - expect(selected.length).toBe(1); - expect(selected[0].textContent.trim()).toBe("Orange"); - - document.querySelector(".select2-input").click(); - document.querySelector(".select2-result").dispatchEvent(events.mouseup_event()); // prettier-ignore - document.querySelector(".select2-input").click(); - document.querySelector(".select2-result").dispatchEvent(events.mouseup_event()); // prettier-ignore - - selected = document.querySelectorAll(".select2-search-choice"); - expect(selected.length).toBe(3); - expect(selected[0].textContent.trim()).toBe("Orange"); - expect(selected[1].textContent.trim()).toBe("Apple"); - expect(selected[2].textContent.trim()).toBe("Lemon"); - expect(input.value).toBe("id-orange,id-apple,id-lemon"); - }); - - it("2.6 - items can be pre-filled without json.", async function () { - document.body.innerHTML = ` - - `; - - const input = document.querySelector("input"); - new pattern(input); - await utils.timeout(1); // wait a tick for async to settle. - - let selected = document.querySelectorAll(".select2-search-choice"); - expect(selected.length).toBe(2); - expect(selected[0].textContent.trim()).toBe("id-orange"); - expect(selected[1].textContent.trim()).toBe("id-lemon"); - expect(input.value).toBe("id-orange,id-lemon"); - }); - - it("2.7.1 - use a custom separator for multiple items.", async function () { - document.body.innerHTML = ` - - " /> - `; - - const input = document.querySelector("input"); - new pattern(input); - await utils.timeout(1); // wait a tick for async to settle. - $(".select2-input").click(); - $(document.querySelector(".select2-result")).mouseup(); - $(".select2-input").click(); - $(document.querySelector(".select2-result")).mouseup(); - - const selected = document.querySelectorAll(".select2-search-choice"); - expect(selected.length).toBe(2); - expect(selected[0].textContent.trim()).toBe("apple"); - expect(selected[1].textContent.trim()).toBe("orange"); - expect(input.value).toBe("apple|orange"); - }); - - it("2.7.2 - use another custom separator for multiple items.", async function () { - document.body.innerHTML = ` - - " /> - `; - - const input = document.querySelector("input"); - new pattern(input); - await utils.timeout(1); // wait a tick for async to settle. - $(".select2-input").click(); - $(document.querySelector(".select2-result")).mouseup(); - $(".select2-input").click(); - $(document.querySelector(".select2-result")).mouseup(); - - const selected = document.querySelectorAll(".select2-search-choice"); - expect(selected.length).toBe(2); - expect(selected[0].textContent.trim()).toBe("apple"); - expect(selected[1].textContent.trim()).toBe("orange"); - expect(input.value).toBe("apple;orange"); - }); - - it("2.7.3 - use a custom separator and pre-fill with json.", async function () { - document.body.innerHTML = ` - - `; - - const input = document.querySelector("input"); - new pattern(input); - await utils.timeout(1); // wait a tick for async to settle. - - let selected = document.querySelectorAll(".select2-search-choice"); - expect(selected.length).toBe(2); - expect(selected[0].textContent.trim()).toBe("Orange"); - expect(selected[1].textContent.trim()).toBe("Lemon"); - expect(input.value).toBe("id-orange;id-lemon"); - }); - - it("2.7.4 - use a custom separator and pre-fill.", async function () { - document.body.innerHTML = ` - - `; - - const input = document.querySelector("input"); - new pattern(input); - await utils.timeout(1); // wait a tick for async to settle. - - let selected = document.querySelectorAll(".select2-search-choice"); - expect(selected.length).toBe(2); - expect(selected[0].textContent.trim()).toBe("id-orange"); - expect(selected[1].textContent.trim()).toBe("id-lemon"); - expect(input.value).toBe("id-orange;id-lemon"); - }); - - it("2.7.5 - use a custom separator and pre-fill with the value attribute.", async function () { - document.body.innerHTML = ` - - `; - - const input = document.querySelector("input"); - new pattern(input); - await utils.timeout(1); // wait a tick for async to settle. - - let selected = document.querySelectorAll(".select2-search-choice"); - expect(selected.length).toBe(2); - expect(selected[0].textContent.trim()).toBe("id-orange"); - expect(selected[1].textContent.trim()).toBe("id-lemon"); - expect(input.value).toBe("id-orange;id-lemon"); - }); - }); - - describe("3 - Placeholder tests", function () { - it("3.1 - A placeholder on the original element is reused on the auto-suggest element", async function () { - var placeholder = "Test placeholder"; - - $("", { - id: "select2", - class: "pat-autosuggest", - placeholder: "Test placeholder", - }).appendTo($("div#lab")); - - var $el = $("input.pat-autosuggest"); - - expect($el.prop("placeholder")).toBe(placeholder); - pattern.init($el); - await utils.timeout(1); // wait a tick for async to settle. - // XXX Placeholder is used as value of the input field. - // Change this as soon Select2 changes this odd behavior. - expect($(".select2-input").val()).toBe(placeholder); - testutils.removeSelect2(); - }); - - it("3.2 - No placeholder doesn't create an automatic one.", async function () { - $("", { - id: "select2", - class: "pat-autosuggest", - }).appendTo($("div#lab")); - - var $el = $("input.pat-autosuggest"); - - expect($el.prop("placeholder")).toBe(""); - pattern.init($el); - await utils.timeout(1); // wait a tick for async to settle. - // XXX Placeholder is used as value of the input field. - // Change this as soon Select2 changes this odd behavior. - expect($(".select2-input").val()).toBe(""); - testutils.removeSelect2(); - }); - }); - - describe("4 - Integration...", function () { - it("4.1 - Works with pat-auto-submit", async function () { - document.body.innerHTML = ` -
    - -
    - `; - - const pattern_autosubmit = (await import("../auto-submit/auto-submit")).default; // prettier-ignore - const input = document.querySelector("input"); - - let submit_dispatched = false; - document.querySelector("form").addEventListener("submit", () => { - submit_dispatched = true; - }); - - new pattern(input); - new pattern_autosubmit(input); - - await utils.timeout(1); // wait a tick for async to settle. - - $(".select2-input").click(); - $(document.querySelector(".select2-result")).mouseup(); - - expect(submit_dispatched).toBe(true); - }); - - it("4.2 - Works with pat-validate on an empty selection.", async function () { - const pattern_validation = (await import("../validation/validation")).default; // prettier-ignore - - document.body.innerHTML = ` -
    - -
    - `; - - const form = document.querySelector("form"); - const input = document.querySelector("input"); - - const instance_validation = new pattern_validation(form); - await events.await_pattern_init(instance_validation); - new pattern(input); - await utils.timeout(1); // wait a tick for async to settle. - - // Open the select2 dropdown - $(".select2-input").click(); - await utils.timeout(1); // wait a tick for async to settle. - - // Close it without selecting something. - $(input).select2("close"); - - await utils.timeout(1); // wait a tick for async to settle. - - // There should be a error message from pat-validation. - expect(form.querySelectorAll("em.warning").length).toBe(1); - }); - - it("4.3 - Works with pat-validate when empty and focus moves away.", async function () { - const pattern_validation = (await import("../validation/validation")).default; // prettier-ignore - - document.body.innerHTML = ` -
    - -
    - `; - - const form = document.querySelector("form"); - const input = document.querySelector("input"); - - const instance_validation = new pattern_validation(form); - await events.await_pattern_init(instance_validation); - new pattern(input); - await utils.timeout(1); // wait a tick for async to settle. - - // Move focus away from select2 - $(".select2-input")[0].dispatchEvent(events.blur_event()); - await utils.timeout(1); // wait a tick for async to settle. - - // There should be a error message from pat-validation. - expect(form.querySelectorAll("em.warning").length).toBe(1); - }); - }); - - describe("5 - Pittfalls...", function () { - it("5.1 - BEWARE! JSON structures must be valid JSON!", async function () { - // The following contains invalid JSON. Note the comma after the last prefill item. - document.body.innerHTML = ` - - `; - - const input = document.querySelector("input"); - new pattern(input); - await utils.timeout(1); // wait a tick for async to settle. - - let selected = document.querySelectorAll(".select2-search-choice"); - - // INVALID JSON! No prefilling should happen. - expect(selected.length).toBe(0); - }); - }); - - describe("6 - AJAX tests", function () { - it("6.1 - AJAX works with a simple data structure.", async function () { - mock_fetch_ajax( - [ - { id: "1", text: "apple" }, - { id: "2", text: "orange" }, - ] // Note the trailing comma to make the multi-argument dereferencing work. - ); - - document.body.innerHTML = ` - - `; - - const input = document.querySelector("input"); - new pattern(input); - await utils.timeout(1); // wait a tick for async to settle. - - $(".select2-input").click(); - await utils.timeout(1); // wait for ajax to finish. - - const results = $(document.querySelectorAll(".select2-results li")); - expect(results.length).toBe(2); - - $(results[0]).mouseup(); - - const selected = document.querySelectorAll(".select2-search-choice"); - expect(selected.length).toBe(1); - expect(selected[0].textContent.trim()).toBe("apple"); - expect(input.value).toBe("1"); - }); - - // This test is so flaky, just skip it if it fails. - it.skip.failing("6.2 - AJAX works with batches.", async function () { - mock_fetch_ajax( - [ - { id: "1", text: "one" }, - { id: "2", text: "two" }, - { id: "3", text: "three" }, - { id: "4", text: "four" }, - ], - [ - { id: "5", text: "five" }, - { id: "6", text: "six" }, - ], - [{ id: "7", text: "seven" }] - ); - - document.body.innerHTML = ` - - `; - - const input = document.querySelector("input"); - new pattern(input); - await utils.timeout(1); // wait a tick for async to settle. - - // Load batch 1 with batch size 4 - $(".select2-input").click(); - await utils.timeout(1); // wait for ajax to finish. - - const results_1 = $( - document.querySelectorAll(".select2-results .select2-result") - ); - expect(results_1.length).toBe(4); - - const load_more_1 = $( - document.querySelectorAll(".select2-results .select2-more-results") - ); - expect(load_more_1.length).toBe(1); - - // Load batch 2 with batch size 2 - $(load_more_1[0]).mouseup(); - // NOTE: Flaky behavior needs multiple timeouts 👌 - await utils.timeout(1); // wait for ajax to finish. - await utils.timeout(1); // wait for ajax to finish. - await utils.timeout(1); // wait for ajax to finish. - await utils.timeout(1); // wait for ajax to finish. - - const results_2 = $( - document.querySelectorAll(".select2-results .select2-result") - ); - expect(results_2.length).toBe(6); - - const load_more_2 = $( - document.querySelectorAll(".select2-results .select2-more-results") - ); - expect(load_more_2.length).toBe(1); - - // Load final batch 2 - $(load_more_2[0]).mouseup(); - // NOTE: Flaky behavior needs multiple timeouts 🤘 - await utils.timeout(1); // wait for ajax to finish. - await utils.timeout(1); // wait for ajax to finish. - await utils.timeout(1); // wait for ajax to finish. - await utils.timeout(1); // wait for ajax to finish. - - const results_3 = $( - document.querySelectorAll(".select2-results .select2-result") - ); - expect(results_3.length).toBe(7); - - const load_more_3 = $( - document.querySelectorAll(".select2-results .select2-more-results") - ); - expect(load_more_3.length).toBe(0); - }); - - describe("6.3 - Test the page_limit logic.", function () { - - it("6.3.1 - page_limit set only by ajax-batch-size.", async function () { - document.body.innerHTML = ` - - `; - - const input = document.querySelector("input"); - const instance = new pattern(input); - await utils.timeout(1); // wait a tick for async to settle. - - expect(instance.page_limit(1)).toBe(10); - expect(instance.page_limit(2)).toBe(2); - }); - - it("6.3.2 - page_limit set by ajax-batch-size and max-initial-size.", async function () { - document.body.innerHTML = ` - - `; - - const input = document.querySelector("input"); - const instance = new pattern(input); - await utils.timeout(1); // wait a tick for async to settle. - - expect(instance.page_limit(1)).toBe(4); - expect(instance.page_limit(2)).toBe(2); - }); - - it("6.3.3 - page_limit set only by max-initial-size and batching not activated.", async function () { - document.body.innerHTML = ` - - `; - - const input = document.querySelector("input"); - const instance = new pattern(input); - await utils.timeout(1); // wait a tick for async to settle. - - expect(instance.page_limit(1)).toBe(4); - expect(instance.page_limit(2)).toBe(0); - }); - - }); + it("loads the implementation.", async function () { + expect(await Pattern.load()).toBe(Implementation); }); }); diff --git a/src/pat/breadcrumbs/breadcrumbs.js b/src/pat/breadcrumbs/breadcrumbs.js index 2e24b063e..1a9bb9133 100644 --- a/src/pat/breadcrumbs/breadcrumbs.js +++ b/src/pat/breadcrumbs/breadcrumbs.js @@ -6,33 +6,33 @@ */ import $ from "jquery"; +import { BasePattern } from "../../core/basepattern"; import registry from "../../core/registry"; -var _ = { - name: "breadcrumbs", - trigger: "nav.pat-breadcrumbs", - init: function ($el, opts) { - if ($el.length > 1) { - return $el.map(function () { - return _.init($(this), opts); - }); - } +class Pattern extends BasePattern { + static name = "breadcrumbs"; + static trigger = "nav.pat-breadcrumbs"; + + init() { + const $el = (this.$el = $(this.el)); // wrap elements in a DIV that will be shifted around - var $content = $el + const $content = (this.$content = $el .children() .wrapAll("
    ") - .parent(); + .parent()); // shift ctrl - var $ctrl = $("shift").prependTo($el); + const $ctrl = (this.$ctrl = $("shift").prependTo( + $el + )); - var shifted = false, - shifting = false, - difference = 0; - var shifter = function (toggle) { + let shifted = false; + let shifting = false; + let difference = 0; + const shifter = function (toggle) { return function () { - var margin; + let margin; if (toggle) { margin = shifted ? 0 : difference; $content.animate({ "margin-left": margin }, function () { @@ -46,7 +46,7 @@ var _ = { }; }; - var maybeshift = function () { + const maybeshift = function () { // account for other stuff on the same line (100px) difference = $el.innerWidth() - $content.width() - 100; @@ -76,11 +76,11 @@ var _ = { } } }; - $(window).on("resize.pat-breadcrumbs", maybeshift); + this.add_event_listener(window, "resize", "maybeshift", maybeshift); - var recalculate = function () { + const recalculate = function () { // set fixed width on content - var width = $content + const width = $content .children() .toArray() .reduce(function (acc, el) { @@ -94,13 +94,20 @@ var _ = { }; $el.on("pat-breadcrumbs-changed.pat-breadcrumbs", recalculate); recalculate(); + } - return $el; - }, - destroy: function ($el) { - $el.off(".pat-breadcrumbs"); - }, -}; -registry.register(_); + destroy() { + if (this.$el) { + // Only clean up, if the pattern was initialized. + this.$el.off(".pat-breadcrumbs"); + this.$ctrl.off(".pat-breadcrumbs"); + // Stop running animations, so that their callbacks are not run. + this.$content.stop(true); + } + super.destroy(); + } +} -export default _; +registry.register(Pattern); +export default Pattern; +export { Pattern }; diff --git a/src/pat/breadcrumbs/breadcrumbs.test.js b/src/pat/breadcrumbs/breadcrumbs.test.js new file mode 100644 index 000000000..73c8a001b --- /dev/null +++ b/src/pat/breadcrumbs/breadcrumbs.test.js @@ -0,0 +1,123 @@ +import $ from "jquery"; +import events from "../../core/events"; +import Pattern from "./breadcrumbs"; +import utils from "../../core/utils"; +import { jest } from "@jest/globals"; + +describe("pat-breadcrumbs", function () { + beforeEach(function () { + // Disable jQuery animations. + $.fx.off = true; + }); + + afterEach(function () { + document.body.innerHTML = ""; + $.fx.off = false; + jest.restoreAllMocks(); + }); + + it("1 - Wraps the content and adds a shift control.", async function () { + document.body.innerHTML = ` + + `; + const pattern_el = document.querySelector(".pat-breadcrumbs"); + const instance = new Pattern(pattern_el); + await events.await_pattern_init(instance); + + const content = pattern_el.querySelector(".pat-breadcrumbs-content"); + expect(content).toBeTruthy(); + expect(content.querySelectorAll("a").length).toBe(2); + // In jsDOM the elements do not have any width. Each child adds a + // buffer of 5px. + expect(content.style.width).toBe("10px"); + + const ctrl = pattern_el.querySelector(".button.shift"); + expect(ctrl).toBeTruthy(); + expect(pattern_el.firstElementChild).toBe(ctrl); + + // The content is wider than the available space (-100px). + expect(pattern_el.classList.contains("shifting")).toBe(true); + }); + + it("2 - Recalculates the width on pat-breadcrumbs-changed.", async function () { + document.body.innerHTML = ` + + `; + const pattern_el = document.querySelector(".pat-breadcrumbs"); + const instance = new Pattern(pattern_el); + await events.await_pattern_init(instance); + + const content = pattern_el.querySelector(".pat-breadcrumbs-content"); + expect(content.style.width).toBe("5px"); + + content.append(document.createElement("a")); + $(pattern_el).trigger("pat-breadcrumbs-changed"); + expect(content.style.width).toBe("10px"); + }); + + it("3 - Recalculates the shifting on window resize.", async function () { + document.body.innerHTML = ` + + `; + const pattern_el = document.querySelector(".pat-breadcrumbs"); + const instance = new Pattern(pattern_el); + await events.await_pattern_init(instance); + + expect(pattern_el.classList.contains("shifting")).toBe(true); + + // Make enough space available. + jest.spyOn($.fn, "innerWidth").mockImplementation(() => 1000); + window.dispatchEvent(new Event("resize")); + expect(pattern_el.classList.contains("shifting")).toBe(false); + }); + + describe("4 - Destroy", function () { + it("4.1 - removes the event listeners.", async function () { + document.body.innerHTML = ` + + `; + const pattern_el = document.querySelector(".pat-breadcrumbs"); + const instance = new Pattern(pattern_el); + await events.await_pattern_init(instance); + + instance.destroy(); + expect(pattern_el["pattern-breadcrumbs"]).toBeUndefined(); + + const spy_inner_width = jest.spyOn($.fn, "innerWidth"); + window.dispatchEvent(new Event("resize")); + $(pattern_el).trigger("pat-breadcrumbs-changed"); + expect(spy_inner_width).not.toHaveBeenCalled(); + + const ctrl = pattern_el.querySelector(".button.shift"); + expect($._data(ctrl, "events")).toBeUndefined(); + }); + + it("4.2 - is destroyed when the element is removed from the DOM.", async function () { + document.body.innerHTML = ` + + `; + const pattern_el = document.querySelector(".pat-breadcrumbs"); + const instance = new Pattern(pattern_el); + await events.await_pattern_init(instance); + + const spy_inner_width = jest.spyOn($.fn, "innerWidth"); + pattern_el.remove(); + await utils.timeout(1); + expect(instance.destroyed).toBe(true); + + window.dispatchEvent(new Event("resize")); + expect(spy_inner_width).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/src/pat/bumper/bumper--implementation.js b/src/pat/bumper/bumper--implementation.js new file mode 100644 index 000000000..e868612f0 --- /dev/null +++ b/src/pat/bumper/bumper--implementation.js @@ -0,0 +1,214 @@ +import { BasePattern } from "@patternslib/patternslib/src/core/basepattern"; +import dom from "../../core/dom"; +import Parser from "../../core/parser"; +import registry from "../../core/registry"; +import utils from "../../core/utils"; + +export const parser = new Parser("bumper"); +parser.addArgument("selector"); +parser.addArgument("bump-add", "bumped"); +parser.addArgument("bump-remove"); +parser.addArgument("unbump-add"); +parser.addArgument("unbump-remove", "bumped"); + +class Pattern extends BasePattern { + static name = "bumper"; + static trigger = ".pat-bumper"; + static parser = parser; + ticking = false; + + async init() { + this.target_element = this.options.selector + ? document.querySelector(this.options.selector) + : this.el; + + // wait for next repaint for things to settle. + // e.g. CSS applied for injected content. + await utils.timeout(1); + + const parent_el = this.el.parentElement; + this.container_x = dom.find_scroll_container(parent_el, "x", null); + this.container_y = dom.find_scroll_container(parent_el, "y", null); + + const containers = new Set([this.container_x, this.container_y]); + for (const container of containers) { + // Scoped to this instance - multiple bumpers can share the same + // scroll container. + this.add_event_listener( + container || document, + "scroll", + "scroll", + async () => { + if (!this.ticking) { + this.ticking = true; + await utils.animation_frame(); + this.set_bumping_classes(); + this.ticking = false; + } + } + ); + } + this.set_bumping_classes(); + } + + /** + * Get the container position values. + * + * @param {DOMElement} container - The container element. + * @param {Objcet} dimensions - The dimension Object of the container, + * which were initialized in the init method. + * + * @returns {Object} The position values. + */ + _get_container_positions(container) { + if (!container) { + // No container = viewport as scrolling container + return { + top: 0, + right: document.documentElement.clientWidth, + bottom: document.documentElement.clientHeight, + left: 0, + }; + } + + // Bounds are dynamic, so we cannot cache them. + const bounds = container.getBoundingClientRect(); + + // Container dimensions + const dimensions = { + border_top_width: dom.get_css_value(container, "border-top-width", true), + border_left_width: dom.get_css_value(container, "border-left-width", true), + padding_top: dom.get_css_value(container, "padding-top", true), + padding_right: dom.get_css_value(container, "padding-right", true), + padding_bottom: dom.get_css_value(container, "padding-bottom", true), + padding_left: dom.get_css_value(container, "padding-left", true), + }; + + const left = + bounds.left + + dimensions.border_left_width + + dimensions.padding_left; // prettier-ignore + const top = + bounds.top + + dimensions.border_top_width + + dimensions.padding_top; // prettier-ignore + + const right = + bounds.left + + dimensions.border_left_width + + container.clientWidth - + dimensions.padding_right; + + const bottom = + bounds.top + + dimensions.border_top_width + + container.clientHeight - + dimensions.padding_bottom; + + return { + top: Math.round(top), + right: Math.round(right), + bottom: Math.round(bottom), + left: Math.round(left), + }; + } + + /** + * Get the element position values. + * + * @returns {Object} The position values. + */ + _get_element_positions() { + const bounds = this.el.getBoundingClientRect(); + + // Element positions + const positions = { + top: dom.get_css_value(this.el, "top", true), + right: dom.get_css_value(this.el, "right", true), + bottom: dom.get_css_value(this.el, "bottom", true), + left: dom.get_css_value(this.el, "left", true), + }; + + return { + top: Math.round(bounds.top - positions.top), + right: Math.round(bounds.right + positions.right), + bottom: Math.round(bounds.bottom + positions.bottom), + left: Math.round(bounds.left - positions.left), + }; + } + + /** + * Get the bumping state of the element. + * + * @returns {Object} The bumping state. + */ + get_bumping_state() { + const pos_el = this._get_element_positions(); + const pos_x = this._get_container_positions(this.container_x); + const pos_y = + this.container_x === this.container_y + ? pos_x + : this._get_container_positions(this.container_y); + + const bump_top = pos_el.top <= pos_y.top && pos_el.bottom >= pos_y.top; + const bump_right = pos_el.right >= pos_x.right && pos_el.left <= pos_x.right; + const bump_bottom = pos_el.bottom >= pos_y.bottom && pos_el.top <= pos_y.bottom; + const bump_left = pos_el.left <= pos_x.left && pos_el.right >= pos_x.left; + + const is_bumping = bump_top || bump_right || bump_bottom || bump_left; + + return { + bump_top, + bump_right, + bump_bottom, + bump_left, + is_bumping, + }; + } + + /** + * Set the bumping classes on the element. + */ + set_bumping_classes() { + const bumping_state = this.get_bumping_state(); + + const classes_to_add = []; + const classes_to_remove = []; + + if (bumping_state.is_bumping) { + this.options.bump.add && classes_to_add.push(this.options.bump.add); + this.options.bump.remove && classes_to_remove.push(this.options.bump.remove); + + bumping_state.bump_top + ? classes_to_add.push("bumped-top") + : classes_to_remove.push("bumped-top"); + bumping_state.bump_right + ? classes_to_add.push("bumped-right") + : classes_to_remove.push("bumped-right"); + bumping_state.bump_bottom + ? classes_to_add.push("bumped-bottom") + : classes_to_remove.push("bumped-bottom"); + bumping_state.bump_left + ? classes_to_add.push("bumped-left") + : classes_to_remove.push("bumped-left"); + } else { + this.options.unbump.add && classes_to_add.push(this.options.unbump.add); + this.options.unbump.remove && + classes_to_remove.push(this.options.unbump.remove); + classes_to_remove.push( + "bumped-top", + "bumped-right", + "bumped-bottom", + "bumped-left" + ); + } + + this.el.classList.remove(...classes_to_remove); + this.el.classList.add(...classes_to_add); + } +} + +registry.register(Pattern); + +export default Pattern; +export { Pattern }; diff --git a/src/pat/bumper/bumper--implementation.test.js b/src/pat/bumper/bumper--implementation.test.js new file mode 100644 index 000000000..6d59618a6 --- /dev/null +++ b/src/pat/bumper/bumper--implementation.test.js @@ -0,0 +1,201 @@ +import Bumper from "./bumper--implementation"; +import events from "../../core/events"; +import utils from "../../core/utils"; +import { jest } from "@jest/globals"; + +describe("pat-bumper", function () { + beforeEach(function () { + document.body.innerHTML = ""; + }); + + describe("Set bumping classes when bumping", function () { + it("against the viewport.", async function () { + document.body.innerHTML = ` +
    + `; + + const el = document.getElementById("bump"); + + // Viewport mocks + Object.defineProperty(document.documentElement, "clientHeight", { + value: 100, + writable: false, + }); + Object.defineProperty(document.documentElement, "clientWidth", { + value: 100, + writable: false, + }); + + // Element mocks + const el_bounds = { top: 40, right: 40, bottom: 40, left: 40 }; + jest.spyOn(el, "getBoundingClientRect").mockImplementation(() => el_bounds); + + const instance = new Bumper(el); + await events.await_pattern_init(instance); + + el.dispatchEvent(events.scroll_event()); + await utils.animation_frame(); + + expect(el.classList.contains("bumped")).toBe(false); + expect(el.classList.contains("bumped-top")).toBe(false); + expect(el.classList.contains("bumped-right")).toBe(false); + expect(el.classList.contains("bumped-bottom")).toBe(false); + expect(el.classList.contains("bumped-left")).toBe(false); + + // Scroll to top, update getBoundingClientRect. + Object.assign(el_bounds, { top: 0, right: 40, bottom: 80, left: 40 }); + el.dispatchEvent(events.scroll_event()); + await utils.animation_frame(); + + expect(el.classList.contains("bumped")).toBe(true); + expect(el.classList.contains("bumped-top")).toBe(true); + expect(el.classList.contains("bumped-right")).toBe(false); + expect(el.classList.contains("bumped-bottom")).toBe(false); + expect(el.classList.contains("bumped-left")).toBe(false); + + // Scroll to top-right, update getBoundingClientRect. + Object.assign(el_bounds, { top: 0, right: 100, bottom: 80, left: 80 }); + + el.dispatchEvent(events.scroll_event()); + await utils.animation_frame(); + + expect(el.classList.contains("bumped")).toBe(true); + expect(el.classList.contains("bumped-top")).toBe(true); + expect(el.classList.contains("bumped-right")).toBe(true); + expect(el.classList.contains("bumped-bottom")).toBe(false); + expect(el.classList.contains("bumped-left")).toBe(false); + + // Scroll to right, update getBoundingClientRect. + Object.assign(el_bounds, { top: 40, right: 100, bottom: 40, left: 80 }); + el.dispatchEvent(events.scroll_event()); + await utils.animation_frame(); + + expect(el.classList.contains("bumped")).toBe(true); + expect(el.classList.contains("bumped-top")).toBe(false); + expect(el.classList.contains("bumped-right")).toBe(true); + expect(el.classList.contains("bumped-bottom")).toBe(false); + expect(el.classList.contains("bumped-left")).toBe(false); + + // Scroll to bottom-right, update getBoundingClientRect. + Object.assign(el_bounds, { top: 80, right: 100, bottom: 100, left: 80 }); + el.dispatchEvent(events.scroll_event()); + await utils.animation_frame(); + + expect(el.classList.contains("bumped")).toBe(true); + expect(el.classList.contains("bumped-top")).toBe(false); + expect(el.classList.contains("bumped-right")).toBe(true); + expect(el.classList.contains("bumped-bottom")).toBe(true); + expect(el.classList.contains("bumped-left")).toBe(false); + + // Scroll to bottom, update getBoundingClientRect. + Object.assign(el_bounds, { top: 80, right: 40, bottom: 100, left: 40 }); + el.dispatchEvent(events.scroll_event()); + await utils.animation_frame(); + + expect(el.classList.contains("bumped")).toBe(true); + expect(el.classList.contains("bumped-top")).toBe(false); + expect(el.classList.contains("bumped-right")).toBe(false); + expect(el.classList.contains("bumped-bottom")).toBe(true); + expect(el.classList.contains("bumped-left")).toBe(false); + + // Scroll to bottom-left, update getBoundingClientRect. + Object.assign(el_bounds, { top: 80, right: 80, bottom: 100, left: 0 }); + el.dispatchEvent(events.scroll_event()); + await utils.animation_frame(); + + expect(el.classList.contains("bumped")).toBe(true); + expect(el.classList.contains("bumped-top")).toBe(false); + expect(el.classList.contains("bumped-right")).toBe(false); + expect(el.classList.contains("bumped-bottom")).toBe(true); + expect(el.classList.contains("bumped-left")).toBe(true); + + // Scroll to left, update getBoundingClientRect. + Object.assign(el_bounds, { top: 40, right: 80, bottom: 40, left: 0 }); + el.dispatchEvent(events.scroll_event()); + await utils.animation_frame(); + + expect(el.classList.contains("bumped")).toBe(true); + expect(el.classList.contains("bumped-top")).toBe(false); + expect(el.classList.contains("bumped-right")).toBe(false); + expect(el.classList.contains("bumped-bottom")).toBe(false); + expect(el.classList.contains("bumped-left")).toBe(true); + + // Scroll to top-left, update getBoundingClientRect. + Object.assign(el_bounds, { top: 0, right: 80, bottom: 80, left: 0 }); + el.dispatchEvent(events.scroll_event()); + await utils.animation_frame(); + + expect(el.classList.contains("bumped")).toBe(true); + expect(el.classList.contains("bumped-top")).toBe(true); + expect(el.classList.contains("bumped-right")).toBe(false); + expect(el.classList.contains("bumped-bottom")).toBe(false); + expect(el.classList.contains("bumped-left")).toBe(true); + + // Scroll to top, update getBoundingClientRect. + Object.assign(el_bounds, { top: 0, right: 40, bottom: 80, left: 40 }); + el.dispatchEvent(events.scroll_event()); + await utils.animation_frame(); + + expect(el.classList.contains("bumped")).toBe(true); + expect(el.classList.contains("bumped-top")).toBe(true); + expect(el.classList.contains("bumped-right")).toBe(false); + expect(el.classList.contains("bumped-bottom")).toBe(false); + expect(el.classList.contains("bumped-left")).toBe(false); + + // Scroll to middle, update getBoundingClientRect. + Object.assign(el_bounds, { top: 40, right: 40, bottom: 40, left: 40 }); + el.dispatchEvent(events.scroll_event()); + await utils.animation_frame(); + + expect(el.classList.contains("bumped")).toBe(false); + expect(el.classList.contains("bumped-top")).toBe(false); + expect(el.classList.contains("bumped-right")).toBe(false); + expect(el.classList.contains("bumped-bottom")).toBe(false); + expect(el.classList.contains("bumped-left")).toBe(false); + }); + }); + + describe("Scroll listeners", function () { + it("Multiple bumpers in the same scroll container are all updated.", async function () { + document.body.innerHTML = ` +
    +
    + `; + const instance1 = new Bumper(document.getElementById("bump1")); + const instance2 = new Bumper(document.getElementById("bump2")); + await events.await_pattern_init(instance1); + await events.await_pattern_init(instance2); + + const spy1 = jest.spyOn(instance1, "set_bumping_classes"); + const spy2 = jest.spyOn(instance2, "set_bumping_classes"); + + document.dispatchEvent(events.scroll_event()); + await utils.animation_frame(); + + expect(spy1).toHaveBeenCalledTimes(1); + expect(spy2).toHaveBeenCalledTimes(1); + }); + + it("The scroll listener is removed on destroy.", async function () { + document.body.innerHTML = ` +
    + `; + const el = document.getElementById("bump1"); + const instance = new Bumper(el); + await events.await_pattern_init(instance); + + const spy = jest.spyOn(instance, "set_bumping_classes"); + + el.remove(); + await utils.timeout(1); + expect(instance.destroyed).toBe(true); + + document.dispatchEvent(events.scroll_event()); + await utils.animation_frame(); + + expect(spy).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/src/pat/bumper/bumper.js b/src/pat/bumper/bumper.js index e868612f0..fc982ceef 100644 --- a/src/pat/bumper/bumper.js +++ b/src/pat/bumper/bumper.js @@ -1,214 +1,20 @@ -import { BasePattern } from "@patternslib/patternslib/src/core/basepattern"; -import dom from "../../core/dom"; -import Parser from "../../core/parser"; +/** + * pat-bumper registration module. + * + * The pattern implementation is loaded lazily when the pattern is used for + * the first time. Import the implementation module to use the pattern class + * or its parser directly: + * ./bumper--implementation.js + */ +import create_lazy_pattern from "../../core/lazy-pattern"; import registry from "../../core/registry"; -import utils from "../../core/utils"; -export const parser = new Parser("bumper"); -parser.addArgument("selector"); -parser.addArgument("bump-add", "bumped"); -parser.addArgument("bump-remove"); -parser.addArgument("unbump-add"); -parser.addArgument("unbump-remove", "bumped"); - -class Pattern extends BasePattern { - static name = "bumper"; - static trigger = ".pat-bumper"; - static parser = parser; - ticking = false; - - async init() { - this.target_element = this.options.selector - ? document.querySelector(this.options.selector) - : this.el; - - // wait for next repaint for things to settle. - // e.g. CSS applied for injected content. - await utils.timeout(1); - - const parent_el = this.el.parentElement; - this.container_x = dom.find_scroll_container(parent_el, "x", null); - this.container_y = dom.find_scroll_container(parent_el, "y", null); - - const containers = new Set([this.container_x, this.container_y]); - for (const container of containers) { - // Scoped to this instance - multiple bumpers can share the same - // scroll container. - this.add_event_listener( - container || document, - "scroll", - "scroll", - async () => { - if (!this.ticking) { - this.ticking = true; - await utils.animation_frame(); - this.set_bumping_classes(); - this.ticking = false; - } - } - ); - } - this.set_bumping_classes(); - } - - /** - * Get the container position values. - * - * @param {DOMElement} container - The container element. - * @param {Objcet} dimensions - The dimension Object of the container, - * which were initialized in the init method. - * - * @returns {Object} The position values. - */ - _get_container_positions(container) { - if (!container) { - // No container = viewport as scrolling container - return { - top: 0, - right: document.documentElement.clientWidth, - bottom: document.documentElement.clientHeight, - left: 0, - }; - } - - // Bounds are dynamic, so we cannot cache them. - const bounds = container.getBoundingClientRect(); - - // Container dimensions - const dimensions = { - border_top_width: dom.get_css_value(container, "border-top-width", true), - border_left_width: dom.get_css_value(container, "border-left-width", true), - padding_top: dom.get_css_value(container, "padding-top", true), - padding_right: dom.get_css_value(container, "padding-right", true), - padding_bottom: dom.get_css_value(container, "padding-bottom", true), - padding_left: dom.get_css_value(container, "padding-left", true), - }; - - const left = - bounds.left + - dimensions.border_left_width + - dimensions.padding_left; // prettier-ignore - const top = - bounds.top + - dimensions.border_top_width + - dimensions.padding_top; // prettier-ignore - - const right = - bounds.left + - dimensions.border_left_width + - container.clientWidth - - dimensions.padding_right; - - const bottom = - bounds.top + - dimensions.border_top_width + - container.clientHeight - - dimensions.padding_bottom; - - return { - top: Math.round(top), - right: Math.round(right), - bottom: Math.round(bottom), - left: Math.round(left), - }; - } - - /** - * Get the element position values. - * - * @returns {Object} The position values. - */ - _get_element_positions() { - const bounds = this.el.getBoundingClientRect(); - - // Element positions - const positions = { - top: dom.get_css_value(this.el, "top", true), - right: dom.get_css_value(this.el, "right", true), - bottom: dom.get_css_value(this.el, "bottom", true), - left: dom.get_css_value(this.el, "left", true), - }; - - return { - top: Math.round(bounds.top - positions.top), - right: Math.round(bounds.right + positions.right), - bottom: Math.round(bounds.bottom + positions.bottom), - left: Math.round(bounds.left - positions.left), - }; - } - - /** - * Get the bumping state of the element. - * - * @returns {Object} The bumping state. - */ - get_bumping_state() { - const pos_el = this._get_element_positions(); - const pos_x = this._get_container_positions(this.container_x); - const pos_y = - this.container_x === this.container_y - ? pos_x - : this._get_container_positions(this.container_y); - - const bump_top = pos_el.top <= pos_y.top && pos_el.bottom >= pos_y.top; - const bump_right = pos_el.right >= pos_x.right && pos_el.left <= pos_x.right; - const bump_bottom = pos_el.bottom >= pos_y.bottom && pos_el.top <= pos_y.bottom; - const bump_left = pos_el.left <= pos_x.left && pos_el.right >= pos_x.left; - - const is_bumping = bump_top || bump_right || bump_bottom || bump_left; - - return { - bump_top, - bump_right, - bump_bottom, - bump_left, - is_bumping, - }; - } - - /** - * Set the bumping classes on the element. - */ - set_bumping_classes() { - const bumping_state = this.get_bumping_state(); - - const classes_to_add = []; - const classes_to_remove = []; - - if (bumping_state.is_bumping) { - this.options.bump.add && classes_to_add.push(this.options.bump.add); - this.options.bump.remove && classes_to_remove.push(this.options.bump.remove); - - bumping_state.bump_top - ? classes_to_add.push("bumped-top") - : classes_to_remove.push("bumped-top"); - bumping_state.bump_right - ? classes_to_add.push("bumped-right") - : classes_to_remove.push("bumped-right"); - bumping_state.bump_bottom - ? classes_to_add.push("bumped-bottom") - : classes_to_remove.push("bumped-bottom"); - bumping_state.bump_left - ? classes_to_add.push("bumped-left") - : classes_to_remove.push("bumped-left"); - } else { - this.options.unbump.add && classes_to_add.push(this.options.unbump.add); - this.options.unbump.remove && - classes_to_remove.push(this.options.unbump.remove); - classes_to_remove.push( - "bumped-top", - "bumped-right", - "bumped-bottom", - "bumped-left" - ); - } - - this.el.classList.remove(...classes_to_remove); - this.el.classList.add(...classes_to_add); - } -} +const Pattern = create_lazy_pattern({ + name: "bumper", + trigger: ".pat-bumper", + load: () => import("./bumper--implementation"), +}); registry.register(Pattern); - export default Pattern; export { Pattern }; diff --git a/src/pat/bumper/bumper.test.js b/src/pat/bumper/bumper.test.js index a9b090278..7e04bccd5 100644 --- a/src/pat/bumper/bumper.test.js +++ b/src/pat/bumper/bumper.test.js @@ -1,201 +1,15 @@ -import Bumper from "./bumper"; -import events from "../../core/events"; -import utils from "../../core/utils"; -import { jest } from "@jest/globals"; - -describe("pat-bumper", function () { - beforeEach(function () { - document.body.innerHTML = ""; - }); - - describe("Set bumping classes when bumping", function () { - it("against the viewport.", async function () { - document.body.innerHTML = ` -
    - `; - - const el = document.getElementById("bump"); - - // Viewport mocks - Object.defineProperty(document.documentElement, "clientHeight", { - value: 100, - writable: false, - }); - Object.defineProperty(document.documentElement, "clientWidth", { - value: 100, - writable: false, - }); - - // Element mocks - const el_bounds = { top: 40, right: 40, bottom: 40, left: 40 }; - jest.spyOn(el, "getBoundingClientRect").mockImplementation(() => el_bounds); - - const instance = new Bumper(el); - await events.await_pattern_init(instance); - - el.dispatchEvent(events.scroll_event()); - await utils.animation_frame(); - - expect(el.classList.contains("bumped")).toBe(false); - expect(el.classList.contains("bumped-top")).toBe(false); - expect(el.classList.contains("bumped-right")).toBe(false); - expect(el.classList.contains("bumped-bottom")).toBe(false); - expect(el.classList.contains("bumped-left")).toBe(false); - - // Scroll to top, update getBoundingClientRect. - Object.assign(el_bounds, { top: 0, right: 40, bottom: 80, left: 40 }); - el.dispatchEvent(events.scroll_event()); - await utils.animation_frame(); - - expect(el.classList.contains("bumped")).toBe(true); - expect(el.classList.contains("bumped-top")).toBe(true); - expect(el.classList.contains("bumped-right")).toBe(false); - expect(el.classList.contains("bumped-bottom")).toBe(false); - expect(el.classList.contains("bumped-left")).toBe(false); - - // Scroll to top-right, update getBoundingClientRect. - Object.assign(el_bounds, { top: 0, right: 100, bottom: 80, left: 80 }); - - el.dispatchEvent(events.scroll_event()); - await utils.animation_frame(); - - expect(el.classList.contains("bumped")).toBe(true); - expect(el.classList.contains("bumped-top")).toBe(true); - expect(el.classList.contains("bumped-right")).toBe(true); - expect(el.classList.contains("bumped-bottom")).toBe(false); - expect(el.classList.contains("bumped-left")).toBe(false); - - // Scroll to right, update getBoundingClientRect. - Object.assign(el_bounds, { top: 40, right: 100, bottom: 40, left: 80 }); - el.dispatchEvent(events.scroll_event()); - await utils.animation_frame(); - - expect(el.classList.contains("bumped")).toBe(true); - expect(el.classList.contains("bumped-top")).toBe(false); - expect(el.classList.contains("bumped-right")).toBe(true); - expect(el.classList.contains("bumped-bottom")).toBe(false); - expect(el.classList.contains("bumped-left")).toBe(false); - - // Scroll to bottom-right, update getBoundingClientRect. - Object.assign(el_bounds, { top: 80, right: 100, bottom: 100, left: 80 }); - el.dispatchEvent(events.scroll_event()); - await utils.animation_frame(); - - expect(el.classList.contains("bumped")).toBe(true); - expect(el.classList.contains("bumped-top")).toBe(false); - expect(el.classList.contains("bumped-right")).toBe(true); - expect(el.classList.contains("bumped-bottom")).toBe(true); - expect(el.classList.contains("bumped-left")).toBe(false); - - // Scroll to bottom, update getBoundingClientRect. - Object.assign(el_bounds, { top: 80, right: 40, bottom: 100, left: 40 }); - el.dispatchEvent(events.scroll_event()); - await utils.animation_frame(); - - expect(el.classList.contains("bumped")).toBe(true); - expect(el.classList.contains("bumped-top")).toBe(false); - expect(el.classList.contains("bumped-right")).toBe(false); - expect(el.classList.contains("bumped-bottom")).toBe(true); - expect(el.classList.contains("bumped-left")).toBe(false); - - // Scroll to bottom-left, update getBoundingClientRect. - Object.assign(el_bounds, { top: 80, right: 80, bottom: 100, left: 0 }); - el.dispatchEvent(events.scroll_event()); - await utils.animation_frame(); - - expect(el.classList.contains("bumped")).toBe(true); - expect(el.classList.contains("bumped-top")).toBe(false); - expect(el.classList.contains("bumped-right")).toBe(false); - expect(el.classList.contains("bumped-bottom")).toBe(true); - expect(el.classList.contains("bumped-left")).toBe(true); - - // Scroll to left, update getBoundingClientRect. - Object.assign(el_bounds, { top: 40, right: 80, bottom: 40, left: 0 }); - el.dispatchEvent(events.scroll_event()); - await utils.animation_frame(); - - expect(el.classList.contains("bumped")).toBe(true); - expect(el.classList.contains("bumped-top")).toBe(false); - expect(el.classList.contains("bumped-right")).toBe(false); - expect(el.classList.contains("bumped-bottom")).toBe(false); - expect(el.classList.contains("bumped-left")).toBe(true); - - // Scroll to top-left, update getBoundingClientRect. - Object.assign(el_bounds, { top: 0, right: 80, bottom: 80, left: 0 }); - el.dispatchEvent(events.scroll_event()); - await utils.animation_frame(); - - expect(el.classList.contains("bumped")).toBe(true); - expect(el.classList.contains("bumped-top")).toBe(true); - expect(el.classList.contains("bumped-right")).toBe(false); - expect(el.classList.contains("bumped-bottom")).toBe(false); - expect(el.classList.contains("bumped-left")).toBe(true); - - // Scroll to top, update getBoundingClientRect. - Object.assign(el_bounds, { top: 0, right: 40, bottom: 80, left: 40 }); - el.dispatchEvent(events.scroll_event()); - await utils.animation_frame(); - - expect(el.classList.contains("bumped")).toBe(true); - expect(el.classList.contains("bumped-top")).toBe(true); - expect(el.classList.contains("bumped-right")).toBe(false); - expect(el.classList.contains("bumped-bottom")).toBe(false); - expect(el.classList.contains("bumped-left")).toBe(false); - - // Scroll to middle, update getBoundingClientRect. - Object.assign(el_bounds, { top: 40, right: 40, bottom: 40, left: 40 }); - el.dispatchEvent(events.scroll_event()); - await utils.animation_frame(); - - expect(el.classList.contains("bumped")).toBe(false); - expect(el.classList.contains("bumped-top")).toBe(false); - expect(el.classList.contains("bumped-right")).toBe(false); - expect(el.classList.contains("bumped-bottom")).toBe(false); - expect(el.classList.contains("bumped-left")).toBe(false); - }); +import Pattern from "./bumper"; +import Implementation from "./bumper--implementation"; + +describe("pat-bumper registration module", function () { + it("registers a lazily loaded pattern with the implementation's metadata.", function () { + expect(Pattern.lazy).toBe(true); + expect(Pattern.name).toBe(Implementation.name); + expect(Pattern.trigger).toBe(Implementation.trigger); + expect(Pattern.order ?? 1000).toBe(Implementation.order ?? 1000); }); - describe("Scroll listeners", function () { - it("Multiple bumpers in the same scroll container are all updated.", async function () { - document.body.innerHTML = ` -
    -
    - `; - const instance1 = new Bumper(document.getElementById("bump1")); - const instance2 = new Bumper(document.getElementById("bump2")); - await events.await_pattern_init(instance1); - await events.await_pattern_init(instance2); - - const spy1 = jest.spyOn(instance1, "set_bumping_classes"); - const spy2 = jest.spyOn(instance2, "set_bumping_classes"); - - document.dispatchEvent(events.scroll_event()); - await utils.animation_frame(); - - expect(spy1).toHaveBeenCalledTimes(1); - expect(spy2).toHaveBeenCalledTimes(1); - }); - - it("The scroll listener is removed on destroy.", async function () { - document.body.innerHTML = ` -
    - `; - const el = document.getElementById("bump1"); - const instance = new Bumper(el); - await events.await_pattern_init(instance); - - const spy = jest.spyOn(instance, "set_bumping_classes"); - - el.remove(); - await utils.timeout(1); - expect(instance.destroyed).toBe(true); - - document.dispatchEvent(events.scroll_event()); - await utils.animation_frame(); - - expect(spy).not.toHaveBeenCalled(); - }); + it("loads the implementation.", async function () { + expect(await Pattern.load()).toBe(Implementation); }); }); diff --git a/src/pat/calendar/calendar--implementation.js b/src/pat/calendar/calendar--implementation.js new file mode 100644 index 000000000..0185b3987 --- /dev/null +++ b/src/pat/calendar/calendar--implementation.js @@ -0,0 +1,715 @@ +import { BasePattern } from "../../core/basepattern"; +import dom from "../../core/dom"; +import events from "../../core/events"; +import logging from "../../core/logging"; +import Modal from "../modal/modal--implementation"; +import Parser from "../../core/parser"; +import registry from "../../core/registry"; +import store from "../../core/store"; + +const log = logging.getLogger("calendar"); +export const parser = new Parser("calendar"); + +parser.addArgument("calendar-controls", null); // Calendar controls must have "id" attr set +parser.addArgument("category-controls", null); +parser.addArgument("column-day", "dddd M/d"); +parser.addArgument("column-month", "ddd"); +parser.addArgument("column-week", "ddd M/d"); +parser.addArgument("initial-date", null); +parser.addArgument("initial-view", "month", [ + // Simple names + "month", + "week", + "day", + "list", + // FC 5 names + "dayGridMonth", + "dayGridWeek", + "dayGridDay", + "timeGridWeek", + "timeGridDay", + "listDay", + "listWeek", + "listMonth", + "listYear", + "listWeek", + // FC 3 names + "basicWeek", + "basicDay", + "agendaWeek", + "agendaDay", +]); +parser.addArgument("drag-and-drop", true, [true, false]); +parser.addArgument("drop-external-events", true, [true, false]); +parser.addArgument("external-event-selector", ""); +parser.addArgument("first-day", null); +parser.addArgument("first-hour", "6"); +parser.addArgument("height", "auto"); +parser.addArgument("ignore-url", false); +parser.addArgument("lang", null); // If not set, use "en" (See below) +parser.addArgument("store", "none", ["none", "session", "local"]); +parser.addArgument("time-format", "24h", ["24h", "12h"]); +parser.addArgument("timezone", null); +parser.addArgument("title-day", "dddd, MMM d, YYYY"); +parser.addArgument("title-month", "MMMM YYYY"); +parser.addArgument("title-week", "MMM D YYYY"); +parser.addArgument("event-color", "blue"); + +parser.addArgument("url", null); +parser.addArgument("event-sources", [], undefined, true); +//parser.addArgument("add-url", null); + +// pat-inject support for individual events +parser.addArgument("pat-inject-source", null); +parser.addArgument("pat-inject-target", null); + +// pat-modal support for individual events +parser.addArgument("pat-modal-class", null); + +// pat-tooltip support for individual events +parser.addArgument("pat-tooltip-source", null, ["ajax", null]); + +// pat-switch support for individual events +parser.addArgument("pat-switch-selector", null); +parser.addArgument("pat-switch-remove", null); +parser.addArgument("pat-switch-add", null); + +parser.addAlias("default-date", "initial-date"); +parser.addAlias("default-view", "initial-view"); + +class Pattern extends BasePattern { + static name = "calendar"; + static trigger = ".pat-calendar"; + static parser = parser; + + classMap = { + month: ".view-month", + agendaWeek: ".view-week", + agendaDay: ".view-day", + }; + viewMap = { + month: "dayGridMonth", + week: "timeGridWeek", + day: "timeGridDay", + list: "listMonth", + basicWeek: "dayGridWeek", + basicDay: "dayGridDay", + agendaWeek: "timeGridWeek", + agendaDay: "timeGridDay", + }; + dayNames = ["su", "mo", "tu", "we", "th", "fr", "sa"]; + active_categories = null; + + // The FullCalendar instance. + calendar = null; + // Timer for filtering events after category changes. + category_timer = null; + + async init() { + this.options = store.updateOptions(this.el, this.options); + + const Calendar = (await import("@fullcalendar/core")).Calendar; + const fcDayGrid = (await import("@fullcalendar/daygrid")).default; + const fcInteraction = (await import("@fullcalendar/interaction")).default; + const fcList = (await import("@fullcalendar/list")).default; + const fcLuxon = (await import("@fullcalendar/luxon2")).default; + const fcTimeGrid = (await import("@fullcalendar/timegrid")).default; + + // Save some UI elements for reuse. + const calendar_controls = this.options.calendarControls + ? document.querySelector(this.options.calendarControls) + : this.el; + this.el_jump_next = calendar_controls.querySelector(".jump-next"); + this.el_jump_prev = calendar_controls.querySelector(".jump-prev"); + this.el_jump_today = calendar_controls.querySelector(".jump-today"); + this.el_view_month = calendar_controls.querySelector(".view-month"); + this.el_view_week = calendar_controls.querySelector(".view-week"); + this.el_view_day = calendar_controls.querySelector(".view-day"); + this.el_view_list_year = calendar_controls.querySelector(".view-listYear"); + this.el_view_list_month = calendar_controls.querySelector(".view-listMonth"); + this.el_view_list_week = calendar_controls.querySelector(".view-listWeek"); + this.el_view_list_day = calendar_controls.querySelector(".view-listDay"); + this.el_timezone = calendar_controls.querySelector("select[name='timezone']"); + this.el_title = + this.el.querySelector(".cal-title") || + calendar_controls.querySelector(".cal-title"); + + const storage_prefix = `${this.name}-${window.location.pathname}`; + this.storage = + this.options.store === "none" + ? null + : store[this.options.store](storage_prefix); + + const query_string = new URLSearchParams(window.location.search); + + const config = {}; + config.headerToolbar = false; + config.initialDate = + query_string.get("date") || + this.storage?.get?.("date") || + this.options.initial.date; + config.initialView = + query_string.get("view") || + this.storage?.get?.("view") || + this.options.initial.view; + config.initialView = this.viewMap[config.initialView] || config.initialView; + config.editable = this.options.editable || false; + config.plugins = [fcDayGrid, fcInteraction, fcList, fcLuxon, fcTimeGrid]; + config.eventColor = this.options.eventColor; + + let lang = this.options.lang || dom.acquire_attribute(this.el, "lang") || "en"; + // we don't support any country-specific language variants, always use first 2 letters + lang = lang.substr(0, 2).toLowerCase(); + if (lang !== "en") { + try { + // Only 2-letter locales can be requested. Every file which + // could match becomes a chunk listed in the entry point's + // runtime. + const locale = await import( + /* webpackInclude: /locales\/[a-z]{2}\.js$/ */ + `@fullcalendar/core/locales/${lang}.js` + ); + config.locale = locale.default; + log.debug(`Loaded locale for ${lang}`); + } catch { + log.warn(`No locale for ${lang}, falling back to English.`); + } + } + if (this.options.first.day !== null) { + config.firstDay = this.options.first.day; + if (this.dayNames.indexOf(this.options.first.day) >= 0) { + // Set firstDay as string + config.firstDay = this.dayNames.indexOf(this.options.first.day); + } + } + + let timezone = this.el_timezone?.value || this.options.timezone || null; + if (timezone) { + config.timeZone = timezone; + } + + if (this.options.timeFormat == "12h") { + // 12h format + config.eventTimeFormat = { + hour12: true, + meridiem: "narrow", + hour: "numeric", + }; + } else { + // 24h format + config.eventTimeFormat = { + hour12: false, + meridiem: "false", + hour: "numeric", + }; + } + + const sources = [...(this.options.event.sources || [])]; + if (this.options.url && !sources.includes(this.options.url)) { + // add, but do not re-add same source twice. + sources.push(this.options.url); + } + config.eventSources = []; + for (const [idx, url] of sources.entries()) { + const src = this.create_event_source(idx, url); + config.eventSources.push(src); + } + + if (this.destroyed) { + // Destroyed while loading the dependencies. + return; + } + + // Restore category controls from local storage before showing events. + this._restoreCategoryControls(); + this._registerCategoryControls(); + this.reset_active_categories(); + config.eventDidMount = (args) => this.init_event(args); + + // Need to create a sub-element of ``pat-calendar`` to allow custom + // controls within pat-calendar to not be overwritten. + const cal_el = document.createElement("div"); + cal_el.setAttribute("class", "pat-calendar__fc"); + this.el.appendChild(cal_el); + + if (this.options.addUrl) { + config.dateClick = this.addNewEvent.bind(this); + // Create a element for modals/injections + this.mod_el = document.createElement("section"); + this.mod_el.setAttribute("class", "pat-calendar__modal"); + this.el.appendChild(this.mod_el); + } + + let calendar = (this.calendar = new Calendar(cal_el, config)); + calendar.render(); + + calendar.on("datesSet", this._viewChanged.bind(this)); + calendar.on("dateClick", this._viewChanged.bind(this)); + + if (this.el_title) { + this.el_title.innerHTML = calendar.view.title; + } + + this._registerCalendarControls(); + this.setActiveClasses(); + } + + destroy() { + if (this.destroyed) { + return; + } + clearTimeout(this.category_timer); + this.calendar?.destroy(); + this.calendar = null; + super.destroy(); + } + + create_event_source(idx, url) { + return { + id: `event-source--${idx + 1}`, + events: (info, success, failure) => + this._fetch_events(url, info, success, failure), + className: `event-source--${idx + 1}`, + }; + } + + event_mapper(event) { + // Maps backend results to the fullcalendar event schema. + // Default implementation confirms to plone.restapi conventions. + const ret = { + id: event.UID, + title: event.title, + start: new Date(event.start), + end: new Date(event.end), + allDay: event.whole_day, + url: event.url || event["@id"], + + backgroundColor: event.color, + borderColor: event.color, + classNames: event.class ? event.class.split(" ") : [], + + // non fullcalendar standard fields + description: event.description, + text: event.text, + location: event.location, + open_end: event.open_end, + recurrence: event.recurrence, + attendees: event.attendees, + contact_name: event.contact_name, + contact_phone: event.contact_phone, + contact_email: event.contact_email, + event_url: event.event_url, + }; + for (const prop in ret) { + if (!ret[prop]) { + delete ret[prop]; + } + } + return ret; + } + + update_event(event, data) { + // Updated an existing event with new event properties. + event.setDates(data.start, data.end); + event.setAllDay(data.allDay); + event.setProp("id", data.id); + event.setProp("title", data.title); + event.setProp("url", data.url); + + event.setProp("backgroundColor", data.color); + event.setProp("borderColor", data.color); + + event.setExtendedProp("description", data.description); + event.setExtendedProp("text", data.text); + event.setExtendedProp("location", data.location); + event.setExtendedProp("open_end", data.open_end); + event.setExtendedProp("recurrence", data.recurrence); + event.setExtendedProp("attendees", data.attendees); + event.setExtendedProp("contact_name", data.contact_name); + event.setExtendedProp("contact_phone", data.contact_phone); + event.setExtendedProp("contact_email", data.contact_email); + event.setExtendedProp("event_url", data.event_url); + } + + async _fetch_events(url, info, success, failure) { + let results = []; + while (url) { + url = url + .replace("${start_str}", info.startStr.split("T")[0]) + .replace("${end_str}", info.endStr.split("T")[0]); + + let response; + try { + response = await fetch(url, { + method: "GET", + mode: "cors", + headers: { + "Accept": "application/json", + }, + }); + } catch (e) { + failure(e); + return; + } + let result = await response.json(); + let results_ = result.items?.map(this.event_mapper) || []; + results = results.concat(results_); + + // resolve all ``next`` batching urls + url = result.batching?.next || null; + } + + success(results); + } + + init_event(args) { + this.filter_event(args.event); + + let do_scan = false; + + // pat-inject support + const source = this.options.pat["inject-source"]; + const target = this.options.pat["inject-target"]; + if (args.event.url && (source || target)) { + // Only set pat-inject if event has a url + args.el.classList.add("pat-inject"); + args.el.setAttribute( + "data-pat-inject", + `target: ${target || "body"}; source: ${source || "body"}` + ); + do_scan = true; + } + + // pat-modal support + if (args.event.url && this.options.pat["modal-class"]) { + // Only set pat-modal if event has a url + args.el.classList.add("pat-modal"); + args.el.setAttribute( + "data-pat-modal", + `class: ${this.options.pat["modal-class"]}` + ); + do_scan = true; + } + + // pat-tooltip support + if (args.event.url && this.options.pat["tooltip-source"] === "ajax") { + // Only set pat-tooltip if event has a url + args.el.classList.add("pat-tooltip"); + args.el.setAttribute("data-pat-tooltip", "source: ajax"); + do_scan = true; + } + + // pat-switch support + const switch_sel = this.options.pat["switch-selector"]; + if (switch_sel) { + const switch_add = this.options.pat["switch-add"]; + const switch_rm = this.options.pat["switch-remove"]; + + args.el.classList.add("pat-switch"); + args.el.setAttribute( + "data-pat-switch", + `selector: ${switch_sel}${switch_add ? "; add: " + switch_add : ""}${ + switch_rm ? "; remove: " + switch_rm : "" + }` + ); + do_scan = true; + } + + if (do_scan) { + registry.scan(args.el); + } + } + + filter_event(event) { + let show = true; + if (this.active_categories !== null) { + // intersection + show = + this.active_categories.filter((it) => event.classNames.includes(it)) + .length > 0; + } + if (show) { + event.setProp("display", "auto"); + } else { + event.setProp("display", "none"); + } + } + + reset_active_categories() { + const ctrls = this.get_category_controls(); + this.active_categories = null; + if (ctrls.length) { + this.active_categories = ctrls.filter((el) => el.checked).map((el) => el.id); + } + this.storage && this.storage.set("active_categories", this.active_categories); + } + + get_category_controls() { + const ctrl_containers = this.options.categoryControls + ? document.querySelectorAll(this.options.categoryControls) + : [this.el]; + const ctrls = []; + for (const it of ctrl_containers) { + const inp = it.querySelectorAll("input[type=checkbox]"); + ctrls.push(...inp); + } + return [...new Set(ctrls)]; // do not return the same inputs multiple times + } + + _registerCategoryControls() { + /* The "category controls" are checkboxes that cause different + * types of events to be shown or hidden. + */ + for (const [idx, ctrl] of this.get_category_controls().entries()) { + this.add_event_listener(ctrl, "change", `category-control-${idx}`, () => { + clearTimeout(this.category_timer); // Cancel scheduled filter runs + this.category_timer = setTimeout(() => { + this.reset_active_categories(); + this.calendar.getEvents().map(this.filter_event.bind(this)); + }, 50); + }); + } + } + + _restoreCategoryControls() { + /* Restore values of the category controls as stored in store. + * NOTE: run BEFORE _registerCalendarControls + */ + const ctrls = this.get_category_controls(); + const active_categories = + (this.storage && this.storage.get("active_categories")) || null; + + if (!ctrls.length || active_categories === null) { + // No category controls or never set, use default un/checked status. + return; + } + + for (const ctrl of ctrls) { + if (ctrl.hidden) { + // Do not set non-user-interactable inputs. + // They are programmatically set. + continue; + } + if (active_categories.includes(ctrl.id)) { + ctrl.checked = true; + } else { + ctrl.checked = false; + } + ctrl.dispatchEvent(new Event("change", { bubbles: true, cancelable: true })); + } + } + + _registerCalendarControls() { + // The calendar controls might be outside of the pattern element. + // Use instance scoped event listeners which are removed on destroy. + // Non-existing controls are ignored by ``add_event_listener``. + this.add_event_listener(this.el_jump_next, "click", "jump-next", (event) => { + event.preventDefault(); + this.calendar.next(); + }); + + this.add_event_listener(this.el_jump_prev, "click", "jump-prev", (event) => { + event.preventDefault(); + this.calendar.prev(); + }); + + this.add_event_listener(this.el_jump_today, "click", "jump-today", (event) => { + event.preventDefault(); + this.calendar.today(); + }); + + this.add_event_listener(this.el_view_month, "click", "view-month", (event) => { + event.preventDefault(); + this.calendar.changeView("dayGridMonth"); + }); + + this.add_event_listener(this.el_view_week, "click", "view-week", (event) => { + event.preventDefault(); + this.calendar.changeView("timeGridWeek"); + }); + + this.add_event_listener(this.el_view_day, "click", "view-day", (event) => { + event.preventDefault(); + this.calendar.changeView("timeGridDay"); + }); + + this.add_event_listener( + this.el_view_list_year, + "click", + "view-list-year", + (event) => { + event.preventDefault(); + this.calendar.changeView("listYear"); + } + ); + + this.add_event_listener( + this.el_view_list_month, + "click", + "view-list-month", + (event) => { + event.preventDefault(); + this.calendar.changeView("listMonth"); + } + ); + + this.add_event_listener( + this.el_view_list_week, + "click", + "view-list-week", + (event) => { + event.preventDefault(); + this.calendar.changeView("listWeek"); + } + ); + + this.add_event_listener( + this.el_view_list_day, + "click", + "view-list-day", + (event) => { + event.preventDefault(); + this.calendar.changeView("listDay"); + } + ); + + this.add_event_listener(this.el_timezone, "change", "timezone", (event) => { + event.preventDefault(); + this.calendar.setOption("timeZone", event.target.value); + }); + } + + setActiveClasses() { + // Set active classes of UI elements. + + this.el_jump_today?.classList.remove("active"); + this.el_view_month?.classList.remove("active"); + this.el_view_week?.classList.remove("active"); + this.el_view_day?.classList.remove("active"); + this.el_view_list_year?.classList.remove("active"); + this.el_view_list_month?.classList.remove("active"); + this.el_view_list_week?.classList.remove("active"); + this.el_view_list_day?.classList.remove("active"); + + const cdate = this.calendar.currentData.currentDate; + const today = new Date(); + if ( + cdate.getYear() === today.getYear() && + cdate.getMonth() === today.getMonth() && + cdate.getDate() === today.getDate() + ) { + this.el_jump_today?.classList.add("active"); + } + + switch (this.calendar.view.type) { + case "dayGridMonth": + this.el_view_month?.classList.add("active"); + break; + case "timeGridWeek": + this.el_view_week?.classList.add("active"); + break; + case "timeGridDay": + this.el_view_day?.classList.add("active"); + break; + case "listYear": + this.el_view_list_year?.classList.add("active"); + break; + case "listMonth": + this.el_view_list_month?.classList.add("active"); + break; + case "listWeek": + this.el_view_list_week?.classList.add("active"); + break; + case "listDay": + this.el_view_list_day?.classList.add("active"); + break; + } + } + + _viewChanged(data) { + // Set title + if (this.el_title) { + this.el_title.innerHTML = data.view.title; + } + // store current date and view + const date = data.view.currentStart.toISOString(); + const view = data.view.type; + this.storage && this.storage.set("date", date); + this.storage && this.storage.set("view", view); + + const query = new URLSearchParams(window.location.search); + query.set("date", date); + query.set("view", view); + history.replaceState(null, null, "?" + query.toString()); + + this.setActiveClasses(); + } + + async addNewEvent(info) { + let addUrl = this.options.addUrl; + if (!addUrl) { + return; + } + + let start, end, allDay; + if (this.calendar.view.type === "timeGridMonth") { + start = info.date; + end = info.date; + allDay = true; + } else { + start = info.date; + end = new Date(start.getTime() + 1 * 60 * 60 * 1000); // same as start, 1h offset + allDay = false; + } + addUrl = addUrl + .replace("${start_str}", start) + .replace("${end_str}", end) + .replace("${all_day}", allDay ? "1" : "0"); + + const event = this.calendar.addEvent( + { + title: "New Event", + start: start, + end: end, + }, + true + ); + + // Destroy a modal pattern of a previously added event, so that a new + // one can be initialized on the same element. + this.mod_el["pattern-modal"]?.destroy(); + const modal = new Modal(this.mod_el, { + url: addUrl, + trigger: "autoload", + }); + await events.await_pattern_init(modal); + + //const mod_el = document.querySelector("#pat-modal form"); + //mod_el.addEventListener("submit", (e) => { + // Only handle the form of the latest added event. Registering under + // the same name replaces the listener of a previously added event. + this.add_event_listener(document, "submit", "add-new-event", async (e) => { + const form = e.target; + const form_data = new FormData(form); + try { + const response = await fetch(form.action, { + method: form.method, + headers: { + "Content-Type": "application/json", + }, + body: form_data, + }); + let data = await response.json(); + data = this.event_mapper(data); + this.update_event(event, data); + } catch (error) { + log.error(error); + event.remove(); + } + }); + } +} + +registry.register(Pattern); +export default Pattern; +export { Pattern }; diff --git a/src/pat/calendar/calendar--implementation.test.js b/src/pat/calendar/calendar--implementation.test.js new file mode 100644 index 000000000..9e312ab35 --- /dev/null +++ b/src/pat/calendar/calendar--implementation.test.js @@ -0,0 +1,684 @@ +import Pattern from "./calendar--implementation"; +import events from "../../core/events"; +import registry from "../../core/registry"; +import utils from "../../core/utils"; + +const mockFetch = () => + Promise.resolve({ + json: () => + Promise.resolve({ + items: [ + { + title: "Event 1", + start: "2020-10-10T16:00:00Z", + end: "2020-10-10T18:00:00Z", + }, + { + "title": "Event 2", + "start": "2020-10-12", + "end": "2020-10-12", + "@id": "./test_event.html", + }, + { + "title": "Event 3", + "start": "2020-10-14", + "end": "2020-10-16", + "@id": "./test_event.html", + "url": "./@@test-event", + }, + ], + }), + }); + +describe("1 - Calendar tests", () => { + beforeEach(() => { + // create container + const el = document.createElement("div"); + el.setAttribute("class", "root-element"); + el.innerHTML = ` +
    +

    title

    +
    +
    + + + +
    +
    + + + +
    +
    + +
    +
    +
    + `; + document.body.appendChild(el); + }); + + afterEach(() => { + // remove container + document.body.removeChild(document.querySelector(".root-element")); + + // reset query string + history.replaceState(null, null, "?"); // empty string doesn't reset, so "?"... + }); + + it("Initializes correctly", async () => { + const el = document.querySelector(".pat-calendar"); + registry.scan(document.body); + await utils.timeout(1); // wait a tick for async to settle. + expect(el.querySelector(".pat-calendar__fc")).toBeTruthy(); + expect(el.querySelector(".pat-calendar__fc").innerHTML).toBeTruthy(); + }); + + it("Initializes with the default dayGridMonth view", async () => { + const el = document.querySelector(".pat-calendar"); + registry.scan(document.body); + await utils.timeout(1); // wait a tick for async to settle. + expect(el.querySelector(".fc-dayGridMonth-view")).toBeTruthy(); + }); + + it("Initializes with the timeGridWeek view when configured", async () => { + const el = document.querySelector(".pat-calendar"); + el.setAttribute("data-pat-calendar", "initial-view: agendaWeek"); + registry.scan(document.body); + await utils.timeout(1); // wait a tick for async to settle. + expect(el.querySelector(".fc-timeGridWeek-view")).toBeTruthy(); + }); + + it("Initializes with the timeGridDay view when configured", async () => { + const el = document.querySelector(".pat-calendar"); + el.setAttribute("data-pat-calendar", "initial-view: agendaDay"); + registry.scan(document.body); + await utils.timeout(1); // wait a tick for async to settle. + expect(el.querySelector(".fc-timeGridDay-view")).toBeTruthy(); + }); + + it("Uses 24h time format by default", async () => { + const el = document.querySelector(".pat-calendar"); + el.setAttribute( + "data-pat-calendar", + `lang: en; initial-date: 2020-10-10; timezone: Europe/Berlin; url: ./test.json;` + ); + + global.fetch = jest.fn().mockImplementation(mockFetch); + + registry.scan(document.body); + await utils.timeout(1); // wait a tick for async to settle. + + expect( + document.querySelector(".event-source--1 .fc-event-time").textContent + ).toBe("18"); + + global.fetch.mockClear(); + delete global.fetch; + }); + + it("Uses 24h time format also with invalid configuration", async () => { + const el = document.querySelector(".pat-calendar"); + el.setAttribute( + "data-pat-calendar", + `lang: en; time-format: h(:mm)t; initial-date: 2020-10-10; timezone: Europe/Berlin; url: ./test.json;` + ); + + global.fetch = jest.fn().mockImplementation(mockFetch); + + registry.scan(document.body); + await utils.timeout(1); // wait a tick for async to settle. + + expect( + document.querySelector(".event-source--1 .fc-event-time").textContent + ).toBe("18"); + + global.fetch.mockClear(); + delete global.fetch; + }); + + it("Uses 12h time format if configured", async () => { + const el = document.querySelector(".pat-calendar"); + el.setAttribute( + "data-pat-calendar", + `lang: en; time-format: 12h; initial-date: 2020-10-10; timezone: Europe/Berlin; url: ./test.json;` + ); + + global.fetch = jest.fn().mockImplementation(mockFetch); + + registry.scan(document.body); + await utils.timeout(1); // wait a tick for async to settle. + + expect( + document.querySelector(".event-source--1 .fc-event-time").textContent + ).toBe("6p"); + + global.fetch.mockClear(); + delete global.fetch; + }); + + it("Updates title according to display", async () => { + const el = document.querySelector(".pat-calendar"); + el.setAttribute( + "data-pat-calendar", + "initial-date: 2000-10-10; initial-view: month" + ); + + const title_el = el.querySelector(".cal-title"); + let title = title_el.innerHTML; + + registry.scan(document.body); + await utils.timeout(1); // wait a tick for async to settle. + + expect(title_el.innerHTML === title).toBeFalsy(); + + title = title_el.innerHTML; + el.querySelector(".view-week").click(); + expect(title_el.innerHTML === title).toBeFalsy(); + + title = title_el.innerHTML; + el.querySelector(".view-day").click(); + expect(title_el.innerHTML === title).toBeFalsy(); + + title = title_el.innerHTML; + el.querySelector(".view-month").click(); + expect(title_el.innerHTML === title).toBeFalsy(); + + title = title_el.innerHTML; + el.querySelector(".jump-next").click(); + expect(title_el.innerHTML === title).toBeFalsy(); + + title = title_el.innerHTML; + el.querySelector(".jump-prev").click(); + expect(title_el.innerHTML === title).toBeFalsy(); + + title = title_el.innerHTML; + el.querySelector(".jump-today").click(); + expect(title_el.innerHTML === title).toBeFalsy(); + }); + + it("Changes views when clicked", async () => { + const el = document.querySelector(".pat-calendar"); + registry.scan(document.body); + await utils.timeout(1); // wait a tick for async to settle. + + el.querySelector(".view-week").click(); + expect(el.querySelector(".view-week.active")).toBeTruthy(); + expect(el.querySelector(".view-day.active")).toBeFalsy(); + expect(el.querySelector(".view-month.active")).toBeFalsy(); + expect(el.querySelector(".fc-dayGridMonth-view")).toBeFalsy(); + expect(el.querySelector(".fc-timeGridWeek-view")).toBeTruthy(); + expect(el.querySelector(".fc-timeGridDay-view")).toBeFalsy(); + + el.querySelector(".view-day").click(); + expect(el.querySelector(".view-week.active")).toBeFalsy(); + expect(el.querySelector(".view-day.active")).toBeTruthy(); + expect(el.querySelector(".view-month.active")).toBeFalsy(); + expect(el.querySelector(".fc-dayGridMonth-view")).toBeFalsy(); + expect(el.querySelector(".fc-timeGridWeek-view")).toBeFalsy(); + expect(el.querySelector(".fc-timeGridDay-view")).toBeTruthy(); + + el.querySelector(".view-month").click(); + expect(el.querySelector(".view-week.active")).toBeFalsy(); + expect(el.querySelector(".view-day.active")).toBeFalsy(); + expect(el.querySelector(".view-month.active")).toBeTruthy(); + expect(el.querySelector(".fc-dayGridMonth-view")).toBeTruthy(); + expect(el.querySelector(".fc-timeGridWeek-view")).toBeFalsy(); + expect(el.querySelector(".fc-timeGridDay-view")).toBeFalsy(); + }); + + it("Loads initial date and navigates for/backwards", async () => { + const el = document.querySelector(".pat-calendar"); + el.setAttribute( + "data-pat-calendar", + "initial-date: 2000-10-10; initial-view: month" + ); + registry.scan(document.body); + await utils.timeout(1); // wait a tick for async to settle. + + expect(el.querySelector("*[data-date='2000-10-10']")).toBeTruthy(); + + el.querySelector(".jump-next").click(); + expect(el.querySelector("*[data-date='2000-11-10']")).toBeTruthy(); + + el.querySelector(".jump-prev").click(); + expect(el.querySelector("*[data-date='2000-10-10']")).toBeTruthy(); + + let date = new Date(); + date = date.toISOString().split("T")[0]; + el.querySelector(".jump-today").click(); + expect(el.querySelector(`*[data-date='${date}']`)).toBeTruthy(); + }); + + it("Loads events from a JSON feed", async () => { + const el = document.querySelector(".pat-calendar"); + el.setAttribute( + "data-pat-calendar", + "initial-date: 2020-10-10; url: ./test.json;" + ); + + global.fetch = jest.fn().mockImplementation(mockFetch); + + registry.scan(document.body); + await utils.timeout(1); // wait a tick for async to settle. + + let titles = [...el.querySelectorAll(".fc-event-title")].map( + (it) => it.innerHTML + ); + + expect(titles.includes("Event 1")).toBeTruthy(); + expect(titles.includes("Event 2")).toBeTruthy(); + expect(titles.includes("Event 3")).toBeTruthy(); + + global.fetch.mockClear(); + delete global.fetch; + }); + + it("Loads events and does not set the href if not present", async () => { + const el = document.querySelector(".pat-calendar"); + el.setAttribute( + "data-pat-calendar", + "initial-date: 2020-10-10; url: ./test.json;" + ); + + global.fetch = jest.fn().mockImplementation(mockFetch); + + registry.scan(document.body); + await utils.timeout(1); // wait a tick for async to settle. + + const events = [...document.querySelectorAll(".fc-event-title")]; + + const event1 = events.filter((it) => it.textContent === "Event 1")[0].closest(".fc-event"); // prettier-ignore + const event2 = events.filter((it) => it.textContent === "Event 2")[0].closest(".fc-event"); // prettier-ignore + const event3 = events.filter((it) => it.textContent === "Event 3")[0].closest(".fc-event"); // prettier-ignore + + expect(event1.href).toBeFalsy(); + expect(event2.href).toBe("http://localhost/test_event.html"); + expect(event3.href).toBe("http://localhost/@@test-event"); + + global.fetch.mockClear(); + delete global.fetch; + }); + + it("Loads events and initializes them with pat-inject and pat-switch", async () => { + // pat-inject is only set if event has a url. + const el = document.querySelector(".pat-calendar"); + el.setAttribute( + "data-pat-calendar", + `initial-date: 2020-10-10; + url: ./test.json; + pat-inject-target: #event-info; + pat-inject-source: #document-body; + pat-switch-selector: #event-info; + pat-switch-remove: event-info--inactive; + pat-switch-add: event-info--active` + ); + + global.fetch = jest.fn().mockImplementation(mockFetch); + + registry.scan(document.body); + await utils.timeout(1); // wait a tick for async to settle. + + const events = [...document.querySelectorAll(".fc-event-title")]; + + const event1 = events.filter((it) => it.textContent === "Event 1")[0].closest(".fc-event"); // prettier-ignore + const event2 = events.filter((it) => it.textContent === "Event 2")[0].closest(".fc-event"); // prettier-ignore + const event3 = events.filter((it) => it.textContent === "Event 3")[0].closest(".fc-event"); // prettier-ignore + + expect(event1.classList.contains("pat-inject")).toBe(false); + expect(event1.classList.contains("pat-switch")).toBe(true); + expect(event1.hasAttribute("data-pat-inject")).toBe(false); + expect(event1.getAttribute("data-pat-switch")).toBe("selector: #event-info; add: event-info--active; remove: event-info--inactive"); // prettier-ignore + + expect(event2.classList.contains("pat-inject")).toBe(true); + expect(event2.classList.contains("pat-switch")).toBe(true); + expect(event2.getAttribute("data-pat-inject")).toBe("target: #event-info; source: #document-body"); // prettier-ignore + expect(event2.getAttribute("data-pat-switch")).toBe("selector: #event-info; add: event-info--active; remove: event-info--inactive"); // prettier-ignore + + expect(event3.classList.contains("pat-inject")).toBe(true); + expect(event3.classList.contains("pat-switch")).toBe(true); + expect(event3.getAttribute("data-pat-inject")).toBe("target: #event-info; source: #document-body"); // prettier-ignore + expect(event3.getAttribute("data-pat-switch")).toBe("selector: #event-info; add: event-info--active; remove: event-info--inactive"); // prettier-ignore + + global.fetch.mockClear(); + delete global.fetch; + }); + + it("Loads events and initializes them with pat-modal", async () => { + // pat-inject is only set if event has a url. + const el = document.querySelector(".pat-calendar"); + el.setAttribute( + "data-pat-calendar", + `initial-date: 2020-10-10; + url: ./test.json; + pat-modal-class: a b c; + ` + ); + + global.fetch = jest.fn().mockImplementation(mockFetch); + + registry.scan(document.body); + await utils.timeout(1); // wait a tick for async to settle. + + const events = [...document.querySelectorAll(".fc-event-title")]; + + const event1 = events.filter((it) => it.textContent === "Event 1")[0].closest(".fc-event"); // prettier-ignore + const event2 = events.filter((it) => it.textContent === "Event 2")[0].closest(".fc-event"); // prettier-ignore + const event3 = events.filter((it) => it.textContent === "Event 3")[0].closest(".fc-event"); // prettier-ignore + + expect(event1.classList.contains("pat-modal")).toBe(false); + expect(event1.hasAttribute("data-pat-modal")).toBe(false); + + expect(event2.classList.contains("pat-modal")).toBe(true); + expect(event2.getAttribute("data-pat-modal")).toBe("class: a b c"); + + expect(event3.classList.contains("pat-modal")).toBe(true); + expect(event3.getAttribute("data-pat-modal")).toBe("class: a b c"); + + global.fetch.mockClear(); + delete global.fetch; + }); + + it("Loads events and initializes them with pat-tooltip", async () => { + // pat-inject is only set if event has a url. + const el = document.querySelector(".pat-calendar"); + el.setAttribute( + "data-pat-calendar", + `initial-date: 2020-10-10; + url: ./test.json; + pat-tooltip-source: ajax; + ` + ); + + global.fetch = jest.fn().mockImplementation(mockFetch); + + registry.scan(document.body); + await utils.timeout(1); // wait a tick for async to settle. + + const events = [...document.querySelectorAll(".fc-event-title")]; + + const event1 = events.filter((it) => it.textContent === "Event 1")[0].closest(".fc-event"); // prettier-ignore + const event2 = events.filter((it) => it.textContent === "Event 2")[0].closest(".fc-event"); // prettier-ignore + const event3 = events.filter((it) => it.textContent === "Event 3")[0].closest(".fc-event"); // prettier-ignore + + expect(event1.classList.contains("pat-tooltip")).toBe(false); + expect(event1.hasAttribute("data-pat-tooltip")).toBe(false); + + expect(event2.classList.contains("pat-tooltip")).toBe(true); + expect(event2.getAttribute("data-pat-tooltip")).toBe("source: ajax"); + + expect(event3.classList.contains("pat-tooltip")).toBe(true); + expect(event3.getAttribute("data-pat-tooltip")).toBe("source: ajax"); + + global.fetch.mockClear(); + delete global.fetch; + }); + + it("Loads correct date if set in query string", async () => { + const el = document.querySelector(".pat-calendar"); + el.setAttribute("data-pat-calendar", "timezone: Europe/Berlin"); + window.history.replaceState( + null, + null, + "?date=2020-02-29T23%3A00%3A00.000Z&view=dayGridMonth" + ); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + const title_el = el.querySelector(".cal-title"); + expect(title_el.innerHTML).toEqual("March 2020"); + }); + + it("Loads correct locale if set", async () => { + const el = document.querySelector(".pat-calendar"); + el.setAttribute("data-pat-calendar", "initial-date: 2020-03-01; lang: de"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + const title_el = el.querySelector(".cal-title"); + expect(title_el.innerHTML).toEqual("März 2020"); + }); + + it("Loads correct locale if set in parent container", async () => { + // Set language on .root-element container + document.querySelector(".root-element").setAttribute("lang", "de"); + const el = document.querySelector(".pat-calendar"); + el.setAttribute("data-pat-calendar", "initial-date: 2020-03-01"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + const title_el = el.querySelector(".cal-title"); + expect(title_el.innerHTML).toEqual("März 2020"); + }); + + it("Falls back to English if no locale exists for the language", async () => { + const el = document.querySelector(".pat-calendar"); + // There is only zh-cn and zh-tw, but the language is cut to 2 letters. + el.setAttribute("data-pat-calendar", "initial-date: 2020-03-01; lang: zh"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + const title_el = el.querySelector(".cal-title"); + expect(title_el.innerHTML).toEqual("March 2020"); + }); +}); + +describe("2 - Calendar tests with calendar controls outside pat-calendar", () => { + beforeEach(() => { + // create container + const el = document.createElement("div"); + el.setAttribute("class", "root-element"); + el.innerHTML = ` +
    +

    title

    +
    +
    + + + +
    +
    + + + +
    +
    +
    + +
    + `; + document.body.appendChild(el); + }); + + afterEach(() => { + // remove container + document.body.removeChild(document.querySelector(".root-element")); + + // reset query string + history.replaceState(null, null, "?"); // empty string doesn't reset, so "?"... + }); + + it("2.1 - Updates title according to display", async () => { + const el = document.querySelector(".pat-calendar"); + el.setAttribute( + "data-pat-calendar", + "initial-date: 2000-10-10; initial-view: month; calendar-controls: .calendar-controls" + ); + + const title_el = document.querySelector(".cal-title"); + let title = title_el.innerHTML; + + registry.scan(document.body); + await utils.timeout(1); // wait a tick for async to settle. + + expect(title_el.innerHTML === title).toBeFalsy(); + + title = title_el.innerHTML; + document.querySelector(".view-week").click(); + expect(title_el.innerHTML === title).toBeFalsy(); + + title = title_el.innerHTML; + document.querySelector(".view-day").click(); + expect(title_el.innerHTML === title).toBeFalsy(); + + title = title_el.innerHTML; + document.querySelector(".view-month").click(); + expect(title_el.innerHTML === title).toBeFalsy(); + + title = title_el.innerHTML; + document.querySelector(".jump-next").click(); + expect(title_el.innerHTML === title).toBeFalsy(); + + title = title_el.innerHTML; + document.querySelector(".jump-prev").click(); + expect(title_el.innerHTML === title).toBeFalsy(); + + title = title_el.innerHTML; + document.querySelector(".jump-today").click(); + expect(title_el.innerHTML === title).toBeFalsy(); + }); + + it("2.2 - Changes views when clicked", async () => { + const el = document.querySelector(".pat-calendar"); + el.setAttribute("data-pat-calendar", "calendar-controls: .calendar-controls"); + + registry.scan(document.body); + await utils.timeout(1); // wait a tick for async to settle. + + document.querySelector(".view-week").click(); + expect(document.querySelector(".view-week.active")).toBeTruthy(); + expect(document.querySelector(".view-day.active")).toBeFalsy(); + expect(document.querySelector(".view-month.active")).toBeFalsy(); + expect(el.querySelector(".fc-dayGridMonth-view")).toBeFalsy(); + expect(el.querySelector(".fc-timeGridWeek-view")).toBeTruthy(); + expect(el.querySelector(".fc-timeGridDay-view")).toBeFalsy(); + + document.querySelector(".view-day").click(); + expect(document.querySelector(".view-week.active")).toBeFalsy(); + expect(document.querySelector(".view-day.active")).toBeTruthy(); + expect(document.querySelector(".view-month.active")).toBeFalsy(); + expect(el.querySelector(".fc-dayGridMonth-view")).toBeFalsy(); + expect(el.querySelector(".fc-timeGridWeek-view")).toBeFalsy(); + expect(el.querySelector(".fc-timeGridDay-view")).toBeTruthy(); + + document.querySelector(".view-month").click(); + expect(document.querySelector(".view-week.active")).toBeFalsy(); + expect(document.querySelector(".view-day.active")).toBeFalsy(); + expect(document.querySelector(".view-month.active")).toBeTruthy(); + expect(el.querySelector(".fc-dayGridMonth-view")).toBeTruthy(); + expect(el.querySelector(".fc-timeGridWeek-view")).toBeFalsy(); + expect(el.querySelector(".fc-timeGridDay-view")).toBeFalsy(); + }); + it("2.3 - Removes the control listeners and the calendar on destroy.", async () => { + const el = document.querySelector(".pat-calendar"); + el.setAttribute( + "data-pat-calendar", + "initial-date: 2000-10-10; initial-view: month; calendar-controls: .calendar-controls" + ); + + const instance = new Pattern(el); + await events.await_pattern_init(instance); + const calendar = instance.calendar; + expect(calendar).toBeTruthy(); + const spy_destroy = jest.spyOn(calendar, "destroy"); + const spy_change_view = jest.spyOn(calendar, "changeView"); + + document.querySelector(".view-week").click(); + expect(spy_change_view).toHaveBeenCalledTimes(1); + + // Removing the pattern element destroys the pattern. + el.remove(); + await utils.timeout(1); // destroy is async - wait for it. + + expect(instance.destroyed).toBe(true); + expect(spy_destroy).toHaveBeenCalledTimes(1); + expect(instance.calendar).toBe(null); + + // The controls outside of the pattern element are not handled anymore. + document.querySelector(".view-day").click(); + expect(spy_change_view).toHaveBeenCalledTimes(1); + }); +}); + +describe("3 - Calendar tests with calendar controls outside pat-calendar but title within", () => { + beforeEach(() => { + // create container + const el = document.createElement("div"); + el.setAttribute("class", "root-element"); + el.innerHTML = ` +
    +
    +
    + + + +
    +
    + + + +
    +
    +
    + +
    +

    title

    +
    + `; + document.body.appendChild(el); + }); + + afterEach(() => { + // remove container + document.body.removeChild(document.querySelector(".root-element")); + + // reset query string + history.replaceState(null, null, "?"); // empty string doesn't reset, so "?"... + }); + + it("3.1 - Updates title according to display", async () => { + const el = document.querySelector(".pat-calendar"); + el.setAttribute( + "data-pat-calendar", + "initial-date: 2000-10-10; initial-view: month; calendar-controls: .calendar-controls" + ); + + const title_el = document.querySelector(".cal-title"); + let title = title_el.innerHTML; + + registry.scan(document.body); + await utils.timeout(1); // wait a tick for async to settle. + + expect(title_el.innerHTML === title).toBeFalsy(); + + title = title_el.innerHTML; + document.querySelector(".view-week").click(); + expect(title_el.innerHTML === title).toBeFalsy(); + + title = title_el.innerHTML; + document.querySelector(".view-day").click(); + expect(title_el.innerHTML === title).toBeFalsy(); + + title = title_el.innerHTML; + document.querySelector(".view-month").click(); + expect(title_el.innerHTML === title).toBeFalsy(); + + title = title_el.innerHTML; + document.querySelector(".jump-next").click(); + expect(title_el.innerHTML === title).toBeFalsy(); + + title = title_el.innerHTML; + document.querySelector(".jump-prev").click(); + expect(title_el.innerHTML === title).toBeFalsy(); + + title = title_el.innerHTML; + document.querySelector(".jump-today").click(); + expect(title_el.innerHTML === title).toBeFalsy(); + }); +}); diff --git a/src/pat/calendar/calendar.js b/src/pat/calendar/calendar.js index db142081f..51754b2ce 100644 --- a/src/pat/calendar/calendar.js +++ b/src/pat/calendar/calendar.js @@ -1,661 +1,20 @@ -import Base from "../../core/base"; -import dom from "../../core/dom"; -import logging from "../../core/logging"; -import Modal from "../modal/modal"; -import Parser from "../../core/parser"; +/** + * pat-calendar registration module. + * + * The pattern implementation is loaded lazily when the pattern is used for + * the first time. Import the implementation module to use the pattern class + * or its parser directly: + * ./calendar--implementation.js + */ +import create_lazy_pattern from "../../core/lazy-pattern"; import registry from "../../core/registry"; -import store from "../../core/store"; -const log = logging.getLogger("calendar"); -export const parser = new Parser("calendar"); - -parser.addArgument("calendar-controls", null); // Calendar controls must have "id" attr set -parser.addArgument("category-controls", null); -parser.addArgument("column-day", "dddd M/d"); -parser.addArgument("column-month", "ddd"); -parser.addArgument("column-week", "ddd M/d"); -parser.addArgument("initial-date", null); -parser.addArgument("initial-view", "month", [ - // Simple names - "month", - "week", - "day", - "list", - // FC 5 names - "dayGridMonth", - "dayGridWeek", - "dayGridDay", - "timeGridWeek", - "timeGridDay", - "listDay", - "listWeek", - "listMonth", - "listYear", - "listWeek", - // FC 3 names - "basicWeek", - "basicDay", - "agendaWeek", - "agendaDay", -]); -parser.addArgument("drag-and-drop", true, [true, false]); -parser.addArgument("drop-external-events", true, [true, false]); -parser.addArgument("external-event-selector", ""); -parser.addArgument("first-day", null); -parser.addArgument("first-hour", "6"); -parser.addArgument("height", "auto"); -parser.addArgument("ignore-url", false); -parser.addArgument("lang", null); // If not set, use "en" (See below) -parser.addArgument("store", "none", ["none", "session", "local"]); -parser.addArgument("time-format", "24h", ["24h", "12h"]); -parser.addArgument("timezone", null); -parser.addArgument("title-day", "dddd, MMM d, YYYY"); -parser.addArgument("title-month", "MMMM YYYY"); -parser.addArgument("title-week", "MMM D YYYY"); -parser.addArgument("event-color", "blue"); - -parser.addArgument("url", null); -parser.addArgument("event-sources", [], undefined, true); -//parser.addArgument("add-url", null); - -// pat-inject support for individual events -parser.addArgument("pat-inject-source", null); -parser.addArgument("pat-inject-target", null); - -// pat-modal support for individual events -parser.addArgument("pat-modal-class", null); - -// pat-tooltip support for individual events -parser.addArgument("pat-tooltip-source", null, ["ajax", null]); - -// pat-switch support for individual events -parser.addArgument("pat-switch-selector", null); -parser.addArgument("pat-switch-remove", null); -parser.addArgument("pat-switch-add", null); - -parser.addAlias("default-date", "initial-date"); -parser.addAlias("default-view", "initial-view"); - -export default Base.extend({ +const Pattern = create_lazy_pattern({ name: "calendar", trigger: ".pat-calendar", - classMap: { - month: ".view-month", - agendaWeek: ".view-week", - agendaDay: ".view-day", - }, - viewMap: { - month: "dayGridMonth", - week: "timeGridWeek", - day: "timeGridDay", - list: "listMonth", - basicWeek: "dayGridWeek", - basicDay: "dayGridDay", - agendaWeek: "timeGridWeek", - agendaDay: "timeGridDay", - }, - dayNames: ["su", "mo", "tu", "we", "th", "fr", "sa"], - active_categories: null, - parser: parser, - - async init() { - this.options = store.updateOptions(this.el, parser.parse(this.el, this.options)); - - const Calendar = (await import("@fullcalendar/core")).Calendar; - const fcDayGrid = (await import("@fullcalendar/daygrid")).default; - const fcInteraction = (await import("@fullcalendar/interaction")).default; - const fcList = (await import("@fullcalendar/list")).default; - const fcLuxon = (await import("@fullcalendar/luxon2")).default; - const fcTimeGrid = (await import("@fullcalendar/timegrid")).default; - - // Save some UI elements for reuse. - const calendar_controls = this.options.calendarControls - ? document.querySelector(this.options.calendarControls) - : this.el; - this.el_jump_next = calendar_controls.querySelector(".jump-next"); - this.el_jump_prev = calendar_controls.querySelector(".jump-prev"); - this.el_jump_today = calendar_controls.querySelector(".jump-today"); - this.el_view_month = calendar_controls.querySelector(".view-month"); - this.el_view_week = calendar_controls.querySelector(".view-week"); - this.el_view_day = calendar_controls.querySelector(".view-day"); - this.el_view_list_year = calendar_controls.querySelector(".view-listYear"); - this.el_view_list_month = calendar_controls.querySelector(".view-listMonth"); - this.el_view_list_week = calendar_controls.querySelector(".view-listWeek"); - this.el_view_list_day = calendar_controls.querySelector(".view-listDay"); - this.el_timezone = calendar_controls.querySelector("select[name='timezone']"); - this.el_title = - this.el.querySelector(".cal-title") || - calendar_controls.querySelector(".cal-title"); - - const storage_prefix = `${this.name}-${window.location.pathname}`; - this.storage = - this.options.store === "none" - ? null - : store[this.options.store](storage_prefix); - - const query_string = new URLSearchParams(window.location.search); - - const config = {}; - config.headerToolbar = false; - config.initialDate = - query_string.get("date") || - this.storage?.get?.("date") || - this.options.initial.date; - config.initialView = - query_string.get("view") || - this.storage?.get?.("view") || - this.options.initial.view; - config.initialView = this.viewMap[config.initialView] || config.initialView; - config.editable = this.options.editable || false; - config.plugins = [fcDayGrid, fcInteraction, fcList, fcLuxon, fcTimeGrid]; - config.eventColor = this.options.eventColor; - - let lang = this.options.lang || dom.acquire_attribute(this.el, "lang") || "en"; - // we don't support any country-specific language variants, always use first 2 letters - lang = lang.substr(0, 2).toLowerCase(); - if (lang !== "en") { - try { - // Only 2-letter locales can be requested. Every file which - // could match becomes a chunk listed in the entry point's - // runtime. - const locale = await import( - /* webpackInclude: /locales\/[a-z]{2}\.js$/ */ - `@fullcalendar/core/locales/${lang}.js` - ); - config.locale = locale.default; - log.debug(`Loaded locale for ${lang}`); - } catch { - log.warn(`No locale for ${lang}, falling back to English.`); - } - } - if (this.options.first.day !== null) { - config.firstDay = this.options.first.day; - if (this.dayNames.indexOf(this.options.first.day) >= 0) { - // Set firstDay as string - config.firstDay = this.dayNames.indexOf(this.options.first.day); - } - } - - let timezone = this.el_timezone?.value || this.options.timezone || null; - if (timezone) { - config.timeZone = timezone; - } - - if (this.options.timeFormat == "12h") { - // 12h format - config.eventTimeFormat = { - hour12: true, - meridiem: "narrow", - hour: "numeric", - }; - } else { - // 24h format - config.eventTimeFormat = { - hour12: false, - meridiem: "false", - hour: "numeric", - }; - } - - const sources = [...(this.options.event.sources || [])]; - if (this.options.url && !sources.includes(this.options.url)) { - // add, but do not re-add same source twice. - sources.push(this.options.url); - } - config.eventSources = []; - for (const [idx, url] of sources.entries()) { - const src = this.create_event_source(idx, url); - config.eventSources.push(src); - } - - // Restore category controls from local storage before showing events. - this._restoreCategoryControls(); - this._registerCategoryControls(); - this.reset_active_categories(); - config.eventDidMount = (args) => this.init_event(args); - - // Need to create a sub-element of ``pat-calendar`` to allow custom - // controls within pat-calendar to not be overwritten. - const cal_el = document.createElement("div"); - cal_el.setAttribute("class", "pat-calendar__fc"); - this.el.appendChild(cal_el); - - if (this.options.addUrl) { - config.dateClick = this.addNewEvent.bind(this); - // Create a element for modals/injections - this.mod_el = document.createElement("section"); - this.mod_el.setAttribute("class", "pat-calendar__modal"); - this.el.appendChild(this.mod_el); - } - - let calendar = (this.calendar = new Calendar(cal_el, config)); - calendar.render(); - - calendar.on("datesSet", this._viewChanged.bind(this)); - calendar.on("dateClick", this._viewChanged.bind(this)); - - if (this.el_title) { - this.el_title.innerHTML = calendar.view.title; - } - - this._registerCalendarControls(); - this.setActiveClasses(); - }, - - create_event_source(idx, url) { - return { - id: `event-source--${idx + 1}`, - events: (info, success, failure) => - this._fetch_events(url, info, success, failure), - className: `event-source--${idx + 1}`, - }; - }, - - event_mapper(event) { - // Maps backend results to the fullcalendar event schema. - // Default implementation confirms to plone.restapi conventions. - const ret = { - id: event.UID, - title: event.title, - start: new Date(event.start), - end: new Date(event.end), - allDay: event.whole_day, - url: event.url || event["@id"], - - backgroundColor: event.color, - borderColor: event.color, - classNames: event.class ? event.class.split(" ") : [], - - // non fullcalendar standard fields - description: event.description, - text: event.text, - location: event.location, - open_end: event.open_end, - recurrence: event.recurrence, - attendees: event.attendees, - contact_name: event.contact_name, - contact_phone: event.contact_phone, - contact_email: event.contact_email, - event_url: event.event_url, - }; - for (const prop in ret) { - if (!ret[prop]) { - delete ret[prop]; - } - } - return ret; - }, - - update_event(event, data) { - // Updated an existing event with new event properties. - event.setDates(data.start, data.end); - event.setAllDay(data.allDay); - event.setProp("id", data.id); - event.setProp("title", data.title); - event.setProp("url", data.url); - - event.setProp("backgroundColor", data.color); - event.setProp("borderColor", data.color); - - event.setExtendedProp("description", data.description); - event.setExtendedProp("text", data.text); - event.setExtendedProp("location", data.location); - event.setExtendedProp("open_end", data.open_end); - event.setExtendedProp("recurrence", data.recurrence); - event.setExtendedProp("attendees", data.attendees); - event.setExtendedProp("contact_name", data.contact_name); - event.setExtendedProp("contact_phone", data.contact_phone); - event.setExtendedProp("contact_email", data.contact_email); - event.setExtendedProp("event_url", data.event_url); - }, - - async _fetch_events(url, info, success, failure) { - let results = []; - while (url) { - url = url - .replace("${start_str}", info.startStr.split("T")[0]) - .replace("${end_str}", info.endStr.split("T")[0]); - - let response; - try { - response = await fetch(url, { - method: "GET", - mode: "cors", - headers: { - "Accept": "application/json", - }, - }); - } catch (e) { - failure(e); - return; - } - let result = await response.json(); - let results_ = result.items?.map(this.event_mapper) || []; - results = results.concat(results_); - - // resolve all ``next`` batching urls - url = result.batching?.next || null; - } - - success(results); - }, - - init_event(args) { - this.filter_event(args.event); - - let do_scan = false; - - // pat-inject support - const source = this.options.pat["inject-source"]; - const target = this.options.pat["inject-target"]; - if (args.event.url && (source || target)) { - // Only set pat-inject if event has a url - args.el.classList.add("pat-inject"); - args.el.setAttribute( - "data-pat-inject", - `target: ${target || "body"}; source: ${source || "body"}` - ); - do_scan = true; - } - - // pat-modal support - if (args.event.url && this.options.pat["modal-class"]) { - // Only set pat-modal if event has a url - args.el.classList.add("pat-modal"); - args.el.setAttribute( - "data-pat-modal", - `class: ${this.options.pat["modal-class"]}` - ); - do_scan = true; - } - - // pat-tooltip support - if (args.event.url && this.options.pat["tooltip-source"] === "ajax") { - // Only set pat-tooltip if event has a url - args.el.classList.add("pat-tooltip"); - args.el.setAttribute("data-pat-tooltip", "source: ajax"); - do_scan = true; - } - - // pat-switch support - const switch_sel = this.options.pat["switch-selector"]; - if (switch_sel) { - const switch_add = this.options.pat["switch-add"]; - const switch_rm = this.options.pat["switch-remove"]; - - args.el.classList.add("pat-switch"); - args.el.setAttribute( - "data-pat-switch", - `selector: ${switch_sel}${switch_add ? "; add: " + switch_add : ""}${ - switch_rm ? "; remove: " + switch_rm : "" - }` - ); - do_scan = true; - } - - if (do_scan) { - registry.scan(args.el); - } - }, - - filter_event(event) { - let show = true; - if (this.active_categories !== null) { - // intersection - show = - this.active_categories.filter((it) => event.classNames.includes(it)) - .length > 0; - } - if (show) { - event.setProp("display", "auto"); - } else { - event.setProp("display", "none"); - } - }, - - reset_active_categories() { - const ctrls = this.get_category_controls(); - this.active_categories = null; - if (ctrls.length) { - this.active_categories = ctrls.filter((el) => el.checked).map((el) => el.id); - } - this.storage && this.storage.set("active_categories", this.active_categories); - }, - - get_category_controls() { - const ctrl_containers = this.options.categoryControls - ? document.querySelectorAll(this.options.categoryControls) - : [this.el]; - const ctrls = []; - for (const it of ctrl_containers) { - const inp = it.querySelectorAll("input[type=checkbox]"); - ctrls.push(...inp); - } - return [...new Set(ctrls)]; // do not return the same inputs multiple times - }, - - _registerCategoryControls() { - /* The "category controls" are checkboxes that cause different - * types of events to be shown or hidden. - */ - let timer; - for (const ctrl of this.get_category_controls()) { - ctrl.addEventListener("change", () => { - clearTimeout(timer); // Cancel scheduled filter runs - timer = setTimeout(() => { - this.reset_active_categories(); - this.calendar.getEvents().map(this.filter_event.bind(this)); - }, 50); - }); - } - }, - - _restoreCategoryControls() { - /* Restore values of the category controls as stored in store. - * NOTE: run BEFORE _registerCalendarControls - */ - const ctrls = this.get_category_controls(); - const active_categories = - (this.storage && this.storage.get("active_categories")) || null; - - if (!ctrls.length || active_categories === null) { - // No category controls or never set, use default un/checked status. - return; - } - - for (const ctrl of ctrls) { - if (ctrl.hidden) { - // Do not set non-user-interactable inputs. - // They are programmatically set. - continue; - } - if (active_categories.includes(ctrl.id)) { - ctrl.checked = true; - } else { - ctrl.checked = false; - } - ctrl.dispatchEvent(new Event("change", { bubbles: true, cancelable: true })); - } - }, - - _registerCalendarControls() { - this.el_jump_next?.addEventListener("click", (event) => { - event.preventDefault(); - this.calendar.next(); - }); - - this.el_jump_prev?.addEventListener("click", (event) => { - event.preventDefault(); - this.calendar.prev(); - }); - - this.el_jump_today?.addEventListener("click", (event) => { - event.preventDefault(); - this.calendar.today(); - }); - - this.el_view_month?.addEventListener("click", (event) => { - event.preventDefault(); - this.calendar.changeView("dayGridMonth"); - }); - - this.el_view_week?.addEventListener("click", (event) => { - event.preventDefault(); - this.calendar.changeView("timeGridWeek"); - }); - - this.el_view_day?.addEventListener("click", (event) => { - event.preventDefault(); - this.calendar.changeView("timeGridDay"); - }); - - this.el_view_list_year?.addEventListener("click", (event) => { - event.preventDefault(); - this.calendar.changeView("listYear"); - }); - - this.el_view_list_month?.addEventListener("click", (event) => { - event.preventDefault(); - this.calendar.changeView("listMonth"); - }); - - this.el_view_list_week?.addEventListener("click", (event) => { - event.preventDefault(); - this.calendar.changeView("listWeek"); - }); - - this.el_view_list_day?.addEventListener("click", (event) => { - event.preventDefault(); - this.calendar.changeView("listDay"); - }); - - this.el_timezone?.addEventListener("change", (event) => { - event.preventDefault(); - this.calendar.setOption("timeZone", event.target.value); - }); - }, - - setActiveClasses() { - // Set active classes of UI elements. - - this.el_jump_today?.classList.remove("active"); - this.el_view_month?.classList.remove("active"); - this.el_view_week?.classList.remove("active"); - this.el_view_day?.classList.remove("active"); - this.el_view_list_year?.classList.remove("active"); - this.el_view_list_month?.classList.remove("active"); - this.el_view_list_week?.classList.remove("active"); - this.el_view_list_day?.classList.remove("active"); - - const cdate = this.calendar.currentData.currentDate; - const today = new Date(); - if ( - cdate.getYear() === today.getYear() && - cdate.getMonth() === today.getMonth() && - cdate.getDate() === today.getDate() - ) { - this.el_jump_today?.classList.add("active"); - } - - switch (this.calendar.view.type) { - case "dayGridMonth": - this.el_view_month?.classList.add("active"); - break; - case "timeGridWeek": - this.el_view_week?.classList.add("active"); - break; - case "timeGridDay": - this.el_view_day?.classList.add("active"); - break; - case "listYear": - this.el_view_list_year?.classList.add("active"); - break; - case "listMonth": - this.el_view_list_month?.classList.add("active"); - break; - case "listWeek": - this.el_view_list_week?.classList.add("active"); - break; - case "listDay": - this.el_view_list_day?.classList.add("active"); - break; - } - }, - - _viewChanged(data) { - // Set title - if (this.el_title) { - this.el_title.innerHTML = data.view.title; - } - // store current date and view - const date = data.view.currentStart.toISOString(); - const view = data.view.type; - this.storage && this.storage.set("date", date); - this.storage && this.storage.set("view", view); - - const query = new URLSearchParams(window.location.search); - query.set("date", date); - query.set("view", view); - history.replaceState(null, null, "?" + query.toString()); - - this.setActiveClasses(); - }, - - async addNewEvent(info) { - let addUrl = this.options.addUrl; - if (!addUrl) { - return; - } - - let start, end, allDay; - if (this.calendar.view.type === "timeGridMonth") { - start = info.date; - end = info.date; - allDay = true; - } else { - start = info.date; - end = new Date(start.getTime() + 1 * 60 * 60 * 1000); // same as start, 1h offset - allDay = false; - } - addUrl = addUrl - .replace("${start_str}", start) - .replace("${end_str}", end) - .replace("${all_day}", allDay ? "1" : "0"); - - const event = this.calendar.addEvent( - { - title: "New Event", - start: start, - end: end, - }, - true - ); - - await new Modal(this.mod_el, { - url: addUrl, - trigger: "autoload", - }); - - //const mod_el = document.querySelector("#pat-modal form"); - //mod_el.addEventListener("submit", (e) => { - document.addEventListener("submit", async (e) => { - const form = e.target; - const form_data = new FormData(form); - try { - const response = await fetch(form.action, { - method: form.method, - headers: { - "Content-Type": "application/json", - }, - body: form_data, - }); - let data = await response.json(); - data = this.event_mapper(data); - this.update_event(event, data); - } catch (error) { - log.error(error); - event.remove(); - } - }); - }, + load: () => import("./calendar--implementation"), }); + +registry.register(Pattern); +export default Pattern; +export { Pattern }; diff --git a/src/pat/calendar/calendar.test.js b/src/pat/calendar/calendar.test.js index 81314366e..39db52e07 100644 --- a/src/pat/calendar/calendar.test.js +++ b/src/pat/calendar/calendar.test.js @@ -1,654 +1,15 @@ -import pattern from "./calendar"; -import registry from "../../core/registry"; -import utils from "../../core/utils"; +import Pattern from "./calendar"; +import Implementation from "./calendar--implementation"; -const mockFetch = () => - Promise.resolve({ - json: () => - Promise.resolve({ - items: [ - { - title: "Event 1", - start: "2020-10-10T16:00:00Z", - end: "2020-10-10T18:00:00Z", - }, - { - "title": "Event 2", - "start": "2020-10-12", - "end": "2020-10-12", - "@id": "./test_event.html", - }, - { - "title": "Event 3", - "start": "2020-10-14", - "end": "2020-10-16", - "@id": "./test_event.html", - "url": "./@@test-event", - }, - ], - }), +describe("pat-calendar registration module", function () { + it("registers a lazily loaded pattern with the implementation's metadata.", function () { + expect(Pattern.lazy).toBe(true); + expect(Pattern.name).toBe(Implementation.name); + expect(Pattern.trigger).toBe(Implementation.trigger); + expect(Pattern.order ?? 1000).toBe(Implementation.order ?? 1000); }); -describe("1 - Calendar tests", () => { - beforeEach(() => { - // create container - const el = document.createElement("div"); - el.setAttribute("class", "root-element"); - el.innerHTML = ` -
    -

    title

    -
    -
    - - - -
    -
    - - - -
    -
    - -
    -
    -
    - `; - document.body.appendChild(el); - }); - - afterEach(() => { - // remove container - document.body.removeChild(document.querySelector(".root-element")); - - // reset query string - history.replaceState(null, null, "?"); // empty string doesn't reset, so "?"... - }); - - it("Initializes correctly", async () => { - const el = document.querySelector(".pat-calendar"); - registry.scan(document.body); - await utils.timeout(1); // wait a tick for async to settle. - expect(el.querySelector(".pat-calendar__fc")).toBeTruthy(); - expect(el.querySelector(".pat-calendar__fc").innerHTML).toBeTruthy(); - }); - - it("Initializes with the default dayGridMonth view", async () => { - const el = document.querySelector(".pat-calendar"); - registry.scan(document.body); - await utils.timeout(1); // wait a tick for async to settle. - expect(el.querySelector(".fc-dayGridMonth-view")).toBeTruthy(); - }); - - it("Initializes with the timeGridWeek view when configured", async () => { - const el = document.querySelector(".pat-calendar"); - el.setAttribute("data-pat-calendar", "initial-view: agendaWeek"); - registry.scan(document.body); - await utils.timeout(1); // wait a tick for async to settle. - expect(el.querySelector(".fc-timeGridWeek-view")).toBeTruthy(); - }); - - it("Initializes with the timeGridDay view when configured", async () => { - const el = document.querySelector(".pat-calendar"); - el.setAttribute("data-pat-calendar", "initial-view: agendaDay"); - registry.scan(document.body); - await utils.timeout(1); // wait a tick for async to settle. - expect(el.querySelector(".fc-timeGridDay-view")).toBeTruthy(); - }); - - it("Uses 24h time format by default", async () => { - const el = document.querySelector(".pat-calendar"); - el.setAttribute( - "data-pat-calendar", - `lang: en; initial-date: 2020-10-10; timezone: Europe/Berlin; url: ./test.json;` - ); - - global.fetch = jest.fn().mockImplementation(mockFetch); - - registry.scan(document.body); - await utils.timeout(1); // wait a tick for async to settle. - - expect( - document.querySelector(".event-source--1 .fc-event-time").textContent - ).toBe("18"); - - global.fetch.mockClear(); - delete global.fetch; - }); - - it("Uses 24h time format also with invalid configuration", async () => { - const el = document.querySelector(".pat-calendar"); - el.setAttribute( - "data-pat-calendar", - `lang: en; time-format: h(:mm)t; initial-date: 2020-10-10; timezone: Europe/Berlin; url: ./test.json;` - ); - - global.fetch = jest.fn().mockImplementation(mockFetch); - - registry.scan(document.body); - await utils.timeout(1); // wait a tick for async to settle. - - expect( - document.querySelector(".event-source--1 .fc-event-time").textContent - ).toBe("18"); - - global.fetch.mockClear(); - delete global.fetch; - }); - - it("Uses 12h time format if configured", async () => { - const el = document.querySelector(".pat-calendar"); - el.setAttribute( - "data-pat-calendar", - `lang: en; time-format: 12h; initial-date: 2020-10-10; timezone: Europe/Berlin; url: ./test.json;` - ); - - global.fetch = jest.fn().mockImplementation(mockFetch); - - registry.scan(document.body); - await utils.timeout(1); // wait a tick for async to settle. - - expect( - document.querySelector(".event-source--1 .fc-event-time").textContent - ).toBe("6p"); - - global.fetch.mockClear(); - delete global.fetch; - }); - - it("Updates title according to display", async () => { - const el = document.querySelector(".pat-calendar"); - el.setAttribute( - "data-pat-calendar", - "initial-date: 2000-10-10; initial-view: month" - ); - - const title_el = el.querySelector(".cal-title"); - let title = title_el.innerHTML; - - registry.scan(document.body); - await utils.timeout(1); // wait a tick for async to settle. - - expect(title_el.innerHTML === title).toBeFalsy(); - - title = title_el.innerHTML; - el.querySelector(".view-week").click(); - expect(title_el.innerHTML === title).toBeFalsy(); - - title = title_el.innerHTML; - el.querySelector(".view-day").click(); - expect(title_el.innerHTML === title).toBeFalsy(); - - title = title_el.innerHTML; - el.querySelector(".view-month").click(); - expect(title_el.innerHTML === title).toBeFalsy(); - - title = title_el.innerHTML; - el.querySelector(".jump-next").click(); - expect(title_el.innerHTML === title).toBeFalsy(); - - title = title_el.innerHTML; - el.querySelector(".jump-prev").click(); - expect(title_el.innerHTML === title).toBeFalsy(); - - title = title_el.innerHTML; - el.querySelector(".jump-today").click(); - expect(title_el.innerHTML === title).toBeFalsy(); - }); - - it("Changes views when clicked", async () => { - const el = document.querySelector(".pat-calendar"); - registry.scan(document.body); - await utils.timeout(1); // wait a tick for async to settle. - - el.querySelector(".view-week").click(); - expect(el.querySelector(".view-week.active")).toBeTruthy(); - expect(el.querySelector(".view-day.active")).toBeFalsy(); - expect(el.querySelector(".view-month.active")).toBeFalsy(); - expect(el.querySelector(".fc-dayGridMonth-view")).toBeFalsy(); - expect(el.querySelector(".fc-timeGridWeek-view")).toBeTruthy(); - expect(el.querySelector(".fc-timeGridDay-view")).toBeFalsy(); - - el.querySelector(".view-day").click(); - expect(el.querySelector(".view-week.active")).toBeFalsy(); - expect(el.querySelector(".view-day.active")).toBeTruthy(); - expect(el.querySelector(".view-month.active")).toBeFalsy(); - expect(el.querySelector(".fc-dayGridMonth-view")).toBeFalsy(); - expect(el.querySelector(".fc-timeGridWeek-view")).toBeFalsy(); - expect(el.querySelector(".fc-timeGridDay-view")).toBeTruthy(); - - el.querySelector(".view-month").click(); - expect(el.querySelector(".view-week.active")).toBeFalsy(); - expect(el.querySelector(".view-day.active")).toBeFalsy(); - expect(el.querySelector(".view-month.active")).toBeTruthy(); - expect(el.querySelector(".fc-dayGridMonth-view")).toBeTruthy(); - expect(el.querySelector(".fc-timeGridWeek-view")).toBeFalsy(); - expect(el.querySelector(".fc-timeGridDay-view")).toBeFalsy(); - }); - - it("Loads initial date and navigates for/backwards", async () => { - const el = document.querySelector(".pat-calendar"); - el.setAttribute( - "data-pat-calendar", - "initial-date: 2000-10-10; initial-view: month" - ); - registry.scan(document.body); - await utils.timeout(1); // wait a tick for async to settle. - - expect(el.querySelector("*[data-date='2000-10-10']")).toBeTruthy(); - - el.querySelector(".jump-next").click(); - expect(el.querySelector("*[data-date='2000-11-10']")).toBeTruthy(); - - el.querySelector(".jump-prev").click(); - expect(el.querySelector("*[data-date='2000-10-10']")).toBeTruthy(); - - let date = new Date(); - date = date.toISOString().split("T")[0]; - el.querySelector(".jump-today").click(); - expect(el.querySelector(`*[data-date='${date}']`)).toBeTruthy(); - }); - - it("Loads events from a JSON feed", async () => { - const el = document.querySelector(".pat-calendar"); - el.setAttribute( - "data-pat-calendar", - "initial-date: 2020-10-10; url: ./test.json;" - ); - - global.fetch = jest.fn().mockImplementation(mockFetch); - - registry.scan(document.body); - await utils.timeout(1); // wait a tick for async to settle. - - let titles = [...el.querySelectorAll(".fc-event-title")].map( - (it) => it.innerHTML - ); - - expect(titles.includes("Event 1")).toBeTruthy(); - expect(titles.includes("Event 2")).toBeTruthy(); - expect(titles.includes("Event 3")).toBeTruthy(); - - global.fetch.mockClear(); - delete global.fetch; - }); - - it("Loads events and does not set the href if not present", async () => { - const el = document.querySelector(".pat-calendar"); - el.setAttribute( - "data-pat-calendar", - "initial-date: 2020-10-10; url: ./test.json;" - ); - - global.fetch = jest.fn().mockImplementation(mockFetch); - - registry.scan(document.body); - await utils.timeout(1); // wait a tick for async to settle. - - const events = [...document.querySelectorAll(".fc-event-title")]; - - const event1 = events.filter((it) => it.textContent === "Event 1")[0].closest(".fc-event"); // prettier-ignore - const event2 = events.filter((it) => it.textContent === "Event 2")[0].closest(".fc-event"); // prettier-ignore - const event3 = events.filter((it) => it.textContent === "Event 3")[0].closest(".fc-event"); // prettier-ignore - - expect(event1.href).toBeFalsy(); - expect(event2.href).toBe("http://localhost/test_event.html"); - expect(event3.href).toBe("http://localhost/@@test-event"); - - global.fetch.mockClear(); - delete global.fetch; - }); - - it("Loads events and initializes them with pat-inject and pat-switch", async () => { - // pat-inject is only set if event has a url. - const el = document.querySelector(".pat-calendar"); - el.setAttribute( - "data-pat-calendar", - `initial-date: 2020-10-10; - url: ./test.json; - pat-inject-target: #event-info; - pat-inject-source: #document-body; - pat-switch-selector: #event-info; - pat-switch-remove: event-info--inactive; - pat-switch-add: event-info--active` - ); - - global.fetch = jest.fn().mockImplementation(mockFetch); - - registry.scan(document.body); - await utils.timeout(1); // wait a tick for async to settle. - - const events = [...document.querySelectorAll(".fc-event-title")]; - - const event1 = events.filter((it) => it.textContent === "Event 1")[0].closest(".fc-event"); // prettier-ignore - const event2 = events.filter((it) => it.textContent === "Event 2")[0].closest(".fc-event"); // prettier-ignore - const event3 = events.filter((it) => it.textContent === "Event 3")[0].closest(".fc-event"); // prettier-ignore - - expect(event1.classList.contains("pat-inject")).toBe(false); - expect(event1.classList.contains("pat-switch")).toBe(true); - expect(event1.hasAttribute("data-pat-inject")).toBe(false); - expect(event1.getAttribute("data-pat-switch")).toBe("selector: #event-info; add: event-info--active; remove: event-info--inactive"); // prettier-ignore - - expect(event2.classList.contains("pat-inject")).toBe(true); - expect(event2.classList.contains("pat-switch")).toBe(true); - expect(event2.getAttribute("data-pat-inject")).toBe("target: #event-info; source: #document-body"); // prettier-ignore - expect(event2.getAttribute("data-pat-switch")).toBe("selector: #event-info; add: event-info--active; remove: event-info--inactive"); // prettier-ignore - - expect(event3.classList.contains("pat-inject")).toBe(true); - expect(event3.classList.contains("pat-switch")).toBe(true); - expect(event3.getAttribute("data-pat-inject")).toBe("target: #event-info; source: #document-body"); // prettier-ignore - expect(event3.getAttribute("data-pat-switch")).toBe("selector: #event-info; add: event-info--active; remove: event-info--inactive"); // prettier-ignore - - global.fetch.mockClear(); - delete global.fetch; - }); - - it("Loads events and initializes them with pat-modal", async () => { - // pat-inject is only set if event has a url. - const el = document.querySelector(".pat-calendar"); - el.setAttribute( - "data-pat-calendar", - `initial-date: 2020-10-10; - url: ./test.json; - pat-modal-class: a b c; - ` - ); - - global.fetch = jest.fn().mockImplementation(mockFetch); - - registry.scan(document.body); - await utils.timeout(1); // wait a tick for async to settle. - - const events = [...document.querySelectorAll(".fc-event-title")]; - - const event1 = events.filter((it) => it.textContent === "Event 1")[0].closest(".fc-event"); // prettier-ignore - const event2 = events.filter((it) => it.textContent === "Event 2")[0].closest(".fc-event"); // prettier-ignore - const event3 = events.filter((it) => it.textContent === "Event 3")[0].closest(".fc-event"); // prettier-ignore - - expect(event1.classList.contains("pat-modal")).toBe(false); - expect(event1.hasAttribute("data-pat-modal")).toBe(false); - - expect(event2.classList.contains("pat-modal")).toBe(true); - expect(event2.getAttribute("data-pat-modal")).toBe("class: a b c"); - - expect(event3.classList.contains("pat-modal")).toBe(true); - expect(event3.getAttribute("data-pat-modal")).toBe("class: a b c"); - - global.fetch.mockClear(); - delete global.fetch; - }); - - it("Loads events and initializes them with pat-tooltip", async () => { - // pat-inject is only set if event has a url. - const el = document.querySelector(".pat-calendar"); - el.setAttribute( - "data-pat-calendar", - `initial-date: 2020-10-10; - url: ./test.json; - pat-tooltip-source: ajax; - ` - ); - - global.fetch = jest.fn().mockImplementation(mockFetch); - - registry.scan(document.body); - await utils.timeout(1); // wait a tick for async to settle. - - const events = [...document.querySelectorAll(".fc-event-title")]; - - const event1 = events.filter((it) => it.textContent === "Event 1")[0].closest(".fc-event"); // prettier-ignore - const event2 = events.filter((it) => it.textContent === "Event 2")[0].closest(".fc-event"); // prettier-ignore - const event3 = events.filter((it) => it.textContent === "Event 3")[0].closest(".fc-event"); // prettier-ignore - - expect(event1.classList.contains("pat-tooltip")).toBe(false); - expect(event1.hasAttribute("data-pat-tooltip")).toBe(false); - - expect(event2.classList.contains("pat-tooltip")).toBe(true); - expect(event2.getAttribute("data-pat-tooltip")).toBe("source: ajax"); - - expect(event3.classList.contains("pat-tooltip")).toBe(true); - expect(event3.getAttribute("data-pat-tooltip")).toBe("source: ajax"); - - global.fetch.mockClear(); - delete global.fetch; - }); - - it("Loads correct date if set in query string", async () => { - const el = document.querySelector(".pat-calendar"); - el.setAttribute("data-pat-calendar", "timezone: Europe/Berlin"); - window.history.replaceState( - null, - null, - "?date=2020-02-29T23%3A00%3A00.000Z&view=dayGridMonth" - ); - pattern.init(el); - await utils.timeout(1); // wait a tick for async to settle. - - const title_el = el.querySelector(".cal-title"); - expect(title_el.innerHTML).toEqual("March 2020"); - }); - - it("Loads correct locale if set", async () => { - const el = document.querySelector(".pat-calendar"); - el.setAttribute("data-pat-calendar", "initial-date: 2020-03-01; lang: de"); - pattern.init(el); - await utils.timeout(1); // wait a tick for async to settle. - - const title_el = el.querySelector(".cal-title"); - expect(title_el.innerHTML).toEqual("März 2020"); - }); - - it("Loads correct locale if set in parent container", async () => { - // Set language on .root-element container - document.querySelector(".root-element").setAttribute("lang", "de"); - const el = document.querySelector(".pat-calendar"); - el.setAttribute("data-pat-calendar", "initial-date: 2020-03-01"); - pattern.init(el); - await utils.timeout(1); // wait a tick for async to settle. - - const title_el = el.querySelector(".cal-title"); - expect(title_el.innerHTML).toEqual("März 2020"); - }); - - it("Falls back to English if no locale exists for the language", async () => { - const el = document.querySelector(".pat-calendar"); - // There is only zh-cn and zh-tw, but the language is cut to 2 letters. - el.setAttribute("data-pat-calendar", "initial-date: 2020-03-01; lang: zh"); - pattern.init(el); - await utils.timeout(1); // wait a tick for async to settle. - - const title_el = el.querySelector(".cal-title"); - expect(title_el.innerHTML).toEqual("March 2020"); - }); -}); - -describe("2 - Calendar tests with calendar controls outside pat-calendar", () => { - beforeEach(() => { - // create container - const el = document.createElement("div"); - el.setAttribute("class", "root-element"); - el.innerHTML = ` -
    -

    title

    -
    -
    - - - -
    -
    - - - -
    -
    -
    - -
    - `; - document.body.appendChild(el); - }); - - afterEach(() => { - // remove container - document.body.removeChild(document.querySelector(".root-element")); - - // reset query string - history.replaceState(null, null, "?"); // empty string doesn't reset, so "?"... - }); - - it("2.1 - Updates title according to display", async () => { - const el = document.querySelector(".pat-calendar"); - el.setAttribute( - "data-pat-calendar", - "initial-date: 2000-10-10; initial-view: month; calendar-controls: .calendar-controls" - ); - - const title_el = document.querySelector(".cal-title"); - let title = title_el.innerHTML; - - registry.scan(document.body); - await utils.timeout(1); // wait a tick for async to settle. - - expect(title_el.innerHTML === title).toBeFalsy(); - - title = title_el.innerHTML; - document.querySelector(".view-week").click(); - expect(title_el.innerHTML === title).toBeFalsy(); - - title = title_el.innerHTML; - document.querySelector(".view-day").click(); - expect(title_el.innerHTML === title).toBeFalsy(); - - title = title_el.innerHTML; - document.querySelector(".view-month").click(); - expect(title_el.innerHTML === title).toBeFalsy(); - - title = title_el.innerHTML; - document.querySelector(".jump-next").click(); - expect(title_el.innerHTML === title).toBeFalsy(); - - title = title_el.innerHTML; - document.querySelector(".jump-prev").click(); - expect(title_el.innerHTML === title).toBeFalsy(); - - title = title_el.innerHTML; - document.querySelector(".jump-today").click(); - expect(title_el.innerHTML === title).toBeFalsy(); - }); - - it("2.2 - Changes views when clicked", async () => { - const el = document.querySelector(".pat-calendar"); - el.setAttribute("data-pat-calendar", "calendar-controls: .calendar-controls"); - - registry.scan(document.body); - await utils.timeout(1); // wait a tick for async to settle. - - document.querySelector(".view-week").click(); - expect(document.querySelector(".view-week.active")).toBeTruthy(); - expect(document.querySelector(".view-day.active")).toBeFalsy(); - expect(document.querySelector(".view-month.active")).toBeFalsy(); - expect(el.querySelector(".fc-dayGridMonth-view")).toBeFalsy(); - expect(el.querySelector(".fc-timeGridWeek-view")).toBeTruthy(); - expect(el.querySelector(".fc-timeGridDay-view")).toBeFalsy(); - - document.querySelector(".view-day").click(); - expect(document.querySelector(".view-week.active")).toBeFalsy(); - expect(document.querySelector(".view-day.active")).toBeTruthy(); - expect(document.querySelector(".view-month.active")).toBeFalsy(); - expect(el.querySelector(".fc-dayGridMonth-view")).toBeFalsy(); - expect(el.querySelector(".fc-timeGridWeek-view")).toBeFalsy(); - expect(el.querySelector(".fc-timeGridDay-view")).toBeTruthy(); - - document.querySelector(".view-month").click(); - expect(document.querySelector(".view-week.active")).toBeFalsy(); - expect(document.querySelector(".view-day.active")).toBeFalsy(); - expect(document.querySelector(".view-month.active")).toBeTruthy(); - expect(el.querySelector(".fc-dayGridMonth-view")).toBeTruthy(); - expect(el.querySelector(".fc-timeGridWeek-view")).toBeFalsy(); - expect(el.querySelector(".fc-timeGridDay-view")).toBeFalsy(); - }); -}); - -describe("3 - Calendar tests with calendar controls outside pat-calendar but title within", () => { - beforeEach(() => { - // create container - const el = document.createElement("div"); - el.setAttribute("class", "root-element"); - el.innerHTML = ` -
    -
    -
    - - - -
    -
    - - - -
    -
    -
    - -
    -

    title

    -
    - `; - document.body.appendChild(el); - }); - - afterEach(() => { - // remove container - document.body.removeChild(document.querySelector(".root-element")); - - // reset query string - history.replaceState(null, null, "?"); // empty string doesn't reset, so "?"... - }); - - it("3.1 - Updates title according to display", async () => { - const el = document.querySelector(".pat-calendar"); - el.setAttribute( - "data-pat-calendar", - "initial-date: 2000-10-10; initial-view: month; calendar-controls: .calendar-controls" - ); - - const title_el = document.querySelector(".cal-title"); - let title = title_el.innerHTML; - - registry.scan(document.body); - await utils.timeout(1); // wait a tick for async to settle. - - expect(title_el.innerHTML === title).toBeFalsy(); - - title = title_el.innerHTML; - document.querySelector(".view-week").click(); - expect(title_el.innerHTML === title).toBeFalsy(); - - title = title_el.innerHTML; - document.querySelector(".view-day").click(); - expect(title_el.innerHTML === title).toBeFalsy(); - - title = title_el.innerHTML; - document.querySelector(".view-month").click(); - expect(title_el.innerHTML === title).toBeFalsy(); - - title = title_el.innerHTML; - document.querySelector(".jump-next").click(); - expect(title_el.innerHTML === title).toBeFalsy(); - - title = title_el.innerHTML; - document.querySelector(".jump-prev").click(); - expect(title_el.innerHTML === title).toBeFalsy(); - - title = title_el.innerHTML; - document.querySelector(".jump-today").click(); - expect(title_el.innerHTML === title).toBeFalsy(); + it("loads the implementation.", async function () { + expect(await Pattern.load()).toBe(Implementation); }); }); diff --git a/src/pat/carousel/carousel--implementation.js b/src/pat/carousel/carousel--implementation.js new file mode 100644 index 000000000..3ebab48b3 --- /dev/null +++ b/src/pat/carousel/carousel--implementation.js @@ -0,0 +1,145 @@ +/** + * Patterns carousel + * + * Copyright 2017 Syslab.com GmbH Alexander Pilz + */ +import $ from "jquery"; +import { BasePattern } from "../../core/basepattern"; +import dom from "../../core/dom"; +import Parser from "../../core/parser"; +import registry from "../../core/registry"; +import utils from "../../core/utils"; + +export const parser = new Parser("carousel"); +parser.addArgument("auto-play", false); +parser.addArgument("auto-play-speed", 1000); +parser.addArgument("speed", 500); +parser.addArgument("height", "fixed"); +parser.addArgument("arrows", "show"); +parser.addArgument("slides-to-show", 1); +parser.addArgument("slides-to-scroll", 1); +parser.addArgument("dots", "show"); +parser.addArgument("append-dots", ""); +parser.addArgument("infinite", false); + +class Pattern extends BasePattern { + static name = "carousel"; + static trigger = ".pat-carousel"; + static parser = parser; + + abort_controller = null; + panel_links = []; + + async init() { + if (window.__patternslib_import_styles) { + import("slick-carousel/slick/slick.scss"); + } + await import("slick-carousel"); + if (this.destroyed) { + return; + } + + this.settings = { + autoplay: this.options.auto.play, + autoplaySpeed: this.options.auto["play-speed"], + speed: this.options.speed, + adaptiveHeight: this.options.height === "adaptive", + arrows: this.options.arrows === "show", + slidesToShow: this.options.slides["to-show"], + slidesToScroll: this.options.slides["to-scroll"], + dots: this.options.dots === "show", + infinite: this.options.infinite, + }; + if (this.options.appendDots) { + this.settings.appendDots = this.options.appendDots; + } + + this.setup(); + + // Recalculate the carousel dimensions whenever an image or video + // within has been loaded. This also catches elements which are added + // later. + const update = utils.debounce(() => { + if (!this.destroyed && this.el.classList.contains("slick-initialized")) { + $(this.el).slick("setPosition"); + } + }, 100); + this.abort_controller = new AbortController(); + dom.on_media_loaded(this.el, update, { signal: this.abort_controller.signal }); + } + + destroy() { + if (this.destroyed) { + return; + } + this.abort_controller?.abort(); + if (this.el.classList.contains("slick-initialized")) { + // Remove slick's window event listeners and timers. + $(this.el).slick("unslick"); + } + $(this.el).off(`.${this.event_namespace}`); + super.destroy(); + } + + setup() { + // Lazy loading: Slick loads images with a ``data-lazy`` attribute + // when their slide is about to be shown. + for (const img of this.el.querySelectorAll("img[data-src]")) { + if (!img.hasAttribute("data-lazy")) { + img.setAttribute("data-lazy", img.getAttribute("data-src")); + img.removeAttribute("data-src"); + } + } + + // Get the panel ids before initializing slick, which might replace + // them with its own ids. + const panel_ids = [...this.el.children].map((panel) => panel.id); + + const $carousel = $(this.el); + $carousel.slick(this.settings); + + // Links pointing to a panel make the carousel jump to that panel. + this.panel_links = []; + panel_ids.forEach((id, index) => { + if (!id) { + return; + } + const links = document.querySelectorAll(`a[href="#${CSS.escape(id)}"]`); + for (const link of links) { + this.add_event_listener(link, "click", "panel-link", (event) => { + event.preventDefault(); + $carousel.slick("slickGoTo", index); + }); + this.panel_links.push({ link: link, index: index }); + } + }); + this.update_panel_links($carousel.slick("slickCurrentSlide")); + + // Slick triggers its events via jQuery. + $carousel.on( + `afterChange.${this.event_namespace}`, + (event, slick, current_index) => { + if (slick.$slider[0] !== this.el) { + // Event from a nested carousel. + return; + } + this.update_panel_links(current_index); + }, + ); + } + + get event_namespace() { + return `pat-carousel--${this.uuid}`; + } + + update_panel_links(current_index) { + // Mark the links pointing to the current panel. + for (const { link, index } of this.panel_links) { + link.classList.toggle("current", index === current_index); + } + } +} + +registry.register(Pattern); +export default Pattern; +export { Pattern }; diff --git a/src/pat/carousel/carousel--implementation.test.js b/src/pat/carousel/carousel--implementation.test.js new file mode 100644 index 000000000..2047cec24 --- /dev/null +++ b/src/pat/carousel/carousel--implementation.test.js @@ -0,0 +1,271 @@ +import $ from "jquery"; +import Pattern from "./carousel--implementation"; +import events from "../../core/events"; +import utils from "../../core/utils"; +import { jest } from "@jest/globals"; + +describe("pat-carousel", function () { + beforeEach(async function () { + // Load slick before setting up any spies on it. + await import("slick-carousel"); + }); + + afterEach(function () { + document.body.innerHTML = ""; + jest.restoreAllMocks(); + }); + + describe("init", function () { + it("Default options 1", async () => { + document.body.innerHTML = ` + + `; + const el = document.querySelector(".pat-carousel"); + const spy_slick = jest.spyOn($.fn, "slick"); + + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + expect(spy_slick).toHaveBeenCalled(); + + const options = spy_slick.mock.calls[0][0]; + expect(options.autoplay).toBe(false); + expect(options.autoplaySpeed).toBe(1000); + expect(options.speed).toBe(500); + expect(options.adaptiveHeight).toBe(false); + expect(options.arrows).toBe(true); + expect(options.slidesToShow).toBe(1); + expect(options.slidesToScroll).toBe(1); + expect(options.dots).toBe(true); + expect(options.appendDots).toBe(undefined); + }); + + it("Default options 2 (DOM test)", async () => { + document.body.innerHTML = ` + + `; + const el = document.querySelector(".pat-carousel"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + // has been initialized + expect(el.classList.contains("slick-initialized")).toBe(true); + expect(el["pattern-carousel"]).toBe(instance); + + // arrows created + expect(el.querySelectorAll(".slick-arrow").length).toBe(2); + + // navigation dots created + expect(el.querySelectorAll(".slick-dots").length).toBe(1); + }); + + it("Tweak options via DOM", async () => { + document.body.innerHTML = ` + + `; + const el = document.querySelector(".pat-carousel"); + const spy_slick = jest.spyOn($.fn, "slick"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + expect(spy_slick).toHaveBeenCalled(); + const options = spy_slick.mock.calls[0][0]; + expect(options.autoplay).toBe(true); + expect(options.autoplaySpeed).toBe(345); + expect(options.adaptiveHeight).toBe(true); + + // Stop the autoplay timer. + instance.destroy(); + }); + + it("Recalculates the dimensions after images have been loaded.", async () => { + document.body.innerHTML = ` + + `; + const el = document.querySelector(".pat-carousel"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + // Initialized immediately, without waiting for images. + expect(el.classList.contains("slick-initialized")).toBe(true); + + const spy_slick = jest.spyOn($.fn, "slick"); + const images = el.querySelectorAll("img"); + images[0].dispatchEvent(new Event("load")); + images[1].dispatchEvent(new Event("error")); + await utils.timeout(150); // debounce + + // Debounced, only called once. + expect(spy_slick).toHaveBeenCalledTimes(1); + expect(spy_slick).toHaveBeenCalledWith("setPosition"); + }); + + it("Recalculates the dimensions after a video has loaded its metadata, but not for other elements.", async () => { + document.body.innerHTML = ` + + `; + const el = document.querySelector(".pat-carousel"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + const spy_slick = jest.spyOn($.fn, "slick"); + + el.querySelector("iframe").dispatchEvent(new Event("load")); + await utils.timeout(150); // debounce + expect(spy_slick).not.toHaveBeenCalled(); + + el.querySelector("video").dispatchEvent(new Event("loadedmetadata")); + await utils.timeout(150); // debounce + expect(spy_slick).toHaveBeenCalledTimes(1); + expect(spy_slick).toHaveBeenCalledWith("setPosition"); + }); + }); + + describe("Panel links", () => { + it("Jumps to the linked panel and marks the links of the current panel.", async () => { + document.body.innerHTML = ` +

    + Panel 1 + Panel 3 + Panel 3, again +

    + + `; + const el = document.querySelector(".pat-carousel"); + const link1 = document.querySelector(".link1"); + const link3 = document.querySelector(".link3"); + const link3_2 = document.querySelector(".link3-2"); + + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + // The first panel is shown initially. + expect(link1.classList.contains("current")).toBe(true); + expect(link3.classList.contains("current")).toBe(false); + expect(link3_2.classList.contains("current")).toBe(false); + + const click = new Event("click", { cancelable: true }); + link3.dispatchEvent(click); + await utils.timeout(1); + + expect(click.defaultPrevented).toBe(true); + expect($(el).slick("slickCurrentSlide")).toBe(2); + expect(link1.classList.contains("current")).toBe(false); + expect(link3.classList.contains("current")).toBe(true); + expect(link3_2.classList.contains("current")).toBe(true); + + link1.dispatchEvent(new Event("click", { cancelable: true })); + await utils.timeout(1); + + expect($(el).slick("slickCurrentSlide")).toBe(0); + expect(link1.classList.contains("current")).toBe(true); + expect(link3.classList.contains("current")).toBe(false); + }); + }); + + describe("Lazy loading", () => { + it("Lazy loads images with a data-src attribute.", async () => { + document.body.innerHTML = ` + + `; + const el = document.querySelector(".pat-carousel"); + + // jsdom does not load images. Record which images slick loads. + const requested = []; + const orig_create_element = document.createElement.bind(document); + jest.spyOn(document, "createElement").mockImplementation((tag, ...args) => { + const created = orig_create_element(tag, ...args); + if (tag === "img") { + requested.push(created); + } + return created; + }); + + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + const images = el.querySelectorAll("img"); + // The data-src attributes were converted for slick. + expect(images[0].hasAttribute("data-src")).toBe(false); + expect(images[2].getAttribute("data-lazy")).toBe("c.png"); + + // The image of the current panel is loaded, the others are not. + const requested_src = requested.map((img) => img.getAttribute("src")); + expect(requested_src).toContain("a.png"); + expect(requested_src).not.toContain("c.png"); + + // After loading, the image source is set. + $.fx.off = true; + requested.find((img) => img.getAttribute("src") === "a.png").onload(); + $.fx.off = false; + expect(images[0].getAttribute("src")).toBe("a.png"); + expect(images[0].hasAttribute("data-lazy")).toBe(false); + expect(images[2].hasAttribute("src")).toBe(false); + }); + }); + + describe("destroy", () => { + it("Cleans up when destroyed.", async () => { + document.body.innerHTML = ` + Panel 2 +
    + +
    + `; + const el = document.querySelector(".pat-carousel"); + const link2 = document.querySelector(".link2"); + const img = el.querySelector("img"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + const spy_slick = jest.spyOn($.fn, "slick"); + + document.querySelector(".wrapper").remove(); + await utils.timeout(1); // wait for the automatic destroy. + + expect(instance.destroyed).toBe(true); + expect(el["pattern-carousel"]).toBeUndefined(); + expect(spy_slick).toHaveBeenCalledWith("unslick"); + expect(el.classList.contains("slick-initialized")).toBe(false); + + spy_slick.mockClear(); + + // The panel links do not work anymore. + const click = new Event("click", { cancelable: true }); + link2.dispatchEvent(click); + expect(click.defaultPrevented).toBe(false); + + // No recalculation after media loaded. + img.dispatchEvent(new Event("load")); + await utils.timeout(150); // debounce + expect(spy_slick).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/src/pat/carousel/carousel.js b/src/pat/carousel/carousel.js index 240d9aa54..06d69613d 100644 --- a/src/pat/carousel/carousel.js +++ b/src/pat/carousel/carousel.js @@ -1,143 +1,20 @@ /** - * Patterns carousel + * pat-carousel registration module. * - * Copyright 2017 Syslab.com GmbH Alexander Pilz + * The pattern implementation is loaded lazily when the pattern is used for + * the first time. Import the implementation module to use the pattern class + * or its parser directly: + * ./carousel--implementation.js */ -import $ from "jquery"; -import Base from "../../core/base"; -import dom from "../../core/dom"; -import logging from "../../core/logging"; -import Parser from "../../core/parser"; -import utils from "../../core/utils"; +import create_lazy_pattern from "../../core/lazy-pattern"; +import registry from "../../core/registry"; -const log = logging.getLogger("pat.carousel"); - -export const parser = new Parser("carousel"); -parser.addArgument("auto-play", false); -parser.addArgument("auto-play-speed", 1000); -parser.addArgument("speed", 500); -parser.addArgument("height", "fixed"); -parser.addArgument("arrows", "show"); -parser.addArgument("slides-to-show", 1); -parser.addArgument("slides-to-scroll", 1); -parser.addArgument("dots", "show"); -parser.addArgument("append-dots", ""); -parser.addArgument("infinite", false); - -export default Base.extend({ +const Pattern = create_lazy_pattern({ name: "carousel", trigger: ".pat-carousel", - - async init() { - if (window.__patternslib_import_styles) { - import("slick-carousel/slick/slick.scss"); - } - await import("slick-carousel"); - - this.options = parser.parse(this.el, this.options); - this.settings = { - autoplay: this.options.auto.play, - autoplaySpeed: this.options.auto["play-speed"], - speed: this.options.speed, - adaptiveHeight: this.options.height === "adaptive", - arrows: this.options.arrows === "show", - slidesToShow: this.options.slides["to-show"], - slidesToScroll: this.options.slides["to-scroll"], - dots: this.options.dots === "show", - infinite: this.options.infinite, - }; - if (this.options.appendDots) { - this.settings.appendDots = this.options.appendDots; - } - - this.setup(); - - // Recalculate the carousel dimensions whenever an image or video - // within has been loaded. This also catches elements which are added - // later. - const update = utils.debounce(() => { - if (this.el.classList.contains("slick-initialized")) { - $(this.el).slick("setPosition"); - } - }, 100); - dom.on_media_loaded(this.el, update); - }, - - setup() { - const $carousel = $(this.el).slick(this.settings); - let $panel_links = $(); - - $carousel - .children() - .each((index, obj) => { - if (!obj.id) { - return; - } - var $links = $("a[href=#" + obj.id + "]"); - // TODO: fix this. - // eslint-disable-next-line no-undef - if (index === control.currentPage) { - $links.addClass("current"); - } else { - $links.removeClass("current"); - } - $links.on( - "click.pat-carousel", - null, - // TODO: fix this. - // eslint-disable-next-line no-undef - { control: control, index: index }, - this.onPanelLinkClick.bind(this) - ); - $panel_links = $panel_links.add($links); - }) - .end() - .on( - "slide_complete.pat-carousel", - null, - $panel_links, - this.onSlideComplete.bind(this) - ); - }, - - _loadPanelImages(slider, page) { - let $img; - log.info("Loading lazy images on panel " + page); - slider.$items - .eq(page) - .find("img") - .addBack() - .filter("[data-src]") - .each((idx, img) => { - $img = $(img); - this.src = $img.attr("data-src"); - $img.removeAttr("data-src"); - }); - }, - - onPanelLinkClick: function (event) { - event.data.control.gotoPage(event.data.index, false); - event.preventDefault(); - }, - - onInitialized: function (event, slider) { - this._loadPanelImages(slider, slider.options.startPanel); - this._loadPanelImages(slider, slider.options.startPanel + 1); - this._loadPanelImages(slider, 0); - this._loadPanelImages(slider, slider.pages + 1); - }, - - onSlideInit: function (event, slider) { - this._loadPanelImages(slider, slider.targetPage); - }, - - onSlideComplete: function (event, slider) { - var $panel_links = event.data; - $panel_links.removeClass("current"); - if (slider.$targetPage[0].id) - $panel_links - .filter("[href=#" + slider.$targetPage[0].id + "]") - .addClass("current"); - this._loadPanelImages(slider, slider.targetPage + 1); - }, + load: () => import("./carousel--implementation"), }); + +registry.register(Pattern); +export default Pattern; +export { Pattern }; diff --git a/src/pat/carousel/carousel.test.js b/src/pat/carousel/carousel.test.js index 000c6d1c3..cbf1f11e6 100644 --- a/src/pat/carousel/carousel.test.js +++ b/src/pat/carousel/carousel.test.js @@ -1,134 +1,15 @@ -import $ from "jquery"; -import pattern from "./carousel"; -import utils from "../../core/utils"; -import { jest } from "@jest/globals"; - -describe("carousel-plugin", function () { - beforeEach(function () { - $("
    ", { id: "lab" }).appendTo(document.body); - }); - - afterEach(function () { - $("#lab").remove(); - jest.restoreAllMocks(); +import Pattern from "./carousel"; +import Implementation from "./carousel--implementation"; + +describe("pat-carousel registration module", function () { + it("registers a lazily loaded pattern with the implementation's metadata.", function () { + expect(Pattern.lazy).toBe(true); + expect(Pattern.name).toBe(Implementation.name); + expect(Pattern.trigger).toBe(Implementation.trigger); + expect(Pattern.order ?? 1000).toBe(Implementation.order ?? 1000); }); - describe("init", function () { - it("Default options 1", async () => { - $("#lab").html( - "" - ); - - pattern.init(document.createElement("div")); // Just to async-load slick before initializing the spy. - await utils.timeout(10); // wait a bit for all to settle. - - var $carousel = $("#lab ul"); - var spy_slick = jest.spyOn($.fn, "slick"); - - pattern.init($carousel); - await utils.timeout(20); // wait a bit for all to settle. - - expect(spy_slick).toHaveBeenCalled(); - - var options = spy_slick.mock.calls[0][0]; - expect(options.autoplay).toBe(false); - expect(options.autoplaySpeed).toBe(1000); - expect(options.speed).toBe(500); - expect(options.adaptiveHeight).toBe(false); - expect(options.arrows).toBe(true); - expect(options.slidesToShow).toBe(1); - expect(options.slidesToScroll).toBe(1); - expect(options.dots).toBe(true); - expect(options.appendDots).toBe(undefined); - }); - - it("Default options 2 (DOM test)", async () => { - $("#lab").html( - "" - ); - var $carousel = $("#lab ul"); - pattern.init($carousel); - await utils.timeout(20); // wait a bit for all to settle. - - // has been initialized - expect($carousel.hasClass("slick-initialized")).toBe(true); - - // arrows created - expect($carousel.find(".slick-arrow").length).toBe(2); - - // No navigation boxes - expect($carousel.find(".slick-dots").length).toBe(1); - }); - - it("Tweak options via DOM", async () => { - $("#lab").html( - "" - ); - var $carousel = $("#lab ul"); - var spy_slick = jest.spyOn($.fn, "slick"); - pattern.init($carousel); - await utils.timeout(20); // wait a bit for all to settle. - - expect(spy_slick).toHaveBeenCalled(); - var options = spy_slick.mock.calls[0][0]; - expect(options.autoplay).toBe(true); - expect(options.autoplaySpeed).toBe(345); - expect(options.adaptiveHeight).toBe(true); - }); - it("Recalculates the dimensions after images have been loaded.", async () => { - $("#lab").html( - "" - ); - const carousel = document.querySelector("#lab ul"); - pattern.init($(carousel)); - await utils.timeout(20); // wait a bit for all to settle. - - // Initialized immediately, without waiting for images. - expect(carousel.classList.contains("slick-initialized")).toBe(true); - - const spy_slick = jest.spyOn($.fn, "slick"); - const images = carousel.querySelectorAll("img"); - images[0].dispatchEvent(new Event("load")); - images[1].dispatchEvent(new Event("error")); - await utils.timeout(150); // debounce - - // Debounced, only called once. - expect(spy_slick).toHaveBeenCalledTimes(1); - expect(spy_slick).toHaveBeenCalledWith("setPosition"); - }); - it("Recalculates the dimensions after a video has loaded its metadata, but not for other elements.", async () => { - $("#lab").html( - "" - ); - const carousel = document.querySelector("#lab ul"); - pattern.init($(carousel)); - await utils.timeout(20); // wait a bit for all to settle. - - const spy_slick = jest.spyOn($.fn, "slick"); - - carousel.querySelector("iframe").dispatchEvent(new Event("load")); - await utils.timeout(150); // debounce - expect(spy_slick).not.toHaveBeenCalled(); - - carousel.querySelector("video").dispatchEvent(new Event("loadedmetadata")); - await utils.timeout(150); // debounce - expect(spy_slick).toHaveBeenCalledTimes(1); - expect(spy_slick).toHaveBeenCalledWith("setPosition"); - }); + it("loads the implementation.", async function () { + expect(await Pattern.load()).toBe(Implementation); }); }); diff --git a/src/pat/checklist/checklist.js b/src/pat/checklist/checklist.js index a59e11586..cfeacfbf8 100644 --- a/src/pat/checklist/checklist.js +++ b/src/pat/checklist/checklist.js @@ -1,7 +1,9 @@ -import Base from "../../core/base"; +import $ from "jquery"; +import { BasePattern } from "../../core/basepattern"; import Parser from "../../core/parser"; import dom from "../../core/dom"; import events from "../../core/events"; +import registry from "../../core/registry"; import utils from "../../core/utils"; import "../../core/jquery-ext"; @@ -10,27 +12,32 @@ parser.addArgument("select", ".select-all"); parser.addArgument("deselect", ".deselect-all"); parser.addArgument("toggle", ".toggle-all"); -export default Base.extend({ - name: "checklist", - trigger: ".pat-checklist", - jquery_plugin: true, - all_selects: [], - all_deselects: [], - all_toggles: [], - all_checkboxes: [], - all_radios: [], +class Pattern extends BasePattern { + static name = "checklist"; + static trigger = ".pat-checklist"; + static parser = parser; + + all_selects = []; + all_deselects = []; + all_toggles = []; + all_checkboxes = []; + all_radios = []; init() { - this.options = parser.parse(this.el, this.options, false); - this.$el.on("patterns-injected", this._init.bind(this)); + this.$el = $(this.el); + // ``patterns-injected`` is triggered via jQuery. + this.$el.on("patterns-injected.pat-checklist", this._init.bind(this)); this.change_handler = utils.debounce(() => { + if (this.destroyed) { + return; + } this.change_buttons_and_toggles(); this.change_checked(); }, 50); this._init(); - }, + } _init() { this.all_checkboxes = this.el.querySelectorAll(`input[type=checkbox]`); @@ -38,30 +45,30 @@ export default Base.extend({ this.all_selects = dom.find_scoped(this.el, this.options.select); for (const btn of this.all_selects) { - events.add_event_listener( + this.add_event_listener( btn, "click", - "pat-checklist--select-all--click", + "select-all--click", this.select_all.bind(this) ); } this.all_deselects = dom.find_scoped(this.el, this.options.deselect); for (const btn of this.all_deselects) { - events.add_event_listener( + this.add_event_listener( btn, "click", - "pat-checklist--deselect-all--click", + "deselect-all--click", this.deselect_all.bind(this) ); } this.all_toggles = dom.find_scoped(this.el, this.options.toggle); for (const btn of this.all_toggles) { - events.add_event_listener( + this.add_event_listener( btn, "click", - "pat-checklist--toggle-all--click", + "toggle-all--click", this.toggle_all.bind(this) ); } @@ -69,27 +76,18 @@ export default Base.extend({ // update select/deselect button status this.change_buttons_and_toggles(); this.change_checked(); - events.add_event_listener( + this.add_event_listener( this.el, "change", - "pat-checklist--change-handler--change", - this.change_handler.bind(this) + "change-handler--change", + this.change_handler ); - }, + } destroy() { - for (const it of this.all_selects) { - events.remove_event_listener(it, "pat-checklist--select-all--click"); - } - for (const it of this.all_deselects) { - events.remove_event_listener(it, "pat-checklist--deselect-all--click"); - } - for (const it of this.all_toggles) { - events.remove_event_listener(it, "pat-checklist--toggle-all--click"); - } - events.remove_event_listener(this.el, "pat-checklist--change-handler--change"); - this.$el.off("patterns_injected"); - }, + this.$el?.off("patterns-injected.pat-checklist"); + super.destroy(); + } find_siblings(el, sel) { // Looks for the closest elements within the `el` tree that match the @@ -104,7 +102,7 @@ export default Base.extend({ } parent = parent.parentNode; } - }, + } find_checkboxes(ref_el, sel) { let chkbxs; @@ -114,7 +112,7 @@ export default Base.extend({ chkbxs = this.find_siblings(ref_el, sel); } return chkbxs; - }, + } change_buttons_and_toggles() { let chkbxs; @@ -136,7 +134,7 @@ export default Base.extend({ .map((el) => el.matches(":checked")) .every((it) => it === true); } - }, + } select_all(e) { e.preventDefault(); @@ -149,7 +147,7 @@ export default Base.extend({ box.dispatchEvent(events.change_event()); box.dispatchEvent(events.input_event()); } - }, + } deselect_all(e) { e.preventDefault(); @@ -159,7 +157,7 @@ export default Base.extend({ box.dispatchEvent(events.change_event()); box.dispatchEvent(events.input_event()); } - }, + } toggle_all(e) { e.preventDefault(); @@ -170,7 +168,7 @@ export default Base.extend({ box.dispatchEvent(events.change_event()); box.dispatchEvent(events.input_event()); } - }, + } change_checked() { for (const it of [...this.all_checkboxes, ...this.all_radios]) { @@ -193,5 +191,9 @@ export default Base.extend({ fieldset.classList.add("unchecked"); } } - }, -}); + } +} + +registry.register(Pattern); +export default Pattern; +export { Pattern }; diff --git a/src/pat/checklist/checklist.test.js b/src/pat/checklist/checklist.test.js index 90aaa8251..dc381b56e 100644 --- a/src/pat/checklist/checklist.test.js +++ b/src/pat/checklist/checklist.test.js @@ -1,5 +1,6 @@ +import $ from "jquery"; import Pattern from "./checklist"; -import registry from "../../core/registry"; +import events from "../../core/events"; import utils from "../../core/utils"; describe("pat-checklist", () => { @@ -18,7 +19,8 @@ describe("pat-checklist", () => { `; - Pattern.init(document.querySelector(".pat-checklist")); + const instance = new Pattern(document.querySelector(".pat-checklist")); + await events.await_pattern_init(instance); const [f1] = document.querySelectorAll("fieldset"); const [b1, b2] = document.querySelectorAll("button"); @@ -79,7 +81,10 @@ describe("pat-checklist", () => { `; - registry.scan(document.body); + for (const el of document.querySelectorAll(".pat-checklist")) { + const instance = new Pattern(el); + await events.await_pattern_init(instance); + } const [f1, f2] = document.querySelectorAll("fieldset"); const [b1, b2] = document.querySelectorAll("button"); @@ -175,7 +180,10 @@ describe("pat-checklist", () => { `; - registry.scan(document.body); + for (const el of document.querySelectorAll(".pat-checklist")) { + const instance = new Pattern(el); + await events.await_pattern_init(instance); + } const [f1, f2, f3, f4, f5, f6] = document.querySelectorAll("fieldset"); const [b1, b2, b3, b4, b5, b6, b7, b8, b9, b10] = document.querySelectorAll("button"); // prettier-ignore @@ -535,7 +543,8 @@ describe("pat-checklist", () => { `; - Pattern.init(document.querySelector(".pat-checklist")); + const instance = new Pattern(document.querySelector(".pat-checklist")); + await events.await_pattern_init(instance); const [f1] = document.querySelectorAll("fieldset"); const [l1, l2, l3] = document.querySelectorAll("label"); @@ -563,7 +572,8 @@ describe("pat-checklist", () => { `; - Pattern.init(document.querySelector(".pat-checklist")); + const instance = new Pattern(document.querySelector(".pat-checklist")); + await events.await_pattern_init(instance); const [f1] = document.querySelectorAll("fieldset"); const [t1] = document.querySelectorAll("input.toggle-all"); @@ -593,4 +603,112 @@ describe("pat-checklist", () => { expect(i3.checked).toEqual(false); expect(t1.checked).toEqual(false); }); + + it("Global de/select buttons can be shared by multiple pat-checklist instances.", async () => { + document.body.innerHTML = ` + + +
    + +
    + +
    + +
    + `; + for (const el of document.querySelectorAll(".pat-checklist")) { + const instance = new Pattern(el); + await events.await_pattern_init(instance); + } + + const [i1, i2] = document.querySelectorAll("input"); + document.querySelector("#b1").click(); + await utils.timeout(100); + + expect(i1.checked).toBe(true); + expect(i2.checked).toBe(true); + }); + + it("Re-initializes after content was injected.", async () => { + document.body.innerHTML = ` +
    + +
    + `; + const el = document.querySelector(".pat-checklist"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + el.insertAdjacentHTML( + "beforeend", + `` + ); + const label = el.querySelector("label.new"); + expect(label.classList.contains("unchecked")).toBe(false); + + $(el).trigger("patterns-injected"); + expect(label.classList.contains("unchecked")).toBe(true); + }); + + describe("Destroy", () => { + it("Removes the event listeners.", async () => { + document.body.innerHTML = ` + +
    + +
    + `; + const el = document.querySelector(".pat-checklist"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + const label = el.querySelector("label"); + const input = el.querySelector("input"); + expect(label.classList.contains("unchecked")).toBe(true); + + instance.destroy(); + expect(el["pattern-checklist"]).toBeUndefined(); + + // The global select-all button does not work anymore. + document.querySelector("#b1").click(); + await utils.timeout(100); + expect(input.checked).toBe(false); + + // Changes are not reflected anymore. + input.click(); + await utils.timeout(100); + expect(input.checked).toBe(true); + expect(label.classList.contains("unchecked")).toBe(true); + + // Injection events are not handled anymore. + el.insertAdjacentHTML( + "beforeend", + `` + ); + $(el).trigger("patterns-injected"); + expect(el.querySelector("label.new").classList.contains("unchecked")).toBe( + false + ); + }); + + it("Is destroyed when removed from the DOM.", async () => { + document.body.innerHTML = ` + +
    + +
    + `; + const el = document.querySelector(".pat-checklist"); + const input = el.querySelector("input"); + const instance = new Pattern(el); + await events.await_pattern_init(instance); + + el.remove(); + await utils.timeout(1); + expect(instance.destroyed).toBe(true); + + document.querySelector("#b1").click(); + expect(input.checked).toBe(false); + }); + }); }); diff --git a/src/pat/clone/clone--implementation.js b/src/pat/clone/clone--implementation.js new file mode 100644 index 000000000..a368a19fc --- /dev/null +++ b/src/pat/clone/clone--implementation.js @@ -0,0 +1,193 @@ +/* Clone pattern */ +import $ from "jquery"; +import Parser from "../../core/parser"; +import registry from "../../core/registry"; +import { BasePattern } from "../../core/basepattern"; +import logging from "../../core/logging"; +import dom from "../../core/dom"; +import utils from "../../core/utils"; + +const log = logging.getLogger("pat-clone"); +const TEXT_NODE = 3; + +export const parser = new Parser("clone"); +parser.addArgument("max"); +parser.addArgument("template", ":first"); +parser.addArgument("trigger-element", ".add-clone"); +parser.addArgument("remove-element", ".remove-clone"); +parser.addArgument("remove-behaviour", "confirm", ["confirm", "none"]); +parser.addArgument( + "remove-confirmation", + "Are you sure you want to remove this element?" +); +parser.addArgument("clone-element", ".clone"); +parser.addAlias("remove-behavior", "remove-behaviour"); + +class Pattern extends BasePattern { + static name = "clone"; + static trigger = ".pat-clone"; + static parser = parser; + + init() { + this.$el = $(this.el); + if (this.options.template.lastIndexOf(":", 0) === 0) { + this.template = $(this.options.template, this.el)[0]; + } else { + this.template = document.querySelector(this.options.template); + } + + this.bind_trigger(document.body); + + const clones = this.el.querySelectorAll(this.options.cloneElement); + this.num_clones = clones.length; + for (const clone of clones) { + this.bind_remove(clone); + } + } + + get clone_triggers() { + // All clone triggers in the document. + return document.querySelectorAll(this.options.triggerElement); + } + + clone() { + if (this.num_clones >= this.options.max) { + alert("Sorry, only " + this.options.max + " elements allowed."); + return; + } + this.num_clones += 1; + + let $clone = + this.template.nodeName === "TEMPLATE" + ? $([...this.template.content.children]).clone() + : $(this.template).safeClone(); + + const ids = ($clone.attr("id") || "").split(" ").filter((it) => it); + $clone.removeAttr("id").removeClass("disable-patterns"); + $.each( + ids, + function (idx, id) { + // Re-add all ids that have the substring #{1} in them, while + // also replacing that substring with the number of clones. + if (id.indexOf("#{1}") !== -1) { + $clone.attr( + "id", + $clone.attr("id") + ? $clone.attr("id") + " " + : "" + id.replace("#{1}", this.num_clones) + ); + } + }.bind(this) + ); + + $clone.appendTo(this.$el); + $clone + .children() + .addBack() + .contents() + .addBack() + .filter(this.incrementValues.bind(this)); + + this.bind_trigger($clone); + this.bind_remove($clone); + + $clone.prop("hidden", false); + registry.scan($clone); + + $clone.trigger("pat-update", { + pattern: "clone", + action: "added", + dom: $clone[0], + }); + if (this.num_clones >= this.options.max) { + for (const el_ of this.clone_triggers) { + dom.hide(el_); + } + } + } + + incrementValues(idx, el) { + const $el = $(el); + $el.children().addBack().contents().filter(this.incrementValues.bind(this)); + const callback = function (idx, attr) { + if (attr.name === "type" || !$el.attr(attr.name)) { + return; + } + try { + $el.attr( + attr.name, + $el.attr(attr.name).replace("#{1}", this.num_clones) + ); + } catch (e) { + log.warn(e); + } + }; + if (el.nodeType !== TEXT_NODE) { + $.each(el.attributes, callback.bind(this)); + } else if (el.data.length) { + el.data = el.data.replace("#{1}", this.num_clones); + } + } + + bind_trigger(triggers) { + // Bind clone trigger + for (const node of utils.ensureArray(triggers)) { + for (const trigger of dom.querySelectorAllAndMe( + node, + this.options.triggerElement + )) { + // The triggers can be anywhere in the document. Register the + // event listeners instance scoped so that they are removed + // when the pattern is destroyed. + this.add_event_listener(trigger, "click", "clone", () => this.clone()); + } + } + } + + bind_remove(clone) { + for (const node of utils.ensureArray(clone)) { + for (const remove_button of dom.querySelectorAllAndMe( + node, + this.options.remove.element + )) { + this.add_event_listener(remove_button, "click", "remove", () => { + if (this.options.remove.behaviour === "confirm") { + if (window.confirm(this.options.remove.confirmation) === true) { + this.remove(clone); + } + } else { + this.remove(clone); + } + }); + } + } + } + + remove(clone) { + for (const node of utils.ensureArray(clone)) { + // Remove the event listeners within the removed clone. + for (const it of dom.querySelectorAllAndMe( + node, + `${this.options.triggerElement}, ${this.options.remove.element}` + )) { + this.remove_event_listener(it); + } + node.remove(); + this.$el.trigger("pat-update", { + pattern: "clone", + action: "removed", + dom: node, + }); + } + this.num_clones -= 1; + if (this.num_clones < this.options.max) { + for (const el_ of this.clone_triggers) { + dom.show(el_); + } + } + } +} + +registry.register(Pattern); +export default Pattern; +export { Pattern }; diff --git a/src/pat/clone/clone--implementation.test.js b/src/pat/clone/clone--implementation.test.js new file mode 100644 index 000000000..1e13350c6 --- /dev/null +++ b/src/pat/clone/clone--implementation.test.js @@ -0,0 +1,562 @@ +import Base from "../../core/base"; +import registry from "../../core/registry"; +import Clone from "./clone--implementation"; +import events from "../../core/events"; +import utils from "../../core/utils"; +import $ from "jquery"; +import { jest } from "@jest/globals"; + +const init_clones = async (root) => { + // Initialize all pat-clone instances within root. + for (const el of root.querySelectorAll(".pat-clone")) { + const instance = new Clone(el); + await events.await_pattern_init(instance); + } +}; + +describe("pat-clone", function () { + describe("1 - Basic tests", function () { + beforeEach(function () { + $("div#lab").remove(); + $("
    ", { id: "lab" }).appendTo(document.body); + }); + afterEach(function () { + $("#lab").remove(); + jest.restoreAllMocks(); + }); + + it("clones the node's first child when .add-clone is clicked and places the clone after the cloned element", async function () { + var $lab = $("#lab"); + $lab.html( + '
    ' + + '
    Clone Me
    ' + + ' ' + + "
    " + ); + await init_clones($lab[0]); + expect($("div.item").length).toBe(1); + $lab.find(".add-clone").click(); + expect($("div.item").length).toBe(2); + + // Try now a different variation with the trigger inside the cloned + // element. + $lab.empty().html( + '
    ' + + '
    ' + + ' ' + + "
    " + + "
    " + ); + + await init_clones($lab[0]); + expect($("div.item").length).toBe(1); + $lab.find(".add-clone").click(); + expect($("div.item").length).toBe(2); + $lab.find(".add-clone:last").click(); + expect($("div.item").length).toBe(3); + $lab.find(".add-clone:first").click(); + expect($("div.item").length).toBe(4); + }); + + it("allows the trigger element to be configured", async function () { + var $lab = $("#lab"); + $lab.html( + '
    ' + + '
    Clone Me
    ' + + ' ' + + ' ' + + "
    " + ); + await init_clones($lab[0]); + expect($("div.item").length).toBe(1); + $lab.find(".add-clone").click(); + expect($("div.item").length).toBe(1); + $lab.find(".real-add-clone").click(); + expect($("div.item").length).toBe(2); + }); + + it("allows the cloned element to be configured", async function () { + var $lab = $("#lab"); + $lab.html( + '
    ' + + '
    Original item
    ' + + '
    Clone template
    ' + + "
    " + + '' + ); + await init_clones($lab[0]); + expect($("div.item").length).toBe(2); + $lab.find(".add-clone").click(); + expect($("div.item").length).toBe(3); + expect($("div.item:last").text()).toBe("Clone template"); + expect($("div.item:contains('Clone template')").length).toBe(2); + }); + + it("will replace #{1} in element attributes with the number of the clone", async function () { + var $lab = $("#lab"); + $lab.html( + '
    ' + + ' ' + + "
    " + + '' + ); + await init_clones($lab[0]); + expect($("p.legend").length).toBe(1); + expect($("p.legend:last").attr("class")).toBe("legend clone clone#{1}"); + + $lab.find(".add-clone").click(); + expect($("p.legend").length).toBe(2); + expect($("p.legend:last").attr("name")).toBe("item-2"); + expect($("p.legend:last").attr("class")).toBe("legend clone clone2"); + + $lab.find(".add-clone").click(); + expect($("p.legend").length).toBe(3); + expect($("p.legend:last").attr("name")).toBe("item-3"); + expect($("p.legend:last").attr("class")).toBe("legend clone clone3"); + }); + + it("will replace #{1} in the element id with the number of the clone and remove ids without the substring #{1}", async function () { + var $lab = $("#lab"); + $lab.html( + '
    ' + + '

    Family member #{1}

    ' + + "
    " + + '' + ); + await init_clones($lab[0]); + expect($("p.legend").length).toBe(1); + expect($("p.legend:last").attr("id")).toBe("hello world#{1}"); + + $lab.find(".add-clone").click(); + expect($("p.legend").length).toBe(2); + expect($("p.legend:last").attr("id")).toBe("world2"); + + $lab.find(".add-clone").click(); + expect($("p.legend").length).toBe(3); + expect($("p.legend:last").attr("id")).toBe("world3"); + }); + + it('has a "clone-element" argument which is necessary when starting with pre-existing clones', async function () { + jest.spyOn(window, "confirm").mockImplementation(() => { + return true; + }); + var $lab = $("#lab"); + $lab.html( + '
    ' + + '
    ' + + '
    ' + + '
    ' + + "
    " + + '' + ); + await init_clones($lab[0]); + expect($("div.item").length).toBe(3); + + $lab.find(".add-clone").click(); + expect($("div.item").length).toBe(4); + + $lab.find(".remove-clone:last").click(); + expect($("div.item").length).toBe(3); + + $lab.find(".remove-clone:last").click(); + expect($("div.item").length).toBe(2); + + $lab.find(".remove-clone:last").click(); + expect($("div.item").length).toBe(1); + + $lab.find(".remove-clone:last").click(); + expect($("div.item").length).toBe(0); + }); + + it("will remove a clone when .remove-clone inside the clone is clicked.", async function () { + var spy_window = jest.spyOn(window, "confirm").mockImplementation(() => { + return true; + }); + var $lab = $("#lab"); + $lab.html( + '
    ' + + '
    ' + + "
    " + + '' + ); + await init_clones($lab[0]); + expect($("div.item").length).toBe(1); + + $lab.find(".add-clone").click(); + expect($("div.item").length).toBe(2); + + $lab.find(".remove-clone:last").click(); + expect(spy_window).toHaveBeenCalled(); + expect($("div.item").length).toBe(1); + + $lab.find(".remove-clone").click(); + expect(spy_window).toHaveBeenCalled(); + expect($("div.item").length).toBe(0); + }); + + it("allows the remove element to be configured", async function () { + var spy_window = jest.spyOn(window, "confirm").mockImplementation(() => { + return true; + }); + var $lab = $("#lab"); + $lab.html( + '
    ' + + '
    ' + + "
    " + + '' + ); + await init_clones($lab[0]); + expect($("div.item").length).toBe(1); + + $lab.find(".add-clone").click(); + expect($("div.item").length).toBe(2); + + $lab.find(".custom-remove-class:last").click(); + expect(spy_window).toHaveBeenCalled(); + expect($("div.item").length).toBe(1); + + $lab.find(".custom-remove-class").click(); + expect(spy_window).toHaveBeenCalled(); + expect($("div.item").length).toBe(0); + }); + + it("will by default ask for confirmation before removing elements, but can be configured otherwise", async function () { + var spy_confirm = jest.spyOn(window, "confirm").mockImplementation(() => { + return true; + }); + var $lab = $("#lab"); + $lab.html( + '
    ' + + '
    ' + + "
    " + + '' + ); + await init_clones($lab[0]); + expect($("div.item").length).toBe(1); + + $lab.find(".add-clone").click(); + expect($("div.item").length).toBe(2); + + $lab.find(".remove-clone:last").click(); + expect(spy_confirm).toHaveBeenCalled(); + expect(window.confirm.mock.calls.length).toBe(1); + expect($("div.item").length).toBe(1); + + $lab.empty(); + $lab.html( + '
    ' + + '
    ' + + "
    " + + '' + ); + await init_clones($lab[0]); + expect($("div.item").length).toBe(1); + + $lab.find(".add-clone").click(); + expect($("div.item").length).toBe(2); + + $lab.find(".remove-clone:last").click(); + expect(window.confirm.mock.calls.length).toBe(1); + expect($("div.item").length).toBe(1); + }); + }); + + describe("2 - pat clone and pattern initialization", function () { + const patterns = registry.patterns; + + beforeEach(function () { + registry.clear(); + registry.register(Clone, "clone"); + }); + + afterEach(function () { + registry.patterns = patterns; + }); + + it("will initialize patterns when cloned.", async function () { + Base.extend({ + name: "example", + trigger: ".pat-example", + init: function () { + this.el.innerHTML += "initialized"; + }, + }); + + document.body.innerHTML = ` +
    +
    +
    +
    + +
    + `; + registry.scan(document.body); + await utils.timeout(1); + + // Without further action patterns in templates are initialized. + // Not what we want, normally. + expect( + document.body.querySelector("#template .pat-example").textContent + ).toBe("initialized"); + + document.body.querySelector("button").click(); + + // The cloned pattern is double-initialized. + expect( + document.body.querySelector(".pat-clone .pat-example").textContent + ).toBe("initializedinitialized"); + }); + + it("will not initialize patterns in the template wrapped in disable-patterns.", async function () { + Base.extend({ + name: "example", + trigger: ".pat-example", + init: function () { + this.el.innerHTML += "initialized"; + }, + }); + + document.body.innerHTML = ` +
    +
    +
    +
    + +
    + `; + registry.scan(document.body); + await utils.timeout(1); + + // The template-pattern isn't initialized. + expect( + document.body.querySelector("#template .pat-example").textContent + ).toBe(""); + + document.body.querySelector("button").click(); + + // The cloned pattern is only initialized once. + expect( + document.body.querySelector(".pat-clone .pat-example").textContent + ).toBe("initialized"); + }); + + it("will not initialize patterns wrapped in