"),
+ };
+ instance.api = {
+ getBounds: function () {
+ return [500, 600];
+ },
+ };
+ instance.inputs = {
+ x1: $('
'),
+ };
+ });
+
+ it("Update preview", function () {
+ instance.updatePreview(c);
+
+ expect(instance.preview.element.width()).toBe(125);
+ expect(instance.preview.element.height()).toBe(100);
+ expect(instance.preview.element.css("marginLeft")).toBe("-25px");
+ expect(instance.preview.element.css("marginTop")).toBe("-50px");
+ });
+
+ it("Update inputs", function () {
+ instance.updateInputs(c);
+
+ expect(instance.inputs.x1.val()).toBe("100");
+ expect(instance.inputs.x2.val()).toBe("300");
+ expect(instance.inputs.y1.val()).toBe("300");
+ expect(instance.inputs.y2.val()).toBe("600");
+ expect(instance.inputs.w.val()).toBe("200");
+ expect(instance.inputs.h.val()).toBe("300");
+ });
+
+ it("Update from user interaction", function () {
+ const spy_updatePreview = jest.spyOn(instance, "updatePreview");
+ const spy_updateInputs = jest.spyOn(instance, "updateInputs");
+
+ instance.onSelect(c);
+
+ expect(spy_updatePreview).toHaveBeenCalledWith(c);
+ expect(spy_updateInputs).toHaveBeenCalledWith(c);
+ });
+ });
+
+ describe("destroy", function () {
+ it("Destroys the Jcrop instance.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-image-crop");
+ set_complete(el);
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ const api = instance.api;
+ const spy_api_destroy = jest.spyOn(api, "destroy");
+
+ document.querySelector(".wrapper").remove();
+ await utils.timeout(1); // wait for the automatic destroy.
+
+ expect(instance.destroyed).toBe(true);
+ expect(el["pattern-image-crop"]).toBeUndefined();
+ expect(spy_api_destroy).toHaveBeenCalledTimes(1);
+ expect(instance.api).toBe(null);
+ });
+
+ it("Does not set up Jcrop when destroyed before the image is loaded.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-image-crop");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+ expect(instance.api).toBe(null);
+
+ instance.destroy();
+
+ set_complete(el);
+ el.dispatchEvent(new Event("load"));
+
+ expect(instance.api).toBe(null);
+ expect(document.querySelector(".jcrop-holder")).toBe(null);
+ });
+ });
+});
diff --git a/src/pat/image-crop/image-crop.js b/src/pat/image-crop/image-crop.js
index a9f4be408..ebaaee656 100644
--- a/src/pat/image-crop/image-crop.js
+++ b/src/pat/image-crop/image-crop.js
@@ -1,162 +1,20 @@
-import $ from "jquery";
-import logging from "../../core/logging";
-import Parser from "../../core/parser";
+/**
+ * pat-image-crop 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:
+ * ./image-crop--implementation.js
+ */
+import create_lazy_pattern from "../../core/lazy-pattern";
import registry from "../../core/registry";
-const log = logging.getLogger("pat.image-crop");
-
-export const parser = new Parser("image-crop");
-parser.addArgument("preview-id", "");
-parser.addArgument("preview-height", 0);
-parser.addArgument("preview-width", 0);
-parser.addArgument("aspect-ratio", 1);
-parser.addArgument("form-id", "");
-parser.addArgument("initial-sel", "0 0 0 0");
-parser.addArgument("min-size", "0 0");
-parser.addArgument("max-size", "0 0");
-parser.addArgument("input-prefix", "");
-
-var _ = {
+const Pattern = create_lazy_pattern({
name: "image-crop",
trigger: "img.pat-image-crop",
- bounds: [0, 0],
- inputNames: ["x1", "y1", "x2", "y2", "w", "h"],
-
- async init($el, options) {
- await import("jquery-jcrop");
-
- // initialize the elements
- return $el.each(function () {
- var $this = $(this),
- opts = parser.parse($this, options),
- data = {};
-
- // Initialize the preview parameters
- if (opts.preview.id.length === 0) data.preview = false;
- else {
- data.preview = {};
- data.preview.element = $(opts.preview.id);
- if (data.preview.element.length === 0) {
- log.error("Invalid preview element ID supplied: " + opts.preview.id);
- return;
- }
- if (opts.previewWidth > 0 && opts.preview.height > 0) {
- data.preview.width = opts.preview.width;
- data.preview.height = opts.preview.height;
- } else {
- data.preview.width = data.preview.element.parent().width();
- data.preview.height = data.preview.element.parent().height();
- }
- }
-
- // Set the form ID
- if (opts.formId.length === 0) {
- // no form ID supplied. Look for the closest parent form element
- data.form = $this.closest("form");
- if (data.form.length === 0) {
- log.error("No form specified or found");
- return;
- }
- } else {
- data.form = $(opts.formId);
- if (data.form.length === 0) {
- log.error("Invalid form ID supplied: " + opts.formId);
- }
- }
-
- // Setup form inputs
- data.prefix = opts.inputPrefix;
- data.inputs = {};
- for (var i = 0; i < _.inputNames.length; i++)
- data.inputs[_.inputNames[i]] = _._setupInput(
- data.form,
- data.prefix,
- _.inputNames[i]
- );
-
- //
- // Initial coordinates
- //
- var ic = _._parseOpt(opts.initialSel);
- if (ic.length !== 4) log.warn("Invalid coordinates for initial selection");
- else if (ic[2] - ic[0] > 0 && ic[3] - ic[1] > 0) data.initialCoords = ic;
-
- data.aspectRatio = opts.aspectRatio;
- data.minSize = _._parseOpt(opts.minSize);
- data.maxSize = _._parseOpt(opts.maxSize);
-
- var handler = function (c) {
- _.onSelect(c, data);
- };
-
- $this.Jcrop(
- {
- onChange: handler,
- onSelect: handler,
- onRelease: handler,
- aspectRatio: data.aspectRatio,
- setSelect: data.initialCoords,
- minSize: data.minSize,
- maxSize: data.maxSize,
- },
- function () {
- data.api = this;
- _.onSelect(this.tellSelect(), data);
- }
- );
- });
- },
-
- _setupInput: function ($form, prefix, name) {
- var input = $form.find("input[name=" + prefix + name + "]");
- if (input.length === 0)
- input = $('
').appendTo(
- $form
- );
- return input;
- },
-
- _parseOpt: function (val) {
- var ret = val
- .replace(/\s{2,}/g, " ")
- .trim()
- .split(" ");
- for (var i = 0; i < ret.length; i++) ret[i] = parseInt(ret[i], 10);
- return ret;
- },
-
- onSelect: function (c, data) {
- if (data.preview) _.updatePreview(c, data);
- _.updateInputs(c, data);
- },
-
- updatePreview: function (c, data) {
- if (!data.api) return;
- if (parseInt(c.w, 10) > 0) {
- var rx = data.preview.width / c.w,
- ry = data.preview.height / c.h,
- bounds = data.api.getBounds();
-
- data.preview.element.css({
- width: Math.round(rx * bounds[0]) + "px",
- height: Math.round(ry * bounds[1]) + "px",
- marginLeft: "-" + Math.round(rx * c.x) + "px",
- marginTop: "-" + Math.round(ry * c.y) + "px",
- });
- }
- },
-
- updateInputs: function (c, data) {
- if (c && c.w && parseInt(c.w, 10) > 0) {
- data.inputs.x1.attr("value", c.x);
- data.inputs.y1.attr("value", c.y);
- data.inputs.x2.attr("value", c.x2);
- data.inputs.y2.attr("value", c.y2);
- data.inputs.w.attr("value", c.w);
- data.inputs.h.attr("value", c.h);
- }
- },
-};
+ load: () => import("./image-crop--implementation"),
+});
-registry.register(_);
-export default _;
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/image-crop/image-crop.test.js b/src/pat/image-crop/image-crop.test.js
index d530cd1d0..cbd73e3ee 100644
--- a/src/pat/image-crop/image-crop.test.js
+++ b/src/pat/image-crop/image-crop.test.js
@@ -1,106 +1,15 @@
-import pattern from "./image-crop";
-import $ from "jquery";
-import { jest } from "@jest/globals";
+import Pattern from "./image-crop";
+import Implementation from "./image-crop--implementation";
-describe("pat-image-crop", function () {
- beforeEach(function () {
- $("
", { id: "lab" }).appendTo(document.body);
+describe("pat-image-crop 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);
});
- afterEach(function () {
- $("#lab").remove();
- });
-
- describe("setup", function () {
- it("Option parsing", function () {
- var opts = pattern._parseOpt(" 20 300 10 15 ");
-
- expect(opts.length).toBe(4);
- expect(opts).toEqual([20, 300, 10, 15]);
- });
-
- it("Input setup - input already exists", function () {
- $("#lab").html('
');
-
- var form = $("#lab form");
- pattern._setupInput(form, "", "x1");
-
- var input = form.find("input");
- expect(input.length).toBe(1);
- });
-
- it("Input setup - input doesn't exist", function () {
- $("#lab").html('
');
-
- var form = $("#lab form");
- pattern._setupInput(form, "p_", "x1");
-
- var input = form.find('input[name="p_x1"]');
- expect(input.length).toBe(1);
- });
- });
-
- describe("Position Update", function () {
- var data = {
- preview: {
- width: 50,
- height: 50,
- },
- inputs: {},
- api: {
- getBounds: function () {
- return [500, 600];
- },
- },
- };
-
- var c = {
- w: 200,
- h: 300,
- x: 100,
- y: 300,
- x2: 300,
- y2: 600,
- };
-
- beforeEach(function () {
- data.preview.element = $("
");
- data.inputs.x1 = $('
');
- data.inputs.x2 = $('
');
- data.inputs.y1 = $('
');
- data.inputs.y2 = $('
');
- data.inputs.w = $('
');
- data.inputs.h = $('
');
- });
-
- it("Update preview", function () {
- pattern.updatePreview(c, data);
-
- expect(data.preview.element.width()).toBe(125);
- expect(data.preview.element.height()).toBe(100);
- expect(data.preview.element.css("marginLeft")).toBe("-25px");
- expect(data.preview.element.css("marginTop")).toBe("-50px");
- });
-
- it("Update inputs", function () {
- pattern.updateInputs(c, data);
-
- expect(data.inputs.x1.val()).toBe("100");
- expect(data.inputs.x2.val()).toBe("300");
- expect(data.inputs.y1.val()).toBe("300");
- expect(data.inputs.y2.val()).toBe("600");
- expect(data.inputs.w.val()).toBe("200");
- expect(data.inputs.h.val()).toBe("300");
- });
-
- it("Update from user interaction", function () {
- var spy_updatePreview = jest.spyOn(pattern, "updatePreview");
- var spy_updateInputs = jest.spyOn(pattern, "updateInputs");
-
- pattern.onSelect(c, data);
-
- expect(spy_updatePreview).toHaveBeenCalledWith(c, data);
- expect(spy_updateInputs).toHaveBeenCalledWith(c, data);
- });
+ it("loads the implementation.", async function () {
+ expect(await Pattern.load()).toBe(Implementation);
});
});
diff --git a/src/pat/inject/inject.test.js b/src/pat/inject/inject.test.js
index ba81b53c1..0309670be 100644
--- a/src/pat/inject/inject.test.js
+++ b/src/pat/inject/inject.test.js
@@ -414,10 +414,10 @@ describe("pat-inject", function () {
});
it("5.9 - rebase pattern configuration", async () => {
- await import("../calendar/calendar");
+ await import("../calendar/calendar--implementation");
await import("../collapsible/collapsible");
- await import("../date-picker/date-picker");
- await import("../datetime-picker/datetime-picker");
+ await import("../date-picker/date-picker--implementation");
+ await import("../datetime-picker/datetime-picker--implementation");
const res = rebaseHTML(
"https://example.com/test/",
@@ -496,7 +496,7 @@ describe("pat-inject", function () {
});
it("5.11 - doesn't rebase invalid pattern configuration options", async () => {
- await import("../calendar/calendar");
+ await import("../calendar/calendar--implementation");
const res = rebaseHTML(
"https://example.com/test/",
@@ -2704,7 +2704,8 @@ describe("pat-inject", function () {
pattern.init($(form));
await utils.timeout(1);
- new PatAutoSubmit(form);
+ const instance_autosubmit = new PatAutoSubmit(form);
+ await events.await_pattern_init(instance_autosubmit);
expect(spy_trigger).not.toHaveBeenCalled();
diff --git a/src/pat/markdown/markdown--implementation.js b/src/pat/markdown/markdown--implementation.js
new file mode 100644
index 000000000..93b4bc347
--- /dev/null
+++ b/src/pat/markdown/markdown--implementation.js
@@ -0,0 +1,109 @@
+import $ from "jquery";
+import { BasePattern } from "../../core/basepattern";
+import dom from "../../core/dom";
+import events from "../../core/events";
+import logging from "../../core/logging";
+import registry from "../../core/registry";
+import utils from "../../core/utils";
+
+const log = logging.getLogger("pat.markdown");
+
+class Pattern extends BasePattern {
+ static name = "markdown";
+ static trigger = ".pat-markdown";
+
+ async init() {
+ if (this.el.matches(this.trigger)) {
+ /* This pattern can either be used standalone or as an enhancement
+ * to pat-inject. The following only applies to standalone, when
+ * the element is explicitly configured with the pat-markdown
+ * trigger.
+ */
+ const source = dom.is_input(this.el) ? this.el.value : this.el.innerHTML;
+ const rendered = await this.render(source);
+ this.el.replaceWith(...rendered);
+ }
+ }
+
+ async render(text) {
+ const marked = (await import("marked")).marked;
+ const DOMPurify = (await import("dompurify")).default;
+
+ const wrapper = document.createElement("div");
+ const parsed = DOMPurify.sanitize(marked.parse(text));
+ wrapper.innerHTML = parsed;
+
+ // If pat-syntax-highlight is available, highlight code blocks.
+ const SyntaxHighlight = registry.patterns["syntax-highlight"];
+ if (SyntaxHighlight) {
+ for (const item of wrapper.querySelectorAll("pre > code")) {
+ const pre = item.parentElement;
+ pre.classList.add("pat-syntax-highlight");
+ // If the code block language was set in a fenced code block,
+ // marked has already set the language as a class on the code tag.
+ // pat-syntax-highlight will understand this.
+ // Await the instance, as the pattern might be loaded lazily.
+ const instance = await new SyntaxHighlight(pre);
+ await events.await_pattern_init(instance);
+ }
+ }
+
+ return $(wrapper);
+ }
+
+ async renderForInjection(cfg, data) {
+ let header;
+ let source = data;
+ if (cfg.source && (header = /^#+\s*(.*)/.exec(cfg.source)) !== null) {
+ source = this.extractSection(source, header[1]);
+ if (source === null) {
+ log.warn('Could not find section "' + cfg.source + '" in ' + cfg.url);
+ return $("
").attr("data-src", cfg.url);
+ }
+ source += "\n"; // Needed for some markdown syntax
+ }
+ const rendered = await this.render(source);
+ return rendered.attr("data-src", cfg.source ? cfg.url + cfg.source : cfg.url);
+ }
+
+ extractSection(text, header) {
+ let pattern;
+ header = utils.escapeRegExp(header);
+ let matcher = new RegExp(
+ "^((#+)\\s*@TEXT@\\s*|@TEXT@\\s*\\n([=-])+\\s*)$".replace(/@TEXT@/g, header),
+ "m"
+ );
+ let match = matcher.exec(text);
+ if (match === null) {
+ return null;
+ } else if (match[2]) {
+ // We have a ##-style header.
+ const level = match[2].length;
+ pattern =
+ "^#{@LEVEL@}\\s*@TEXT@\\s*$\\n+((?:.|\\n)*?(?=^#{1,@LEVEL@}\\s)|.*(?:.|\\n)*)";
+ pattern = pattern.replace(/@LEVEL@/g, level);
+ } else if (match[3]) {
+ // We have an underscore-style header.
+ if (match[3] === "=")
+ pattern =
+ "^@TEXT@\\s*\\n=+\\s*\\n+((?:.|\\n)*?(?=^.*?\\n=+\\s*$)|(?:.|\\n)*)";
+ else
+ pattern =
+ "^@TEXT@\\s*\\n-+\\s*\\n+((?:.|\\n)*?(?=^.*?\\n[-=]+\\s*$)|(?:.|\\n)*)";
+ } else {
+ log.error("Unexpected section match result", match);
+ return null;
+ }
+ pattern = pattern.replace(/@TEXT@/g, header);
+ matcher = new RegExp(pattern, "m");
+ match = matcher.exec(text);
+ if (match === null) {
+ log.error("Failed to find section with known present header?");
+ }
+ return match !== null ? match[0] : null;
+ }
+}
+
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/markdown/markdown--implementation.test.js b/src/pat/markdown/markdown--implementation.test.js
new file mode 100644
index 000000000..df4ea41d6
--- /dev/null
+++ b/src/pat/markdown/markdown--implementation.test.js
@@ -0,0 +1,200 @@
+import $ from "jquery";
+import events from "../../core/events";
+import Pattern from "./markdown--implementation";
+import { jest } from "@jest/globals";
+
+describe("pat-markdown", function () {
+ beforeEach(function () {
+ $("
", { id: "lab" }).appendTo(document.body);
+ });
+
+ afterEach(function () {
+ $("#lab").remove();
+ });
+
+ describe("when initialized", function () {
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+ it("Replaces the DOM element with the rendered Markdown content.", async function () {
+ var $el = $('
');
+ $el.appendTo("#lab");
+ jest.spyOn(Pattern.prototype, "render").mockImplementation(() => {
+ return $("
Rendering
");
+ });
+
+ const instance = new Pattern($el);
+ await events.await_pattern_init(instance);
+
+ expect($("#lab").html()).toBe("
Rendering
");
+ });
+
+ it("It does not render when the DOM element doesn't have the pattern trigger", async function () {
+ var $el = $("
");
+ $el.appendTo("#lab");
+ jest.spyOn(Pattern.prototype, "render").mockImplementation(() => {
+ return $("
Rendering
");
+ });
+ const instance = new Pattern($el);
+ await events.await_pattern_init(instance);
+
+ expect($("#lab").html()).toBe("
");
+ });
+
+ it("uses content for non-input elements", async function () {
+ var $el = $('
').text("This is markdown");
+ $el.appendTo("#lab");
+ const spy_render = jest
+ .spyOn(Pattern.prototype, "render")
+ .mockImplementation(() => {
+ return $("
");
+ });
+ const instance = new Pattern($el);
+ await events.await_pattern_init(instance);
+
+ expect(spy_render).toHaveBeenCalledWith("This is markdown");
+ });
+
+ it("uses value for input elements", async function () {
+ var $el = $('
').val("This is markdown");
+ $el.appendTo("#lab");
+ const spy_render = jest
+ .spyOn(Pattern.prototype, "render")
+ .mockImplementation(() => {
+ return $("
");
+ });
+ const instance = new Pattern($el);
+ await events.await_pattern_init(instance);
+
+ expect(spy_render).toHaveBeenCalledWith("This is markdown");
+ });
+ });
+
+ describe("when rendering", function () {
+ it("wraps rendering in a div", async function () {
+ const $rendering = await Pattern.prototype.render("*This is markdown*");
+ expect($rendering[0].tagName).toBe("DIV");
+ });
+
+ it("converts markdown into HTML", async function () {
+ const $rendering = await Pattern.prototype.render("*This is markdown*");
+ expect($rendering.html()).toBe(`
This is markdown
\n`);
+ });
+ });
+
+ describe("Session extraction", function () {
+ it("Unknown section", function () {
+ expect(
+ Pattern.prototype.extractSection("## My title\n\nContent", "Other title")
+ ).toBe(null);
+ });
+
+ it("Last hash-section", function () {
+ expect(
+ Pattern.prototype.extractSection("## My title\n\nContent", "My title")
+ ).toBe("## My title\n\nContent");
+ });
+
+ it("Hash-section with following section at same level ", function () {
+ expect(
+ Pattern.prototype.extractSection(
+ "## My title\n\nContent\n## Next section\n",
+ "My title"
+ )
+ ).toBe("## My title\n\nContent\n");
+ });
+
+ it("Hash-section with following section at lower level ", function () {
+ expect(
+ Pattern.prototype.extractSection(
+ "## My title\n\nContent\n### Next section\n",
+ "My title"
+ )
+ ).toBe("## My title\n\nContent\n### Next section\n");
+ });
+
+ it("Double underscore section", function () {
+ expect(
+ Pattern.prototype.extractSection(
+ "My title\n=======\nContent",
+ "My title"
+ )
+ ).toBe("My title\n=======\nContent");
+ });
+
+ it("Double underscore section with following section at same level", function () {
+ expect(
+ Pattern.prototype.extractSection(
+ "My title\n=======\nContent\n\nNext\n====\n",
+ "My title"
+ )
+ ).toBe("My title\n=======\nContent\n\n");
+ });
+
+ it("Double underscore section with following section at lower level", function () {
+ expect(
+ Pattern.prototype.extractSection(
+ "My title\n=======\nContent\n\nNext\n----\n",
+ "My title"
+ )
+ ).toBe("My title\n=======\nContent\n\nNext\n----\n");
+ });
+
+ it("Single underscore section", function () {
+ expect(
+ Pattern.prototype.extractSection(
+ "My title\n-------\nContent",
+ "My title"
+ )
+ ).toBe("My title\n-------\nContent");
+ });
+
+ it("Single underscore section with following section at same level", function () {
+ expect(
+ Pattern.prototype.extractSection(
+ "My title\n-------\nContent\n\nNext\n----\n",
+ "My title"
+ )
+ ).toBe("My title\n-------\nContent\n\n");
+ });
+
+ it("Single underscore section with following section at higher level", function () {
+ expect(
+ Pattern.prototype.extractSection(
+ "My title\n-------\nContent\n\nNext\n====\n",
+ "My title"
+ )
+ ).toBe("My title\n-------\nContent\n\n");
+ });
+ });
+
+ describe("Code blocks", function () {
+ it("It correctly renders code blocks", async function () {
+ await import("../syntax-highlight/syntax-highlight--implementation");
+
+ document.body.innerHTML = `
+
+
+# Title
+
+some content
+
+\`\`\`javascript
+ const foo = "bar";
+\`\`\`
+
+
+
+ `;
+
+ const instance = new Pattern(document.querySelector(".pat-markdown"));
+ await events.await_pattern_init(instance);
+
+ expect(document.body.querySelector("main > div > h1").textContent).toBe("Title"); // prettier-ignore
+ expect(document.body.querySelector("main > div > p").textContent).toBe("some content"); // prettier-ignore
+ expect(document.body.querySelector("main > div > pre code")).toBeTruthy(); // prettier-ignore
+ expect(document.body.querySelector("main > div > pre.language-javascript code.language-javascript")).toBeTruthy(); // prettier-ignore
+ expect(document.body.querySelector("main > div > pre code .hljs-keyword")).toBeTruthy(); // prettier-ignore
+ });
+ });
+});
diff --git a/src/pat/markdown/markdown.js b/src/pat/markdown/markdown.js
index 0fe1976f8..b2ae1713e 100644
--- a/src/pat/markdown/markdown.js
+++ b/src/pat/markdown/markdown.js
@@ -1,108 +1,28 @@
+/**
+ * pat-markdown 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:
+ * ./markdown--implementation.js
+ *
+ * The pat-inject integration for markdown resources stays in this module, so
+ * that injecting markdown files works without a pat-markdown element on the
+ * page.
+ */
import $ from "jquery";
-import { BasePattern } from "../../core/basepattern";
+import create_lazy_pattern from "../../core/lazy-pattern";
import dom from "../../core/dom";
-import events from "../../core/events";
-import logging from "../../core/logging";
import registry from "../../core/registry";
import utils from "../../core/utils";
-const log = logging.getLogger("pat.markdown");
const is_markdown_resource = /\.md$/;
-class Pattern extends BasePattern {
- static name = "markdown";
- static trigger = ".pat-markdown";
-
- async init() {
- if (this.el.matches(this.trigger)) {
- /* This pattern can either be used standalone or as an enhancement
- * to pat-inject. The following only applies to standalone, when
- * the element is explicitly configured with the pat-markdown
- * trigger.
- */
- const source = dom.is_input(this.el) ? this.el.value : this.el.innerHTML;
- const rendered = await this.render(source);
- this.el.replaceWith(...rendered);
- }
- }
-
- async render(text) {
- const marked = (await import("marked")).marked;
- const DOMPurify = (await import("dompurify")).default;
-
- const wrapper = document.createElement("div");
- const parsed = DOMPurify.sanitize(marked.parse(text));
- wrapper.innerHTML = parsed;
-
- // If pat-syntax-highlight is available, highlight code blocks.
- const SyntaxHighlight = registry.patterns["syntax-highlight"];
- if (SyntaxHighlight) {
- for (const item of wrapper.querySelectorAll("pre > code")) {
- const pre = item.parentElement;
- pre.classList.add("pat-syntax-highlight");
- // If the code block language was set in a fenced code block,
- // marked has already set the language as a class on the code tag.
- // pat-syntax-highlight will understand this.
- new SyntaxHighlight(pre);
- await events.await_event(pre, "init.syntax-highlight.patterns");
- }
- }
-
- return $(wrapper);
- }
-
- async renderForInjection(cfg, data) {
- let header;
- let source = data;
- if (cfg.source && (header = /^#+\s*(.*)/.exec(cfg.source)) !== null) {
- source = this.extractSection(source, header[1]);
- if (source === null) {
- log.warn('Could not find section "' + cfg.source + '" in ' + cfg.url);
- return $("
").attr("data-src", cfg.url);
- }
- source += "\n"; // Needed for some markdown syntax
- }
- const rendered = await this.render(source);
- return rendered.attr("data-src", cfg.source ? cfg.url + cfg.source : cfg.url);
- }
-
- extractSection(text, header) {
- let pattern;
- header = utils.escapeRegExp(header);
- let matcher = new RegExp(
- "^((#+)\\s*@TEXT@\\s*|@TEXT@\\s*\\n([=-])+\\s*)$".replace(/@TEXT@/g, header),
- "m"
- );
- let match = matcher.exec(text);
- if (match === null) {
- return null;
- } else if (match[2]) {
- // We have a ##-style header.
- const level = match[2].length;
- pattern =
- "^#{@LEVEL@}\\s*@TEXT@\\s*$\\n+((?:.|\\n)*?(?=^#{1,@LEVEL@}\\s)|.*(?:.|\\n)*)";
- pattern = pattern.replace(/@LEVEL@/g, level);
- } else if (match[3]) {
- // We have an underscore-style header.
- if (match[3] === "=")
- pattern =
- "^@TEXT@\\s*\\n=+\\s*\\n+((?:.|\\n)*?(?=^.*?\\n=+\\s*$)|(?:.|\\n)*)";
- else
- pattern =
- "^@TEXT@\\s*\\n-+\\s*\\n+((?:.|\\n)*?(?=^.*?\\n[-=]+\\s*$)|(?:.|\\n)*)";
- } else {
- log.error("Unexpected section match result", match);
- return null;
- }
- pattern = pattern.replace(/@TEXT@/g, header);
- matcher = new RegExp(pattern, "m");
- match = matcher.exec(text);
- if (match === null) {
- log.error("Failed to find section with known present header?");
- }
- return match !== null ? match[0] : null;
- }
-}
+const Pattern = create_lazy_pattern({
+ name: "markdown",
+ trigger: ".pat-markdown",
+ load: () => import("./markdown--implementation"),
+});
dom.document_ready(() => {
$(document.body).on(
@@ -131,7 +51,8 @@ async function register_external_handlers() {
async sources(cfgs, data) {
return await Promise.all(
cfgs.map(async function (cfg) {
- const pat = new Pattern(cfg.$target[0]);
+ // Await the instance, as the pattern is loaded lazily.
+ const pat = await new Pattern(cfg.$target[0]);
const rendered = await pat.renderForInjection(cfg, data);
return rendered;
})
diff --git a/src/pat/markdown/markdown.test.js b/src/pat/markdown/markdown.test.js
index 4c1db9383..9e8bce62d 100644
--- a/src/pat/markdown/markdown.test.js
+++ b/src/pat/markdown/markdown.test.js
@@ -1,200 +1,61 @@
import $ from "jquery";
-import events from "../../core/events";
+import inject from "../inject/inject";
import Pattern from "./markdown";
-import { jest } from "@jest/globals";
-
-describe("pat-markdown", function () {
- beforeEach(function () {
- $("
", { id: "lab" }).appendTo(document.body);
- });
+import Implementation from "./markdown--implementation";
+import utils from "../../core/utils";
+describe("pat-markdown registration module", function () {
afterEach(function () {
- $("#lab").remove();
+ document.body.innerHTML = "";
});
- describe("when initialized", function () {
- afterEach(() => {
- jest.restoreAllMocks();
- });
- it("Replaces the DOM element with the rendered Markdown content.", async function () {
- var $el = $('
');
- $el.appendTo("#lab");
- jest.spyOn(Pattern.prototype, "render").mockImplementation(() => {
- return $("
Rendering
");
- });
-
- const instance = new Pattern($el);
- await events.await_pattern_init(instance);
-
- expect($("#lab").html()).toBe("
Rendering
");
- });
-
- it("It does not render when the DOM element doesn't have the pattern trigger", async function () {
- var $el = $("
");
- $el.appendTo("#lab");
- jest.spyOn(Pattern.prototype, "render").mockImplementation(() => {
- return $("
Rendering
");
- });
- const instance = new Pattern($el);
- await events.await_pattern_init(instance);
-
- expect($("#lab").html()).toBe("
");
- });
-
- it("uses content for non-input elements", async function () {
- var $el = $('
').text("This is markdown");
- $el.appendTo("#lab");
- const spy_render = jest
- .spyOn(Pattern.prototype, "render")
- .mockImplementation(() => {
- return $("
");
- });
- const instance = new Pattern($el);
- await events.await_pattern_init(instance);
-
- expect(spy_render).toHaveBeenCalledWith("This is markdown");
- });
-
- it("uses value for input elements", async function () {
- var $el = $('
').val("This is markdown");
- $el.appendTo("#lab");
- const spy_render = jest
- .spyOn(Pattern.prototype, "render")
- .mockImplementation(() => {
- return $("
");
- });
- const instance = new Pattern($el);
- await events.await_pattern_init(instance);
-
- expect(spy_render).toHaveBeenCalledWith("This is markdown");
- });
+ 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("when rendering", function () {
- it("wraps rendering in a div", async function () {
- const $rendering = await Pattern.prototype.render("*This is markdown*");
- expect($rendering[0].tagName).toBe("DIV");
- });
-
- it("converts markdown into HTML", async function () {
- const $rendering = await Pattern.prototype.render("*This is markdown*");
- expect($rendering.html()).toBe(`
This is markdown
\n`);
- });
+ it("loads the implementation.", async function () {
+ expect(await Pattern.load()).toBe(Implementation);
});
- describe("Session extraction", function () {
- it("Unknown section", function () {
- expect(
- Pattern.prototype.extractSection("## My title\n\nContent", "Other title")
- ).toBe(null);
- });
-
- it("Last hash-section", function () {
- expect(
- Pattern.prototype.extractSection("## My title\n\nContent", "My title")
- ).toBe("## My title\n\nContent");
- });
-
- it("Hash-section with following section at same level ", function () {
- expect(
- Pattern.prototype.extractSection(
- "## My title\n\nContent\n## Next section\n",
- "My title"
- )
- ).toBe("## My title\n\nContent\n");
- });
-
- it("Hash-section with following section at lower level ", function () {
- expect(
- Pattern.prototype.extractSection(
- "## My title\n\nContent\n### Next section\n",
- "My title"
- )
- ).toBe("## My title\n\nContent\n### Next section\n");
- });
-
- it("Double underscore section", function () {
- expect(
- Pattern.prototype.extractSection(
- "My title\n=======\nContent",
- "My title"
- )
- ).toBe("My title\n=======\nContent");
- });
-
- it("Double underscore section with following section at same level", function () {
- expect(
- Pattern.prototype.extractSection(
- "My title\n=======\nContent\n\nNext\n====\n",
- "My title"
- )
- ).toBe("My title\n=======\nContent\n\n");
- });
-
- it("Double underscore section with following section at lower level", function () {
- expect(
- Pattern.prototype.extractSection(
- "My title\n=======\nContent\n\nNext\n----\n",
- "My title"
- )
- ).toBe("My title\n=======\nContent\n\nNext\n----\n");
- });
-
- it("Single underscore section", function () {
- expect(
- Pattern.prototype.extractSection(
- "My title\n-------\nContent",
- "My title"
- )
- ).toBe("My title\n-------\nContent");
- });
-
- it("Single underscore section with following section at same level", function () {
- expect(
- Pattern.prototype.extractSection(
- "My title\n-------\nContent\n\nNext\n----\n",
- "My title"
- )
- ).toBe("My title\n-------\nContent\n\n");
- });
-
- it("Single underscore section with following section at higher level", function () {
- expect(
- Pattern.prototype.extractSection(
- "My title\n-------\nContent\n\nNext\n====\n",
- "My title"
- )
- ).toBe("My title\n-------\nContent\n\n");
- });
+ it("registers a markdown type handler for pat-inject.", async function () {
+ // The handler is registered one tick after the module was loaded.
+ await utils.timeout(1);
+
+ document.body.innerHTML = `
`;
+ const cfg = {
+ url: "README.md",
+ $target: $("#target"),
+ };
+ const sources = await inject.callTypeHandler("markdown", "sources", inject, [
+ [cfg],
+ "# Title\n\nSome *text*.",
+ ]);
+
+ expect(sources.length).toBe(1);
+ const rendered = sources[0][0];
+ expect(rendered.querySelector("h1").textContent).toBe("Title");
+ expect(rendered.querySelector("em").textContent).toBe("text");
+ expect(rendered.getAttribute("data-src")).toBe("README.md");
});
- describe("Code blocks", function () {
- it("It correctly renders code blocks", async function () {
- await import("../syntax-highlight/syntax-highlight");
-
- document.body.innerHTML = `
-
-
-# Title
-
-some content
-
-\`\`\`javascript
- const foo = "bar";
-\`\`\`
-
-
-
- `;
-
- const instance = new Pattern(document.querySelector(".pat-markdown"));
- await events.await_pattern_init(instance);
-
- expect(document.body.querySelector("main > div > h1").textContent).toBe("Title"); // prettier-ignore
- expect(document.body.querySelector("main > div > p").textContent).toBe("some content"); // prettier-ignore
- expect(document.body.querySelector("main > div > pre code")).toBeTruthy(); // prettier-ignore
- expect(document.body.querySelector("main > div > pre.language-javascript code.language-javascript")).toBeTruthy(); // prettier-ignore
- expect(document.body.querySelector("main > div > pre code .hljs-keyword")).toBeTruthy(); // prettier-ignore
- });
+ it("marks pat-inject URLs to markdown resources with the markdown data type.", async function () {
+ document.body.innerHTML = `
+
+
+ `;
+ const [md_link, html_link] = document.querySelectorAll("a");
+ const md_cfgs = [{ url: "README.md" }];
+ const html_cfgs = [{ url: "page.html" }];
+ $(md_link).data("pat-inject", md_cfgs);
+ $(html_link).data("pat-inject", html_cfgs);
+
+ $(md_link).trigger("patterns-inject-triggered");
+ $(html_link).trigger("patterns-inject-triggered");
+
+ expect(md_cfgs[0].dataType).toBe("markdown");
+ expect(html_cfgs[0].dataType).toBeUndefined();
});
});
diff --git a/src/pat/masonry/masonry--implementation.js b/src/pat/masonry/masonry--implementation.js
new file mode 100644
index 000000000..ebc043993
--- /dev/null
+++ b/src/pat/masonry/masonry--implementation.js
@@ -0,0 +1,195 @@
+/**
+ * Patternslib pattern for Masonry
+ * Copyright 2015 Syslab.com GmBH
+ */
+import $ from "jquery";
+import logging from "../../core/logging";
+import Parser from "../../core/parser";
+import { BasePattern } from "../../core/basepattern";
+import dom from "../../core/dom";
+import registry from "../../core/registry";
+import utils from "../../core/utils";
+
+// Lazy loading modules.
+let Masonry;
+
+const log = logging.getLogger("pat.masonry");
+
+export const parser = new Parser("masonry");
+// parser.addArgument("stagger", "");
+parser.addArgument("column-width");
+parser.addArgument("container-style", '{ "position": "relative" }');
+parser.addArgument("gutter");
+parser.addArgument("is-fit-width", false);
+parser.addArgument("is-horizontal-order", false); // preserve horizontal order.
+parser.addArgument("is-origin-left", true);
+parser.addArgument("is-origin-top", true);
+parser.addArgument("is-percent-position", false); // set item positions in percent values. items will not transition on resize.
+parser.addArgument("is-resize", true); // adjust sizes and position on resize.
+parser.addArgument("item-selector", ".item");
+parser.addArgument("stamp", "");
+parser.addArgument("transition-duration", "0.4s");
+
+// is-* are masonry v3 options, here we add v4 style names.
+// we keep the is-* as there is special support with options parsing.
+parser.addAlias("fit-width", "is-fit-width");
+parser.addAlias("origin-left", "is-origin-left");
+parser.addAlias("origin-top", "is-origin-top");
+parser.addAlias("horizontal-order", "is-horizontal-order");
+parser.addAlias("percent-position", "is-percent-position");
+parser.addAlias("resize", "is-resize");
+
+class Pattern extends BasePattern {
+ static name = "masonry";
+ static trigger = ".pat-masonry";
+ static parser = parser;
+
+ msnry = null;
+ observer = null;
+ abort_controller = null;
+
+ async init() {
+ Masonry = (await import("masonry-layout")).default;
+ if (this.destroyed) {
+ return;
+ }
+
+ this.$el = $(this.el);
+
+ // Initialize
+ this.initMasonry();
+
+ // Used to stop listening for loaded media on destroy.
+ this.abort_controller = new AbortController();
+ const signal = this.abort_controller.signal;
+
+ // Re-layout whenever an image or video within has been loaded.
+ // This also catches elements which are added later.
+ dom.on_media_loaded(this.el, () => this.quicklayout(), { signal });
+ // When all images are loaded, do a full layout which sets the
+ // ``masonry-ready`` class.
+ dom.images_loaded(this.el, { signal })
+ .then(() => this.layout())
+ .catch(() => {
+ // Aborted on destroy.
+ });
+
+ // Update if something gets injected inside the pat-masonry.
+ // These events are triggered via jQuery, so we need to listen via
+ // jQuery.
+ const debounced_update = utils.debounce(() => {
+ if (!this.destroyed) {
+ this.update();
+ }
+ }, 100);
+ const debounced_quicklayout_on_update = utils.debounce(() => {
+ if (!this.destroyed) {
+ this.quicklayout();
+ }
+ }, 200);
+ this.$el
+ .on(`patterns-injected.${this.event_namespace}`, debounced_update)
+ .on(`pat-update.${this.event_namespace}`, debounced_quicklayout_on_update);
+
+ const debounced_quicklayout = utils.debounce(() => {
+ if (!this.destroyed) {
+ this.quicklayout();
+ }
+ }, 400);
+ this.observer = new MutationObserver(debounced_quicklayout);
+ /* Explicitly not including style. We assume style is set dynamically only by scripts and we do all our controlled changes through classes.
+ That way we avoid masonry to react on its own style calculation */
+ this.observer.observe(document.body, {
+ childList: true,
+ subtree: true,
+ characterData: false,
+ attributeOldValue: true,
+ attributes: true,
+ attributeFilter: ["class"],
+ });
+ }
+
+ get event_namespace() {
+ return `pat-masonry--${this.uuid}`;
+ }
+
+ destroy() {
+ if (this.destroyed) {
+ return;
+ }
+ this.observer?.disconnect();
+ this.abort_controller?.abort();
+ this.$el?.off(`.${this.event_namespace}`);
+ this.msnry?.destroy();
+ this.msnry = null;
+ super.destroy();
+ }
+
+ initMasonry() {
+ let container_style;
+ try {
+ container_style = JSON.parse(this.options.containerStyle);
+ } catch {
+ container_style = { position: "relative" };
+ log.warn(
+ "Invalid value passed in as containerStyle. Needs to " +
+ "be valid JSON so that it can be converted to an object for Masonry.",
+ );
+ }
+ this.msnry = new Masonry(this.el, {
+ columnWidth: this.getTypeCastedValue(this.options.columnWidth),
+ containerStyle: container_style,
+ fitWidth: this.options.is["fit-width"],
+ gutter: this.getTypeCastedValue(this.options.gutter),
+ horizontalOrder: this.options.is["horizontal-order"],
+ initLayout: false,
+ itemSelector: this.options.itemSelector,
+ originLeft: this.options.is["origin-left"],
+ originTop: this.options.is["origin-top"],
+ percentPosition: this.options.is["percent-position"],
+ resize: this.options.is["resize"],
+ stamp: this.options.stamp,
+ transitionDuration: this.options.transitionDuration,
+ });
+ }
+
+ update() {
+ this.msnry.remove();
+ this.initMasonry();
+ this.layout();
+ }
+
+ quicklayout() {
+ if (!this.msnry) {
+ // Not initialized yet or already destroyed.
+ return;
+ }
+ // call masonry layout on the children before calling it on this element
+ for (const child of this.el.querySelectorAll(".pat-masonry")) {
+ child["pattern-masonry"]?.quicklayout();
+ }
+ this.msnry.layout();
+ }
+
+ layout() {
+ if (!this.msnry) {
+ // Not initialized yet or already destroyed.
+ return;
+ }
+ this.el.classList.remove("masonry-ready");
+ this.msnry.once("layoutComplete", () => {
+ this.el.classList.add("masonry-ready");
+ });
+ this.msnry.layout();
+ this.quicklayout();
+ }
+
+ getTypeCastedValue(original) {
+ const val = Number(original);
+ return isNaN(val) ? original || 0 : val;
+ }
+}
+
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/masonry/masonry--implementation.test.js b/src/pat/masonry/masonry--implementation.test.js
new file mode 100644
index 000000000..c70ed234a
--- /dev/null
+++ b/src/pat/masonry/masonry--implementation.test.js
@@ -0,0 +1,193 @@
+import $ from "jquery";
+import Pattern from "./masonry--implementation";
+import events from "../../core/events";
+import utils from "../../core/utils";
+import { jest } from "@jest/globals";
+
+const set_complete = (img) => {
+ // jsdom does not load images. Mark them as loaded.
+ Object.defineProperty(img, "complete", { value: true });
+};
+
+describe("pat-masonry", function () {
+ afterEach(function () {
+ document.body.innerHTML = "";
+ jest.restoreAllMocks();
+ });
+
+ it("Sets class masonry-ready on the element after masonry has finished", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-masonry");
+ expect(el.classList.contains("masonry-ready")).toBe(false);
+
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ expect(el.classList.contains("masonry-ready")).toBe(true);
+ });
+
+ it("Waits for all images to be loaded before setting masonry-ready", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-masonry");
+ const [img1, img2] = el.querySelectorAll("img");
+
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+ const spy_quicklayout = jest.spyOn(instance, "quicklayout");
+ const spy_layout = jest.spyOn(instance, "layout");
+
+ expect(el.classList.contains("masonry-ready")).toBe(false);
+
+ // First image loaded - quick re-layout, but not ready yet.
+ set_complete(img1);
+ img1.dispatchEvent(new Event("load"));
+ await utils.timeout(1); // wait a tick for async to settle.
+ expect(spy_quicklayout).toHaveBeenCalled();
+ expect(spy_layout).not.toHaveBeenCalled();
+ expect(el.classList.contains("masonry-ready")).toBe(false);
+
+ // Second image failed loading - full layout and ready.
+ set_complete(img2);
+ img2.dispatchEvent(new Event("error"));
+ await utils.timeout(1); // wait a tick for async to settle.
+ expect(spy_layout).toHaveBeenCalledTimes(1);
+ expect(el.classList.contains("masonry-ready")).toBe(true);
+
+ // Images loaded later only lead to a quick re-layout.
+ spy_quicklayout.mockClear();
+ img1.dispatchEvent(new Event("load"));
+ await utils.timeout(1); // wait a tick for async to settle.
+ expect(spy_quicklayout).toHaveBeenCalledTimes(1);
+ expect(spy_layout).toHaveBeenCalledTimes(1);
+ });
+
+ it("Re-layouts when a video has loaded its metadata, but not for other elements", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-masonry");
+
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+ await utils.timeout(1); // wait a tick for async to settle.
+ const spy_quicklayout = jest.spyOn(instance, "quicklayout");
+
+ el.querySelector("iframe").dispatchEvent(new Event("load"));
+ expect(spy_quicklayout).not.toHaveBeenCalled();
+
+ el.querySelector("video").dispatchEvent(new Event("loadedmetadata"));
+ expect(spy_quicklayout).toHaveBeenCalledTimes(1);
+ });
+
+ it("Does not wait for lazy loading images", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-masonry");
+
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ expect(el.classList.contains("masonry-ready")).toBe(true);
+ });
+
+ it("Does not accumulate layoutComplete event listeners", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-masonry");
+
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ instance.layout();
+ instance.layout();
+ instance.layout();
+
+ expect(instance.msnry._events?.layoutComplete?.length || 0).toBe(0);
+ });
+
+ it("Calls quicklayout on nested masonry patterns", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const inner_el = document.querySelector(".inner");
+ const outer_el = document.querySelector(".outer");
+
+ const inner = new Pattern(inner_el);
+ await events.await_pattern_init(inner);
+ const outer = new Pattern(outer_el);
+ await events.await_pattern_init(outer);
+
+ expect(inner_el["pattern-masonry"]).toBe(inner);
+ const spy_inner_quicklayout = jest.spyOn(inner, "quicklayout");
+ outer.quicklayout();
+ expect(spy_inner_quicklayout).toHaveBeenCalledTimes(1);
+ });
+
+ it("Cleans up when destroyed", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-masonry");
+ const img = el.querySelector("img");
+
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ const msnry = instance.msnry;
+ const spy_msnry_destroy = jest.spyOn(msnry, "destroy");
+ const spy_disconnect = jest.spyOn(instance.observer, "disconnect");
+ const spy_quicklayout = jest.spyOn(instance, "quicklayout");
+ const spy_layout = jest.spyOn(instance, "layout");
+ const spy_update = jest.spyOn(instance, "update");
+
+ el.remove();
+ await utils.timeout(1); // wait for the automatic destroy.
+
+ expect(instance.destroyed).toBe(true);
+ expect(el["pattern-masonry"]).toBeUndefined();
+ expect(spy_msnry_destroy).toHaveBeenCalledTimes(1);
+ expect(spy_disconnect).toHaveBeenCalledTimes(1);
+ expect(instance.msnry).toBe(null);
+
+ // No more re-layouts on media load.
+ set_complete(img);
+ img.dispatchEvent(new Event("load"));
+ await utils.timeout(1);
+ expect(spy_quicklayout).not.toHaveBeenCalled();
+ expect(spy_layout).not.toHaveBeenCalled();
+
+ // No more updates on injection or pat-update events.
+ $(el).trigger("patterns-injected");
+ $(el).trigger("pat-update");
+ await utils.timeout(250);
+ expect(spy_update).not.toHaveBeenCalled();
+ expect(spy_quicklayout).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/pat/masonry/masonry.js b/src/pat/masonry/masonry.js
index 0d6681615..cb8151d7f 100644
--- a/src/pat/masonry/masonry.js
+++ b/src/pat/masonry/masonry.js
@@ -1,141 +1,20 @@
/**
- * Patternslib pattern for Masonry
- * Copyright 2015 Syslab.com GmBH
+ * pat-masonry 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:
+ * ./masonry--implementation.js
*/
-import $ from "jquery";
-import logging from "../../core/logging";
-import Parser from "../../core/parser";
-import Base from "../../core/base";
-import dom from "../../core/dom";
-import utils from "../../core/utils";
+import create_lazy_pattern from "../../core/lazy-pattern";
+import registry from "../../core/registry";
-// Lazy loading modules.
-let Masonry;
-
-const log = logging.getLogger("pat.masonry");
-
-export const parser = new Parser("masonry");
-// parser.addArgument("stagger", "");
-parser.addArgument("column-width");
-parser.addArgument("container-style", '{ "position": "relative" }');
-parser.addArgument("gutter");
-parser.addArgument("is-fit-width", false);
-parser.addArgument("is-horizontal-order", false); // preserve horizontal order.
-parser.addArgument("is-origin-left", true);
-parser.addArgument("is-origin-top", true);
-parser.addArgument("is-percent-position", false); // set item positions in percent values. items will not transition on resize.
-parser.addArgument("is-resize", true); // adjust sizes and position on resize.
-parser.addArgument("item-selector", ".item");
-parser.addArgument("stamp", "");
-parser.addArgument("transition-duration", "0.4s");
-
-// is-* are masonry v3 options, here we add v4 style names.
-// we keep the is-* as there is special support with options parsing.
-parser.addAlias("fit-width", "is-fit-width");
-parser.addAlias("origin-left", "is-origin-left");
-parser.addAlias("origin-top", "is-origin-top");
-parser.addAlias("horizontal-order", "is-horizontal-order");
-parser.addAlias("percent-position", "is-percent-position");
-parser.addAlias("resize", "is-resize");
-
-export default Base.extend({
+const Pattern = create_lazy_pattern({
name: "masonry",
trigger: ".pat-masonry",
-
- async init($el, opts) {
- Masonry = (await import("masonry-layout")).default;
-
- this.options = parser.parse(this.$el, opts);
- // Initialize
- this.initMasonry();
-
- // Re-layout whenever an image or video within has been loaded.
- // This also catches elements which are added later.
- dom.on_media_loaded(this.el, () => this.quicklayout());
- // When all images are loaded, do a full layout which sets the
- // ``masonry-ready`` class.
- dom.images_loaded(this.el).then(() => this.layout());
-
- // Update if something gets injected inside the pat-masonry
- this.$el
- .on(
- "patterns-injected.pat-masonry",
- utils.debounce(this.update.bind(this), 100)
- )
- .on("pat-update", utils.debounce(this.quicklayout.bind(this), 200));
-
- var callback = utils.debounce(this.quicklayout.bind(this), 400);
- var observer = new MutationObserver(callback);
- /* Explicitly not including style. We assume style is set dynamically only by scripts and we do all our controlled changes through classes.
- That way we avoid masonry to react on its own style calculation */
- var config = {
- childList: true,
- subtree: true,
- characterData: false,
- attributeOldValue: true,
- attributes: true,
- attributeFilter: ["class"],
- };
- observer.observe(document.body, config);
- },
-
- async initMasonry() {
- var containerStyle;
- try {
- containerStyle = JSON.parse(this.options.containerStyle);
- } catch {
- containerStyle = { position: "relative" };
- log.warn(
- "Invalid value passed in as containerStyle. Needs to " +
- "be valid JSON so that it can be converted to an object for Masonry."
- );
- }
- this.msnry = new Masonry(this.$el[0], {
- columnWidth: this.getTypeCastedValue(this.options.columnWidth),
- containerStyle: containerStyle,
- fitWidth: this.options.is["fit-width"],
- gutter: this.getTypeCastedValue(this.options.gutter),
- horizontalOrder: this.options.is["horizontal-order"],
- initLayout: false,
- itemSelector: this.options.itemSelector,
- originLeft: this.options.is["origin-left"],
- originTop: this.options.is["origin-top"],
- percentPosition: this.options.is["percent-position"],
- resize: this.options.is["resize"],
- stamp: this.options.stamp,
- transitionDuration: this.options.transitionDuration,
- });
- },
-
- update: function () {
- this.msnry.remove();
- this.initMasonry();
- this.layout();
- },
-
- quicklayout: function () {
- if (!this.msnry) {
- // Not initialized yet
- return;
- }
- // call masonry layout on the children before calling it on this element
- this.$el.find(".pat-masonry").each(function (idx, child) {
- $(child).patMasonry("quicklayout");
- });
- this.msnry.layout();
- },
-
- layout: function () {
- this.$el.removeClass("masonry-ready");
- this.msnry.once("layoutComplete", () => {
- this.$el.addClass("masonry-ready");
- });
- this.msnry.layout();
- this.quicklayout();
- },
-
- getTypeCastedValue: function (original) {
- var val = Number(original);
- return isNaN(val) ? original || 0 : val;
- },
+ load: () => import("./masonry--implementation"),
});
+
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/masonry/masonry.test.js b/src/pat/masonry/masonry.test.js
index 6595f901c..47e013df7 100644
--- a/src/pat/masonry/masonry.test.js
+++ b/src/pat/masonry/masonry.test.js
@@ -1,125 +1,15 @@
-import pattern from "./masonry";
-import events from "../../core/events";
-import utils from "../../core/utils";
-import { jest } from "@jest/globals";
+import Pattern from "./masonry";
+import Implementation from "./masonry--implementation";
-const set_complete = (img) => {
- // jsdom does not load images. Mark them as loaded.
- Object.defineProperty(img, "complete", { value: true });
-};
-
-describe("pat-masonry", function () {
- afterEach(function () {
- document.body.innerHTML = "";
- jest.restoreAllMocks();
- });
-
- it("Sets class masonry-ready on the element after masonry has finished", async function () {
- document.body.innerHTML = `
-
- `;
- const el = document.querySelector(".pat-masonry");
- expect(el.classList.contains("masonry-ready")).toBe(false);
-
- const instance = pattern.init(el);
- await events.await_pattern_init(instance);
-
- expect(el.classList.contains("masonry-ready")).toBe(true);
- });
-
- it("Waits for all images to be loaded before setting masonry-ready", async function () {
- document.body.innerHTML = `
-
- `;
- const el = document.querySelector(".pat-masonry");
- const [img1, img2] = el.querySelectorAll("img");
-
- const instance = pattern.init(el);
- await events.await_pattern_init(instance);
- const spy_quicklayout = jest.spyOn(instance, "quicklayout");
- const spy_layout = jest.spyOn(instance, "layout");
-
- expect(el.classList.contains("masonry-ready")).toBe(false);
-
- // First image loaded - quick re-layout, but not ready yet.
- set_complete(img1);
- img1.dispatchEvent(new Event("load"));
- await utils.timeout(1); // wait a tick for async to settle.
- expect(spy_quicklayout).toHaveBeenCalled();
- expect(spy_layout).not.toHaveBeenCalled();
- expect(el.classList.contains("masonry-ready")).toBe(false);
-
- // Second image failed loading - full layout and ready.
- set_complete(img2);
- img2.dispatchEvent(new Event("error"));
- await utils.timeout(1); // wait a tick for async to settle.
- expect(spy_layout).toHaveBeenCalledTimes(1);
- expect(el.classList.contains("masonry-ready")).toBe(true);
-
- // Images loaded later only lead to a quick re-layout.
- spy_quicklayout.mockClear();
- img1.dispatchEvent(new Event("load"));
- await utils.timeout(1); // wait a tick for async to settle.
- expect(spy_quicklayout).toHaveBeenCalledTimes(1);
- expect(spy_layout).toHaveBeenCalledTimes(1);
+describe("pat-masonry 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);
});
- it("Re-layouts when a video has loaded its metadata, but not for other elements", async function () {
- document.body.innerHTML = `
-
- `;
- const el = document.querySelector(".pat-masonry");
-
- const instance = pattern.init(el);
- await events.await_pattern_init(instance);
- await utils.timeout(1); // wait a tick for async to settle.
- const spy_quicklayout = jest.spyOn(instance, "quicklayout");
-
- el.querySelector("iframe").dispatchEvent(new Event("load"));
- expect(spy_quicklayout).not.toHaveBeenCalled();
-
- el.querySelector("video").dispatchEvent(new Event("loadedmetadata"));
- expect(spy_quicklayout).toHaveBeenCalledTimes(1);
- });
-
- it("Does not wait for lazy loading images", async function () {
- document.body.innerHTML = `
-
- `;
- const el = document.querySelector(".pat-masonry");
-
- const instance = pattern.init(el);
- await events.await_pattern_init(instance);
-
- expect(el.classList.contains("masonry-ready")).toBe(true);
- });
-
- it("Does not accumulate layoutComplete event listeners", async function () {
- document.body.innerHTML = `
-
- `;
- const el = document.querySelector(".pat-masonry");
-
- const instance = pattern.init(el);
- await events.await_pattern_init(instance);
-
- instance.layout();
- instance.layout();
- instance.layout();
-
- expect(instance.msnry._events?.layoutComplete?.length || 0).toBe(0);
+ it("loads the implementation.", async function () {
+ expect(await Pattern.load()).toBe(Implementation);
});
});
diff --git a/src/pat/menu/menu.js b/src/pat/menu/menu.js
index 15f5e1df5..e3f37e183 100644
--- a/src/pat/menu/menu.js
+++ b/src/pat/menu/menu.js
@@ -1,64 +1,74 @@
import $ from "jquery";
-import Base from "../../core/base";
+import { BasePattern } from "../../core/basepattern";
import Parser from "../../core/parser";
+import registry from "../../core/registry";
-export const parser = new Parser("fullscreen");
+export const parser = new Parser("menu");
parser.addArgument("nav-item-selector", "li"); // CSS Selector for navigation items.
-export default Base.extend({
- name: "menu",
- trigger: ".pat-menu",
+class Pattern extends BasePattern {
+ static name = "menu";
+ static trigger = ".pat-menu";
+ static parser = parser;
- timer: null,
+ timer = null;
- init: function ($el, opts) {
- this.options = parser.parse(this.$el, opts);
- var self = this;
- $el.find(this.options.navItemSelector).each(function () {
- var $it = $(this);
+ init() {
+ this.$el = $(this.el);
+ const self = this;
+ this.$el.find(this.options.navItemSelector).each(function () {
+ const $it = $(this);
$it.addClass("closed")
- .on("mouseover", self.mouseOverHandler.bind(self))
- .on("mouseout", self.mouseOutHandler.bind(self));
+ .on("mouseover.pat-menu", self.mouseOverHandler.bind(self))
+ .on("mouseout.pat-menu", self.mouseOutHandler.bind(self));
if ($it.children(self.options.navItemSelector).length > 0) {
$it.addClass("hasChildren");
}
});
- },
+ }
- openMenu: function (it) {
+ destroy() {
+ this.clear_timer();
+ this.$el?.find(this.options.navItemSelector).off(".pat-menu");
+ super.destroy();
+ }
+
+ clear_timer() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
+ }
+
+ openMenu(it) {
+ this.clear_timer();
it = $(it);
if (!it.hasClass("open")) {
- it.siblings(".open").each(
- function () {
- this.closeMenu(this.$el);
- }.bind(this)
- );
+ it.siblings(".open").each((idx, sibling) => {
+ this.closeMenu(sibling);
+ });
it.addClass("open").removeClass("closed");
}
- },
+ }
- closeMenu: function (it) {
+ closeMenu(it) {
$(it).find(".open").addBack().removeClass("open").addClass("closed");
- },
+ }
- mouseOverHandler: function (ev) {
- this.openMenu(ev.target);
- },
+ mouseOverHandler(ev) {
+ this.openMenu(ev.currentTarget);
+ }
- mouseOutHandler: function (ev) {
- if (this.timer) {
- clearTimeout(this.timer);
+ mouseOutHandler(ev) {
+ this.clear_timer();
+ const it = ev.currentTarget;
+ this.timer = setTimeout(() => {
this.timer = null;
- }
- this.timer = setTimeout(
- function () {
- this.closeMenu(ev.target);
- }.bind(this),
- 1000
- );
- },
-});
+ this.closeMenu(it);
+ }, 1000);
+ }
+}
+
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/menu/menu.test.js b/src/pat/menu/menu.test.js
index 3a53de9a2..e032058c6 100644
--- a/src/pat/menu/menu.test.js
+++ b/src/pat/menu/menu.test.js
@@ -1,32 +1,206 @@
-import $ from "jquery";
-import pattern from "./menu";
+import Pattern from "./menu";
+import events from "../../core/events";
+import utils from "../../core/utils";
+import { jest } from "@jest/globals";
-describe("pat-menu", function () {
- beforeEach(function () {
- $("
", { id: "lab" }).appendTo(document.body);
- });
+const mouseover = (el) => {
+ el.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
+};
+const mouseout = (el) => {
+ el.dispatchEvent(new MouseEvent("mouseout", { bubbles: true }));
+};
+describe("pat-menu", function () {
afterEach(function () {
- $("#lab").remove();
+ document.body.innerHTML = "";
+ jest.useRealTimers();
});
describe("init tests", function () {
- it("adds class closed on init", function () {
- var $lab = $("#lab");
- $lab.html(
- [
- '",
- ].join("\n")
- );
- var $list = $("ul.pat-menu");
-
- pattern.init($list);
-
- expect($($list).children().not(".closed").length).toBe(0);
+ it("adds class closed on init", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-menu");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ for (const it of el.children) {
+ expect(it.classList.contains("closed")).toBe(true);
+ }
+ });
+
+ it("uses the nav-item-selector option", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-menu");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ const [li1, li2] = el.children;
+ expect(li1.classList.contains("closed")).toBe(true);
+ expect(li2.classList.contains("closed")).toBe(false);
+ });
+ });
+
+ describe("opening and closing", function () {
+ it("opens the hovered item and closes the open siblings", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-menu");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ const [li1, li2] = el.children;
+
+ // Hovering over a child element opens the menu item.
+ mouseover(li1.querySelector("a"));
+ expect(li1.classList.contains("open")).toBe(true);
+ expect(li1.classList.contains("closed")).toBe(false);
+ expect(li1.querySelector("a").classList.contains("open")).toBe(false);
+
+ mouseover(li2);
+ expect(li1.classList.contains("open")).toBe(false);
+ expect(li1.classList.contains("closed")).toBe(true);
+ expect(li2.classList.contains("open")).toBe(true);
+ });
+
+ it("keeps the parent item open when switching between sub items", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-menu");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ const parent = el.querySelector(".parent");
+ const sub1 = el.querySelector(".sub1");
+ const sub2 = el.querySelector(".sub2");
+
+ mouseover(sub1);
+ expect(parent.classList.contains("open")).toBe(true);
+ expect(sub1.classList.contains("open")).toBe(true);
+
+ mouseover(sub2);
+ expect(parent.classList.contains("open")).toBe(true);
+ expect(sub1.classList.contains("open")).toBe(false);
+ expect(sub2.classList.contains("open")).toBe(true);
+ });
+
+ it("closes the item and its sub items after leaving it", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-menu");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ const parent = el.querySelector(".parent");
+ const sub1 = el.querySelector(".sub1");
+
+ jest.useFakeTimers();
+ mouseover(sub1);
+ mouseout(sub1);
+ jest.advanceTimersByTime(999);
+ expect(parent.classList.contains("open")).toBe(true);
+ expect(sub1.classList.contains("open")).toBe(true);
+
+ jest.advanceTimersByTime(1);
+ expect(parent.classList.contains("closed")).toBe(true);
+ expect(sub1.classList.contains("closed")).toBe(true);
+ });
+
+ it("does not close the item when entering it again", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-menu");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ const li = el.querySelector("li");
+
+ jest.useFakeTimers();
+ mouseover(li);
+ mouseout(li);
+ jest.advanceTimersByTime(500);
+ mouseover(li);
+ jest.advanceTimersByTime(1000);
+ expect(li.classList.contains("open")).toBe(true);
+ });
+ });
+
+ describe("destroy", function () {
+ it("removes the event handlers and the pending timer", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-menu");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ const [li1, li2] = el.children;
+
+ mouseover(li1);
+ mouseout(li1);
+ expect(instance.timer).not.toBe(null);
+
+ instance.destroy();
+ expect(el["pattern-menu"]).toBeUndefined();
+ expect(instance.timer).toBe(null);
+
+ mouseover(li2);
+ expect(li2.classList.contains("open")).toBe(false);
+ });
+
+ it("is destroyed when removed from the DOM", async function () {
+ document.body.innerHTML = `
+
+
+
+ `;
+ const el = document.querySelector(".pat-menu");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ el.remove();
+ await utils.timeout(1);
+ expect(instance.destroyed).toBe(true);
});
});
});
diff --git a/src/pat/minimalpattern/documentation.md b/src/pat/minimalpattern/documentation.md
index 9983c9e80..47578333a 100644
--- a/src/pat/minimalpattern/documentation.md
+++ b/src/pat/minimalpattern/documentation.md
@@ -22,7 +22,7 @@ Custom color:
### Option reference
-The fullscreen pattern can be configured through a `data-pat-fullscreen` attribute.
+The minimalpattern pattern can be configured through a `data-pat-minimalpattern` attribute.
The available options are:
| Field | Default | Options | Description |
diff --git a/src/pat/minimalpattern/minimalpattern.js b/src/pat/minimalpattern/minimalpattern.js
index b9c154ea1..cdc44a09d 100644
--- a/src/pat/minimalpattern/minimalpattern.js
+++ b/src/pat/minimalpattern/minimalpattern.js
@@ -1,25 +1,37 @@
-import Base from "../../core/base";
-import Parser from "../../core/parser";
+import { BasePattern } from "../../core/basepattern";
import logging from "../../core/logging";
+import Parser from "../../core/parser";
+import registry from "../../core/registry";
const log = logging.getLogger("minimalpattern");
export const parser = new Parser("minimalpattern");
parser.addArgument("background-color", "green");
-export default Base.extend({
- name: "minimalpattern",
- trigger: ".pat-minimalpattern",
+class Pattern extends BasePattern {
+ static name = "minimalpattern";
+ static trigger = ".pat-minimalpattern";
+ static parser = parser;
init() {
- this.options = parser.parse(this.el, this.options);
- this.el.addEventListener("click", this.change_color.bind(this));
+ // The options are parsed from the element automatically and are
+ // available as ``this.options``.
+ //
+ // Event listeners registered with ``add_event_listener`` are removed
+ // when the pattern is destroyed.
+ this.add_event_listener(this.el, "click", "change-color", (e) =>
+ this.change_color(e)
+ );
log.info("pattern initialized");
- },
+ }
change_color(e) {
e.preventDefault();
this.el.style["background-color"] = this.options.backgroundColor;
log.info("element clicked");
- },
-});
+ }
+}
+
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/minimalpattern/minimalpattern.test.js b/src/pat/minimalpattern/minimalpattern.test.js
index 21ad206a6..fa5082974 100644
--- a/src/pat/minimalpattern/minimalpattern.test.js
+++ b/src/pat/minimalpattern/minimalpattern.test.js
@@ -1,43 +1,52 @@
+import events from "../../core/events";
import Pattern from "./minimalpattern";
-describe("Minimalpattern tests", function () {
- beforeEach(function () {
- const el = document.createElement("div");
- el.setAttribute("id", "lab");
- document.body.appendChild(el);
- });
+describe("pat-minimalpattern", function () {
afterEach(function () {
- document.body.removeChild(document.querySelector("#lab"));
+ document.body.innerHTML = "";
});
- it("Changes the color on click.", function (done) {
- const el = document.createElement("div");
- el.setAttribute("class", "pat-minimalpattern");
- document.body.appendChild(el);
-
- new Pattern(el);
-
- expect(el.getAttribute("style")).toBeFalsy();
- el.click();
-
- expect(el.getAttribute("style") === "background-color: green;").toBeTruthy();
-
- done();
+ it("1 - Changes the color on click.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const pattern_el = document.querySelector(".pat-minimalpattern");
+ const instance = new Pattern(pattern_el);
+ await events.await_pattern_init(instance);
+
+ expect(pattern_el.getAttribute("style")).toBeFalsy();
+ pattern_el.click();
+ expect(pattern_el.getAttribute("style")).toBe("background-color: green;");
});
- it("Changes the color to the one specified on click.", function (done) {
- const el = document.createElement("div");
- el.setAttribute("class", "pat-minimalpattern");
- el.setAttribute("data-pat-minimalpattern", "background-color: red;");
- document.body.appendChild(el);
-
- new Pattern(el);
+ it("2 - Changes the color to the one specified on click.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const pattern_el = document.querySelector(".pat-minimalpattern");
+ const instance = new Pattern(pattern_el);
+ await events.await_pattern_init(instance);
+
+ expect(pattern_el.getAttribute("style")).toBeFalsy();
+ pattern_el.click();
+ expect(pattern_el.getAttribute("style")).toBe("background-color: red;");
+ });
- expect(el.getAttribute("style")).toBeFalsy();
- el.click();
+ it("3 - Does not change the color after being destroyed.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const pattern_el = document.querySelector(".pat-minimalpattern");
+ const instance = new Pattern(pattern_el);
+ await events.await_pattern_init(instance);
- expect(el.getAttribute("style") === "background-color: red;").toBeTruthy();
+ instance.destroy();
+ expect(pattern_el["pattern-minimalpattern"]).toBeUndefined();
- done();
+ pattern_el.click();
+ expect(pattern_el.getAttribute("style")).toBeFalsy();
});
});
diff --git a/src/pat/modal/modal--implementation.js b/src/pat/modal/modal--implementation.js
new file mode 100644
index 000000000..be7b40bea
--- /dev/null
+++ b/src/pat/modal/modal--implementation.js
@@ -0,0 +1,259 @@
+import $ from "jquery";
+import { BasePattern } from "../../core/basepattern";
+import Parser from "../../core/parser";
+import inject from "../inject/inject";
+import registry from "../../core/registry";
+import utils from "../../core/utils";
+
+// Initialize close-panel functionality.
+import "../close-panel/close-panel";
+
+export const parser = new Parser("modal");
+parser.addArgument("class");
+parser.addArgument("closing", ["close-button"], ["close-button", "outside"], true);
+parser.addArgument("close-text", "Close");
+parser.addArgument("panel-header-content", ":first:not(.header)");
+parser.addArgument("source", null); // If not given, the href should specify the source via a url fragment.
+parser.addArgument("target", "#pat-modal");
+
+class Pattern extends BasePattern {
+ static name = "modal";
+ // div's are turned into modals
+ // links, forms and subforms inject modals
+ static trigger =
+ "div.pat-modal, a.pat-modal, form.pat-modal, .pat-modal.pat-subform";
+ static parser = parser;
+
+ is_open = false;
+ is_closing = false;
+
+ constructor(el, options, trigger) {
+ super(el, options);
+ // The injection trigger, passed by the registry when the modal was
+ // initialized as part of injected content.
+ this.injection_trigger = trigger;
+ }
+
+ async init() {
+ if (window.__patternslib_import_styles) {
+ import("./_modal.scss");
+ }
+
+ this.$el = $(this.el);
+
+ const trigger = this.injection_trigger;
+ if (trigger && trigger.type === "injection") {
+ $.extend(this.options, parser.parse($(trigger.element), {}, false, false));
+ }
+ if (this.$el.is("div")) {
+ this._init_div1();
+ } else {
+ await this._init_inject1();
+ }
+ }
+
+ async _init_inject1() {
+ // This will get remote content via pat-inject, add the pat-modal class
+ // to the result and pat-inject's pattern scanning will then call
+ // ``_init_div1``.
+
+ const opts = {
+ ...(this.options.source && { source: this.options.source }),
+ target: this.options.target,
+ class:
+ "pat-modal" + (this.options["class"] ? " " + this.options["class"] : ""),
+ };
+ if (this.options.url) {
+ opts.url = this.options.url;
+ }
+ if (this.options.trigger) {
+ opts.trigger = this.options.trigger;
+ }
+
+ // if $el is already inside a modal, do not detach #pat-modal,
+ // because this would unnecessarily close the modal itself
+ if (!this.$el.closest("#pat-modal")) {
+ $("#pat-modal").detach();
+ }
+ this.$el.on(
+ `pat-inject-missingSource.${this.jquery_namespace} pat-inject-missingTarget.${this.jquery_namespace}`,
+ () => {
+ $("#pat-modal").detach();
+ }
+ );
+
+ await inject.init(this.$el, opts);
+ }
+
+ _init_div1() {
+ // This is always called and will inject the modal in the page.
+
+ const header = document.createElement("div");
+ header.setAttribute("class", "header");
+
+ if (this.options.closing.indexOf("close-button") !== -1) {
+ header.innerHTML = `
${this.options.closeText} `;
+ registry.scan(header, ["close-panel"]); // initialize close-panel
+ }
+
+ // We cannot handle text nodes here
+ let $children;
+ if (this.options.panelHeaderContent === "none") {
+ $children = this.$el.children();
+ } else {
+ $children = this.$el.children(
+ ":last, :not(" + this.options.panelHeaderContent + ")"
+ );
+ }
+
+ if ($children.length) {
+ $children.wrapAll("
");
+ } else {
+ this.$el.append("
");
+ }
+ this.$el.children(".panel-content").before(header);
+ this.$el.children(this.options.panelHeaderContent).prependTo(header);
+
+ // Restore focus in case the active element was a child of $el and
+ // the focus was lost during the wrapping.
+ document.activeElement?.focus();
+
+ this._init_handlers();
+ this.resize();
+ this.setPosition();
+
+ this.is_open = true;
+ $("body").addClass("modal-active");
+ this.el.dispatchEvent(
+ new Event("pat-modal-ready", { bubbles: true, cancelable: true })
+ );
+ }
+
+ get jquery_namespace() {
+ // Instance scoped jQuery event namespace.
+ return `pat-modal--${this.uuid}`;
+ }
+
+ _init_handlers() {
+ this.add_event_listener(this.el, "close-panel", "close-panel", () =>
+ this.close()
+ );
+
+ this.add_event_listener(document, "keyup", "close-on-escape", (ev) =>
+ this._onKeyUp(ev)
+ );
+ if (this.options.closing.indexOf("outside") !== -1) {
+ this.add_event_listener(document, "click", "close-on-outside-click", (ev) =>
+ this._onPossibleOutsideClick(ev)
+ );
+ }
+
+ const debounced_resize = (timeout) =>
+ utils.debounce(() => {
+ if (!this.destroyed) {
+ this.resize();
+ }
+ }, timeout);
+
+ this.add_event_listener(window, "resize", "resize", debounced_resize(400));
+
+ // These events are triggered via jQuery and cannot be caught with
+ // native event listeners. Use an instance scoped jQuery namespace,
+ // which is removed on destroy.
+ const ns = this.jquery_namespace;
+ $(document).on(
+ `pat-inject-content-loaded.${ns}`,
+ "#pat-modal",
+ debounced_resize(400)
+ );
+ $(document).on(
+ `patterns-injected.${ns}`,
+ "#pat-modal,div.pat-modal",
+ debounced_resize(400)
+ );
+ $(document).on(
+ `pat-update.${ns}`,
+ "#pat-modal,div.pat-modal",
+ debounced_resize(50)
+ );
+ }
+
+ _onPossibleOutsideClick(ev) {
+ // Close the modal when clicking outside of it.
+ // Use the event path, as the click target might have been removed
+ // from the modal in the meantime, e.g. by an injection.
+ if (!ev.composedPath().includes(this.el)) {
+ this.close();
+ }
+ }
+
+ _onKeyUp(ev) {
+ if (ev.key === "Escape" || ev.which === 27) {
+ this.close();
+ }
+ }
+
+ getTallestChild() {
+ let $tallest_child;
+ for (const child of $("*", this.$el)) {
+ const $child = $(child);
+ if (typeof $tallest_child === "undefined") {
+ $tallest_child = $child;
+ } else if ($child.outerHeight(true) > $tallest_child.outerHeight(true)) {
+ $tallest_child = $child;
+ }
+ }
+ return $tallest_child;
+ }
+
+ setPosition() {
+ this.$el.css("top", ($(window).innerHeight() - this.$el.height()) / 2);
+ }
+
+ resize() {
+ // reset the height before setting a new one
+ this.$el.removeClass("max-height").css("height", "");
+
+ const panel_content_elem = this.$el.find(".panel-content");
+ const header_elem = this.$el.find(".header");
+ const modal_height =
+ panel_content_elem.outerHeight(true) + header_elem.outerHeight(true);
+ if (this.$el.height() < modal_height) {
+ this.$el.addClass("max-height").css({ height: modal_height + "px" });
+ this.setPosition();
+ }
+ }
+
+ async close() {
+ // Close the modal: remove it from the page.
+ if (this.is_closing || this.destroyed) {
+ return;
+ }
+ this.is_closing = true;
+ await utils.timeout(1); // wait a tick for event handlers (e.g. form submit) have a chance to kick in first.
+ this.$el.remove();
+ // The pattern is destroyed automatically when removed from the
+ // document. Destroy it explicitly for the case it wasn't tracked.
+ this.destroy();
+ }
+
+ destroy() {
+ if (this.destroyed) {
+ return;
+ }
+ $(document).off(`.${this.jquery_namespace}`);
+ this.$el?.off(`.${this.jquery_namespace}`);
+ if (this.is_open) {
+ // The modal is closed - either via ``close()`` or because it was
+ // removed from the document, e.g. by an injection.
+ this.is_open = false;
+ $("body").removeClass("modal-active");
+ $("body").removeClass("modal-panel");
+ }
+ super.destroy();
+ }
+}
+
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/modal/modal--implementation.test.js b/src/pat/modal/modal--implementation.test.js
new file mode 100644
index 000000000..e56a37949
--- /dev/null
+++ b/src/pat/modal/modal--implementation.test.js
@@ -0,0 +1,552 @@
+import $ from "jquery";
+import events from "../../core/events";
+import Pattern from "./modal--implementation";
+import registry from "../../core/registry";
+import utils from "../../core/utils";
+import { jest } from "@jest/globals";
+
+describe("pat-modal", function () {
+ let deferred;
+
+ const answer = function (html) {
+ deferred.resolve(html, "ok", { responseText: html });
+ };
+
+ beforeEach(function () {
+ deferred = new $.Deferred();
+ document.body.innerHTML = `
`;
+ });
+
+ afterEach(function () {
+ document.body.innerHTML = "";
+ document.body.classList.remove("modal-active");
+ jest.restoreAllMocks();
+ });
+
+ describe("1 - init", function () {
+ it("1.1 - Modal with single element", async function () {
+ $("#lab").html(
+ [
+ '
',
+ "
Modal content
",
+ "
",
+ ].join("\n")
+ );
+ expect($("body").hasClass("modal-active")).toBeFalsy();
+ var $modal = $("#modal");
+ const instance = new Pattern($modal[0]);
+ await events.await_pattern_init(instance);
+ expect($modal.find(".header").length).toBeTruthy();
+ expect($modal.find(".header").text()).toBe("Close");
+ expect($modal.find(".header .close-panel").length).toBeTruthy();
+ expect($modal.find(".panel-content").length).toBeTruthy();
+ expect($modal.find(".panel-content").text()).toBe("Modal content");
+ expect($("body").hasClass("modal-active")).toBeTruthy();
+ });
+
+ it("1.2 - Modal with header ", async function () {
+ $("#lab").html(
+ [
+ '
',
+ "
Modal header ",
+ "
Modal content
",
+ "
",
+ ].join("\n")
+ );
+ expect($("body").hasClass("modal-active")).toBeFalsy();
+ var $modal = $("#modal");
+ const instance = new Pattern($modal[0]);
+ await events.await_pattern_init(instance);
+ expect($modal.find(".header").text()).toBe("Modal headerClose");
+ expect($modal.find(".header .close-panel").length).toBeTruthy();
+ expect($modal.find(".panel-content").text()).toBe("Modal content");
+ expect($("body").hasClass("modal-active")).toBeTruthy();
+ });
+
+ it("1.3 - Modal with multiple content items ", async function () {
+ $("#lab").html(
+ [
+ '
',
+ "
Modal header ",
+ "
Modal content
",
+ "
Subheader ",
+ "
More content
",
+ "
",
+ ].join("\n")
+ );
+ expect($("body").hasClass("modal-active")).toBeFalsy();
+ var $modal = $("#modal");
+ const instance = new Pattern($modal[0]);
+ await events.await_pattern_init(instance);
+ expect($modal.find(".header").text()).toBe("Modal headerClose");
+ expect($modal.find(".header .close-panel").length).toBeTruthy();
+ expect($modal.find(".panel-content p").length).toBe(2);
+ expect($modal.find(".panel-content h4").length).toBe(1);
+ expect($("body").hasClass("modal-active")).toBeTruthy();
+ });
+
+ it("1.4 - Modal with a form that has the pat-modal CSS class", async function () {
+ var $modal, // main modal container
+ $modalLink; // link that triggers the modal
+
+ $("#lab")[0].innerHTML = `
+
+ Open a modal containing a form with pat-modal CSS class.
+
+ `;
+
+ $modalLink = $("#modalLink");
+ const instance = new Pattern($modalLink[0]);
+ await events.await_pattern_init(instance);
+
+ // najprej #modalLink ne obstaja
+ $modal = $("div#pat-modal");
+ expect($modal.length).toBe(0);
+
+ $modalLink.click(); // trigger panel loading
+ utils.timeout(1); // wait a tick for async to settle.
+
+ $modal = $("div#pat-modal");
+ expect($modal.length).toBeGreaterThan(0);
+ });
+
+ it("1.5 - Modal with single element that specifies a custom close button string", async function () {
+ $("#lab").html(
+ [
+ '
',
+ "
Modal content
",
+ "
",
+ ].join("\n")
+ );
+ expect($("body").hasClass("modal-active")).toBeFalsy();
+ var $modal = $("#modal");
+ const instance = new Pattern($modal[0]);
+ await events.await_pattern_init(instance);
+ expect($modal.find(".header").length).toBeTruthy();
+ expect($modal.find(".header").text()).toBe("Shutdown");
+ expect($modal.find(".header .close-panel").length).toBeTruthy();
+ expect($("body").hasClass("modal-active")).toBeTruthy();
+ });
+
+ it("1.6 - Dispatch pat-modal-ready with a div-modal.", async function () {
+ document.body.innerHTML = `
+
+ `;
+
+ const callback = jest.fn();
+ const modal_el = document.querySelector(".pat-modal");
+ modal_el.addEventListener("pat-modal-ready", callback);
+ const instance = new Pattern(modal_el);
+ await events.await_pattern_init(instance);
+
+ // Opened immediately
+ expect(callback).toHaveBeenCalledTimes(1);
+ });
+
+ it("1.7 - Dispatch pat-modal-ready with a inject-modal.", async function () {
+ jest.spyOn($, "ajax").mockImplementation(() => deferred);
+ document.body.innerHTML = `
+
Open modal
+ `;
+
+ const callback = jest.fn();
+ document.body.addEventListener("pat-modal-ready", callback);
+ const modal_el = document.querySelector(".pat-modal");
+ const instance = new Pattern(modal_el);
+ await events.await_pattern_init(instance);
+
+ expect(callback).not.toHaveBeenCalled();
+
+ answer(`
`);
+ modal_el.click();
+ await utils.timeout(1); // wait a tick for async to settle.
+ await utils.timeout(1); // wait a tick for the injected modal to initialize.
+ expect(callback).toHaveBeenCalledTimes(1);
+ });
+
+ it("1.8 - Submit form, do injection and close overlay.", async function () {
+ await import("../inject/inject");
+
+ jest.spyOn($, "ajax").mockImplementation(() => deferred);
+ answer(
+ `
hello.
there
`
+ );
+
+ document.body.innerHTML = `
+
+
+
+
+
+
+
+ `;
+ registry.scan(document.body);
+ await utils.timeout(1); // wait a tick for async to settle.
+
+ document.querySelector("button.close-panel[type=submit]").click();
+ await utils.timeout(1); // close-button is async - wait for it.
+ await utils.timeout(1); // wait a tick for pat-inject to settle.
+ await utils.timeout(1); // wait a tick for pat-modal destroy to settle.
+
+ expect(document.querySelector(".pat-modal")).toBe(null);
+ expect(document.querySelector("#target").textContent).toBe("hello.");
+ expect(document.querySelector("#target2").textContent).toBe("there");
+ });
+
+ it("1.9 - Submit form, do injection and close overlay with multiple forms.", async function () {
+ await import("../inject/inject");
+
+ jest.spyOn($, "ajax").mockImplementation(() => deferred);
+ answer(
+ `
hello.
there
`
+ );
+
+ document.body.innerHTML = `
+
+
+
+
+
+
+ `;
+ registry.scan(document.body);
+ await utils.timeout(1); // wait a tick for async to settle.
+
+ document.querySelector(".form2 button.close-panel[type=submit]").click();
+ await utils.timeout(1); // close-button is async - wait for it.
+ await utils.timeout(1); // wait a tick for pat-inject to settle.
+ await utils.timeout(1); // wait a tick for pat-modal destroy to settle.
+
+ expect(document.querySelector(".pat-modal")).toBe(null);
+ expect(document.querySelector("#target").textContent).toBe("hello.");
+ });
+
+ it("1.10 - Ensure close callback isn't called multiple times.", async function () {
+ document.body.innerHTML = `
+
+ close
+
+ `;
+
+ const instance = new Pattern(document.querySelector(".pat-modal"));
+ await events.await_pattern_init(instance);
+ registry.scan(document.body); // Also need to instantiate close-panel
+ await utils.timeout(1); // wait a tick for async to settle.
+
+ const spy_close = jest.spyOn(instance, "close");
+
+ // The handlers were already registered with instantiating the
+ // pattern above. Call init again for new instantiation.
+ await instance.init();
+
+ document.querySelector("#close-modal").click();
+ await utils.timeout(1); // close-button is async - wait for it.
+ await utils.timeout(1); // wait a tick for pat-modal close to settle.
+
+ expect(spy_close).toHaveBeenCalledTimes(1);
+ });
+
+ it("1.11 - Ensure destroy callback isn't called multiple times with forms and injection.", async function () {
+ const markup = `
+
+
+
+ `;
+
+ // Set up inject mocks
+ const pattern_inject = (await import("../inject/inject")).default;
+ jest.spyOn($, "ajax").mockImplementation(() => deferred);
+ answer("
OK
"); // empties body
+
+ document.body.innerHTML = markup;
+
+ pattern_inject.init($(".pat-inject"));
+ const instance = new Pattern(document.querySelector(".pat-modal"));
+ await events.await_pattern_init(instance);
+ registry.scan(document.body); // Also need to instantiate close-panel
+ await utils.timeout(1); // wait a tick for async to settle.
+ expect(document.body.classList.contains("modal-active")).toBe(true);
+
+ const spy_destroy = jest.spyOn(instance, "destroy");
+
+ // The handlers were already registered with instantiating the
+ // pattern above. Call init again for new instantiation.
+ await instance.init();
+
+ document.querySelector("#close-modal").click();
+ await utils.timeout(1); // close-button is async - wait for it.
+ await utils.timeout(1); // wait a tick for pat-inject to settle.
+
+ // The injection replaced the modal, which destroyed it and
+ // closed the modal.
+ expect(spy_destroy).toHaveBeenCalled();
+ expect(instance.destroyed).toBe(true);
+ expect(document.body.classList.contains("modal-active")).toBe(false);
+ const destroy_calls = spy_destroy.mock.calls.length;
+
+ // re-attach and re-initialize. Event handler should only be active once.
+ document.body.innerHTML = markup;
+ pattern_inject.init($(".pat-inject"));
+ const instance2 = new Pattern(document.querySelector(".pat-modal"));
+ await events.await_pattern_init(instance2);
+ registry.scan(document.body); // Also need to instantiate close-panel
+ await utils.timeout(1); // wait a tick for async to settle.
+ document.querySelector("#close-modal").click();
+ await utils.timeout(1); // close-button is async - wait for it.
+ await utils.timeout(1); // wait a tick for pat-inject to settle.
+ // Previous mocks still active.
+ // Handlers of the first instance are not executed anymore.
+ expect(spy_destroy).toHaveBeenCalledTimes(destroy_calls);
+ expect(instance2.destroyed).toBe(true);
+ });
+ });
+
+ it("2.1 - Allow to open a modal in a modal", async function () {
+ document.body.innerHTML = `
+
open modal 1
+
+ Open another modal
+
+
+
+ modal in modal.
+
+
+ `;
+ const el = document.querySelector(".pat-modal");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ el.click();
+ await utils.timeout(1); // wait a tick for async to settle.
+ await utils.timeout(1); // wait a tick for async to settle.
+
+ expect(document.querySelectorAll("#pat-modal").length).toBe(1);
+
+ const trigger_sub = document.querySelector("#pat-modal .pat-modal");
+ expect(trigger_sub).toBeTruthy();
+ await utils.timeout(1); // wait a tick for pat-inject on the sub-trigger to initialize.
+
+ trigger_sub.click();
+ await utils.timeout(1); // wait a tick for async to settle.
+ expect(document.querySelectorAll("#pat-modal").length).toBe(1);
+ expect(document.querySelector("#pat-modal").textContent).toMatch(
+ /modal in modal\./
+ );
+ });
+
+ it("2.2 - Allow to open a modal in a modal via ajax", async function () {
+ document.body.innerHTML = `
+
open modal 1
+
+ Open another modal
+
+ `;
+
+ jest.spyOn($, "ajax").mockImplementation(() => deferred);
+ answer(`
+
+
+
+
+ modal in modal.
+
+
+
+
+ `);
+
+ const el = document.querySelector(".pat-modal");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ el.click();
+ await utils.timeout(1); // wait a tick for async to settle.
+ await utils.timeout(1); // wait a tick for async to settle.
+
+ expect(document.querySelectorAll("#pat-modal").length).toBe(1);
+
+ const trigger_sub = document.querySelector("#pat-modal .pat-modal");
+ expect(trigger_sub).toBeTruthy();
+ await utils.timeout(1); // wait a tick for pat-inject on the sub-trigger to initialize.
+
+ trigger_sub.click();
+ await utils.timeout(1); // wait a tick for async to settle.
+
+ expect(document.querySelectorAll("#pat-modal").length).toBe(1);
+ expect(document.querySelector("#pat-modal").textContent).toMatch(
+ /modal in modal\./
+ );
+ });
+
+ describe("3 - closing and destroy", function () {
+ it("3.1 - Closes the modal on Escape.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-modal");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+ expect(document.body.classList.contains("modal-active")).toBe(true);
+
+ document.dispatchEvent(new KeyboardEvent("keyup", { key: "Escape" }));
+ await utils.timeout(1); // close is async - wait for it.
+
+ expect(document.querySelector(".pat-modal")).toBe(null);
+ expect(document.body.classList.contains("modal-active")).toBe(false);
+ expect(instance.destroyed).toBe(true);
+ });
+
+ it("3.2 - Closes the modal when clicking outside, but not inside.", async function () {
+ document.body.innerHTML = `
+
outside
+
+ `;
+ const el = document.querySelector(".pat-modal");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+ const spy_close = jest.spyOn(instance, "close");
+
+ document.querySelector(".inside").click();
+ await utils.timeout(1);
+ expect(spy_close).not.toHaveBeenCalled();
+ expect(document.querySelector(".pat-modal")).toBeTruthy();
+
+ document.querySelector(".outside").click();
+ await utils.timeout(1);
+ expect(spy_close).toHaveBeenCalledTimes(1);
+ expect(document.querySelector(".pat-modal")).toBe(null);
+ });
+
+ it("3.3 - Does not close on outside clicks without the outside closing option.", async function () {
+ document.body.innerHTML = `
+
outside
+
+ `;
+ const el = document.querySelector(".pat-modal");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+ const spy_close = jest.spyOn(instance, "close");
+
+ document.querySelector(".outside").click();
+ await utils.timeout(1);
+ expect(spy_close).not.toHaveBeenCalled();
+ expect(document.querySelector(".pat-modal")).toBeTruthy();
+ });
+
+ it("3.4 - Closes the modal via close-panel.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-modal");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+ await utils.timeout(1); // wait for close-panel to initialize.
+
+ el.querySelector(".header .close-panel").click();
+ await utils.timeout(1); // close-panel is async - wait for it.
+ await utils.timeout(1); // close is async - wait for it.
+
+ expect(document.querySelector(".pat-modal")).toBe(null);
+ expect(document.body.classList.contains("modal-active")).toBe(false);
+ expect(instance.destroyed).toBe(true);
+ });
+
+ it("3.5 - Removes the global event listeners when removed from the DOM.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-modal");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+ const spy_close = jest.spyOn(instance, "close");
+ const spy_resize = jest.spyOn(instance, "resize");
+
+ const ns = instance.jquery_namespace;
+ const has_jquery_listeners = () =>
+ Object.values($._data(document, "events") || {})
+ .flat()
+ .some((handler) => handler.namespace === ns);
+ expect(has_jquery_listeners()).toBe(true);
+
+ el.remove();
+ await utils.timeout(1); // destroy is async - wait for it.
+ expect(instance.destroyed).toBe(true);
+ expect(document.body.classList.contains("modal-active")).toBe(false);
+ expect(has_jquery_listeners()).toBe(false);
+
+ document.dispatchEvent(new KeyboardEvent("keyup", { key: "Escape" }));
+ document.body.click();
+ window.dispatchEvent(new Event("resize"));
+ await utils.timeout(500); // wait for the debounced resize.
+
+ expect(spy_close).not.toHaveBeenCalled();
+ expect(spy_resize).not.toHaveBeenCalled();
+ });
+
+ it("3.6 - Does not remove the listeners of other modals on destroy.", async function () {
+ document.body.innerHTML = `
+
+
+ `;
+ const el1 = document.querySelector(".modal1");
+ const el2 = document.querySelector(".modal2");
+ const instance1 = new Pattern(el1);
+ const instance2 = new Pattern(el2);
+ await events.await_pattern_init(instance1);
+ await events.await_pattern_init(instance2);
+ const spy_close2 = jest.spyOn(instance2, "close");
+
+ el1.remove();
+ await utils.timeout(1); // destroy is async - wait for it.
+ expect(instance1.destroyed).toBe(true);
+ expect(instance2.destroyed).toBe(false);
+
+ document.dispatchEvent(new KeyboardEvent("keyup", { key: "Escape" }));
+ expect(spy_close2).toHaveBeenCalledTimes(1);
+ });
+ });
+});
diff --git a/src/pat/modal/modal.js b/src/pat/modal/modal.js
index d73a660a8..e708ada27 100644
--- a/src/pat/modal/modal.js
+++ b/src/pat/modal/modal.js
@@ -1,196 +1,20 @@
-import $ from "jquery";
-import Base from "../../core/base";
-import Parser from "../../core/parser";
-import events from "../../core/events";
-import inject from "../inject/inject";
+/**
+ * pat-modal 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:
+ * ./modal--implementation.js
+ */
+import create_lazy_pattern from "../../core/lazy-pattern";
import registry from "../../core/registry";
-import utils from "../../core/utils";
-// Initialize close-panel functionality.
-import "../close-panel/close-panel";
-
-export const parser = new Parser("modal");
-parser.addArgument("class");
-parser.addArgument("closing", ["close-button"], ["close-button", "outside"], true);
-parser.addArgument("close-text", "Close");
-parser.addArgument("panel-header-content", ":first:not(.header)");
-parser.addArgument("source", null); // If not given, the href should specify the source via a url fragment.
-parser.addArgument("target", "#pat-modal");
-
-export default Base.extend({
+const Pattern = create_lazy_pattern({
name: "modal",
- jquery_plugin: true,
- // div's are turned into modals
- // links, forms and subforms inject modals
trigger: "div.pat-modal, a.pat-modal, form.pat-modal, .pat-modal.pat-subform",
-
- async init($el, opts, trigger) {
- if (window.__patternslib_import_styles) {
- import("./_modal.scss");
- }
-
- this.options = parser.parse(this.$el, opts);
- if (trigger && trigger.type === "injection") {
- $.extend(this.options, parser.parse($(trigger.element), {}, false, false));
- }
- if (this.$el.is("div")) {
- this._init_div1();
- } else {
- await this._init_inject1();
- }
- },
-
- async _init_inject1() {
- // This will get remote content via pat-inject, add the pat-modal class
- // to the result and pat-inject's pattern scanning will then call
- // ``_init_div1``.
-
- const opts = {
- ...(this.options.source && { source: this.options.source }),
- target: this.options.target,
- class:
- "pat-modal" + (this.options["class"] ? " " + this.options["class"] : ""),
- };
- if (this.options.url) {
- opts.url = this.options.url;
- }
- if (this.options.trigger) {
- opts.trigger = this.options.trigger;
- }
-
- // if $el is already inside a modal, do not detach #pat-modal,
- // because this would unnecessarily close the modal itself
- if (!this.$el.closest("#pat-modal")) {
- $("#pat-modal").detach();
- }
- this.$el.on("pat-inject-missingSource pat-inject-missingTarget", () => {
- $("#pat-modal").detach();
- });
-
- await inject.init(this.$el, opts);
- },
-
- _init_div1() {
- // This is always called and will inject the modal in the page.
-
- const header = document.createElement("div");
- header.setAttribute("class", "header");
-
- if (this.options.closing.indexOf("close-button") !== -1) {
- header.innerHTML = `
${this.options.closeText} `;
- registry.scan(header, ["close-panel"]); // initialize close-panel
- }
-
- // We cannot handle text nodes here
- let $children;
- if (this.options.panelHeaderContent === "none") {
- $children = this.$el.children();
- } else {
- $children = this.$el.children(
- ":last, :not(" + this.options.panelHeaderContent + ")"
- );
- }
-
- if ($children.length) {
- $children.wrapAll("
");
- } else {
- this.$el.append("
");
- }
- this.$el.children(".panel-content").before(header);
- this.$el.children(this.options.panelHeaderContent).prependTo(header);
-
- // Restore focus in case the active element was a child of $el and
- // the focus was lost during the wrapping.
- document.activeElement?.focus();
-
- this._init_handlers();
- this.resize();
- this.setPosition();
-
- $("body").addClass("modal-active");
- this.el.dispatchEvent(
- new Event("pat-modal-ready", { bubbles: true, cancelable: true })
- );
- },
-
- _init_handlers() {
- events.add_event_listener(this.el, "close-panel", "pat-modal--close-panel", () =>
- this.destroy()
- );
-
- $(document).on("keyup.pat-modal", this._onKeyUp.bind(this));
- if (this.options.closing.indexOf("outside") !== -1) {
- $(document).on("click.pat-modal", this._onPossibleOutsideClick.bind(this));
- }
- $(window).on(
- "resize.pat-modal-position",
- utils.debounce(this.resize.bind(this), 400)
- );
- $(document).on(
- "pat-inject-content-loaded.pat-modal-position",
- "#pat-modal",
- utils.debounce(this.resize.bind(this), 400)
- );
- $(document).on(
- "patterns-injected.pat-modal-position",
- "#pat-modal,div.pat-modal",
- utils.debounce(this.resize.bind(this), 400)
- );
- $(document).on(
- "pat-update.pat-modal-position",
- "#pat-modal,div.pat-modal",
- utils.debounce(this.resize.bind(this), 50)
- );
- },
-
- _onPossibleOutsideClick(ev) {
- if (this.$el.has(ev.target)) {
- this.destroy();
- }
- },
-
- _onKeyUp(ev) {
- if (ev.which === 27) {
- this.destroy();
- }
- },
-
- getTallestChild() {
- let $tallest_child;
- for (const child of $("*", this.$el)) {
- const $child = $(child);
- if (typeof $tallest_child === "undefined") {
- $tallest_child = $child;
- } else if ($child.outerHeight(true) > $tallest_child.outerHeight(true)) {
- $tallest_child = $child;
- }
- }
- return $tallest_child;
- },
-
- setPosition() {
- this.$el.css("top", ($(window).innerHeight() - this.$el.height()) / 2);
- },
-
- resize() {
- // reset the height before setting a new one
- this.$el.removeClass("max-height").css("height", "");
-
- const panel_content_elem = this.$el.find(".panel-content");
- const header_elem = this.$el.find(".header");
- const modal_height =
- panel_content_elem.outerHeight(true) + header_elem.outerHeight(true);
- if (this.$el.height() < modal_height) {
- this.$el.addClass("max-height").css({ height: modal_height + "px" });
- this.setPosition();
- }
- },
-
- async destroy() {
- await utils.timeout(1); // wait a tick for event handlers (e.g. form submit) have a chance to kick in first.
- $(document).off(".pat-modal");
- this.$el.remove();
- $("body").removeClass("modal-active");
- $("body").removeClass("modal-panel");
- },
+ load: () => import("./modal--implementation"),
});
+
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/modal/modal.test.js b/src/pat/modal/modal.test.js
index 1a61ad730..6b06faced 100644
--- a/src/pat/modal/modal.test.js
+++ b/src/pat/modal/modal.test.js
@@ -1,402 +1,15 @@
-import $ from "jquery";
-import events from "../../core/events";
-import pattern from "./modal";
-import registry from "../../core/registry";
-import utils from "../../core/utils";
-import { jest } from "@jest/globals";
+import Pattern from "./modal";
+import Implementation from "./modal--implementation";
-describe("pat-modal", function () {
- let deferred;
-
- const answer = function (html) {
- deferred.resolve(html, "ok", { responseText: html });
- };
-
- beforeEach(function () {
- deferred = new $.Deferred();
- document.body.innerHTML = `
`;
- });
-
- afterEach(function () {
- document.body.innerHTML = "";
- document.body.classList.remove("modal-active");
- jest.restoreAllMocks();
+describe("pat-modal 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 - init", function () {
- it("1.1 - Modal with single element", function () {
- $("#lab").html(
- [
- '
',
- "
Modal content
",
- "
",
- ].join("\n")
- );
- expect($("body").hasClass("modal-active")).toBeFalsy();
- var $modal = $("#modal");
- pattern.init($modal);
- expect($modal.find(".header").length).toBeTruthy();
- expect($modal.find(".header").text()).toBe("Close");
- expect($modal.find(".header .close-panel").length).toBeTruthy();
- expect($modal.find(".panel-content").length).toBeTruthy();
- expect($modal.find(".panel-content").text()).toBe("Modal content");
- expect($("body").hasClass("modal-active")).toBeTruthy();
- });
-
- it("1.2 - Modal with header ", function () {
- $("#lab").html(
- [
- '
',
- "
Modal header ",
- "
Modal content
",
- "
",
- ].join("\n")
- );
- expect($("body").hasClass("modal-active")).toBeFalsy();
- var $modal = $("#modal");
- pattern.init($modal);
- expect($modal.find(".header").text()).toBe("Modal headerClose");
- expect($modal.find(".header .close-panel").length).toBeTruthy();
- expect($modal.find(".panel-content").text()).toBe("Modal content");
- expect($("body").hasClass("modal-active")).toBeTruthy();
- });
-
- it("1.3 - Modal with multiple content items ", function () {
- $("#lab").html(
- [
- '
',
- "
Modal header ",
- "
Modal content
",
- "
Subheader ",
- "
More content
",
- "
",
- ].join("\n")
- );
- expect($("body").hasClass("modal-active")).toBeFalsy();
- var $modal = $("#modal");
- pattern.init($modal);
- expect($modal.find(".header").text()).toBe("Modal headerClose");
- expect($modal.find(".header .close-panel").length).toBeTruthy();
- expect($modal.find(".panel-content p").length).toBe(2);
- expect($modal.find(".panel-content h4").length).toBe(1);
- expect($("body").hasClass("modal-active")).toBeTruthy();
- });
-
- it("1.4 - Modal with a form that has the pat-modal CSS class", async function () {
- var $modal, // main modal container
- $modalLink; // link that triggers the modal
-
- $("#lab")[0].innerHTML = `
-
- Open a modal containing a form with pat-modal CSS class.
-
- `;
-
- $modalLink = $("#modalLink");
- const instance = new pattern($modalLink);
- await events.await_pattern_init(instance);
-
- // najprej #modalLink ne obstaja
- $modal = $("div#pat-modal");
- expect($modal.length).toBe(0);
-
- $modalLink.click(); // trigger panel loading
- utils.timeout(1); // wait a tick for async to settle.
-
- $modal = $("div#pat-modal");
- expect($modal.length).toBeGreaterThan(0);
- });
-
- it("1.5 - Modal with single element that specifies a custom close button string", function () {
- $("#lab").html(
- [
- '
',
- "
Modal content
",
- "
",
- ].join("\n")
- );
- expect($("body").hasClass("modal-active")).toBeFalsy();
- var $modal = $("#modal");
- pattern.init($modal);
- expect($modal.find(".header").length).toBeTruthy();
- expect($modal.find(".header").text()).toBe("Shutdown");
- expect($modal.find(".header .close-panel").length).toBeTruthy();
- expect($("body").hasClass("modal-active")).toBeTruthy();
- });
-
- it("1.6 - Dispatch pat-modal-ready with a div-modal.", async function () {
- document.body.innerHTML = `
-
- `;
-
- const callback = jest.fn();
- const modal_el = document.querySelector(".pat-modal");
- modal_el.addEventListener("pat-modal-ready", callback);
- pattern.init(modal_el);
- await utils.timeout(1); // wait a tick for async to settle.
-
- // Opened immediately
- expect(callback).toHaveBeenCalledTimes(1);
- });
-
- it("1.7 - Dispatch pat-modal-ready with a inject-modal.", async function () {
- jest.spyOn($, "ajax").mockImplementation(() => deferred);
- document.body.innerHTML = `
-
Open modal
- `;
-
- const callback = jest.fn();
- document.body.addEventListener("pat-modal-ready", callback);
- const modal_el = document.querySelector(".pat-modal");
- pattern.init(modal_el);
- await utils.timeout(1); // wait a tick for async to settle.
-
- expect(callback).not.toHaveBeenCalled();
-
- answer(`
`);
- modal_el.click();
- await utils.timeout(1); // wait a tick for async to settle.
- expect(callback).toHaveBeenCalledTimes(1);
- });
-
- it("1.8 - Submit form, do injection and close overlay.", async function () {
- await import("../inject/inject");
-
- jest.spyOn($, "ajax").mockImplementation(() => deferred);
- answer(
- `
hello.
there
`
- );
-
- document.body.innerHTML = `
-
-
-
-
-
-
-
- `;
- registry.scan(document.body);
- await utils.timeout(1); // wait a tick for async to settle.
-
- document.querySelector("button.close-panel[type=submit]").click();
- await utils.timeout(1); // close-button is async - wait for it.
- await utils.timeout(1); // wait a tick for pat-inject to settle.
- await utils.timeout(1); // wait a tick for pat-modal destroy to settle.
-
- expect(document.querySelector(".pat-modal")).toBe(null);
- expect(document.querySelector("#target").textContent).toBe("hello.");
- expect(document.querySelector("#target2").textContent).toBe("there");
- });
-
- it("1.9 - Submit form, do injection and close overlay with multiple forms.", async function () {
- await import("../inject/inject");
-
- jest.spyOn($, "ajax").mockImplementation(() => deferred);
- answer(
- `
hello.
there
`
- );
-
- document.body.innerHTML = `
-
-
-
-
-
-
- `;
- registry.scan(document.body);
- await utils.timeout(1); // wait a tick for async to settle.
-
- document.querySelector(".form2 button.close-panel[type=submit]").click();
- await utils.timeout(1); // close-button is async - wait for it.
- await utils.timeout(1); // wait a tick for pat-inject to settle.
- await utils.timeout(1); // wait a tick for pat-modal destroy to settle.
-
- expect(document.querySelector(".pat-modal")).toBe(null);
- expect(document.querySelector("#target").textContent).toBe("hello.");
- });
-
- it("1.10 - Ensure destroy callback isn't called multiple times.", async function () {
- document.body.innerHTML = `
-
- close
-
- `;
-
- const instance = new pattern(document.querySelector(".pat-modal"));
- registry.scan(document.body); // Also need to instantiate close-panel
-
- await utils.timeout(1); // wait a tick for async to settle.
-
- const spy_destroy = jest.spyOn(instance, "destroy");
-
- // ``destroy`` was already initialized with instantiating the pattern above.
- // Call init again for new instantiation.
- instance.init($(".pat-modal"));
-
- document.querySelector("#close-modal").click();
- await utils.timeout(1); // wait a tick for pat-modal destroy to settle.
-
- expect(spy_destroy).toHaveBeenCalledTimes(1);
- });
-
- it("1.11 - Ensure destroy callback isn't called multiple times with forms and injection.", async function () {
- const markup = `
-
-
-
- `;
-
- // Set up inject mocks
- const pattern_inject = (await import("../inject/inject")).default;
- jest.spyOn($, "ajax").mockImplementation(() => deferred);
- answer("
OK
"); // empties body
-
- document.body.innerHTML = markup;
-
- pattern_inject.init($(".pat-inject"));
- const instance = new pattern(document.querySelector(".pat-modal"));
- registry.scan(document.body); // Also need to instantiate close-panel
- await utils.timeout(1); // wait a tick for async to settle.
-
- const spy_destroy = jest.spyOn(instance, "destroy");
-
- // ``destroy`` was already initialized with instantiating the pattern above.
- // Call init again for new instantiation.
- instance.init($(".pat-modal"));
-
- document.querySelector("#close-modal").click();
- await utils.timeout(1); // close-button is async - wait for it.
- await utils.timeout(1); // wait a tick for pat-inject to settle.
-
- expect(spy_destroy).toHaveBeenCalledTimes(1);
-
- // re-attach and re-initialize. Event handler should only be active once.
- document.body.innerHTML = markup;
- pattern_inject.init($(".pat-inject"));
- new pattern(document.querySelector(".pat-modal"));
- await utils.timeout(1); // wait a tick for async to settle.
- document.querySelector("#close-modal").click();
- await utils.timeout(1); // close-button is async - wait for it.
- await utils.timeout(1); // wait a tick for pat-inject to settle.
- // Previous mocks still active.
- // Handlers executed exactly once.
- expect(spy_destroy).toHaveBeenCalledTimes(1);
- });
- });
-
- it("2.1 - Allow to open a modal in a modal", async function () {
- document.body.innerHTML = `
-
open modal 1
-
- Open another modal
-
-
-
- modal in modal.
-
-
- `;
- const el = document.querySelector(".pat-modal");
- new pattern(el);
- await utils.timeout(1); // wait a tick for async to settle.
-
- el.click();
- await utils.timeout(1); // wait a tick for async to settle.
- await utils.timeout(1); // wait a tick for async to settle.
-
- expect(document.querySelectorAll("#pat-modal").length).toBe(1);
-
- const trigger_sub = document.querySelector("#pat-modal .pat-modal");
- expect(trigger_sub).toBeTruthy();
-
- trigger_sub.click();
- await utils.timeout(1); // wait a tick for async to settle.
- expect(document.querySelectorAll("#pat-modal").length).toBe(1);
- expect(document.querySelector("#pat-modal").textContent).toMatch(
- /modal in modal\./
- );
- });
-
- it("2.2 - Allow to open a modal in a modal via ajax", async function () {
- document.body.innerHTML = `
-
open modal 1
-
- Open another modal
-
- `;
-
- jest.spyOn($, "ajax").mockImplementation(() => deferred);
- answer(`
-
-
-
-
- modal in modal.
-
-
-
-
- `);
-
- const el = document.querySelector(".pat-modal");
- new pattern(el);
- await utils.timeout(1); // wait a tick for async to settle.
-
- el.click();
- await utils.timeout(1); // wait a tick for async to settle.
- await utils.timeout(1); // wait a tick for async to settle.
-
- expect(document.querySelectorAll("#pat-modal").length).toBe(1);
-
- const trigger_sub = document.querySelector("#pat-modal .pat-modal");
- expect(trigger_sub).toBeTruthy();
-
- trigger_sub.click();
- await utils.timeout(1); // wait a tick for async to settle.
-
- expect(document.querySelectorAll("#pat-modal").length).toBe(1);
- expect(document.querySelector("#pat-modal").textContent).toMatch(
- /modal in modal\./
- );
+ it("loads the implementation.", async function () {
+ expect(await Pattern.load()).toBe(Implementation);
});
});
diff --git a/src/pat/navigation/navigation--implementation.js b/src/pat/navigation/navigation--implementation.js
new file mode 100644
index 000000000..92ac1f0ab
--- /dev/null
+++ b/src/pat/navigation/navigation--implementation.js
@@ -0,0 +1,311 @@
+import $ from "jquery";
+import { BasePattern } from "../../core/basepattern";
+import Parser from "../../core/parser";
+import ScrollMarker from "../scroll-marker/scroll-marker--implementation";
+import dom from "../../core/dom";
+import logging from "../../core/logging";
+import registry from "../../core/registry";
+import utils from "../../core/utils";
+
+const log = logging.getLogger("navigation");
+
+export const parser = new Parser("navigation");
+parser.addArgument("item-wrapper", "li");
+parser.addArgument("in-path-class", "navigation-in-path");
+parser.addArgument("in-view-class", "in-view");
+parser.addArgument("current-class", "current");
+parser.addArgument("current-content-class", "navigation-current");
+
+parser.addArgument("scroll-item-side", "top", ["top", "bottom", "middle", "auto"]);
+parser.addArgument("scroll-item-distance", "50%");
+parser.addArgument("scroll-item-visibility", null, [null, "none", "most-visible"]);
+parser.addArgument("scroll-trigger-selector", "a[href^='#'].scroll-trigger");
+
+class Pattern extends BasePattern {
+ static name = "navigation";
+ static trigger = ".pat-navigation";
+ static parser = parser;
+
+ parser_group_options = false;
+
+ init() {
+ this.$el = $(this.el);
+
+ this.init_listeners();
+ this.init_markings();
+
+ if (utils.is_option_truthy(this.options["scroll-trigger-selector"])) {
+ this.scroll_marker = new ScrollMarker(this.el, {
+ "current-class": this.options["current-class"],
+ "current-content-class": this.options["current-content-class"],
+ "in-view-class": this.options["in-view-class"],
+ "side": this.options["scroll-item-side"],
+ "distance": this.options["scroll-item-distance"],
+ "visibility": this.options["scroll-item-visibility"],
+ "selector": this.options["scroll-trigger-selector"],
+ });
+
+ this.debounced_scroll_marker_enabler = utils.debounce(() => {
+ log.debug("Enable scroll-marker.");
+ this.scroll_marker.set_current_disabled = false;
+ this.remove_event_listener(
+ this.scroll_marker.scroll_container === window
+ ? document
+ : this.scroll_marker.scroll_container,
+ "scroll-marker-enable"
+ );
+ }, 200);
+ }
+ }
+
+ /**
+ * Initialize listeners for the navigation.
+ */
+ init_listeners() {
+ const current = this.options["current-class"];
+
+ this.add_event_listener(
+ this.el,
+ "click",
+ "click",
+ (ev) => {
+ // Get the click target's anchor element. The click target
+ // might be a child of the link, e.g. a span wrapped within an
+ // anchor.
+ const target = ev.target.closest("a");
+ if (target?.matches(":not(.pat-inject)")) {
+
+ // Remove all set current classes
+ this.clear_items();
+ // Mark the current item
+ this.mark_current(target);
+
+ if (
+ !utils.is_option_truthy(this.options["scroll-trigger-selector"])
+ ) {
+ // Don't do the scroll-marker stuff below, if it is disabled by the settings.
+ return;
+ }
+ // Disable scroll marker to set the current class after
+ // clicking in the menu and scrolling to the target.
+ log.debug("Disable scroll-marker.");
+ this.scroll_marker.set_current_disabled = true;
+ this.debounced_scroll_marker_enabler();
+ this.add_event_listener(
+ this.scroll_marker.scroll_container === window
+ ? document
+ : this.scroll_marker.scroll_container,
+ "scroll",
+ "scroll-marker-enable",
+ this.debounced_scroll_marker_enabler
+ );
+ }
+ }
+ );
+
+ // Mark the navigation items after pat-inject triggered within this navigation menu.
+ this.$el.on("patterns-inject-triggered", "a", (ev) => {
+ // Remove all set current classes
+ this.clear_items();
+ // Mark the current item
+ this.mark_current(ev.target);
+ });
+
+ // Mark the navigation items after pat-inject injected into this navigation menu.
+ this.$el.on("patterns-injected-scanned", () => {
+ this.init_markings();
+ });
+
+ // Automatically and recursively load the ``.current`` item.
+ if (this.el.classList.contains("navigation-load-current")) {
+ // Check for current elements injected here.
+ this.$el.on("patterns-injected-scanned", (ev) => {
+ const target = ev.target;
+ if (target.matches(`a.${current}`)) target.click();
+ else if (target.matches(`.${current}`)) target.querySelector("a")?.click(); // prettier-ignore
+ });
+ this.el.querySelector(`a.${current}, .${current} a`)?.click();
+ }
+ }
+
+ /**
+ * Initial run to mark the current item and its parents.
+ */
+ init_markings() {
+ if (this.el.querySelector(`.${this.options["current-class"]}`)) {
+ log.debug("Mark navigation items based on existing current class");
+ this.mark_current();
+ } else {
+ log.debug("Mark navigation items based on URL pattern.");
+ this.mark_items_url();
+ }
+ }
+
+ /**
+ * Get a matching parent or stop at stop_el.
+ *
+ * @param {Node} item - The item to start with.
+ * @param {String} selector - The CSS selector to search parent elements for.
+ * @param {Node} stop_el - The element to stop at.
+ *
+ * @returns {Node} - The matching parent or null.
+ */
+ get_parent(item, selector, stop_el) {
+ let matching_parent = item.parentNode;
+ while (matching_parent) {
+ if (matching_parent === stop_el || matching_parent === document) {
+ return null;
+ }
+ if (matching_parent.matches(selector)) {
+ return matching_parent;
+ }
+ matching_parent = matching_parent.parentNode;
+ }
+ }
+
+ /**
+ * Mark an item and it's wrapper as current.
+ *
+ * @param {Node} [current_el] - The item to mark as current.
+ * If not given, the element's tree will be searched for an existing current item.
+ * This is to also mark the wrapper and it's path appropriately.
+ */
+ mark_current(current_el) {
+ const current_els = current_el
+ ? [current_el]
+ : this.el.querySelectorAll(`.current > a, a.current`);
+
+ for (const item of current_els) {
+ item.classList.add(this.options["current-class"]);
+ const wrapper = item.closest(this.options["item-wrapper"]);
+ wrapper?.classList.add(this.options["current-class"]);
+ this.mark_in_path(wrapper || item);
+ log.debug("Statically set current item marked as current", item);
+
+ // Clear all previous current content items.
+ for (const it of [
+ ...document.querySelectorAll(
+ `.${this.options["current-content-class"]}`
+ ),
+ ]) {
+ it.classList.remove(this.options["current-content-class"]);
+ }
+ // Mark the current content item, if it is a hash link.
+ if (item.matches("a[href^='#']")) {
+ const content_item = document.querySelector(
+ dom.escape_css_id(item.hash)
+ );
+ if (content_item) {
+ content_item.classList.add(this.options["current-content-class"]);
+ }
+ }
+ }
+ }
+
+ /**
+ * Mark all parent navigation elements as in path.
+ *
+ * @param {Node} start_el - The element to start with.
+ *
+ */
+ mark_in_path(start_el) {
+ let path_el = this.get_parent(start_el, this.options["item-wrapper"], this.el);
+ while (path_el) {
+ if (!path_el.matches(`.${this.options["current-class"]}`)) {
+ path_el.classList.add(this.options["in-path-class"]);
+ for (const it of [...path_el.children].filter((it) => it.matches("a"))) {
+ it.classList.add(this.options["in-path-class"]);
+ }
+ log.debug("Marked item as in-path", path_el);
+ }
+ path_el = this.get_parent(path_el, this.options["item-wrapper"], this.el);
+ }
+ }
+
+ /**
+ * Mark all navigation items that are in the path of the current url.
+ *
+ * @param {String} [url] - The url to check against.
+ * If not given, the current url will be used.
+ */
+ mark_items_url(url) {
+ const current_url = url || this.base_url();
+ const current_url_prepared = this.prepare_url(current_url);
+
+ const portal_url = this.prepare_url(document.body.dataset?.portalUrl);
+ const nav_items = this.el.querySelectorAll("a");
+
+ for (const nav_item of nav_items) {
+ // Get the nav item's url and rebase it against the current url to
+ // make absolute or relative URLs FQDN URLs.
+ const nav_url = this.prepare_url(
+ new URL(nav_item.getAttribute("href", ""), current_url)?.href
+ );
+
+ const wrapper = nav_item.closest(this.options["item-wrapper"]);
+
+ if (nav_url === current_url_prepared) {
+ nav_item.classList.add(this.options["current-class"]);
+ wrapper?.classList.add(this.options["current-class"]);
+ this.mark_in_path(nav_item);
+ } else if (
+ // Compare the current navigation item url with a slash at the
+ // end - if it is "inPath" it must have a slash in it.
+ current_url_prepared.indexOf(`${nav_url}/`) === 0 &&
+ // Do not set inPath for the "Home" url, as this would always
+ // be in the path.
+ nav_url !== portal_url
+ ) {
+ nav_item.classList.add(this.options["in-path-class"]);
+ wrapper?.classList.add(this.options["in-path-class"]);
+ } else {
+ // Not even in path.
+ continue;
+ }
+ }
+ }
+
+ /**
+ * Clear all navigation items from the inPath and current classes
+ */
+ clear_items() {
+ const items = this.el.querySelectorAll(
+ `.${this.options["in-path-class"]}, .${this.options["current-class"]}`
+ );
+ for (const item of items) {
+ item.classList.remove(this.options["in-path-class"]);
+ item.classList.remove(this.options["current-class"]);
+ }
+ }
+
+ /**
+ * Prepare a URL for comparison.
+ * Plone-specific "/view" and "@@" will be removed as well as a trailing slash.
+ *
+ * @param {String} url - The url to prepare.
+ *
+ * @returns {String} - The prepared url.
+ */
+ prepare_url(url) {
+ return url?.replace("/view", "").replaceAll("@@", "").replace(/\/$/, "");
+ }
+
+ /**
+ * Get the URL of the current page.
+ * If a ``canonical`` meta tag is found, return this.
+ * Otherwise return the window.location URL.
+ * Already prepare the URL for comparison.
+ *
+ * @returns {String} - The current URL.
+ */
+ base_url() {
+ return this.prepare_url(
+ document.querySelector('head link[rel="canonical"]')?.href ||
+ window.location.href
+ );
+ }
+}
+
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/navigation/navigation--implementation.test.js b/src/pat/navigation/navigation--implementation.test.js
new file mode 100644
index 000000000..c084d7f39
--- /dev/null
+++ b/src/pat/navigation/navigation--implementation.test.js
@@ -0,0 +1,537 @@
+import "../inject/inject";
+import Pattern from "./navigation--implementation";
+import Registry from "../../core/registry";
+import events, { event_listener_map } from "../../core/events";
+import utils from "../../core/utils";
+
+describe("1 - Navigation pattern tests", function () {
+ beforeEach(function () {
+ document.body.innerHTML = `
+
+
test content
+
+
+
+
+
+
+ `;
+ });
+ afterEach(function () {
+ document.body.innerHTML = "";
+ });
+
+ it("Test 1: Test roundtrip", async () => {
+ const injection_area = document.querySelector("#injection_area");
+
+ const nav1 = document.querySelector(".nav1");
+ const w1 = nav1.querySelector(".w1");
+ const a1 = nav1.querySelector(".a1");
+ const w11 = nav1.querySelector(".w11");
+ const a11 = nav1.querySelector(".a11");
+
+ const nav2 = document.querySelector(".nav2");
+ const w2 = nav2.querySelector(".w2");
+ const a2 = nav2.querySelector(".a2");
+ const w21 = nav2.querySelector(".w21");
+ const a21 = nav2.querySelector(".a21");
+
+ Registry.scan("body");
+ await utils.timeout(1); // wait a tick for async to settle.
+
+ a1.click();
+ await utils.timeout(1); // wait a tick for async to settle.
+
+ expect(injection_area.textContent === "test content").toBeTruthy();
+ expect(w1.classList.contains("current")).toBeTruthy();
+ expect(w1.classList.contains("navigation-in-path")).toBeFalsy();
+ expect(a1.classList.contains("current")).toBeTruthy();
+ expect(a1.classList.contains("navigation-in-path")).toBeFalsy();
+ expect(w11.classList.contains("current")).toBeFalsy();
+ expect(w11.classList.contains("navigation-in-path")).toBeFalsy();
+ expect(a11.classList.contains("current")).toBeFalsy();
+ expect(a11.classList.contains("navigation-in-path")).toBeFalsy();
+
+ injection_area.innerHTML = "";
+
+ a11.click();
+ await utils.timeout(1); // wait a tick for async to settle.
+
+ expect(injection_area.textContent === "test content").toBeTruthy();
+ expect(w1.classList.contains("current")).toBeFalsy();
+ expect(w1.classList.contains("navigation-in-path")).toBeTruthy();
+ expect(a1.classList.contains("current")).toBeFalsy();
+ expect(a1.classList.contains("navigation-in-path")).toBeTruthy();
+ expect(w11.classList.contains("current")).toBeTruthy();
+ expect(w11.classList.contains("navigation-in-path")).toBeFalsy();
+ expect(a11.classList.contains("current")).toBeTruthy();
+ expect(a11.classList.contains("navigation-in-path")).toBeFalsy();
+
+ injection_area.innerHTML = "";
+
+ a2.click();
+ await utils.timeout(1); // wait a tick for async to settle.
+
+ expect(injection_area.textContent === "test content").toBeTruthy();
+ expect(w2.classList.contains("active")).toBeTruthy();
+ expect(w2.classList.contains("in-path")).toBeFalsy();
+ expect(a2.classList.contains("active")).toBeTruthy();
+ expect(a2.classList.contains("in-path")).toBeFalsy();
+ expect(w21.classList.contains("active")).toBeFalsy();
+ expect(w21.classList.contains("in-path")).toBeFalsy();
+ expect(a21.classList.contains("active")).toBeFalsy();
+ expect(a21.classList.contains("in-path")).toBeFalsy();
+
+ injection_area.innerHTML = "";
+
+ a21.click();
+ await utils.timeout(1); // wait a tick for async to settle.
+
+ expect(injection_area.textContent === "test content").toBeTruthy();
+ expect(w2.classList.contains("active")).toBeFalsy();
+ expect(w2.classList.contains("in-path")).toBeTruthy();
+ expect(a2.classList.contains("active")).toBeFalsy();
+ expect(a2.classList.contains("in-path")).toBeTruthy();
+ expect(w21.classList.contains("active")).toBeTruthy();
+ expect(w21.classList.contains("in-path")).toBeFalsy();
+ expect(a21.classList.contains("active")).toBeTruthy();
+ expect(a21.classList.contains("in-path")).toBeFalsy();
+ });
+
+ it("Test 2: Auto load current", async () => {
+ const injection_area = document.querySelector("#injection_area");
+
+ const nav2 = document.querySelector(".nav2");
+ nav2.classList.add("navigation-load-current");
+
+ const w2 = nav2.querySelector(".w2");
+ const a2 = nav2.querySelector(".a2");
+ const w21 = nav2.querySelector(".w21");
+ const a21 = nav2.querySelector(".a21");
+ a21.classList.add("active");
+
+ Registry.scan("body");
+ await utils.timeout(1); // wait a tick for async to settle.
+
+ expect(injection_area.textContent === "test content").toBeTruthy();
+ expect(w2.classList.contains("active")).toBeFalsy();
+ expect(w2.classList.contains("in-path")).toBeTruthy();
+ expect(a2.classList.contains("active")).toBeFalsy();
+ expect(a2.classList.contains("in-path")).toBeTruthy();
+ expect(w21.classList.contains("active")).toBeTruthy();
+ expect(w21.classList.contains("in-path")).toBeFalsy();
+ expect(a21.classList.contains("active")).toBeTruthy();
+ expect(a21.classList.contains("in-path")).toBeFalsy();
+ });
+});
+
+describe("2 - Navigation pattern tests - mark after navigation injection", function () {
+ let _originalBaseUrl;
+
+ beforeEach(() => {
+ document.body.innerHTML = "";
+ _originalBaseUrl = Pattern.prototype.base_url;
+ Pattern.prototype.base_url = function () {
+ return "https://patternslib.com/path/to/test";
+ };
+ });
+
+ afterEach(() => {
+ document.body.innerHTML = "";
+ Pattern.prototype.base_url = _originalBaseUrl;
+ });
+
+ it("navigation roundtrip", async () => {
+ document.body.innerHTML = `
+
+
load navigation
+
+
+ `;
+
+ // Set portal URL directly on document body
+ document.body.dataset.portalUrl = "https://patternslib.com";
+
+ Registry.scan(document.body);
+ await utils.timeout(1); // wait a tick for async to settle.
+
+ const nav = document.querySelector("nav");
+ const load_nav = document.querySelector(".load-nav");
+ load_nav.click();
+
+ await utils.timeout(1); // wait for MutationObserver
+
+ const w1 = nav.querySelector(".w1");
+ const a1 = nav.querySelector(".a1");
+ const w11 = nav.querySelector(".w11");
+ const a11 = nav.querySelector(".a11");
+
+ expect(w1.classList.contains("current")).toBeFalsy();
+ expect(w1.classList.contains("navigation-in-path")).toBeTruthy();
+ expect(a1.classList.contains("current")).toBeFalsy();
+ expect(a1.classList.contains("navigation-in-path")).toBeTruthy();
+ expect(w11.classList.contains("current")).toBeTruthy();
+ expect(w11.classList.contains("navigation-in-path")).toBeFalsy();
+ expect(a11.classList.contains("current")).toBeTruthy();
+ expect(a11.classList.contains("navigation-in-path")).toBeFalsy();
+ });
+});
+
+describe("3 - Navigation pattern tests - Mark items based on URL", () => {
+ let _originalBaseUrl;
+
+ beforeEach(() => {
+ document.body.innerHTML = "";
+ _originalBaseUrl = Pattern.prototype.base_url;
+ Pattern.prototype.base_url = function () {
+ return "https://patternslib.com/";
+ };
+ });
+
+ afterEach(() => {
+ Pattern.prototype.base_url = _originalBaseUrl;
+ });
+
+ it("navigation roundtrip", async () => {
+ document.body.innerHTML = `
+
+
+
+ `;
+
+ // Set portal URL directly on document body
+ document.body.dataset.portalUrl = "https://patternslib.com";
+
+ const instance = new Pattern(document.querySelector(".pat-navigation"));
+ await events.await_pattern_init(instance);
+
+ const it0 = document.querySelector("a[href='/']");
+ const it1 = document.querySelector("a[href='/path1']");
+ const it2 = document.querySelector("a[href='/path2']");
+ const it21 = document.querySelector("a[href='/path2/path2.1']");
+ const it22 = document.querySelector("a[href='/path2/path2.2']");
+ const it221 = document.querySelector("a[href='/path2/path2.2/path2.2.1']");
+ const it222 = document.querySelector("a[href='/path2/path2.2/path2.2.2']");
+ const it2n = document.querySelector("a[href='/i-do-not-math-the-url-path-hierachy']"); // prettier-ignore
+ const it3 = document.querySelector("a[href='../../path3']");
+ const it4 = document.querySelector("a[href='https://patternslib.com/path4']");
+
+ expect(document.querySelectorAll(".current").length).toBe(2);
+ expect(document.querySelectorAll(".inPath").length).toBe(0);
+ expect(document.querySelector(".current a")).toBe(it0);
+
+ instance.clear_items();
+ instance.mark_items_url("https://patternslib.com/path1");
+
+ expect(document.querySelectorAll(".current").length).toBe(2);
+ expect(document.querySelectorAll(".inPath").length).toBe(0);
+ expect(document.querySelector(".current a")).toBe(it1);
+
+ instance.clear_items();
+ instance.mark_items_url("https://patternslib.com/path2");
+
+ expect(document.querySelectorAll(".current").length).toBe(2);
+ expect(document.querySelectorAll(".inPath").length).toBe(0);
+ expect(document.querySelector(".current a")).toBe(it2);
+
+ instance.clear_items();
+ instance.mark_items_url("https://patternslib.com/path2/path2.1");
+
+ expect(document.querySelectorAll(".current").length).toBe(2);
+ expect(document.querySelectorAll(".inPath").length).toBe(2);
+ expect(document.querySelector(".current a")).toBe(it21);
+
+ instance.clear_items();
+ instance.mark_items_url("https://patternslib.com/path2/path2.2");
+
+ expect(document.querySelectorAll(".current").length).toBe(2);
+ expect(document.querySelectorAll(".inPath").length).toBe(2);
+ expect(document.querySelector(".current a")).toBe(it22);
+
+ instance.clear_items();
+ instance.mark_items_url("https://patternslib.com/path2/path2.2/path2.2.1");
+
+ expect(document.querySelectorAll(".current").length).toBe(2);
+ expect(document.querySelectorAll(".inPath").length).toBe(4);
+ expect(document.querySelector(".current a")).toBe(it221);
+
+ instance.clear_items();
+ instance.mark_items_url("https://patternslib.com/path2/path2.2/path2.2.2");
+
+ expect(document.querySelectorAll(".current").length).toBe(2);
+ expect(document.querySelectorAll(".inPath").length).toBe(4);
+ expect(document.querySelector(".current a")).toBe(it222);
+
+ instance.clear_items();
+ instance.mark_items_url(
+ "https://patternslib.com/i-do-not-math-the-url-path-hierachy"
+ );
+
+ expect(document.querySelectorAll(".current").length).toBe(2);
+ expect(document.querySelectorAll(".inPath").length).toBe(2);
+ expect(document.querySelector(".current a")).toBe(it2n);
+
+ instance.clear_items();
+ instance.mark_items_url("https://patternslib.com/path3");
+
+ expect(document.querySelectorAll(".current").length).toBe(2);
+ expect(document.querySelectorAll(".inPath").length).toBe(0);
+ expect(document.querySelector(".current a")).toBe(it3);
+
+ instance.clear_items();
+ instance.mark_items_url("https://patternslib.com/path4");
+
+ expect(document.querySelectorAll(".current").length).toBe(2);
+ expect(document.querySelectorAll(".inPath").length).toBe(0);
+ expect(document.querySelector(".current a")).toBe(it4);
+ });
+});
+
+describe("4 - Navigation pattern tests - Mark items based based clicking without pat-inject.", () => {
+ beforeEach(() => {
+ document.body.innerHTML = "";
+ });
+
+ afterEach(() => {
+ document.body.innerHTML = "";
+ });
+
+ it("navigation roundtrip", async () => {
+ document.body.innerHTML = `
+
+
+
+ `;
+
+ const instance = new Pattern(document.querySelector(".pat-navigation"));
+ await events.await_pattern_init(instance);
+
+ const it0 = document.querySelector("a[href='/home']");
+ const it1 = document.querySelector("a[href='/path1']");
+ const it2 = document.querySelector("a[href='/path2']");
+ const it21 = document.querySelector("a[href='/path2/path2.1']");
+ const it22 = document.querySelector("a[href='/path2/path2.2']");
+ const it221 = document.querySelector("a[href='/path2/path2.2/path2.2.1']");
+ const it222 = document.querySelector("a[href='/path2/path2.2/path2.2.2']");
+
+ expect(document.querySelectorAll(".current").length).toBe(2);
+ expect(document.querySelectorAll(".inPath").length).toBe(0);
+ expect(document.querySelector(".current a")).toBe(it0);
+
+ instance.clear_items();
+ it1.click();
+
+ expect(document.querySelectorAll(".current").length).toBe(2);
+ expect(document.querySelectorAll(".inPath").length).toBe(0);
+ expect(document.querySelector(".current a")).toBe(it1);
+
+ instance.clear_items();
+ it2.click();
+
+ expect(document.querySelectorAll(".current").length).toBe(2);
+ expect(document.querySelectorAll(".inPath").length).toBe(0);
+ expect(document.querySelector(".current a")).toBe(it2);
+
+ instance.clear_items();
+ it21.click();
+
+ expect(document.querySelectorAll(".current").length).toBe(2);
+ expect(document.querySelectorAll(".inPath").length).toBe(2);
+ expect(document.querySelector(".current a")).toBe(it21);
+
+ instance.clear_items();
+ it22.click();
+
+ expect(document.querySelectorAll(".current").length).toBe(2);
+ expect(document.querySelectorAll(".inPath").length).toBe(2);
+ expect(document.querySelector(".current a")).toBe(it22);
+
+ instance.clear_items();
+ it221.click();
+
+ expect(document.querySelectorAll(".current").length).toBe(2);
+ expect(document.querySelectorAll(".inPath").length).toBe(4);
+ expect(document.querySelector(".current a")).toBe(it221);
+
+ instance.clear_items();
+ it222.click();
+
+ expect(document.querySelectorAll(".current").length).toBe(2);
+ expect(document.querySelectorAll(".inPath").length).toBe(4);
+ expect(document.querySelector(".current a")).toBe(it222);
+ });
+});
+
+describe("5 - Navigation pattern tests - Destroy.", () => {
+ const listener_ids = (el, name) =>
+ [...(event_listener_map.get(el)?.keys() || [])].filter((id) =>
+ id.includes(name)
+ );
+
+ afterEach(() => {
+ document.body.innerHTML = "";
+ });
+
+ it("5.1 - Removing the navigation removes its listeners.", async () => {
+ document.body.innerHTML = `
+
+
+
+
+
+ `;
+
+ const nav = document.querySelector(".pat-navigation");
+ const instance = new Pattern(nav);
+ await events.await_pattern_init(instance);
+ await events.await_pattern_init(instance.scroll_marker);
+
+ expect(listener_ids(nav, "navigation--").length).toBe(1);
+
+ // Clicking a scroll trigger temporarily disables the scroll marker
+ // and listens for scroll events on the scroll container.
+ document.querySelector("a[href='#s1']").click();
+ expect(instance.scroll_marker.set_current_disabled).toBe(true);
+ expect(listener_ids(document, "scroll-marker-enable").length).toBe(1);
+
+ nav.remove();
+ await utils.timeout(1);
+
+ expect(instance.destroyed).toBe(true);
+ expect(instance.scroll_marker.destroyed).toBe(true);
+ expect(listener_ids(nav, "navigation--").length).toBe(0);
+ expect(listener_ids(document, "scroll-marker-enable").length).toBe(0);
+ });
+
+ it("5.2 - The scroll marker is re-enabled after scrolling.", async () => {
+ document.body.innerHTML = `
+
+
+
+
+ `;
+
+ const nav = document.querySelector(".pat-navigation");
+ const instance = new Pattern(nav);
+ await events.await_pattern_init(instance);
+ await events.await_pattern_init(instance.scroll_marker);
+
+ document.querySelector("a[href='#s1']").click();
+ expect(instance.scroll_marker.set_current_disabled).toBe(true);
+
+ document.dispatchEvent(new Event("scroll"));
+ await utils.timeout(210); // Wait for the debounced enabler.
+
+ expect(instance.scroll_marker.set_current_disabled).toBe(false);
+ expect(listener_ids(document, "scroll-marker-enable").length).toBe(0);
+ });
+});
diff --git a/src/pat/navigation/navigation.js b/src/pat/navigation/navigation.js
index 59ae4e6a9..79759e9b9 100644
--- a/src/pat/navigation/navigation.js
+++ b/src/pat/navigation/navigation.js
@@ -1,310 +1,19 @@
-import $ from "jquery";
-import { BasePattern } from "../../core/basepattern";
-import Parser from "../../core/parser";
-import ScrollMarker from "../scroll-marker/scroll-marker";
-import dom from "../../core/dom";
-import logging from "../../core/logging";
+/**
+ * pat-navigation 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:
+ * ./navigation--implementation.js
+ */
+import create_lazy_pattern from "../../core/lazy-pattern";
import registry from "../../core/registry";
-import utils from "../../core/utils";
-const log = logging.getLogger("navigation");
-
-export const parser = new Parser("navigation");
-parser.addArgument("item-wrapper", "li");
-parser.addArgument("in-path-class", "navigation-in-path");
-parser.addArgument("in-view-class", "in-view");
-parser.addArgument("current-class", "current");
-parser.addArgument("current-content-class", "navigation-current");
-
-parser.addArgument("scroll-item-side", "top", ["top", "bottom", "middle", "auto"]);
-parser.addArgument("scroll-item-distance", "50%");
-parser.addArgument("scroll-item-visibility", null, [null, "none", "most-visible"]);
-parser.addArgument("scroll-trigger-selector", "a[href^='#'].scroll-trigger");
-
-class Pattern extends BasePattern {
- static name = "navigation";
- static trigger = ".pat-navigation";
- static parser = parser;
-
- parser_group_options = false;
-
- init() {
- this.$el = $(this.el);
-
- this.init_listeners();
- this.init_markings();
-
- if (utils.is_option_truthy(this.options["scroll-trigger-selector"])) {
- this.scroll_marker = new ScrollMarker(this.el, {
- "current-class": this.options["current-class"],
- "current-content-class": this.options["current-content-class"],
- "in-view-class": this.options["in-view-class"],
- "side": this.options["scroll-item-side"],
- "distance": this.options["scroll-item-distance"],
- "visibility": this.options["scroll-item-visibility"],
- "selector": this.options["scroll-trigger-selector"],
- });
-
- this.debounced_scroll_marker_enabler = utils.debounce(() => {
- log.debug("Enable scroll-marker.");
- this.scroll_marker.set_current_disabled = false;
- this.remove_event_listener(
- this.scroll_marker.scroll_container === window
- ? document
- : this.scroll_marker.scroll_container,
- "scroll-marker-enable"
- );
- }, 200);
- }
- }
-
- /**
- * Initialize listeners for the navigation.
- */
- init_listeners() {
- const current = this.options["current-class"];
-
- this.add_event_listener(
- this.el,
- "click",
- "click",
- (ev) => {
- // Get the click target's anchor element. The click target
- // might be a child of the link, e.g. a span wrapped within an
- // anchor.
- const target = ev.target.closest("a");
- if (target?.matches(":not(.pat-inject)")) {
-
- // Remove all set current classes
- this.clear_items();
- // Mark the current item
- this.mark_current(target);
-
- if (
- !utils.is_option_truthy(this.options["scroll-trigger-selector"])
- ) {
- // Don't do the scroll-marker stuff below, if it is disabled by the settings.
- return;
- }
- // Disable scroll marker to set the current class after
- // clicking in the menu and scrolling to the target.
- log.debug("Disable scroll-marker.");
- this.scroll_marker.set_current_disabled = true;
- this.debounced_scroll_marker_enabler();
- this.add_event_listener(
- this.scroll_marker.scroll_container === window
- ? document
- : this.scroll_marker.scroll_container,
- "scroll",
- "scroll-marker-enable",
- this.debounced_scroll_marker_enabler
- );
- }
- }
- );
-
- // Mark the navigation items after pat-inject triggered within this navigation menu.
- this.$el.on("patterns-inject-triggered", "a", (ev) => {
- // Remove all set current classes
- this.clear_items();
- // Mark the current item
- this.mark_current(ev.target);
- });
-
- // Mark the navigation items after pat-inject injected into this navigation menu.
- this.$el.on("patterns-injected-scanned", () => {
- this.init_markings();
- });
-
- // Automatically and recursively load the ``.current`` item.
- if (this.el.classList.contains("navigation-load-current")) {
- // Check for current elements injected here.
- this.$el.on("patterns-injected-scanned", (ev) => {
- const target = ev.target;
- if (target.matches(`a.${current}`)) target.click();
- else if (target.matches(`.${current}`)) target.querySelector("a")?.click(); // prettier-ignore
- });
- this.el.querySelector(`a.${current}, .${current} a`)?.click();
- }
- }
-
- /**
- * Initial run to mark the current item and its parents.
- */
- init_markings() {
- if (this.el.querySelector(`.${this.options["current-class"]}`)) {
- log.debug("Mark navigation items based on existing current class");
- this.mark_current();
- } else {
- log.debug("Mark navigation items based on URL pattern.");
- this.mark_items_url();
- }
- }
-
- /**
- * Get a matching parent or stop at stop_el.
- *
- * @param {Node} item - The item to start with.
- * @param {String} selector - The CSS selector to search parent elements for.
- * @param {Node} stop_el - The element to stop at.
- *
- * @returns {Node} - The matching parent or null.
- */
- get_parent(item, selector, stop_el) {
- let matching_parent = item.parentNode;
- while (matching_parent) {
- if (matching_parent === stop_el || matching_parent === document) {
- return null;
- }
- if (matching_parent.matches(selector)) {
- return matching_parent;
- }
- matching_parent = matching_parent.parentNode;
- }
- }
-
- /**
- * Mark an item and it's wrapper as current.
- *
- * @param {Node} [current_el] - The item to mark as current.
- * If not given, the element's tree will be searched for an existing current item.
- * This is to also mark the wrapper and it's path appropriately.
- */
- mark_current(current_el) {
- const current_els = current_el
- ? [current_el]
- : this.el.querySelectorAll(`.current > a, a.current`);
-
- for (const item of current_els) {
- item.classList.add(this.options["current-class"]);
- const wrapper = item.closest(this.options["item-wrapper"]);
- wrapper?.classList.add(this.options["current-class"]);
- this.mark_in_path(wrapper || item);
- log.debug("Statically set current item marked as current", item);
-
- // Clear all previous current content items.
- for (const it of [
- ...document.querySelectorAll(
- `.${this.options["current-content-class"]}`
- ),
- ]) {
- it.classList.remove(this.options["current-content-class"]);
- }
- // Mark the current content item, if it is a hash link.
- if (item.matches("a[href^='#']")) {
- const content_item = document.querySelector(
- dom.escape_css_id(item.hash)
- );
- if (content_item) {
- content_item.classList.add(this.options["current-content-class"]);
- }
- }
- }
- }
-
- /**
- * Mark all parent navigation elements as in path.
- *
- * @param {Node} start_el - The element to start with.
- *
- */
- mark_in_path(start_el) {
- let path_el = this.get_parent(start_el, this.options["item-wrapper"], this.el);
- while (path_el) {
- if (!path_el.matches(`.${this.options["current-class"]}`)) {
- path_el.classList.add(this.options["in-path-class"]);
- for (const it of [...path_el.children].filter((it) => it.matches("a"))) {
- it.classList.add(this.options["in-path-class"]);
- }
- log.debug("Marked item as in-path", path_el);
- }
- path_el = this.get_parent(path_el, this.options["item-wrapper"], this.el);
- }
- }
-
- /**
- * Mark all navigation items that are in the path of the current url.
- *
- * @param {String} [url] - The url to check against.
- * If not given, the current url will be used.
- */
- mark_items_url(url) {
- const current_url = url || this.base_url();
- const current_url_prepared = this.prepare_url(current_url);
-
- const portal_url = this.prepare_url(document.body.dataset?.portalUrl);
- const nav_items = this.el.querySelectorAll("a");
-
- for (const nav_item of nav_items) {
- // Get the nav item's url and rebase it against the current url to
- // make absolute or relative URLs FQDN URLs.
- const nav_url = this.prepare_url(
- new URL(nav_item.getAttribute("href", ""), current_url)?.href
- );
-
- const wrapper = nav_item.closest(this.options["item-wrapper"]);
-
- if (nav_url === current_url_prepared) {
- nav_item.classList.add(this.options["current-class"]);
- wrapper?.classList.add(this.options["current-class"]);
- this.mark_in_path(nav_item);
- } else if (
- // Compare the current navigation item url with a slash at the
- // end - if it is "inPath" it must have a slash in it.
- current_url_prepared.indexOf(`${nav_url}/`) === 0 &&
- // Do not set inPath for the "Home" url, as this would always
- // be in the path.
- nav_url !== portal_url
- ) {
- nav_item.classList.add(this.options["in-path-class"]);
- wrapper?.classList.add(this.options["in-path-class"]);
- } else {
- // Not even in path.
- continue;
- }
- }
- }
-
- /**
- * Clear all navigation items from the inPath and current classes
- */
- clear_items() {
- const items = this.el.querySelectorAll(
- `.${this.options["in-path-class"]}, .${this.options["current-class"]}`
- );
- for (const item of items) {
- item.classList.remove(this.options["in-path-class"]);
- item.classList.remove(this.options["current-class"]);
- }
- }
-
- /**
- * Prepare a URL for comparison.
- * Plone-specific "/view" and "@@" will be removed as well as a trailing slash.
- *
- * @param {String} url - The url to prepare.
- *
- * @returns {String} - The prepared url.
- */
- prepare_url(url) {
- return url?.replace("/view", "").replaceAll("@@", "").replace(/\/$/, "");
- }
-
- /**
- * Get the URL of the current page.
- * If a ``canonical`` meta tag is found, return this.
- * Otherwise return the window.location URL.
- * Already prepare the URL for comparison.
- *
- * @returns {String} - The current URL.
- */
- base_url() {
- return this.prepare_url(
- document.querySelector('head link[rel="canonical"]')?.href ||
- window.location.href
- );
- }
-}
+const Pattern = create_lazy_pattern({
+ name: "navigation",
+ trigger: ".pat-navigation",
+ load: () => import("./navigation--implementation"),
+});
registry.register(Pattern);
export default Pattern;
diff --git a/src/pat/navigation/navigation.test.js b/src/pat/navigation/navigation.test.js
index 5f94b7e13..e1bb65094 100644
--- a/src/pat/navigation/navigation.test.js
+++ b/src/pat/navigation/navigation.test.js
@@ -1,537 +1,15 @@
-import "../inject/inject";
import Pattern from "./navigation";
-import Registry from "../../core/registry";
-import events, { event_listener_map } from "../../core/events";
-import utils from "../../core/utils";
+import Implementation from "./navigation--implementation";
-describe("1 - Navigation pattern tests", function () {
- beforeEach(function () {
- document.body.innerHTML = `
-
-
test content
-
-
-
-
-
-
- `;
+describe("pat-navigation 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);
});
- afterEach(function () {
- document.body.innerHTML = "";
- });
-
- it("Test 1: Test roundtrip", async () => {
- const injection_area = document.querySelector("#injection_area");
-
- const nav1 = document.querySelector(".nav1");
- const w1 = nav1.querySelector(".w1");
- const a1 = nav1.querySelector(".a1");
- const w11 = nav1.querySelector(".w11");
- const a11 = nav1.querySelector(".a11");
-
- const nav2 = document.querySelector(".nav2");
- const w2 = nav2.querySelector(".w2");
- const a2 = nav2.querySelector(".a2");
- const w21 = nav2.querySelector(".w21");
- const a21 = nav2.querySelector(".a21");
-
- Registry.scan("body");
- await utils.timeout(1); // wait a tick for async to settle.
-
- a1.click();
- await utils.timeout(1); // wait a tick for async to settle.
-
- expect(injection_area.textContent === "test content").toBeTruthy();
- expect(w1.classList.contains("current")).toBeTruthy();
- expect(w1.classList.contains("navigation-in-path")).toBeFalsy();
- expect(a1.classList.contains("current")).toBeTruthy();
- expect(a1.classList.contains("navigation-in-path")).toBeFalsy();
- expect(w11.classList.contains("current")).toBeFalsy();
- expect(w11.classList.contains("navigation-in-path")).toBeFalsy();
- expect(a11.classList.contains("current")).toBeFalsy();
- expect(a11.classList.contains("navigation-in-path")).toBeFalsy();
-
- injection_area.innerHTML = "";
-
- a11.click();
- await utils.timeout(1); // wait a tick for async to settle.
-
- expect(injection_area.textContent === "test content").toBeTruthy();
- expect(w1.classList.contains("current")).toBeFalsy();
- expect(w1.classList.contains("navigation-in-path")).toBeTruthy();
- expect(a1.classList.contains("current")).toBeFalsy();
- expect(a1.classList.contains("navigation-in-path")).toBeTruthy();
- expect(w11.classList.contains("current")).toBeTruthy();
- expect(w11.classList.contains("navigation-in-path")).toBeFalsy();
- expect(a11.classList.contains("current")).toBeTruthy();
- expect(a11.classList.contains("navigation-in-path")).toBeFalsy();
-
- injection_area.innerHTML = "";
-
- a2.click();
- await utils.timeout(1); // wait a tick for async to settle.
-
- expect(injection_area.textContent === "test content").toBeTruthy();
- expect(w2.classList.contains("active")).toBeTruthy();
- expect(w2.classList.contains("in-path")).toBeFalsy();
- expect(a2.classList.contains("active")).toBeTruthy();
- expect(a2.classList.contains("in-path")).toBeFalsy();
- expect(w21.classList.contains("active")).toBeFalsy();
- expect(w21.classList.contains("in-path")).toBeFalsy();
- expect(a21.classList.contains("active")).toBeFalsy();
- expect(a21.classList.contains("in-path")).toBeFalsy();
-
- injection_area.innerHTML = "";
-
- a21.click();
- await utils.timeout(1); // wait a tick for async to settle.
-
- expect(injection_area.textContent === "test content").toBeTruthy();
- expect(w2.classList.contains("active")).toBeFalsy();
- expect(w2.classList.contains("in-path")).toBeTruthy();
- expect(a2.classList.contains("active")).toBeFalsy();
- expect(a2.classList.contains("in-path")).toBeTruthy();
- expect(w21.classList.contains("active")).toBeTruthy();
- expect(w21.classList.contains("in-path")).toBeFalsy();
- expect(a21.classList.contains("active")).toBeTruthy();
- expect(a21.classList.contains("in-path")).toBeFalsy();
- });
-
- it("Test 2: Auto load current", async () => {
- const injection_area = document.querySelector("#injection_area");
-
- const nav2 = document.querySelector(".nav2");
- nav2.classList.add("navigation-load-current");
-
- const w2 = nav2.querySelector(".w2");
- const a2 = nav2.querySelector(".a2");
- const w21 = nav2.querySelector(".w21");
- const a21 = nav2.querySelector(".a21");
- a21.classList.add("active");
-
- Registry.scan("body");
- await utils.timeout(1); // wait a tick for async to settle.
-
- expect(injection_area.textContent === "test content").toBeTruthy();
- expect(w2.classList.contains("active")).toBeFalsy();
- expect(w2.classList.contains("in-path")).toBeTruthy();
- expect(a2.classList.contains("active")).toBeFalsy();
- expect(a2.classList.contains("in-path")).toBeTruthy();
- expect(w21.classList.contains("active")).toBeTruthy();
- expect(w21.classList.contains("in-path")).toBeFalsy();
- expect(a21.classList.contains("active")).toBeTruthy();
- expect(a21.classList.contains("in-path")).toBeFalsy();
- });
-});
-
-describe("2 - Navigation pattern tests - mark after navigation injection", function () {
- let _originalBaseUrl;
-
- beforeEach(() => {
- document.body.innerHTML = "";
- _originalBaseUrl = Pattern.prototype.base_url;
- Pattern.prototype.base_url = function () {
- return "https://patternslib.com/path/to/test";
- };
- });
-
- afterEach(() => {
- document.body.innerHTML = "";
- Pattern.prototype.base_url = _originalBaseUrl;
- });
-
- it("navigation roundtrip", async () => {
- document.body.innerHTML = `
-
-
load navigation
-
-
- `;
-
- // Set portal URL directly on document body
- document.body.dataset.portalUrl = "https://patternslib.com";
-
- Registry.scan(document.body);
- await utils.timeout(1); // wait a tick for async to settle.
-
- const nav = document.querySelector("nav");
- const load_nav = document.querySelector(".load-nav");
- load_nav.click();
-
- await utils.timeout(1); // wait for MutationObserver
-
- const w1 = nav.querySelector(".w1");
- const a1 = nav.querySelector(".a1");
- const w11 = nav.querySelector(".w11");
- const a11 = nav.querySelector(".a11");
-
- expect(w1.classList.contains("current")).toBeFalsy();
- expect(w1.classList.contains("navigation-in-path")).toBeTruthy();
- expect(a1.classList.contains("current")).toBeFalsy();
- expect(a1.classList.contains("navigation-in-path")).toBeTruthy();
- expect(w11.classList.contains("current")).toBeTruthy();
- expect(w11.classList.contains("navigation-in-path")).toBeFalsy();
- expect(a11.classList.contains("current")).toBeTruthy();
- expect(a11.classList.contains("navigation-in-path")).toBeFalsy();
- });
-});
-
-describe("3 - Navigation pattern tests - Mark items based on URL", () => {
- let _originalBaseUrl;
-
- beforeEach(() => {
- document.body.innerHTML = "";
- _originalBaseUrl = Pattern.prototype.base_url;
- Pattern.prototype.base_url = function () {
- return "https://patternslib.com/";
- };
- });
-
- afterEach(() => {
- Pattern.prototype.base_url = _originalBaseUrl;
- });
-
- it("navigation roundtrip", async () => {
- document.body.innerHTML = `
-
-
-
- `;
-
- // Set portal URL directly on document body
- document.body.dataset.portalUrl = "https://patternslib.com";
-
- const instance = new Pattern(document.querySelector(".pat-navigation"));
- await events.await_pattern_init(instance);
-
- const it0 = document.querySelector("a[href='/']");
- const it1 = document.querySelector("a[href='/path1']");
- const it2 = document.querySelector("a[href='/path2']");
- const it21 = document.querySelector("a[href='/path2/path2.1']");
- const it22 = document.querySelector("a[href='/path2/path2.2']");
- const it221 = document.querySelector("a[href='/path2/path2.2/path2.2.1']");
- const it222 = document.querySelector("a[href='/path2/path2.2/path2.2.2']");
- const it2n = document.querySelector("a[href='/i-do-not-math-the-url-path-hierachy']"); // prettier-ignore
- const it3 = document.querySelector("a[href='../../path3']");
- const it4 = document.querySelector("a[href='https://patternslib.com/path4']");
-
- expect(document.querySelectorAll(".current").length).toBe(2);
- expect(document.querySelectorAll(".inPath").length).toBe(0);
- expect(document.querySelector(".current a")).toBe(it0);
-
- instance.clear_items();
- instance.mark_items_url("https://patternslib.com/path1");
-
- expect(document.querySelectorAll(".current").length).toBe(2);
- expect(document.querySelectorAll(".inPath").length).toBe(0);
- expect(document.querySelector(".current a")).toBe(it1);
-
- instance.clear_items();
- instance.mark_items_url("https://patternslib.com/path2");
-
- expect(document.querySelectorAll(".current").length).toBe(2);
- expect(document.querySelectorAll(".inPath").length).toBe(0);
- expect(document.querySelector(".current a")).toBe(it2);
-
- instance.clear_items();
- instance.mark_items_url("https://patternslib.com/path2/path2.1");
-
- expect(document.querySelectorAll(".current").length).toBe(2);
- expect(document.querySelectorAll(".inPath").length).toBe(2);
- expect(document.querySelector(".current a")).toBe(it21);
-
- instance.clear_items();
- instance.mark_items_url("https://patternslib.com/path2/path2.2");
-
- expect(document.querySelectorAll(".current").length).toBe(2);
- expect(document.querySelectorAll(".inPath").length).toBe(2);
- expect(document.querySelector(".current a")).toBe(it22);
-
- instance.clear_items();
- instance.mark_items_url("https://patternslib.com/path2/path2.2/path2.2.1");
-
- expect(document.querySelectorAll(".current").length).toBe(2);
- expect(document.querySelectorAll(".inPath").length).toBe(4);
- expect(document.querySelector(".current a")).toBe(it221);
-
- instance.clear_items();
- instance.mark_items_url("https://patternslib.com/path2/path2.2/path2.2.2");
-
- expect(document.querySelectorAll(".current").length).toBe(2);
- expect(document.querySelectorAll(".inPath").length).toBe(4);
- expect(document.querySelector(".current a")).toBe(it222);
-
- instance.clear_items();
- instance.mark_items_url(
- "https://patternslib.com/i-do-not-math-the-url-path-hierachy"
- );
-
- expect(document.querySelectorAll(".current").length).toBe(2);
- expect(document.querySelectorAll(".inPath").length).toBe(2);
- expect(document.querySelector(".current a")).toBe(it2n);
-
- instance.clear_items();
- instance.mark_items_url("https://patternslib.com/path3");
-
- expect(document.querySelectorAll(".current").length).toBe(2);
- expect(document.querySelectorAll(".inPath").length).toBe(0);
- expect(document.querySelector(".current a")).toBe(it3);
-
- instance.clear_items();
- instance.mark_items_url("https://patternslib.com/path4");
-
- expect(document.querySelectorAll(".current").length).toBe(2);
- expect(document.querySelectorAll(".inPath").length).toBe(0);
- expect(document.querySelector(".current a")).toBe(it4);
- });
-});
-
-describe("4 - Navigation pattern tests - Mark items based based clicking without pat-inject.", () => {
- beforeEach(() => {
- document.body.innerHTML = "";
- });
-
- afterEach(() => {
- document.body.innerHTML = "";
- });
-
- it("navigation roundtrip", async () => {
- document.body.innerHTML = `
-
-
-
- `;
-
- const instance = new Pattern(document.querySelector(".pat-navigation"));
- await events.await_pattern_init(instance);
-
- const it0 = document.querySelector("a[href='/home']");
- const it1 = document.querySelector("a[href='/path1']");
- const it2 = document.querySelector("a[href='/path2']");
- const it21 = document.querySelector("a[href='/path2/path2.1']");
- const it22 = document.querySelector("a[href='/path2/path2.2']");
- const it221 = document.querySelector("a[href='/path2/path2.2/path2.2.1']");
- const it222 = document.querySelector("a[href='/path2/path2.2/path2.2.2']");
-
- expect(document.querySelectorAll(".current").length).toBe(2);
- expect(document.querySelectorAll(".inPath").length).toBe(0);
- expect(document.querySelector(".current a")).toBe(it0);
-
- instance.clear_items();
- it1.click();
-
- expect(document.querySelectorAll(".current").length).toBe(2);
- expect(document.querySelectorAll(".inPath").length).toBe(0);
- expect(document.querySelector(".current a")).toBe(it1);
-
- instance.clear_items();
- it2.click();
-
- expect(document.querySelectorAll(".current").length).toBe(2);
- expect(document.querySelectorAll(".inPath").length).toBe(0);
- expect(document.querySelector(".current a")).toBe(it2);
-
- instance.clear_items();
- it21.click();
-
- expect(document.querySelectorAll(".current").length).toBe(2);
- expect(document.querySelectorAll(".inPath").length).toBe(2);
- expect(document.querySelector(".current a")).toBe(it21);
-
- instance.clear_items();
- it22.click();
-
- expect(document.querySelectorAll(".current").length).toBe(2);
- expect(document.querySelectorAll(".inPath").length).toBe(2);
- expect(document.querySelector(".current a")).toBe(it22);
-
- instance.clear_items();
- it221.click();
-
- expect(document.querySelectorAll(".current").length).toBe(2);
- expect(document.querySelectorAll(".inPath").length).toBe(4);
- expect(document.querySelector(".current a")).toBe(it221);
-
- instance.clear_items();
- it222.click();
-
- expect(document.querySelectorAll(".current").length).toBe(2);
- expect(document.querySelectorAll(".inPath").length).toBe(4);
- expect(document.querySelector(".current a")).toBe(it222);
- });
-});
-
-describe("5 - Navigation pattern tests - Destroy.", () => {
- const listener_ids = (el, name) =>
- [...(event_listener_map.get(el)?.keys() || [])].filter((id) =>
- id.includes(name)
- );
-
- afterEach(() => {
- document.body.innerHTML = "";
- });
-
- it("5.1 - Removing the navigation removes its listeners.", async () => {
- document.body.innerHTML = `
-
-
-
-
-
- `;
-
- const nav = document.querySelector(".pat-navigation");
- const instance = new Pattern(nav);
- await events.await_pattern_init(instance);
- await events.await_pattern_init(instance.scroll_marker);
-
- expect(listener_ids(nav, "navigation--").length).toBe(1);
-
- // Clicking a scroll trigger temporarily disables the scroll marker
- // and listens for scroll events on the scroll container.
- document.querySelector("a[href='#s1']").click();
- expect(instance.scroll_marker.set_current_disabled).toBe(true);
- expect(listener_ids(document, "scroll-marker-enable").length).toBe(1);
-
- nav.remove();
- await utils.timeout(1);
-
- expect(instance.destroyed).toBe(true);
- expect(instance.scroll_marker.destroyed).toBe(true);
- expect(listener_ids(nav, "navigation--").length).toBe(0);
- expect(listener_ids(document, "scroll-marker-enable").length).toBe(0);
- });
-
- it("5.2 - The scroll marker is re-enabled after scrolling.", async () => {
- document.body.innerHTML = `
-
-
-
-
- `;
-
- const nav = document.querySelector(".pat-navigation");
- const instance = new Pattern(nav);
- await events.await_pattern_init(instance);
- await events.await_pattern_init(instance.scroll_marker);
-
- document.querySelector("a[href='#s1']").click();
- expect(instance.scroll_marker.set_current_disabled).toBe(true);
-
- document.dispatchEvent(new Event("scroll"));
- await utils.timeout(210); // Wait for the debounced enabler.
- expect(instance.scroll_marker.set_current_disabled).toBe(false);
- expect(listener_ids(document, "scroll-marker-enable").length).toBe(0);
+ it("loads the implementation.", async function () {
+ expect(await Pattern.load()).toBe(Implementation);
});
});
diff --git a/src/pat/notification/notification--implementation.js b/src/pat/notification/notification--implementation.js
new file mode 100644
index 000000000..f00567bda
--- /dev/null
+++ b/src/pat/notification/notification--implementation.js
@@ -0,0 +1,248 @@
+// Patterns notification - Display (self-healing) notifications.
+import $ from "jquery";
+import { BasePattern } from "../../core/basepattern";
+import dom from "../../core/dom";
+import events from "../../core/events";
+import inject from "../inject/inject";
+import logging from "../../core/logging";
+import Parser from "../../core/parser";
+import registry from "../../core/registry";
+import utils from "../../core/utils";
+
+// Initialize close-panel functionality.
+import "../close-panel/close-panel";
+
+const log = logging.getLogger("notification");
+//log.setLevel(logging.Level.DEBUG);
+
+export const parser = new Parser("notification");
+parser.addArgument("type", "static", ["static", "banner"]);
+parser.addArgument("healing", "5s");
+parser.addArgument("controls", "icons", ["icons", "buttons", "none"]);
+parser.addArgument("class");
+parser.addArgument("close-text", "Close");
+
+// Counter for unique notification panel ids.
+let count = 0;
+
+class Pattern extends BasePattern {
+ static name = "notification";
+ static trigger = ".pat-notification";
+ static parser = parser;
+
+ // The notification panel wrapping the pattern element.
+ panel = null;
+
+ init() {
+ if (this.el.matches("a, form")) {
+ this._init_inject();
+ } else {
+ this.panel = this._init_notification(this.el, this.options);
+ }
+ }
+
+ destroy() {
+ if (this.destroyed) {
+ return;
+ }
+ // Stop the healing timer of the notification panel of this element.
+ // Notifications created via injection are independent of the
+ // triggering element and heal on their own.
+ if (this.panel) {
+ clearTimeout(dom.get_data(this.panel, "timer"));
+ }
+ super.destroy();
+ }
+
+ _init_notification(el, options) {
+ count++;
+
+ const closetext = options.closeText;
+
+ const wrapper = document.createElement("div");
+ wrapper.setAttribute("id", `pat-notification-${count}`);
+ wrapper.setAttribute("class", "pat-notification-panel");
+ dom.wrap(el, wrapper);
+
+ events.add_event_listener(
+ wrapper,
+ "mouseenter",
+ "notification__mouseenter",
+ this.onMouseEnter.bind(this)
+ );
+ events.add_event_listener(
+ wrapper,
+ "mouseleave",
+ "notification__mouseleave",
+ this.onMouseLeave.bind(this)
+ );
+
+ if (options["class"]) {
+ wrapper.classList.add(options["class"]);
+ }
+
+ if (!Array.isArray(options.controls)) {
+ options.controls = [options.controls];
+ }
+
+ // add close icon if requested
+ if (options.controls.indexOf("icons") >= 0) {
+ wrapper.append(
+ dom.create_from_string(
+ `
${closetext} `
+ )
+ );
+ }
+
+ // add close button if requested
+ if (options.controls.indexOf("buttons") >= 0) {
+ wrapper.append(
+ dom.create_from_string(
+ `
+ ${closetext}
+
`
+ )
+ );
+ }
+
+ if (wrapper.querySelector(".close-panel")) {
+ events.add_event_listener(
+ wrapper,
+ "close-panel",
+ "pat-notification--close-panel",
+ this.onClick.bind(this)
+ );
+ registry.scan(wrapper, ["close-panel"]);
+ } else {
+ events.add_event_listener(
+ wrapper,
+ "click",
+ "notification__click",
+ this.onClick.bind(this)
+ );
+ }
+
+ if (options.type === "banner") {
+ let container = document.querySelector("#pat-notification-banners");
+ if (!container) {
+ container = document.createElement("div");
+ container.setAttribute("id", "pat-notification-banners");
+ container.setAttribute("class", "pat-notification-container");
+ document.body.append(container);
+ }
+ container.append(wrapper);
+ }
+
+ let healing = options.healing;
+ if (healing !== "persistent") {
+ healing = utils.parseTime(healing);
+ }
+
+ log.debug(`Healing value is: ${healing}`);
+ dom.set_data(wrapper, "healing", healing);
+
+ $(el).animate({ opacity: 1 }, "fast", () => {
+ this.init_remove_timer(wrapper);
+ });
+
+ return wrapper;
+ }
+
+ _init_inject() {
+ this.add_event_listener(this.el, "pat-inject-success", "inject-success", (e) => {
+ const $trigger = $(e.target);
+ const cfg = parser.parse($trigger, { type: "banner" });
+
+ const $temp = $("#pat-notification-temp")
+ .contents()
+ .wrapAll("
")
+ .parent()
+ .addClass("pat-notification");
+
+ if ($trigger.is("a")) {
+ $trigger.after($temp);
+ } else {
+ $temp.prependTo($trigger);
+ }
+ this._init_notification($temp[0], cfg);
+
+ // XXX: Do this later as inject tries to access its target afterwards.
+ // This should be fixed in injection.
+ setTimeout(() => {
+ $("#pat-notification-temp").remove();
+ }, 0);
+ });
+ inject.init($(this.el), {
+ target: "#pat-notification-temp",
+ });
+ }
+
+ init_remove_timer(panel) {
+ const healing = dom.get_data(panel, "healing");
+ if (healing !== "persistent") {
+ clearTimeout(dom.get_data(panel, "timer"));
+ dom.set_data(
+ panel,
+ "timer",
+ setTimeout(() => {
+ log.debug("Timeout reached.");
+ this.remove(panel);
+ }, healing)
+ );
+ }
+ }
+
+ onMouseEnter(e) {
+ dom.set_data(e.target, "persistent", true);
+ }
+
+ onMouseLeave(e) {
+ const panel = e.target;
+ dom.set_data(panel, "persistent", false);
+ this.init_remove_timer(panel);
+ }
+
+ onClick(e) {
+ const panel = e.target.closest(".pat-notification-panel");
+ dom.set_data(panel, "persistent", false);
+ this.remove(panel);
+ }
+
+ remove(panel) {
+ if (
+ dom.get_data(panel, "persistent") === true ||
+ dom.get_data(panel, "removing") === true
+ ) {
+ return;
+ }
+ const $panel = $(panel);
+
+ dom.set_data(panel, "removing", true);
+
+ $panel.stop(true).animate(
+ { opacity: 0 },
+ {
+ step() {
+ if (dom.get_data(panel, "persistent") === true) {
+ // remove the timer and show notification
+ clearTimeout(dom.get_data(panel, "timer"));
+ $panel.stop(true).animate({ opacity: 1 });
+ dom.set_data(panel, "removing", false);
+ return false;
+ }
+ },
+
+ complete() {
+ $panel.off(".pat-notification");
+ $panel.slideUp("slow", () => {
+ $panel.remove();
+ });
+ },
+ }
+ );
+ }
+}
+
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/notification/notification--implementation.test.js b/src/pat/notification/notification--implementation.test.js
new file mode 100644
index 000000000..ceb05fcce
--- /dev/null
+++ b/src/pat/notification/notification--implementation.test.js
@@ -0,0 +1,131 @@
+import Pattern from "./notification--implementation";
+import dom from "../../core/dom";
+import events from "../../core/events";
+import utils from "../../core/utils";
+import { jest } from "@jest/globals";
+
+describe("pat notification", function () {
+ afterEach(() => {
+ document.body.innerHTML = "";
+ jest.restoreAllMocks();
+ });
+
+ it("Gets initialized and will disappear as per default settings.", async function () {
+ document.body.innerHTML = `
+
+ okay
+
+ `;
+
+ const el = document.querySelector(".pat-notification");
+ expect(el.parentNode).toBe(document.body);
+
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+ await utils.timeout(1); // wait for close-panel to initialize.
+ const spy_remove = jest.spyOn(instance, "remove");
+
+ expect(el.parentNode).not.toBe(document.body);
+ expect(el.parentNode.classList.contains("pat-notification-panel")).toBe(true);
+ expect(instance.panel).toBe(el.parentNode);
+
+ const btn_close = el.parentNode.querySelector(".close-panel");
+ expect(btn_close).not.toBe(null);
+ btn_close.click();
+
+ await utils.timeout(1); // close-button is async - wait for it.
+
+ expect(spy_remove).toHaveBeenCalled();
+ });
+
+ it("Moves banner notifications to the banner container.", async function () {
+ document.body.innerHTML = `
+
+ okay
+
+ `;
+
+ const el = document.querySelector(".pat-notification");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ const container = document.querySelector("#pat-notification-banners");
+ expect(container).toBeTruthy();
+ expect(el.parentNode.parentNode).toBe(container);
+ expect(instance.destroyed).toBe(false);
+ });
+
+ it("Creates notification panels with unique ids.", async function () {
+ document.body.innerHTML = `
+
one
+
two
+ `;
+
+ const instance1 = new Pattern(document.querySelector(".one"));
+ const instance2 = new Pattern(document.querySelector(".two"));
+ await events.await_pattern_init(instance1);
+ await events.await_pattern_init(instance2);
+
+ expect(instance1.panel.id).toMatch(/^pat-notification-\d+$/);
+ expect(instance2.panel.id).toMatch(/^pat-notification-\d+$/);
+ expect(instance1.panel.id).not.toBe(instance2.panel.id);
+ });
+
+ it("Stops the healing timer when destroyed.", async function () {
+ document.body.innerHTML = `
+
+ okay
+
+ `;
+
+ const el = document.querySelector(".pat-notification");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+ await utils.timeout(250); // fade-in animation, start the timer.
+ const spy_remove = jest.spyOn(instance, "remove");
+
+ expect(dom.get_data(instance.panel, "timer")).toBeTruthy();
+
+ instance.destroy();
+ await utils.timeout(400);
+
+ expect(spy_remove).not.toHaveBeenCalled();
+ });
+
+ it("Stops the healing timer when removed from the DOM.", async function () {
+ document.body.innerHTML = `
+
+ okay
+
+ `;
+
+ const el = document.querySelector(".pat-notification");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+ await utils.timeout(250); // fade-in animation, start the timer.
+ const spy_remove = jest.spyOn(instance, "remove");
+
+ instance.panel.remove();
+ await utils.timeout(400);
+
+ expect(instance.destroyed).toBe(true);
+ expect(spy_remove).not.toHaveBeenCalled();
+ });
+
+ it("Removes the notification after the healing time.", async function () {
+ document.body.innerHTML = `
+
+ okay
+
+ `;
+
+ const el = document.querySelector(".pat-notification");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+ const spy_remove = jest.spyOn(instance, "remove");
+
+ await utils.timeout(650); // fade-in animation and healing time.
+
+ expect(spy_remove).toHaveBeenCalledWith(instance.panel);
+ });
+});
diff --git a/src/pat/notification/notification.js b/src/pat/notification/notification.js
index 3d9d08d4f..8bbccdb62 100644
--- a/src/pat/notification/notification.js
+++ b/src/pat/notification/notification.js
@@ -1,225 +1,20 @@
-// Patterns notification - Display (self-healing) notifications.
-import $ from "jquery";
-import Base from "../../core/base";
-import dom from "../../core/dom";
-import events from "../../core/events";
-import inject from "../inject/inject";
-import logging from "../../core/logging";
-import Parser from "../../core/parser";
+/**
+ * pat-notification 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:
+ * ./notification--implementation.js
+ */
+import create_lazy_pattern from "../../core/lazy-pattern";
import registry from "../../core/registry";
-import utils from "../../core/utils";
-// Initialize close-panel functionality.
-import "../close-panel/close-panel";
-
-const log = logging.getLogger("notification");
-//log.setLevel(logging.Level.DEBUG);
-
-export const parser = new Parser("notification");
-parser.addArgument("type", "static", ["static", "banner"]);
-parser.addArgument("healing", "5s");
-parser.addArgument("controls", "icons", ["icons", "buttons", "none"]);
-parser.addArgument("class");
-parser.addArgument("close-text", "Close");
-
-export default Base.extend({
+const Pattern = create_lazy_pattern({
name: "notification",
trigger: ".pat-notification",
- count: 0,
-
- init($el, opts) {
- if (this.el.matches("a, form")) {
- this._init_inject($el, opts);
- } else {
- this._init_notification($el, opts);
- }
- },
-
- _init_notification($el, opts) {
- this.count++;
-
- const el = $el[0];
- const options = parser.parse($el, opts);
- const closetext = options.closeText;
-
- const wrapper = document.createElement("div");
- wrapper.setAttribute("id", `pat-notification-${this.count}`);
- wrapper.setAttribute("class", "pat-notification-panel");
- dom.wrap(el, wrapper);
-
- events.add_event_listener(
- wrapper,
- "mouseenter",
- "notification__mouseenter",
- this.onMouseEnter.bind(this)
- );
- events.add_event_listener(
- wrapper,
- "mouseleave",
- "notification__mouseleave",
- this.onMouseLeave.bind(this)
- );
-
- if (options["class"]) {
- wrapper.classList.add(options["class"]);
- }
-
- if (!Array.isArray(options.controls)) {
- options.controls = [options.controls];
- }
-
- // add close icon if requested
- if (options.controls.indexOf("icons") >= 0) {
- wrapper.append(
- dom.create_from_string(
- `
${closetext} `
- )
- );
- }
-
- // add close button if requested
- if (options.controls.indexOf("buttons") >= 0) {
- wrapper.append(
- dom.create_from_string(
- `
- ${closetext}
-
`
- )
- );
- }
-
- if (wrapper.querySelector(".close-panel")) {
- events.add_event_listener(
- wrapper,
- "close-panel",
- "pat-notification--close-panel",
- this.onClick.bind(this)
- );
- registry.scan(wrapper, ["close-panel"]);
- } else {
- events.add_event_listener(
- wrapper,
- "click",
- "notification__click",
- this.onClick.bind(this)
- );
- }
-
- if (options.type === "banner") {
- let container = document.querySelector("#pat-notification-banners");
- if (!container) {
- container = document.createElement("div");
- container.setAttribute("id", "pat-notification-banners");
- container.setAttribute("class", "pat-notification-container");
- document.body.append(container);
- }
- container.append(wrapper);
- }
-
- let healing = options.healing;
- if (healing !== "persistent") {
- healing = utils.parseTime(healing);
- }
-
- log.debug(`Healing value is: ${healing}`);
- dom.set_data(wrapper, "healing", healing);
-
- $el.animate({ opacity: 1 }, "fast", () => {
- this.init_remove_timer(wrapper);
- });
- },
-
- _init_inject($el) {
- $el[0].addEventListener("pat-inject-success", (e) => {
- const $trigger = $(e.target);
- const cfg = parser.parse($trigger, { type: "banner" });
-
- const $temp = $("#pat-notification-temp")
- .contents()
- .wrapAll("
")
- .parent()
- .addClass("pat-notification");
-
- if ($trigger.is("a")) {
- $trigger.after($temp);
- } else {
- $temp.prependTo($trigger);
- }
- this._init_notification($temp, cfg);
-
- // XXX: Do this later as inject tries to access its target afterwards.
- // This should be fixed in injection.
- setTimeout(() => {
- $("#pat-notification-temp").remove();
- }, 0);
- });
- inject.init($el, {
- target: "#pat-notification-temp",
- });
- },
-
- init_remove_timer(panel) {
- const healing = dom.get_data(panel, "healing");
- if (healing !== "persistent") {
- clearTimeout(dom.get_data(panel, "timer"));
- dom.set_data(
- panel,
- "timer",
- setTimeout(() => {
- log.debug("Timeout reached.");
- this.remove(panel);
- }, healing)
- );
- }
- },
-
- onMouseEnter(e) {
- dom.set_data(e.target, "persistent", true);
- },
-
- onMouseLeave(e) {
- const panel = e.target;
- dom.set_data(panel, "persistent", false);
- this.init_remove_timer(panel);
- },
-
- onClick(e) {
- const panel = e.target.closest(".pat-notification-panel");
- dom.set_data(panel, "persistent", false);
- this.remove(panel);
- },
-
- remove(panel) {
- if (
- dom.get_data(panel, "persistent") === true ||
- dom.get_data(panel, "removing") === true
- ) {
- return;
- }
- const $panel = $(panel);
-
- dom.set_data(panel, "removing", true);
-
- $panel.stop(true).animate(
- { opacity: 0 },
- {
- step() {
- if (dom.get_data(panel, "persistent") === true) {
- // remove the timer and show notification
- clearTimeout(dom.get_data(panel, "timer"));
- $panel.stop(true).animate({ opacity: 1 });
- dom.set_data(panel, "removing", false);
- return false;
- }
- },
-
- complete() {
- $panel.off(".pat-notification");
- $panel.slideUp("slow", () => {
- $panel.remove();
- });
- },
- }
- );
- },
+ load: () => import("./notification--implementation"),
});
+
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/notification/notification.test.js b/src/pat/notification/notification.test.js
index ac7f99a21..6e8f90610 100644
--- a/src/pat/notification/notification.test.js
+++ b/src/pat/notification/notification.test.js
@@ -1,33 +1,15 @@
import Pattern from "./notification";
-import utils from "../../core/utils";
-
-describe("pat notification", function () {
- afterEach(() => {
- document.body.innerHTML = "";
+import Implementation from "./notification--implementation";
+
+describe("pat-notification 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);
});
- it("Gets initialized and will disappear as per default settings.", async function () {
- document.body.innerHTML = `
-
- okay
-
- `;
-
- const el = document.querySelector(".pat-notification");
- expect(el.parentNode).toBe(document.body);
-
- const instance = new Pattern(el);
- const spy_remove = jest.spyOn(instance, "remove");
-
- expect(el.parentNode).not.toBe(document.body);
- expect(el.parentNode.classList.contains("pat-notification-panel")).toBe(true);
-
- const btn_close = el.parentNode.querySelector(".close-panel");
- expect(btn_close).not.toBe(null);
- btn_close.click();
-
- await utils.timeout(1); // close-button is async - wait for it.
-
- expect(spy_remove).toHaveBeenCalled();
+ it("loads the implementation.", async function () {
+ expect(await Pattern.load()).toBe(Implementation);
});
});
diff --git a/src/pat/push/push.js b/src/pat/push/push.js
index a37073435..9f1ffac4d 100644
--- a/src/pat/push/push.js
+++ b/src/pat/push/push.js
@@ -1,4 +1,4 @@
-import Base from "../../core/base";
+import { BasePattern } from "../../core/basepattern";
import events from "../../core/events";
import logging from "../../core/logging";
import Parser from "../../core/parser";
@@ -14,18 +14,20 @@ parser.addArgument("mode", "replace", ["replace", "append", "desktop-notificatio
const rfp_key = "pat-push__desktop-notification__request_for_permission";
-export default Base.extend({
- name: "push",
- trigger: ".pat-push",
+class Pattern extends BasePattern {
+ static name = "push";
+ static trigger = ".pat-push";
+ static parser = parser;
init() {
- this.options = parser.parse(this.el, this.options);
-
if (
this.options.mode === "desktop-notification" &&
- !(Notification.permission in ["denied", "granted"])
+ "Notification" in window &&
+ !["denied", "granted"].includes(Notification.permission)
) {
// Try to get a notification permission on any click.
+ // This is a global event listener, shared by all pat-push
+ // instances and removed once the permission was requested.
events.add_event_listener(
document,
"click",
@@ -34,7 +36,7 @@ export default Base.extend({
);
}
- document.body.addEventListener("push", (e) => {
+ this.add_event_listener(document.body, "push", "on-push", (e) => {
logger.debug("received push marker");
const data = e?.detail?.body;
if (data === this.options.pushId) {
@@ -47,7 +49,7 @@ export default Base.extend({
}
}
});
- },
+ }
async perform_inject() {
let data = null;
@@ -61,7 +63,7 @@ export default Base.extend({
);
}
- if (data === null) {
+ if (data === null || this.destroyed) {
return;
}
@@ -71,7 +73,7 @@ export default Base.extend({
this.el.innerHTML = data;
}
registry.scan(this.el);
- },
+ }
async desktop_notification__request_permission() {
// Wait a bit to make the dialog more prominent...
@@ -81,7 +83,7 @@ export default Base.extend({
// Note: Current browsers don't allow an automatic request for
// permission but need an interaction to allow it.
// The following code won't work out of the box in such cases.
- if (!(Notification.permission in ["denied", "granted"])) {
+ if (!["denied", "granted"].includes(Notification.permission)) {
Notification.requestPermission((permission) => {
// Unregister the event handler, which should only be necessary once.
events.remove_event_listener(document, rfp_key);
@@ -92,7 +94,7 @@ export default Base.extend({
}
});
}
- },
+ }
async desktop_notification() {
// Let's check if the browser supports notifications
@@ -150,5 +152,9 @@ export default Base.extend({
});
}
}
- },
-});
+ }
+}
+
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/push/push.test.js b/src/pat/push/push.test.js
new file mode 100644
index 000000000..19e62aa26
--- /dev/null
+++ b/src/pat/push/push.test.js
@@ -0,0 +1,185 @@
+import Pattern from "./push";
+import events from "../../core/events";
+import utils from "../../core/utils";
+import { jest } from "@jest/globals";
+
+const push_event = (push_id) => {
+ return new CustomEvent("push", { detail: { body: push_id } });
+};
+
+describe("pat-push", function () {
+ let original_fetch;
+
+ beforeEach(function () {
+ original_fetch = global.fetch;
+ global.fetch = jest.fn().mockImplementation(async () => {
+ return {
+ text: async () => "
pushed
",
+ };
+ });
+ });
+
+ afterEach(function () {
+ global.fetch = original_fetch;
+ document.body.innerHTML = "";
+ jest.restoreAllMocks();
+ });
+
+ it("1 - Replaces the content on a matching push event.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-push");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ document.body.dispatchEvent(push_event("counter"));
+ await utils.timeout(1);
+
+ expect(global.fetch).toHaveBeenCalledWith("/counter");
+ expect(el.innerHTML).toBe("
pushed
");
+ });
+
+ it("2 - Appends the content in append mode.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-push");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ document.body.dispatchEvent(push_event("counter"));
+ await utils.timeout(1);
+
+ expect(el.innerHTML).toBe("
initial
pushed
");
+ });
+
+ it("3 - Ignores push events with another push id.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-push");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ document.body.dispatchEvent(push_event("other"));
+ await utils.timeout(1);
+
+ expect(global.fetch).not.toHaveBeenCalled();
+ expect(el.innerHTML).toBe("
initial
");
+ });
+
+ it("4 - Submits a form on a matching push event.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-push");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ let submitted = false;
+ el.addEventListener("submit", (e) => {
+ e.preventDefault();
+ submitted = true;
+ });
+
+ document.body.dispatchEvent(push_event("counter"));
+ await utils.timeout(1);
+
+ expect(submitted).toBe(true);
+ expect(global.fetch).not.toHaveBeenCalled();
+ });
+
+ it("5 - Does not request a notification permission if it was already granted.", async function () {
+ global.Notification = { permission: "granted" };
+ const spy_add = jest.spyOn(events, "add_event_listener");
+
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-push");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ const ids = spy_add.mock.calls.map((call) => call[2]);
+ expect(ids).not.toContain(
+ "pat-push__desktop-notification__request_for_permission"
+ );
+ delete global.Notification;
+ });
+
+ it("6 - Requests a notification permission if not yet decided.", async function () {
+ global.Notification = { permission: "default" };
+ const spy_add = jest.spyOn(events, "add_event_listener");
+
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-push");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ const ids = spy_add.mock.calls.map((call) => call[2]);
+ expect(ids).toContain("pat-push__desktop-notification__request_for_permission");
+ events.remove_event_listener(
+ document,
+ "pat-push__desktop-notification__request_for_permission"
+ );
+ delete global.Notification;
+ });
+
+ describe("7 - Destroy", function () {
+ it("7.1 - Does not handle push events anymore after being destroyed.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-push");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ instance.destroy();
+ expect(el["pattern-push"]).toBeUndefined();
+
+ document.body.dispatchEvent(push_event("counter"));
+ await utils.timeout(1);
+
+ expect(global.fetch).not.toHaveBeenCalled();
+ expect(el.innerHTML).toBe("
initial
");
+ });
+
+ it("7.2 - Is destroyed when removed from the DOM.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-push");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ el.remove();
+ await utils.timeout(1);
+ expect(instance.destroyed).toBe(true);
+
+ document.body.dispatchEvent(push_event("counter"));
+ await utils.timeout(1);
+ expect(global.fetch).not.toHaveBeenCalled();
+ });
+
+ it("7.3 - Does not inject content after being destroyed while fetching.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-push");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ document.body.dispatchEvent(push_event("counter"));
+ instance.destroy();
+ await utils.timeout(1);
+
+ expect(global.fetch).toHaveBeenCalled();
+ expect(el.innerHTML).toBe("
initial
");
+ });
+ });
+});
diff --git a/src/pat/scroll-box/scroll-box.js b/src/pat/scroll-box/scroll-box.js
index 0ab3d5523..1742b79c8 100644
--- a/src/pat/scroll-box/scroll-box.js
+++ b/src/pat/scroll-box/scroll-box.js
@@ -1,22 +1,22 @@
-import Base from "../../core/base";
+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";
export const parser = new Parser("scroll-box");
parser.addArgument("timeout-stop", 600); // Timeout to detect when stopping scrolling.
-export default Base.extend({
- name: "scroll-box",
- trigger: ".pat-scroll-box",
+class Pattern extends BasePattern {
+ static name = "scroll-box";
+ static trigger = ".pat-scroll-box";
+ static parser = parser;
- scroll_listener: null,
- last_known_scroll_position: 0,
- timeout_id__scroll_stop: null,
+ scroll_listener = null;
+ last_known_scroll_position = 0;
+ timeout_id__scroll_stop = null;
init() {
const el = this.el;
- this.options = parser.parse(el);
this.scroll_listener = el === document.body ? window : el;
// If scolling is not possible, exit.
@@ -29,13 +29,17 @@ export default Base.extend({
}
let ticking = false;
- events.add_event_listener(
+ this.add_event_listener(
this.scroll_listener,
"scroll",
- "pat-scroll-box--scroll_listener",
+ "scroll-listener",
() => {
if (!ticking) {
window.requestAnimationFrame(() => {
+ ticking = false;
+ if (this.destroyed) {
+ return;
+ }
this.set_scroll_classes();
// Detect case when user stops scrolling.
@@ -44,17 +48,20 @@ export default Base.extend({
// When user stopped scrolling, set/clear scroll classes.
this.clear_scrolling_classes();
}, this.options.timeoutStop);
-
- ticking = false;
});
ticking = true;
}
- }
+ },
);
// Set initial state
this.set_scroll_classes();
- },
+ }
+
+ destroy() {
+ window.clearTimeout(this.timeout_id__scroll_stop);
+ super.destroy();
+ }
set_scroll_classes() {
const scroll_pos = dom.get_scroll_y(this.scroll_listener);
@@ -86,16 +93,20 @@ export default Base.extend({
"scrolling-up",
"scrolling-down",
"scroll-position-top",
- "scroll-position-bottom"
+ "scroll-position-bottom",
);
this.el.classList.add(...to_add);
this.last_known_scroll_position = scroll_pos;
- },
+ }
clear_scrolling_classes() {
// Remove ``scrolling-up`` and ``scrolling-down``
// but keep ``scroll-up`` and ``scroll-down``.
this.el.classList.remove("scrolling-up", "scrolling-down");
- },
-});
+ }
+}
+
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/scroll-box/scroll-box.test.js b/src/pat/scroll-box/scroll-box.test.js
index 124beaa0a..b59236a16 100644
--- a/src/pat/scroll-box/scroll-box.test.js
+++ b/src/pat/scroll-box/scroll-box.test.js
@@ -1,4 +1,4 @@
-import pattern, { parser } from "./scroll-box";
+import Pattern, { parser } from "./scroll-box";
import utils from "../../core/utils";
import events from "../../core/events";
@@ -27,8 +27,9 @@ describe("pat-scroll-box", function () {
Object.defineProperty(el, "scrollHeight", { value: 300, writable: false });
Object.defineProperty(el, "scrollTop", { value: 0, writable: true });
- new pattern(el);
- await utils.timeout(1);
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+ expect(el["pattern-scroll-box"]).toBe(instance);
el.scrollTop = 0;
el.dispatchEvent(events.scroll_event());
@@ -127,4 +128,53 @@ describe("pat-scroll-box", function () {
await utils.timeout(custom_timeout + 1);
expect(el.classList).not.toContain("scrolling-down");
});
+
+ it("Uses the window as scroll container for the body", async function () {
+ document.body.classList.add("pat-scroll-box");
+ const instance = new Pattern(document.body);
+ await events.await_pattern_init(instance);
+
+ expect(instance.scroll_listener).toBe(window);
+ expect(document.body.classList).toContain("scroll-position-top");
+
+ instance.destroy();
+ document.body.className = "";
+ });
+
+ it("Stops updating the scroll classes after destroy", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector("#el1");
+
+ // mocks
+ Object.defineProperty(el, "clientHeight", { value: 100, writable: false });
+ Object.defineProperty(el, "scrollHeight", { value: 300, writable: false });
+ Object.defineProperty(el, "scrollTop", { value: 0, writable: true });
+
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ el.scrollTop = 100;
+ el.dispatchEvent(events.scroll_event());
+ await utils.animation_frame();
+ expect(el.classList).toContain("scrolling-down");
+
+ // Destroy while the scroll stop timeout is pending.
+ document.querySelector(".wrapper").remove();
+ await utils.timeout(1); // wait for the automatic destroy.
+ expect(instance.destroyed).toBe(true);
+ expect(el["pattern-scroll-box"]).toBeUndefined();
+
+ // The pending scroll stop timeout was cleared.
+ await utils.timeout(custom_timeout + 1);
+ expect(el.classList).toContain("scrolling-down");
+
+ // The scroll listener was removed.
+ el.scrollTop = 50;
+ el.dispatchEvent(events.scroll_event());
+ await utils.animation_frame();
+ expect(el.classList).not.toContain("scroll-up");
+ expect(el.classList).toContain("scroll-down");
+ });
});
diff --git a/src/pat/scroll-marker/scroll-marker--implementation.js b/src/pat/scroll-marker/scroll-marker--implementation.js
new file mode 100644
index 000000000..ab1bffc5c
--- /dev/null
+++ b/src/pat/scroll-marker/scroll-marker--implementation.js
@@ -0,0 +1,262 @@
+import { BasePattern } from "../../core/basepattern";
+import dom from "../../core/dom";
+import logging from "../../core/logging";
+import Parser from "../../core/parser";
+import registry from "../../core/registry";
+import utils from "../../core/utils";
+
+const log = logging.getLogger("scroll-marker");
+//logging.setLevel(logging.Level.DEBUG);
+
+export const parser = new Parser("scroll-marker");
+parser.addArgument("in-view-class", "in-view");
+parser.addArgument("current-class", "current");
+parser.addArgument("current-content-class", "scroll-marker-current");
+
+parser.addArgument("side", "top", ["top", "bottom", "middle", "auto"]);
+parser.addArgument("distance", "50%");
+parser.addArgument("visibility", null, [null, "none", "most-visible"]);
+parser.addArgument("selector", "a[href^='#']");
+
+class Pattern extends BasePattern {
+ static name = "scroll-marker";
+ static trigger = ".pat-scroll-marker";
+ static parser = parser;
+
+ parser_group_options = false;
+
+ // Used to disable automatically setting the current class when it's set
+ // differently, e.g. by clicking in a pat-navigation menu.
+ set_current_disabled = false;
+
+ init() {
+ // Get all elements that are referenced by links in the current page.
+ this.observables = new Map(
+ [...dom.querySelectorAllAndMe(this.el, this.options.selector)]
+ .map(
+ // Create the structure:
+ // id: {link, target}
+ // to create the resulting Map holding all necessary information.
+ (it) => [
+ it.hash.split("#")[1],
+ {
+ link: it,
+ target: document.querySelector(dom.escape_css_id(it.hash)),
+ },
+ ]
+ )
+ .filter(
+ // Filter again for any missing targets.
+ (it) => it[1].target
+ )
+ );
+
+ // Find a possible scroll container based on the first target/content
+ // element in the observables map.
+ // Note, a Map's values method returns an iterator.
+ const first_observable = this.observables.values().next();
+ if (!first_observable.value) {
+ // No targets found.
+ return;
+ }
+ this.scroll_container = dom.find_scroll_container(
+ first_observable.value.target,
+ "y",
+ window
+ );
+ // window.innerHeight or el.clientHeight
+ const scroll_container_height =
+ typeof this.scroll_container.innerHeight !== "undefined"
+ ? this.scroll_container.innerHeight
+ : this.scroll_container.clientHeight;
+ this.scroll_marker_distance = utils.parseLength(
+ this.options.distance,
+ scroll_container_height
+ );
+
+ log.debug("scroll_container: ", this.scroll_container);
+ log.debug("scroll_container_height: ", scroll_container_height);
+ log.debug("distance: ", this.options.distance);
+ log.debug("distance parsed: ", this.scroll_marker_distance);
+ log.debug("side: ", this.options.side);
+ log.debug("visibility: ", this.options.visibility);
+
+ this.debounced_scroll_marker_current_callback = utils.debounce(
+ this.scroll_marker_current_callback.bind(this),
+ 200,
+ { timer: null },
+ false
+ );
+
+ // For debugging.
+ this.callback_cnt = 0;
+
+ this.observer = new IntersectionObserver(
+ this.scroll_marker_callback.bind(this),
+ {
+ root: this.scroll_container === window ? null : this.scroll_container,
+ threshold: utils.threshold_list(10),
+ }
+ );
+ for (const it of this.observables.values()) {
+ this.observer.observe(it.target);
+ }
+ }
+
+ destroy() {
+ if (this.destroyed) {
+ return;
+ }
+ super.destroy();
+ this.observer?.disconnect();
+ // Remove the current class from the content elements, which are
+ // usually not part of the removed pattern element.
+ for (const item of this.observables?.values() || []) {
+ item.target.classList.remove(this.options["current-content-class"]);
+ }
+ }
+
+ scroll_marker_callback(entries) {
+ log.debug("cnt: ", this.callback_cnt++);
+ log.debug("entries: ", entries);
+
+ for (const entry of entries) {
+ // Set the in-view class on the link.
+ const id = entry.target.getAttribute("id");
+ const item = this.observables.get(id);
+ if (!item) {
+ continue;
+ }
+
+ if (entry.isIntersecting) {
+ item.link.classList.add(this.options["in-view-class"]);
+ } else {
+ item.link.classList.remove(this.options["in-view-class"]);
+ }
+ }
+
+ // Return if the scroll marker is disabled.
+ // E.g. when navigation item was clicked.
+ if (this.set_current_disabled) {
+ return;
+ }
+
+ this.debounced_scroll_marker_current_callback();
+ }
+
+ scroll_marker_current_callback() {
+ // Set the item which is nearest to the scroll container's middle to current.
+
+ if (this.destroyed) {
+ // Debounced call after the pattern was destroyed.
+ return;
+ }
+
+ // First, set all to non-current.
+ for (const item of this.observables.values()) {
+ item.link.classList.remove(this.options["current-class"]);
+ item.target.classList.remove(this.options["current-content-class"]);
+ }
+
+ // Sort by distance to the middle of the scroll container.
+ let items_by_weight = [...this.observables.values()].map((it) => it.target);
+ log.debug("items_by_weight initial: ", items_by_weight);
+
+ if (this.options.visibility === "most-visible") {
+ // Create a map with all ratios.
+ const ratio_map = new Map(
+ items_by_weight.map((it) => [
+ it,
+ dom.get_visible_ratio(it, this.scroll_container),
+ ])
+ );
+
+ log.debug("ratio_map: ", ratio_map);
+
+ // Sort items by ratio of visible area.
+ items_by_weight.sort((a, b) => {
+ const ratio_a = ratio_map.get(a);
+ const ratio_b = ratio_map.get(b);
+ if (ratio_a > ratio_b) {
+ return -1;
+ }
+ if (ratio_a < ratio_b) {
+ return 1;
+ }
+ return 0;
+ });
+
+ log.debug("items_by_weight per ratio: ", items_by_weight);
+
+ // Filter all items which have a ratio smaller than the first item.
+ const ratio_0 = ratio_map.get(items_by_weight[0]);
+ items_by_weight = items_by_weight.filter(
+ (it) => ratio_map.get(it) >= ratio_0
+ );
+
+ log.debug("items_by_weight filtered: ", items_by_weight);
+ log.debug("ratio item 0: ", ratio_0);
+ }
+ // Always sort by distance.
+ items_by_weight.sort((a, b) => {
+ let distance_a;
+ let distance_b;
+
+ const a_rect = a.getBoundingClientRect();
+ const b_rect = b.getBoundingClientRect();
+ const scroll_marker_distance = this.scroll_marker_distance;
+
+ switch (this.options.side) {
+ case "top":
+ distance_a = Math.abs(a_rect.top - scroll_marker_distance);
+ distance_b = Math.abs(b_rect.top - scroll_marker_distance);
+ break;
+ case "bottom":
+ distance_a = Math.abs(a_rect.bottom - scroll_marker_distance);
+ distance_b = Math.abs(b_rect.bottom - scroll_marker_distance);
+ break;
+ case "middle":
+ distance_a = Math.abs(
+ (a_rect.top - a_rect.bottom) / 2 - scroll_marker_distance
+ );
+ distance_b = Math.abs(
+ (b_rect.top - b_rect.bottom) / 2 - scroll_marker_distance
+ );
+ break;
+ default:
+ distance_a = Math.min(
+ Math.abs(a_rect.top - scroll_marker_distance),
+ Math.abs(a_rect.bottom - scroll_marker_distance)
+ );
+ distance_b = Math.min(
+ Math.abs(b_rect.top - scroll_marker_distance),
+ Math.abs(b_rect.bottom - scroll_marker_distance)
+ );
+ }
+
+ if (distance_a < distance_b) {
+ return -1;
+ }
+ if (distance_a > distance_b) {
+ return 1;
+ }
+ return 0;
+ });
+
+ log.debug("items_by_weight per distance: ", items_by_weight);
+
+ // Finally, set the nearest to current.
+ const nearest = items_by_weight[0];
+ const nearest_link = this.observables.get(nearest?.getAttribute("id"))?.link;
+ log.debug("nearest: ", nearest);
+ log.debug("nearest_link: ", nearest_link);
+ if (nearest_link) {
+ nearest_link.classList.add(this.options["current-class"]);
+ nearest.classList.add(this.options["current-content-class"]);
+ }
+ }
+}
+
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/scroll-marker/scroll-marker--implementation.test.js b/src/pat/scroll-marker/scroll-marker--implementation.test.js
new file mode 100644
index 000000000..c7a2078de
--- /dev/null
+++ b/src/pat/scroll-marker/scroll-marker--implementation.test.js
@@ -0,0 +1,417 @@
+import Pattern from "./scroll-marker--implementation";
+import events from "../../core/events";
+import utils from "../../core/utils";
+
+async function create_scroll_marker({
+ options = {},
+ scroll_container_main = false,
+} = {}) {
+ document.body.innerHTML = `
+
+ link 1
+ link 2
+ link 3
+
+
+
+
+
+
+
+
+
+ `;
+ const el = document.querySelector(".pat-scroll-marker");
+
+ const main = document.querySelector("main");
+ if (scroll_container_main) {
+ main.style["overflow-y"] = "auto";
+ }
+
+ const nav_id1 = document.querySelector("[href='#id1']");
+ const nav_id2 = document.querySelector("[href='#id2']");
+ const nav_id3 = document.querySelector("[href='#id3']");
+
+ const id1 = document.querySelector("#id1");
+ const id2 = document.querySelector("#id2");
+ const id3 = document.querySelector("#id3");
+
+ // id1 not, id2 fully, id3 partly visible
+
+ jest.spyOn(main, "clientHeight", "get").mockReturnValue(100);
+ jest.spyOn(main, "getBoundingClientRect").mockImplementation(() => {
+ return {
+ top: 0,
+ bottom: 100,
+ };
+ });
+
+ jest.replaceProperty(window, "innerHeight", 100);
+ jest.spyOn(id1, "getBoundingClientRect").mockImplementation(() => {
+ return {
+ top: -100,
+ bottom: -50,
+ };
+ });
+ jest.spyOn(id2, "getBoundingClientRect").mockImplementation(() => {
+ return {
+ top: 10,
+ bottom: 60,
+ };
+ });
+ jest.spyOn(id3, "getBoundingClientRect").mockImplementation(() => {
+ return {
+ top: 70,
+ bottom: 120,
+ };
+ });
+
+ const instance = new Pattern(el, options);
+ jest.spyOn(instance, "scroll_marker_callback");
+ jest.spyOn(instance, "scroll_marker_current_callback");
+
+ await events.await_pattern_init(instance);
+
+ instance.scroll_marker_callback([
+ { target: id1, isIntersecting: false },
+ { target: id2, isIntersecting: true },
+ { target: id3, isIntersecting: true },
+ ]);
+
+ // wait for the debounced_scroll_marker_current_callback
+ await utils.timeout(200);
+
+ return {
+ instance: instance,
+ el: el,
+ nav_id1: nav_id1,
+ nav_id2: nav_id2,
+ nav_id3: nav_id3,
+ id1: id1,
+ id2: id2,
+ id3: id3,
+ main: main,
+ };
+}
+
+describe("pat-scroll-marker", () => {
+ afterEach(() => {
+ document.body.innerHTML = "";
+ });
+
+ it("0: Inexistent targets do not break the runtime", async () => {
+ document.body.innerHTML = `
+
+ link 1
+ link 2
+ link 3
+
+ `;
+ const el = document.querySelector(".pat-scroll-marker");
+ const instance = new Pattern(el);
+ jest.spyOn(instance, "scroll_marker_callback");
+ jest.spyOn(instance, "scroll_marker_current_callback");
+ await events.await_pattern_init(instance);
+
+ expect(instance.scroll_marker_callback).not.toHaveBeenCalled();
+ expect(instance.scroll_marker_current_callback).not.toHaveBeenCalled();
+ });
+
+ describe("1: Test on window as scroll container", () => {
+ it("1.1: default values, id3 is current", async () => {
+ // With the default values the baseline is in the middle and the
+ // content element side's are calculated from the top. id3 is therefore
+ // the current one, as it's top is nearer to the middle than the top of
+ // id2.
+
+ const { instance, nav_id1, nav_id2, nav_id3, id1, id2, id3 } =
+ await create_scroll_marker();
+
+ // Without any overflow settings in other containers, the scroll
+ // container is the window object.
+ expect(instance.scroll_container).toBe(window);
+
+ // Callbacks have been called.
+ expect(instance.scroll_marker_callback).toHaveBeenCalled();
+ expect(instance.scroll_marker_current_callback).toHaveBeenCalled();
+
+ expect(nav_id1.classList.contains("in-view")).toBe(false);
+ expect(nav_id2.classList.contains("in-view")).toBe(true);
+ expect(nav_id3.classList.contains("in-view")).toBe(true);
+
+ expect(nav_id1.classList.contains("current")).toBe(false);
+ expect(nav_id2.classList.contains("current")).toBe(false);
+ expect(nav_id3.classList.contains("current")).toBe(true);
+
+ expect(id1.classList.contains("scroll-marker-current")).toBe(false);
+ expect(id2.classList.contains("scroll-marker-current")).toBe(false);
+ expect(id3.classList.contains("scroll-marker-current")).toBe(true);
+ });
+
+ it("1.2: distance 0, id2 is current", async () => {
+ const { instance, nav_id1, nav_id2, nav_id3, id1, id2, id3 } =
+ await create_scroll_marker({
+ options: {
+ distance: 0,
+ },
+ });
+
+ // Callbacks have been called.
+ expect(instance.scroll_marker_callback).toHaveBeenCalled();
+ expect(instance.scroll_marker_current_callback).toHaveBeenCalled();
+
+ expect(nav_id1.classList.contains("in-view")).toBe(false);
+ expect(nav_id2.classList.contains("in-view")).toBe(true);
+ expect(nav_id3.classList.contains("in-view")).toBe(true);
+
+ expect(nav_id1.classList.contains("current")).toBe(false);
+ expect(nav_id2.classList.contains("current")).toBe(true);
+ expect(nav_id3.classList.contains("current")).toBe(false);
+
+ expect(id1.classList.contains("scroll-marker-current")).toBe(false);
+ expect(id2.classList.contains("scroll-marker-current")).toBe(true);
+ expect(id3.classList.contains("scroll-marker-current")).toBe(false);
+ });
+
+ it("1.3: distance 50, side bottom, id2 is current", async () => {
+ const { instance, nav_id1, nav_id2, nav_id3, id1, id2, id3 } =
+ await create_scroll_marker({
+ options: {
+ distance: "50%",
+ side: "bottom",
+ },
+ });
+
+ // Callbacks have been called.
+ expect(instance.scroll_marker_callback).toHaveBeenCalled();
+ expect(instance.scroll_marker_current_callback).toHaveBeenCalled();
+
+ expect(nav_id1.classList.contains("in-view")).toBe(false);
+ expect(nav_id2.classList.contains("in-view")).toBe(true);
+ expect(nav_id3.classList.contains("in-view")).toBe(true);
+
+ expect(nav_id1.classList.contains("current")).toBe(false);
+ expect(nav_id2.classList.contains("current")).toBe(true);
+ expect(nav_id3.classList.contains("current")).toBe(false);
+
+ expect(id1.classList.contains("scroll-marker-current")).toBe(false);
+ expect(id2.classList.contains("scroll-marker-current")).toBe(true);
+ expect(id3.classList.contains("scroll-marker-current")).toBe(false);
+ });
+
+ it("1.4: distance 50, side top, visibility: most-visible, id2 is current", async () => {
+ // Here we have again the default values, this time explicitly set.
+ // Only the visibility is set to most-visible, which means that id2 is
+ // the current one,
+ //
+ const { instance, nav_id1, nav_id2, nav_id3, id1, id2, id3 } =
+ await create_scroll_marker({
+ options: {
+ distance: "50%",
+ side: "top",
+ visibility: "most-visible",
+ },
+ });
+
+ // Callbacks have been called.
+ expect(instance.scroll_marker_callback).toHaveBeenCalled();
+ expect(instance.scroll_marker_current_callback).toHaveBeenCalled();
+
+ expect(nav_id1.classList.contains("in-view")).toBe(false);
+ expect(nav_id2.classList.contains("in-view")).toBe(true);
+ expect(nav_id3.classList.contains("in-view")).toBe(true);
+
+ expect(nav_id1.classList.contains("current")).toBe(false);
+ expect(nav_id2.classList.contains("current")).toBe(true);
+ expect(nav_id3.classList.contains("current")).toBe(false);
+
+ expect(id1.classList.contains("scroll-marker-current")).toBe(false);
+ expect(id2.classList.contains("scroll-marker-current")).toBe(true);
+ expect(id3.classList.contains("scroll-marker-current")).toBe(false);
+ });
+
+ it("1.5: The selector option can exclude some items", async () => {
+ // With the selector option you can include/exclude some items from
+ // being included in the scroll-marker functionality.
+
+ const { nav_id1, nav_id2, nav_id3, id1, id2, id3 } =
+ await create_scroll_marker({
+ options: {
+ selector: "a[href^='#']:not([href='#id3'])",
+ },
+ });
+
+ expect(nav_id1.classList.contains("in-view")).toBe(false);
+ expect(nav_id2.classList.contains("in-view")).toBe(true);
+ expect(nav_id3.classList.contains("in-view")).toBe(false);
+
+ expect(nav_id1.classList.contains("current")).toBe(false);
+ expect(nav_id2.classList.contains("current")).toBe(true);
+ expect(nav_id3.classList.contains("current")).toBe(false);
+
+ expect(id1.classList.contains("scroll-marker-current")).toBe(false);
+ expect(id2.classList.contains("scroll-marker-current")).toBe(true);
+ expect(id3.classList.contains("scroll-marker-current")).toBe(false);
+ });
+ });
+
+ describe("2: Test on element as scroll container", () => {
+ it("2.1: default values, id3 is current", async () => {
+ // With the default values the baseline is in the middle and the
+ // content element side's are calculated from the top. id3 is therefore
+ // the current one, as it's top is nearer to the middle than the top of
+ // id2.
+
+ const { instance, nav_id1, nav_id2, nav_id3, id1, id2, id3, main } =
+ await create_scroll_marker({ scroll_container_main: true });
+
+ // Without any overflow settings in other containers, the scroll
+ // container is the window object.
+ expect(instance.scroll_container).toBe(main);
+
+ // Callbacks have been called.
+ expect(instance.scroll_marker_callback).toHaveBeenCalled();
+ expect(instance.scroll_marker_current_callback).toHaveBeenCalled();
+
+ expect(nav_id1.classList.contains("in-view")).toBe(false);
+ expect(nav_id2.classList.contains("in-view")).toBe(true);
+ expect(nav_id3.classList.contains("in-view")).toBe(true);
+
+ expect(nav_id1.classList.contains("current")).toBe(false);
+ expect(nav_id2.classList.contains("current")).toBe(false);
+ expect(nav_id3.classList.contains("current")).toBe(true);
+
+ expect(id1.classList.contains("scroll-marker-current")).toBe(false);
+ expect(id2.classList.contains("scroll-marker-current")).toBe(false);
+ expect(id3.classList.contains("scroll-marker-current")).toBe(true);
+ });
+
+ it("2.2: distance 0, id2 is current", async () => {
+ const { instance, nav_id1, nav_id2, nav_id3, id1, id2, id3 } =
+ await create_scroll_marker({
+ options: {
+ distance: 0,
+ },
+ scroll_container_main: true,
+ });
+
+ // Callbacks have been called.
+ expect(instance.scroll_marker_callback).toHaveBeenCalled();
+ expect(instance.scroll_marker_current_callback).toHaveBeenCalled();
+
+ expect(nav_id1.classList.contains("in-view")).toBe(false);
+ expect(nav_id2.classList.contains("in-view")).toBe(true);
+ expect(nav_id3.classList.contains("in-view")).toBe(true);
+
+ expect(nav_id1.classList.contains("current")).toBe(false);
+ expect(nav_id2.classList.contains("current")).toBe(true);
+ expect(nav_id3.classList.contains("current")).toBe(false);
+
+ expect(id1.classList.contains("scroll-marker-current")).toBe(false);
+ expect(id2.classList.contains("scroll-marker-current")).toBe(true);
+ expect(id3.classList.contains("scroll-marker-current")).toBe(false);
+ });
+
+ it("2.3: distance 50, side bottom, id2 is current", async () => {
+ const { instance, nav_id1, nav_id2, nav_id3, id1, id2, id3 } =
+ await create_scroll_marker({
+ options: {
+ distance: "50%",
+ side: "bottom",
+ },
+ scroll_container_main: true,
+ });
+
+ // Callbacks have been called.
+ expect(instance.scroll_marker_callback).toHaveBeenCalled();
+ expect(instance.scroll_marker_current_callback).toHaveBeenCalled();
+
+ expect(nav_id1.classList.contains("in-view")).toBe(false);
+ expect(nav_id2.classList.contains("in-view")).toBe(true);
+ expect(nav_id3.classList.contains("in-view")).toBe(true);
+
+ expect(nav_id1.classList.contains("current")).toBe(false);
+ expect(nav_id2.classList.contains("current")).toBe(true);
+ expect(nav_id3.classList.contains("current")).toBe(false);
+
+ expect(id1.classList.contains("scroll-marker-current")).toBe(false);
+ expect(id2.classList.contains("scroll-marker-current")).toBe(true);
+ expect(id3.classList.contains("scroll-marker-current")).toBe(false);
+ });
+
+ it("2.4: distance 50, side top, visibility: most-visible, id2 is current", async () => {
+ // Here we have again the default values, this time explicitly set.
+ // Only the visibility is set to most-visible, which means that id2 is
+ // the current one,
+ //
+ const { instance, nav_id1, nav_id2, nav_id3, id1, id2, id3 } =
+ await create_scroll_marker({
+ options: {
+ distance: "50%",
+ side: "top",
+ visibility: "most-visible",
+ },
+ scroll_container_main: true,
+ });
+
+ // Callbacks have been called.
+ expect(instance.scroll_marker_callback).toHaveBeenCalled();
+ expect(instance.scroll_marker_current_callback).toHaveBeenCalled();
+
+ expect(nav_id1.classList.contains("in-view")).toBe(false);
+ expect(nav_id2.classList.contains("in-view")).toBe(true);
+ expect(nav_id3.classList.contains("in-view")).toBe(true);
+
+ expect(nav_id1.classList.contains("current")).toBe(false);
+ expect(nav_id2.classList.contains("current")).toBe(true);
+ expect(nav_id3.classList.contains("current")).toBe(false);
+
+ expect(id1.classList.contains("scroll-marker-current")).toBe(false);
+ expect(id2.classList.contains("scroll-marker-current")).toBe(true);
+ expect(id3.classList.contains("scroll-marker-current")).toBe(false);
+ });
+ });
+
+ describe("3: Destroy", () => {
+ it("3.1: Removing the element disconnects the observer and cleans up the content elements", async () => {
+ const { instance, el, id1, id2, id3 } = await create_scroll_marker();
+ const spy_disconnect = jest.spyOn(instance.observer, "disconnect");
+ const current = () =>
+ [id1, id2, id3].filter((it) =>
+ it.classList.contains("scroll-marker-current")
+ );
+
+ expect(current().length).toBe(1);
+
+ el.remove();
+ await utils.timeout(1);
+
+ expect(instance.destroyed).toBe(true);
+ expect(spy_disconnect).toHaveBeenCalled();
+ expect(current().length).toBe(0);
+ });
+
+ it("3.2: A pending debounced update does not run after destroy", async () => {
+ const { instance, el, id1, id2, id3 } = await create_scroll_marker();
+
+ instance.scroll_marker_callback([
+ { target: id1, isIntersecting: false },
+ { target: id2, isIntersecting: true },
+ { target: id3, isIntersecting: true },
+ ]);
+ el.remove();
+ await utils.timeout(1);
+ expect(instance.destroyed).toBe(true);
+
+ // wait for the debounced_scroll_marker_current_callback
+ await utils.timeout(200);
+
+ for (const target of [id1, id2, id3]) {
+ expect(target.classList.contains("scroll-marker-current")).toBe(false);
+ }
+ });
+ });
+});
diff --git a/src/pat/scroll-marker/scroll-marker.js b/src/pat/scroll-marker/scroll-marker.js
index ab1bffc5c..5318f2e41 100644
--- a/src/pat/scroll-marker/scroll-marker.js
+++ b/src/pat/scroll-marker/scroll-marker.js
@@ -1,261 +1,19 @@
-import { BasePattern } from "../../core/basepattern";
-import dom from "../../core/dom";
-import logging from "../../core/logging";
-import Parser from "../../core/parser";
+/**
+ * pat-scroll-marker 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:
+ * ./scroll-marker--implementation.js
+ */
+import create_lazy_pattern from "../../core/lazy-pattern";
import registry from "../../core/registry";
-import utils from "../../core/utils";
-const log = logging.getLogger("scroll-marker");
-//logging.setLevel(logging.Level.DEBUG);
-
-export const parser = new Parser("scroll-marker");
-parser.addArgument("in-view-class", "in-view");
-parser.addArgument("current-class", "current");
-parser.addArgument("current-content-class", "scroll-marker-current");
-
-parser.addArgument("side", "top", ["top", "bottom", "middle", "auto"]);
-parser.addArgument("distance", "50%");
-parser.addArgument("visibility", null, [null, "none", "most-visible"]);
-parser.addArgument("selector", "a[href^='#']");
-
-class Pattern extends BasePattern {
- static name = "scroll-marker";
- static trigger = ".pat-scroll-marker";
- static parser = parser;
-
- parser_group_options = false;
-
- // Used to disable automatically setting the current class when it's set
- // differently, e.g. by clicking in a pat-navigation menu.
- set_current_disabled = false;
-
- init() {
- // Get all elements that are referenced by links in the current page.
- this.observables = new Map(
- [...dom.querySelectorAllAndMe(this.el, this.options.selector)]
- .map(
- // Create the structure:
- // id: {link, target}
- // to create the resulting Map holding all necessary information.
- (it) => [
- it.hash.split("#")[1],
- {
- link: it,
- target: document.querySelector(dom.escape_css_id(it.hash)),
- },
- ]
- )
- .filter(
- // Filter again for any missing targets.
- (it) => it[1].target
- )
- );
-
- // Find a possible scroll container based on the first target/content
- // element in the observables map.
- // Note, a Map's values method returns an iterator.
- const first_observable = this.observables.values().next();
- if (!first_observable.value) {
- // No targets found.
- return;
- }
- this.scroll_container = dom.find_scroll_container(
- first_observable.value.target,
- "y",
- window
- );
- // window.innerHeight or el.clientHeight
- const scroll_container_height =
- typeof this.scroll_container.innerHeight !== "undefined"
- ? this.scroll_container.innerHeight
- : this.scroll_container.clientHeight;
- this.scroll_marker_distance = utils.parseLength(
- this.options.distance,
- scroll_container_height
- );
-
- log.debug("scroll_container: ", this.scroll_container);
- log.debug("scroll_container_height: ", scroll_container_height);
- log.debug("distance: ", this.options.distance);
- log.debug("distance parsed: ", this.scroll_marker_distance);
- log.debug("side: ", this.options.side);
- log.debug("visibility: ", this.options.visibility);
-
- this.debounced_scroll_marker_current_callback = utils.debounce(
- this.scroll_marker_current_callback.bind(this),
- 200,
- { timer: null },
- false
- );
-
- // For debugging.
- this.callback_cnt = 0;
-
- this.observer = new IntersectionObserver(
- this.scroll_marker_callback.bind(this),
- {
- root: this.scroll_container === window ? null : this.scroll_container,
- threshold: utils.threshold_list(10),
- }
- );
- for (const it of this.observables.values()) {
- this.observer.observe(it.target);
- }
- }
-
- destroy() {
- if (this.destroyed) {
- return;
- }
- super.destroy();
- this.observer?.disconnect();
- // Remove the current class from the content elements, which are
- // usually not part of the removed pattern element.
- for (const item of this.observables?.values() || []) {
- item.target.classList.remove(this.options["current-content-class"]);
- }
- }
-
- scroll_marker_callback(entries) {
- log.debug("cnt: ", this.callback_cnt++);
- log.debug("entries: ", entries);
-
- for (const entry of entries) {
- // Set the in-view class on the link.
- const id = entry.target.getAttribute("id");
- const item = this.observables.get(id);
- if (!item) {
- continue;
- }
-
- if (entry.isIntersecting) {
- item.link.classList.add(this.options["in-view-class"]);
- } else {
- item.link.classList.remove(this.options["in-view-class"]);
- }
- }
-
- // Return if the scroll marker is disabled.
- // E.g. when navigation item was clicked.
- if (this.set_current_disabled) {
- return;
- }
-
- this.debounced_scroll_marker_current_callback();
- }
-
- scroll_marker_current_callback() {
- // Set the item which is nearest to the scroll container's middle to current.
-
- if (this.destroyed) {
- // Debounced call after the pattern was destroyed.
- return;
- }
-
- // First, set all to non-current.
- for (const item of this.observables.values()) {
- item.link.classList.remove(this.options["current-class"]);
- item.target.classList.remove(this.options["current-content-class"]);
- }
-
- // Sort by distance to the middle of the scroll container.
- let items_by_weight = [...this.observables.values()].map((it) => it.target);
- log.debug("items_by_weight initial: ", items_by_weight);
-
- if (this.options.visibility === "most-visible") {
- // Create a map with all ratios.
- const ratio_map = new Map(
- items_by_weight.map((it) => [
- it,
- dom.get_visible_ratio(it, this.scroll_container),
- ])
- );
-
- log.debug("ratio_map: ", ratio_map);
-
- // Sort items by ratio of visible area.
- items_by_weight.sort((a, b) => {
- const ratio_a = ratio_map.get(a);
- const ratio_b = ratio_map.get(b);
- if (ratio_a > ratio_b) {
- return -1;
- }
- if (ratio_a < ratio_b) {
- return 1;
- }
- return 0;
- });
-
- log.debug("items_by_weight per ratio: ", items_by_weight);
-
- // Filter all items which have a ratio smaller than the first item.
- const ratio_0 = ratio_map.get(items_by_weight[0]);
- items_by_weight = items_by_weight.filter(
- (it) => ratio_map.get(it) >= ratio_0
- );
-
- log.debug("items_by_weight filtered: ", items_by_weight);
- log.debug("ratio item 0: ", ratio_0);
- }
- // Always sort by distance.
- items_by_weight.sort((a, b) => {
- let distance_a;
- let distance_b;
-
- const a_rect = a.getBoundingClientRect();
- const b_rect = b.getBoundingClientRect();
- const scroll_marker_distance = this.scroll_marker_distance;
-
- switch (this.options.side) {
- case "top":
- distance_a = Math.abs(a_rect.top - scroll_marker_distance);
- distance_b = Math.abs(b_rect.top - scroll_marker_distance);
- break;
- case "bottom":
- distance_a = Math.abs(a_rect.bottom - scroll_marker_distance);
- distance_b = Math.abs(b_rect.bottom - scroll_marker_distance);
- break;
- case "middle":
- distance_a = Math.abs(
- (a_rect.top - a_rect.bottom) / 2 - scroll_marker_distance
- );
- distance_b = Math.abs(
- (b_rect.top - b_rect.bottom) / 2 - scroll_marker_distance
- );
- break;
- default:
- distance_a = Math.min(
- Math.abs(a_rect.top - scroll_marker_distance),
- Math.abs(a_rect.bottom - scroll_marker_distance)
- );
- distance_b = Math.min(
- Math.abs(b_rect.top - scroll_marker_distance),
- Math.abs(b_rect.bottom - scroll_marker_distance)
- );
- }
-
- if (distance_a < distance_b) {
- return -1;
- }
- if (distance_a > distance_b) {
- return 1;
- }
- return 0;
- });
-
- log.debug("items_by_weight per distance: ", items_by_weight);
-
- // Finally, set the nearest to current.
- const nearest = items_by_weight[0];
- const nearest_link = this.observables.get(nearest?.getAttribute("id"))?.link;
- log.debug("nearest: ", nearest);
- log.debug("nearest_link: ", nearest_link);
- if (nearest_link) {
- nearest_link.classList.add(this.options["current-class"]);
- nearest.classList.add(this.options["current-content-class"]);
- }
- }
-}
+const Pattern = create_lazy_pattern({
+ name: "scroll-marker",
+ trigger: ".pat-scroll-marker",
+ load: () => import("./scroll-marker--implementation"),
+});
registry.register(Pattern);
export default Pattern;
diff --git a/src/pat/scroll-marker/scroll-marker.test.js b/src/pat/scroll-marker/scroll-marker.test.js
index 0a0dea361..062e0e511 100644
--- a/src/pat/scroll-marker/scroll-marker.test.js
+++ b/src/pat/scroll-marker/scroll-marker.test.js
@@ -1,417 +1,15 @@
import Pattern from "./scroll-marker";
-import events from "../../core/events";
-import utils from "../../core/utils";
+import Implementation from "./scroll-marker--implementation";
-async function create_scroll_marker({
- options = {},
- scroll_container_main = false,
-} = {}) {
- document.body.innerHTML = `
-
- link 1
- link 2
- link 3
-
-
-
-
-
-
-
-
-
- `;
- const el = document.querySelector(".pat-scroll-marker");
-
- const main = document.querySelector("main");
- if (scroll_container_main) {
- main.style["overflow-y"] = "auto";
- }
-
- const nav_id1 = document.querySelector("[href='#id1']");
- const nav_id2 = document.querySelector("[href='#id2']");
- const nav_id3 = document.querySelector("[href='#id3']");
-
- const id1 = document.querySelector("#id1");
- const id2 = document.querySelector("#id2");
- const id3 = document.querySelector("#id3");
-
- // id1 not, id2 fully, id3 partly visible
-
- jest.spyOn(main, "clientHeight", "get").mockReturnValue(100);
- jest.spyOn(main, "getBoundingClientRect").mockImplementation(() => {
- return {
- top: 0,
- bottom: 100,
- };
- });
-
- jest.replaceProperty(window, "innerHeight", 100);
- jest.spyOn(id1, "getBoundingClientRect").mockImplementation(() => {
- return {
- top: -100,
- bottom: -50,
- };
- });
- jest.spyOn(id2, "getBoundingClientRect").mockImplementation(() => {
- return {
- top: 10,
- bottom: 60,
- };
- });
- jest.spyOn(id3, "getBoundingClientRect").mockImplementation(() => {
- return {
- top: 70,
- bottom: 120,
- };
- });
-
- const instance = new Pattern(el, options);
- jest.spyOn(instance, "scroll_marker_callback");
- jest.spyOn(instance, "scroll_marker_current_callback");
-
- await events.await_pattern_init(instance);
-
- instance.scroll_marker_callback([
- { target: id1, isIntersecting: false },
- { target: id2, isIntersecting: true },
- { target: id3, isIntersecting: true },
- ]);
-
- // wait for the debounced_scroll_marker_current_callback
- await utils.timeout(200);
-
- return {
- instance: instance,
- el: el,
- nav_id1: nav_id1,
- nav_id2: nav_id2,
- nav_id3: nav_id3,
- id1: id1,
- id2: id2,
- id3: id3,
- main: main,
- };
-}
-
-describe("pat-scroll-marker", () => {
- afterEach(() => {
- document.body.innerHTML = "";
- });
-
- it("0: Inexistent targets do not break the runtime", async () => {
- document.body.innerHTML = `
-
- link 1
- link 2
- link 3
-
- `;
- const el = document.querySelector(".pat-scroll-marker");
- const instance = new Pattern(el);
- jest.spyOn(instance, "scroll_marker_callback");
- jest.spyOn(instance, "scroll_marker_current_callback");
- await events.await_pattern_init(instance);
-
- expect(instance.scroll_marker_callback).not.toHaveBeenCalled();
- expect(instance.scroll_marker_current_callback).not.toHaveBeenCalled();
- });
-
- describe("1: Test on window as scroll container", () => {
- it("1.1: default values, id3 is current", async () => {
- // With the default values the baseline is in the middle and the
- // content element side's are calculated from the top. id3 is therefore
- // the current one, as it's top is nearer to the middle than the top of
- // id2.
-
- const { instance, nav_id1, nav_id2, nav_id3, id1, id2, id3 } =
- await create_scroll_marker();
-
- // Without any overflow settings in other containers, the scroll
- // container is the window object.
- expect(instance.scroll_container).toBe(window);
-
- // Callbacks have been called.
- expect(instance.scroll_marker_callback).toHaveBeenCalled();
- expect(instance.scroll_marker_current_callback).toHaveBeenCalled();
-
- expect(nav_id1.classList.contains("in-view")).toBe(false);
- expect(nav_id2.classList.contains("in-view")).toBe(true);
- expect(nav_id3.classList.contains("in-view")).toBe(true);
-
- expect(nav_id1.classList.contains("current")).toBe(false);
- expect(nav_id2.classList.contains("current")).toBe(false);
- expect(nav_id3.classList.contains("current")).toBe(true);
-
- expect(id1.classList.contains("scroll-marker-current")).toBe(false);
- expect(id2.classList.contains("scroll-marker-current")).toBe(false);
- expect(id3.classList.contains("scroll-marker-current")).toBe(true);
- });
-
- it("1.2: distance 0, id2 is current", async () => {
- const { instance, nav_id1, nav_id2, nav_id3, id1, id2, id3 } =
- await create_scroll_marker({
- options: {
- distance: 0,
- },
- });
-
- // Callbacks have been called.
- expect(instance.scroll_marker_callback).toHaveBeenCalled();
- expect(instance.scroll_marker_current_callback).toHaveBeenCalled();
-
- expect(nav_id1.classList.contains("in-view")).toBe(false);
- expect(nav_id2.classList.contains("in-view")).toBe(true);
- expect(nav_id3.classList.contains("in-view")).toBe(true);
-
- expect(nav_id1.classList.contains("current")).toBe(false);
- expect(nav_id2.classList.contains("current")).toBe(true);
- expect(nav_id3.classList.contains("current")).toBe(false);
-
- expect(id1.classList.contains("scroll-marker-current")).toBe(false);
- expect(id2.classList.contains("scroll-marker-current")).toBe(true);
- expect(id3.classList.contains("scroll-marker-current")).toBe(false);
- });
-
- it("1.3: distance 50, side bottom, id2 is current", async () => {
- const { instance, nav_id1, nav_id2, nav_id3, id1, id2, id3 } =
- await create_scroll_marker({
- options: {
- distance: "50%",
- side: "bottom",
- },
- });
-
- // Callbacks have been called.
- expect(instance.scroll_marker_callback).toHaveBeenCalled();
- expect(instance.scroll_marker_current_callback).toHaveBeenCalled();
-
- expect(nav_id1.classList.contains("in-view")).toBe(false);
- expect(nav_id2.classList.contains("in-view")).toBe(true);
- expect(nav_id3.classList.contains("in-view")).toBe(true);
-
- expect(nav_id1.classList.contains("current")).toBe(false);
- expect(nav_id2.classList.contains("current")).toBe(true);
- expect(nav_id3.classList.contains("current")).toBe(false);
-
- expect(id1.classList.contains("scroll-marker-current")).toBe(false);
- expect(id2.classList.contains("scroll-marker-current")).toBe(true);
- expect(id3.classList.contains("scroll-marker-current")).toBe(false);
- });
-
- it("1.4: distance 50, side top, visibility: most-visible, id2 is current", async () => {
- // Here we have again the default values, this time explicitly set.
- // Only the visibility is set to most-visible, which means that id2 is
- // the current one,
- //
- const { instance, nav_id1, nav_id2, nav_id3, id1, id2, id3 } =
- await create_scroll_marker({
- options: {
- distance: "50%",
- side: "top",
- visibility: "most-visible",
- },
- });
-
- // Callbacks have been called.
- expect(instance.scroll_marker_callback).toHaveBeenCalled();
- expect(instance.scroll_marker_current_callback).toHaveBeenCalled();
-
- expect(nav_id1.classList.contains("in-view")).toBe(false);
- expect(nav_id2.classList.contains("in-view")).toBe(true);
- expect(nav_id3.classList.contains("in-view")).toBe(true);
-
- expect(nav_id1.classList.contains("current")).toBe(false);
- expect(nav_id2.classList.contains("current")).toBe(true);
- expect(nav_id3.classList.contains("current")).toBe(false);
-
- expect(id1.classList.contains("scroll-marker-current")).toBe(false);
- expect(id2.classList.contains("scroll-marker-current")).toBe(true);
- expect(id3.classList.contains("scroll-marker-current")).toBe(false);
- });
-
- it("1.5: The selector option can exclude some items", async () => {
- // With the selector option you can include/exclude some items from
- // being included in the scroll-marker functionality.
-
- const { nav_id1, nav_id2, nav_id3, id1, id2, id3 } =
- await create_scroll_marker({
- options: {
- selector: "a[href^='#']:not([href='#id3'])",
- },
- });
-
- expect(nav_id1.classList.contains("in-view")).toBe(false);
- expect(nav_id2.classList.contains("in-view")).toBe(true);
- expect(nav_id3.classList.contains("in-view")).toBe(false);
-
- expect(nav_id1.classList.contains("current")).toBe(false);
- expect(nav_id2.classList.contains("current")).toBe(true);
- expect(nav_id3.classList.contains("current")).toBe(false);
-
- expect(id1.classList.contains("scroll-marker-current")).toBe(false);
- expect(id2.classList.contains("scroll-marker-current")).toBe(true);
- expect(id3.classList.contains("scroll-marker-current")).toBe(false);
- });
- });
-
- describe("2: Test on element as scroll container", () => {
- it("2.1: default values, id3 is current", async () => {
- // With the default values the baseline is in the middle and the
- // content element side's are calculated from the top. id3 is therefore
- // the current one, as it's top is nearer to the middle than the top of
- // id2.
-
- const { instance, nav_id1, nav_id2, nav_id3, id1, id2, id3, main } =
- await create_scroll_marker({ scroll_container_main: true });
-
- // Without any overflow settings in other containers, the scroll
- // container is the window object.
- expect(instance.scroll_container).toBe(main);
-
- // Callbacks have been called.
- expect(instance.scroll_marker_callback).toHaveBeenCalled();
- expect(instance.scroll_marker_current_callback).toHaveBeenCalled();
-
- expect(nav_id1.classList.contains("in-view")).toBe(false);
- expect(nav_id2.classList.contains("in-view")).toBe(true);
- expect(nav_id3.classList.contains("in-view")).toBe(true);
-
- expect(nav_id1.classList.contains("current")).toBe(false);
- expect(nav_id2.classList.contains("current")).toBe(false);
- expect(nav_id3.classList.contains("current")).toBe(true);
-
- expect(id1.classList.contains("scroll-marker-current")).toBe(false);
- expect(id2.classList.contains("scroll-marker-current")).toBe(false);
- expect(id3.classList.contains("scroll-marker-current")).toBe(true);
- });
-
- it("2.2: distance 0, id2 is current", async () => {
- const { instance, nav_id1, nav_id2, nav_id3, id1, id2, id3 } =
- await create_scroll_marker({
- options: {
- distance: 0,
- },
- scroll_container_main: true,
- });
-
- // Callbacks have been called.
- expect(instance.scroll_marker_callback).toHaveBeenCalled();
- expect(instance.scroll_marker_current_callback).toHaveBeenCalled();
-
- expect(nav_id1.classList.contains("in-view")).toBe(false);
- expect(nav_id2.classList.contains("in-view")).toBe(true);
- expect(nav_id3.classList.contains("in-view")).toBe(true);
-
- expect(nav_id1.classList.contains("current")).toBe(false);
- expect(nav_id2.classList.contains("current")).toBe(true);
- expect(nav_id3.classList.contains("current")).toBe(false);
-
- expect(id1.classList.contains("scroll-marker-current")).toBe(false);
- expect(id2.classList.contains("scroll-marker-current")).toBe(true);
- expect(id3.classList.contains("scroll-marker-current")).toBe(false);
- });
-
- it("2.3: distance 50, side bottom, id2 is current", async () => {
- const { instance, nav_id1, nav_id2, nav_id3, id1, id2, id3 } =
- await create_scroll_marker({
- options: {
- distance: "50%",
- side: "bottom",
- },
- scroll_container_main: true,
- });
-
- // Callbacks have been called.
- expect(instance.scroll_marker_callback).toHaveBeenCalled();
- expect(instance.scroll_marker_current_callback).toHaveBeenCalled();
-
- expect(nav_id1.classList.contains("in-view")).toBe(false);
- expect(nav_id2.classList.contains("in-view")).toBe(true);
- expect(nav_id3.classList.contains("in-view")).toBe(true);
-
- expect(nav_id1.classList.contains("current")).toBe(false);
- expect(nav_id2.classList.contains("current")).toBe(true);
- expect(nav_id3.classList.contains("current")).toBe(false);
-
- expect(id1.classList.contains("scroll-marker-current")).toBe(false);
- expect(id2.classList.contains("scroll-marker-current")).toBe(true);
- expect(id3.classList.contains("scroll-marker-current")).toBe(false);
- });
-
- it("2.4: distance 50, side top, visibility: most-visible, id2 is current", async () => {
- // Here we have again the default values, this time explicitly set.
- // Only the visibility is set to most-visible, which means that id2 is
- // the current one,
- //
- const { instance, nav_id1, nav_id2, nav_id3, id1, id2, id3 } =
- await create_scroll_marker({
- options: {
- distance: "50%",
- side: "top",
- visibility: "most-visible",
- },
- scroll_container_main: true,
- });
-
- // Callbacks have been called.
- expect(instance.scroll_marker_callback).toHaveBeenCalled();
- expect(instance.scroll_marker_current_callback).toHaveBeenCalled();
-
- expect(nav_id1.classList.contains("in-view")).toBe(false);
- expect(nav_id2.classList.contains("in-view")).toBe(true);
- expect(nav_id3.classList.contains("in-view")).toBe(true);
-
- expect(nav_id1.classList.contains("current")).toBe(false);
- expect(nav_id2.classList.contains("current")).toBe(true);
- expect(nav_id3.classList.contains("current")).toBe(false);
-
- expect(id1.classList.contains("scroll-marker-current")).toBe(false);
- expect(id2.classList.contains("scroll-marker-current")).toBe(true);
- expect(id3.classList.contains("scroll-marker-current")).toBe(false);
- });
+describe("pat-scroll-marker 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("3: Destroy", () => {
- it("3.1: Removing the element disconnects the observer and cleans up the content elements", async () => {
- const { instance, el, id1, id2, id3 } = await create_scroll_marker();
- const spy_disconnect = jest.spyOn(instance.observer, "disconnect");
- const current = () =>
- [id1, id2, id3].filter((it) =>
- it.classList.contains("scroll-marker-current")
- );
-
- expect(current().length).toBe(1);
-
- el.remove();
- await utils.timeout(1);
-
- expect(instance.destroyed).toBe(true);
- expect(spy_disconnect).toHaveBeenCalled();
- expect(current().length).toBe(0);
- });
-
- it("3.2: A pending debounced update does not run after destroy", async () => {
- const { instance, el, id1, id2, id3 } = await create_scroll_marker();
-
- instance.scroll_marker_callback([
- { target: id1, isIntersecting: false },
- { target: id2, isIntersecting: true },
- { target: id3, isIntersecting: true },
- ]);
- el.remove();
- await utils.timeout(1);
- expect(instance.destroyed).toBe(true);
-
- // wait for the debounced_scroll_marker_current_callback
- await utils.timeout(200);
-
- for (const target of [id1, id2, id3]) {
- expect(target.classList.contains("scroll-marker-current")).toBe(false);
- }
- });
+ it("loads the implementation.", async function () {
+ expect(await Pattern.load()).toBe(Implementation);
});
});
diff --git a/src/pat/selectbox/selectbox.js b/src/pat/selectbox/selectbox.js
index 829f18d01..b1500656c 100644
--- a/src/pat/selectbox/selectbox.js
+++ b/src/pat/selectbox/selectbox.js
@@ -1,21 +1,23 @@
/* Patterns selectbox - Expose select option for (un)checking. */
import $ from "jquery";
-import Base from "../../core/base";
+import { BasePattern } from "../../core/basepattern";
import dom from "../../core/dom";
+import registry from "../../core/registry";
-const KEY_RESET = "__patternslib__pat_selectbox__reset";
+class Pattern extends BasePattern {
+ static name = "selectbox";
+ static trigger = ".pat-select";
-export default Base.extend({
- name: "selectbox",
- trigger: ".pat-select",
- all_selects: [],
+ all_selects = [];
+ reset_timer = null;
init() {
const el = this.el;
- if (el.form && !el[KEY_RESET]) {
- $(el.form).on("reset.pat-selectbox", () => this.form_reset());
- el[KEY_RESET] = true;
+ if (el.form) {
+ this.add_event_listener(el.form, "reset", "update-on-reset", () =>
+ this.form_reset(),
+ );
}
this.all_selects = dom.querySelectorAllAndMe(el, "select:not([multiple])");
@@ -25,27 +27,40 @@ export default Base.extend({
dom.wrap(sel, document.createElement("span"));
}
this.change_select(sel);
- $(sel).on("change.pat-selectbox", () => this.change_select(sel));
+ // Use jQuery to also catch change events triggered by jQuery.
+ $(sel).on(`change.${this.event_namespace}`, () => this.change_select(sel));
}
- },
+ }
- destroy($el) {
- return $el.off(".pat-selectbox");
- },
+ get event_namespace() {
+ // Instance specific jQuery event namespace.
+ return `pat-selectbox-${this.uuid}`;
+ }
+
+ destroy() {
+ window.clearTimeout(this.reset_timer);
+ $(this.all_selects).off(`.${this.event_namespace}`);
+ super.destroy();
+ }
form_reset() {
// This event is triggered before the form is reset, and we need
// the post-reset state to update our pattern. Use a small delay
// to fix this.
- setTimeout(() => {
+ window.clearTimeout(this.reset_timer);
+ this.reset_timer = window.setTimeout(() => {
for (const sel of this.all_selects) {
this.change_select(sel);
}
}, 50);
- },
+ }
change_select(el) {
el.parentNode.setAttribute("data-option", el.querySelector("option:checked")?.text || ''); // prettier-ignore
el.parentNode.setAttribute("data-option-value", el.value);
- },
-});
+ }
+}
+
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/selectbox/selectbox.test.js b/src/pat/selectbox/selectbox.test.js
index ddf2eefd6..d6413f82a 100644
--- a/src/pat/selectbox/selectbox.test.js
+++ b/src/pat/selectbox/selectbox.test.js
@@ -1,12 +1,25 @@
-import Pattern from "./selectbox"; // eslint-disable-line no-unused-vars
-import registry from "../../core/registry";
+import $ from "jquery";
+import Pattern from "./selectbox";
+import events from "../../core/events";
import utils from "../../core/utils";
+const init_all = async (root) => {
+ const instances = [...root.querySelectorAll(".pat-select")].map(
+ (pattern_el) => new Pattern(pattern_el),
+ );
+ for (const instance of instances) {
+ await events.await_pattern_init(instance);
+ }
+ return instances;
+};
+
describe("pat selectbox tests", () => {
- // Tests from the core.dom module
+ afterEach(() => {
+ document.body.innerHTML = "";
+ });
it("works as indented.", async () => {
- const el = document.createElement("div");
+ const el = document.body;
el.innerHTML = `
`;
- registry.scan(el);
+ await init_all(el);
const sel1 = el.querySelector(".sel1");
const sel2 = el.querySelector(".sel2");
@@ -80,4 +93,92 @@ describe("pat selectbox tests", () => {
expect(sel3.parentNode.getAttribute("data-option")).toBe("E");
expect(sel3.parentNode.getAttribute("data-option-value")).toBe("e");
});
+
+ it("updates on change events triggered by jQuery.", async () => {
+ document.body.innerHTML = `
+
+ A
+ B
+
+ `;
+ await init_all(document.body);
+ const sel = document.querySelector("select");
+
+ sel.value = "b";
+ $(sel).trigger("change");
+
+ expect(sel.parentNode.getAttribute("data-option")).toBe("B");
+ expect(sel.parentNode.getAttribute("data-option-value")).toBe("b");
+ });
+
+ it("removes its event listeners on destroy.", async () => {
+ document.body.innerHTML = `
+
+ `;
+ const [instance] = await init_all(document.body);
+ const sel = document.querySelector("select");
+ expect(sel["pattern-selectbox"]).toBe(instance);
+
+ instance.destroy();
+ expect(instance.destroyed).toBe(true);
+ expect(sel["pattern-selectbox"]).toBe(undefined);
+
+ sel.value = "b";
+ sel.dispatchEvent(new Event("change"));
+ expect(sel.parentNode.getAttribute("data-option")).toBe("A");
+
+ document.querySelector("form").reset();
+ sel.value = "b";
+ await utils.timeout(100);
+ expect(sel.parentNode.getAttribute("data-option")).toBe("A");
+ });
+
+ it("cancels a pending reset update on destroy.", async () => {
+ document.body.innerHTML = `
+
+ `;
+ const [instance] = await init_all(document.body);
+ const sel = document.querySelector("select");
+
+ document.querySelector("form").reset();
+ sel.value = "b";
+ instance.destroy();
+ await utils.timeout(100);
+ expect(sel.parentNode.getAttribute("data-option")).toBe("A");
+ });
+
+ it("can be re-initialized after destroy.", async () => {
+ document.body.innerHTML = `
+
+ `;
+ const [instance] = await init_all(document.body);
+ instance.destroy();
+
+ const sel = document.querySelector("select");
+ const instance_2 = new Pattern(sel);
+ await events.await_pattern_init(instance_2);
+
+ sel.value = "b";
+ sel.dispatchEvent(new Event("change"));
+ expect(sel.parentNode.getAttribute("data-option")).toBe("B");
+
+ document.querySelector("form").reset();
+ await utils.timeout(100);
+ expect(sel.parentNode.getAttribute("data-option")).toBe("A");
+ });
});
diff --git a/src/pat/slides/slides.js b/src/pat/slides/slides.js
index a4a9d8d63..3a90d719c 100644
--- a/src/pat/slides/slides.js
+++ b/src/pat/slides/slides.js
@@ -4,100 +4,115 @@
* Copyright 2013 Simplon B.V. - Wichert Akkerman
*/
import $ from "jquery";
+import { BasePattern } from "../../core/basepattern";
import registry from "../../core/registry";
import utils from "../../core/utils";
-var slides = {
- name: "slides",
- trigger: ".pat-slides",
+class Pattern extends BasePattern {
+ static name = "slides";
+ static trigger = ".pat-slides";
- setup: function () {
- $(document).on("patterns-injected", utils.debounce(slides._reset, 100));
- },
+ presentation = null;
- async init($el) {
+ async init() {
if (!this.el.querySelector(".slide")) {
// no slides, nothing to do.
return;
}
await import("slides/src/slides"); // loads ``Presentation`` globally.
+ if (this.destroyed) {
+ return;
+ }
const parameters = new URL(window.location.href).searchParams;
- if (parameters.get("slides") !== null) {
- var requested_ids = slides._collapse_ids(parameters.get("slides"));
- if (requested_ids) slides._remove_slides($el, requested_ids);
+ const requested_ids = this._collapse_ids(parameters.getAll("slides"));
+ if (requested_ids.length) {
+ this._remove_slides(requested_ids);
}
- $el.each(function () {
- var presentation = new window.Presentation(this),
- $container = $(this);
- $container
- .data("pat-slide", presentation)
- .on("SlideDisplay", slides._onSlideDisplay)
- .on("SlideHide", slides._onSlideHide);
- });
- return slides._hook($el);
- },
- _onSlideDisplay: function (event) {
- var slide = event.originalEvent.detail.slide.element,
- $videos = $("video", slide);
+ this.presentation = new window.Presentation(this.el);
- $videos.each(function () {
- if (this.paused) {
- this.currentTime = 0;
- this.play();
+ this.add_event_listener(this.el, "SlideDisplay", "slide-display", (event) =>
+ this._onSlideDisplay(event),
+ );
+ this.add_event_listener(this.el, "SlideHide", "slide-hide", (event) =>
+ this._onSlideHide(event),
+ );
+
+ // Rescan the slides when new content is injected into the slideshow.
+ // The ``patterns-injected`` event is triggered via jQuery, so we need
+ // to listen via jQuery.
+ const debounced_reset = utils.debounce(() => {
+ if (!this.destroyed) {
+ this._reset();
}
- });
- },
+ }, 100);
+ $(this.el).on(`patterns-injected.${this.event_namespace}`, debounced_reset);
+ }
- _onSlideHide: function (event) {
- var slide = event.originalEvent.detail.slide.element,
- $videos = $("video", slide);
+ get event_namespace() {
+ return `pat-slides--${this.uuid}`;
+ }
- $videos.each(function () {
- if (!this.paused) this.pause();
- });
- },
+ destroy() {
+ if (this.destroyed) {
+ return;
+ }
+ $(this.el).off(`.${this.event_namespace}`);
+ if (this.presentation?.running) {
+ // Stop a running presentation, which removes its global event
+ // listeners.
+ this.presentation.stop();
+ }
+ this.presentation = null;
+ super.destroy();
+ }
- _collapse_ids: function (params) {
- var ids = [];
+ _onSlideDisplay(event) {
+ const slide = event.detail.slide.element;
+ for (const video of slide.querySelectorAll("video")) {
+ if (video.paused) {
+ video.currentTime = 0;
+ video.play();
+ }
+ }
+ }
+
+ _onSlideHide(event) {
+ const slide = event.detail.slide.element;
+ for (const video of slide.querySelectorAll("video")) {
+ if (!video.paused) {
+ video.pause();
+ }
+ }
+ }
+
+ _collapse_ids(params) {
+ let ids = [];
params.forEach(function (param) {
if (param)
ids = ids.concat(
param.split(",").filter(function (id) {
return !!id;
- })
+ }),
);
});
return ids;
- },
-
- _remove_slides: function ($shows, ids) {
- var has_bad_id = function (idx, el) {
- return ids.indexOf(el.id) === -1;
- };
+ }
- for (var i = 0; i < $shows.length; i++) {
- var $show = $shows.eq(i),
- $bad_slides = $show.find(".slide[id]").filter(has_bad_id);
- $bad_slides.remove();
+ _remove_slides(ids) {
+ for (const slide of this.el.querySelectorAll(".slide[id]")) {
+ if (!ids.includes(slide.id)) {
+ slide.remove();
+ }
}
- },
-
- _hook: function ($el) {
- return $el
- .off("destroy.pat-slide")
- .on("destroy.pat-slide", utils.debounce(slides._reset, 100));
- },
+ }
- _reset: function () {
- var $container = $(this).closest(".pat-slides"),
- presentation = $container.data("pat-slide");
- if (presentation) presentation.scan();
- slides._hook($(this.trigger));
- },
-};
+ _reset() {
+ this.presentation?.scan();
+ }
+}
-slides.setup();
-registry.register(slides);
-export default slides;
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/slides/slides.test.js b/src/pat/slides/slides.test.js
index c9c6940c1..51188e1d2 100644
--- a/src/pat/slides/slides.test.js
+++ b/src/pat/slides/slides.test.js
@@ -1,74 +1,184 @@
-import pattern from "./slides";
+import Pattern from "./slides";
import $ from "jquery";
+import events from "../../core/events";
import utils from "../../core/utils";
import { jest } from "@jest/globals";
+const SLIDES = `
+
+`;
+
describe("pat-slides", function () {
afterEach(function () {
+ document.body.innerHTML = "";
+ window.history.replaceState(null, "", "/");
jest.restoreAllMocks();
});
describe("_collapse_ids", function () {
+ let instance;
+ beforeEach(function () {
+ instance = new Pattern(document.createElement("div"));
+ });
+
it("Single id", function () {
- expect(pattern._collapse_ids(["foo"])).toEqual(["foo"]);
+ expect(instance._collapse_ids(["foo"])).toEqual(["foo"]);
});
it("Comma-separated list of ids", function () {
- expect(pattern._collapse_ids(["foo,bar"])).toEqual(["foo", "bar"]);
+ expect(instance._collapse_ids(["foo,bar"])).toEqual(["foo", "bar"]);
});
it("Skip empty ids", function () {
- expect(pattern._collapse_ids(["foo,,bar"])).toEqual(["foo", "bar"]);
+ expect(instance._collapse_ids(["foo,,bar"])).toEqual(["foo", "bar"]);
});
it("Parameter without value", function () {
- expect(pattern._collapse_ids([null])).toEqual([]);
+ expect(instance._collapse_ids([null])).toEqual([]);
});
it("Parameter with empty value", function () {
- expect(pattern._collapse_ids([""])).toEqual([]);
+ expect(instance._collapse_ids([""])).toEqual([]);
});
it("Multiple parameters", function () {
- expect(pattern._collapse_ids(["foo", "bar"])).toEqual(["foo", "bar"]);
+ expect(instance._collapse_ids(["foo", "bar"])).toEqual(["foo", "bar"]);
});
});
describe("_remove_slides", function () {
it("Remove slides from DOM", function () {
- var $show = $("
", { class: "pat-slides" });
- for (var i = 1; i <= 4; i++)
- $("
", { class: "slide", id: "slide" + i }).appendTo($show);
- pattern._remove_slides($show, ["slide1", "slide3"]);
- var ids = $.makeArray(
- $show.find(".slide").map(function (idx, el) {
- return el.id;
- })
- );
+ document.body.innerHTML = SLIDES;
+ const el = document.querySelector(".pat-slides");
+ const instance = new Pattern(el);
+ instance._remove_slides(["slide1", "slide3"]);
+ const ids = [...el.querySelectorAll(".slide")].map((slide) => slide.id);
expect(ids).toEqual(["slide1", "slide3"]);
});
+ });
+
+ describe("init", function () {
+ it("Does nothing without slides.", async function () {
+ document.body.innerHTML = `
`;
+ const el = document.querySelector(".pat-slides");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ expect(instance.presentation).toBe(null);
+ });
+
+ it("Creates a presentation.", async function () {
+ document.body.innerHTML = SLIDES;
+ const el = document.querySelector(".pat-slides");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ expect(el["pattern-slides"]).toBe(instance);
+ expect(instance.presentation).toBeInstanceOf(window.Presentation);
+ expect(instance.presentation.slides.length).toBe(4);
+ expect(el.classList.contains("mode-list")).toBe(true);
+ });
+
+ it("Only keeps the slides from the URL filter.", async function () {
+ window.history.replaceState(
+ null,
+ "",
+ "/?slides=slide1,slide3&slides=slide4",
+ );
+ document.body.innerHTML = SLIDES;
+ const el = document.querySelector(".pat-slides");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ const ids = [...el.querySelectorAll(".slide")].map((slide) => slide.id);
+ expect(ids).toEqual(["slide1", "slide3", "slide4"]);
+ expect(instance.presentation.slides.length).toBe(3);
+ });
- it.skip("Trigger reset when removing slides", function () {
- var $show = $("
", { class: "pat-slides" });
- for (var i = 1; i <= 4; i++) {
- $("
", { class: "slide", id: "slide" + i }).appendTo($show);
- }
- jest.spyOn(utils, "debounce").mockImplementation((func) => {
- return func;
- });
- var spy_reset = jest.spyOn(pattern, "_reset");
- pattern._hook($show);
- pattern._remove_slides($show, ["slide1", "slide3"]);
- expect(spy_reset).toHaveBeenCalled();
+ it("Plays and pauses videos when a slide is shown or hidden.", async function () {
+ document.body.innerHTML = SLIDES;
+ const el = document.querySelector(".pat-slides");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ const slide = el.querySelector("#slide1");
+ const video = slide.querySelector("video");
+ let paused = true;
+ jest.spyOn(video, "paused", "get").mockImplementation(() => paused);
+ const spy_play = jest
+ .spyOn(video, "play")
+ .mockImplementation(() => (paused = false));
+ const spy_pause = jest
+ .spyOn(video, "pause")
+ .mockImplementation(() => (paused = true));
+
+ slide.dispatchEvent(
+ new CustomEvent("SlideDisplay", {
+ bubbles: true,
+ detail: { slide: { element: slide } },
+ }),
+ );
+ expect(spy_play).toHaveBeenCalledTimes(1);
+
+ slide.dispatchEvent(
+ new CustomEvent("SlideHide", {
+ bubbles: true,
+ detail: { slide: { element: slide } },
+ }),
+ );
+ expect(spy_pause).toHaveBeenCalledTimes(1);
});
- it("Do not trigger reset when not doing anything", function () {
- var $show = $("
", { class: "pat-slides" });
- for (var i = 1; i <= 2; i++)
- $("
", { class: "slide", id: "slide" + i }).appendTo($show);
- var spy_reset = jest.spyOn(pattern, "_reset");
- pattern._remove_slides($show, ["slide1", "slide2"]);
- expect(spy_reset).not.toHaveBeenCalled();
+ it("Rescans the slides after content was injected.", async function () {
+ document.body.innerHTML = SLIDES;
+ const el = document.querySelector(".pat-slides");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ const new_slide = document.createElement("div");
+ new_slide.classList.add("slide");
+ el.appendChild(new_slide);
+ $(new_slide).trigger("patterns-injected");
+ await utils.timeout(110); // debounce
+
+ expect(instance.presentation.slides.length).toBe(5);
+ });
+ });
+
+ describe("destroy", function () {
+ it("Stops a running presentation and does not rescan anymore.", async function () {
+ document.body.innerHTML = `
${SLIDES}
`;
+ const el = document.querySelector(".pat-slides");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ const presentation = instance.presentation;
+ jest.spyOn(presentation, "_scaleDocument").mockImplementation(() => {});
+ jest.spyOn(presentation, "_display").mockImplementation(() => {});
+ jest.spyOn(presentation, "_applyScale").mockImplementation(() => {});
+ presentation.start();
+ expect(presentation.running).toBe(true);
+ expect(document.body.classList.contains("slideshow-running")).toBe(true);
+
+ const spy_scan = jest.spyOn(presentation, "scan");
+
+ document.querySelector(".wrapper").remove();
+ await utils.timeout(1); // wait for the automatic destroy.
+
+ expect(instance.destroyed).toBe(true);
+ expect(el["pattern-slides"]).toBeUndefined();
+ expect(presentation.running).toBe(false);
+ expect(presentation.events.listeners.length).toBe(0);
+ expect(document.body.classList.contains("slideshow-running")).toBe(false);
+
+ $(el).trigger("patterns-injected");
+ await utils.timeout(110); // debounce
+ expect(spy_scan).not.toHaveBeenCalled();
});
});
});
diff --git a/src/pat/sortable/sortable--implementation.js b/src/pat/sortable/sortable--implementation.js
new file mode 100644
index 000000000..d1b83ef30
--- /dev/null
+++ b/src/pat/sortable/sortable--implementation.js
@@ -0,0 +1,262 @@
+import $ from "jquery";
+import { BasePattern } from "../../core/basepattern";
+import dom from "../../core/dom";
+import Parser from "../../core/parser";
+import registry from "../../core/registry";
+
+export const parser = new Parser("sortable");
+parser.addArgument("selector", "li");
+parser.addArgument("drag-class", "dragged"); // Class to apply to item that is being dragged.
+parser.addArgument("drop"); // Callback function for when item is dropped (null)
+
+// BBB for the mockup sortable pattern.
+parser.addAlias("dragClass", "drag-class");
+
+class Pattern extends BasePattern {
+ static name = "sortable";
+ static trigger = ".pat-sortable";
+ static parser = parser;
+
+ init() {
+ if (window.__patternslib_import_styles) {
+ import("./_sortable.scss");
+ }
+ this.$el = $(this.el);
+ this.$form = this.$el.closest("form");
+ this.recordPositions().initScrolling();
+
+ // Use an instance specific namespace. The ``.pat-sortable``
+ // namespace is used for the drag handlers which are removed on
+ // drag end.
+ this.namespace = `pat-sortable--${this.uuid}`;
+ this.$el.on(`pat-update.${this.namespace}`, (ev, data) =>
+ this.onPatternUpdate(ev, data)
+ );
+ this.$el.on(`patterns-injected.${this.namespace}`, () =>
+ this.recordPositions()
+ );
+ }
+
+ destroy() {
+ if (this.$el) {
+ // Only clean up, if the pattern was initialized.
+ this.$el.off(`.${this.namespace}`);
+ this.$el.off(".pat-sortable");
+ this.$sortables?.off(".pat-sortable");
+ }
+ super.destroy();
+ }
+
+ onPatternUpdate(ev, data) {
+ /* Handler which gets called when pat-update is triggered within
+ * the .pat-sortable element.
+ */
+ if (data?.pattern !== "clone" || data?.action !== "added") {
+ // Nothing to do.
+ return;
+ }
+ this.recordPositions();
+ }
+
+ recordPositions() {
+ // use only direct descendants to support nested lists
+ this.$sortables = this.$el.children().filter(this.options.selector);
+ this.$sortables.each(function (idx) {
+ $(this).data("patterns.sortable", { position: idx });
+ // Add `.sortable-item` class to each sortable.
+ this.classList.add("sortable-item");
+ });
+ this.addHandles();
+ return this;
+ }
+
+ addHandles() {
+ for (const sortable of this.$sortables) {
+ // Ignore the handles of nested sortables.
+ const handles = dom
+ .querySelectorAllAndMe(sortable, ".sortable-handle")
+ .filter((handle) => handle.closest(this.trigger) === this.el);
+ if (handles.length === 0) {
+ // TODO: we should change to a
.
+ const handle = document.createElement("a");
+ handle.textContent = "⇕";
+ handle.classList.add("sortable-handle");
+ handle.setAttribute("draggable", "true");
+ handle.setAttribute("href", "#");
+ //handle.setAttribute("title", "Drag to reorder"); // TODO: specify if that should be kept.
+ handle.setAttribute("aria-label", "Drag to reorder");
+ sortable.appendChild(handle);
+ handles.push(handle);
+ }
+
+ for (const handle of handles) {
+ // TODO: remove when element is a button.
+ this.add_event_listener(handle, "click", "handle-click", (e) => {
+ e.preventDefault();
+ });
+ this.add_event_listener(handle, "dragstart", "handle-dragstart", (e) =>
+ this.onDragStart(e)
+ );
+ this.add_event_listener(handle, "dragend", "handle-dragend", (e) =>
+ this.onDragEnd(e)
+ );
+ }
+ }
+ }
+
+ initScrolling() {
+ // invisible scroll activation areas
+ var scrollup = $('
'),
+ scrolldn = $('
'),
+ scroll = $().add(scrollup).add(scrolldn);
+ scrollup.css({ top: 0 });
+ scrolldn.css({ bottom: 0 });
+ scroll.css({
+ position: "fixed",
+ zIndex: 999999,
+ height: 32,
+ left: 0,
+ right: 0,
+ });
+ scroll.on("dragover", function (ev) {
+ ev.preventDefault();
+ if ($("html,body").is(":animated")) {
+ return;
+ }
+ var newpos =
+ $(window).scrollTop() +
+ ($(this).attr("id") === "pat-scroll-up" ? -32 : 32);
+ $("html,body").animate({ scrollTop: newpos }, 50, "linear");
+ });
+ return this;
+ }
+
+ onDragEnd(ev) {
+ const $dragged = $(ev.target.closest(this.options.selector));
+ $dragged.removeClass(this.options.dragClass);
+ this.$sortables.off(".pat-sortable");
+ this.$el.off(".pat-sortable");
+ $("#pat-scroll-up, #pat-scroll-dn").detach();
+ var change = this.submitChangedAmount(
+ $(ev.target).closest(this.options.selector)
+ );
+ // Call the optionally passed-in callback function
+ if (this.options.drop) {
+ this.options.drop($dragged, change);
+ }
+ // Inform other patterns about sorting changes
+ $dragged.trigger("pat-update", {
+ pattern: "sortable",
+ action: "changed",
+ dom: $dragged[0],
+ });
+ }
+
+ submitChangedAmount($dragged) {
+ /* If we are in a form, then submit the form with the right amount
+ * that the sortable element was moved up or down.
+ */
+ var $amount_input = this.$form.find(".sortable-amount");
+ if ($amount_input.length === 0) {
+ return;
+ }
+ var old_position = $dragged.data("patterns.sortable").position;
+ this.recordPositions();
+ var new_position = $dragged.data("patterns.sortable").position;
+ var change = Math.abs(new_position - old_position);
+ var direction = (new_position > old_position && "down") || "up";
+ if (this.$form.length > 0) {
+ $amount_input.val(change);
+ if (direction == "up") {
+ $dragged.find(".sortable-button-up").click();
+ } else {
+ $dragged.find(".sortable-button-down").click();
+ }
+ }
+ return change;
+ }
+
+ onDragStart(ev) {
+ const $dragged = $(ev.target.closest(this.options.selector));
+ var that = this;
+ if (ev.dataTransfer) {
+ // Firefox seems to need this set to any value
+ ev.dataTransfer.setData("Text", "");
+ ev.dataTransfer.effectAllowed = ["move"];
+ if ("setDragImage" in ev.dataTransfer) {
+ ev.dataTransfer.setDragImage($dragged[0], 0, 0);
+ }
+ }
+ $dragged.addClass(this.options.dragClass);
+
+ // Scroll the list if near the borders
+ this.$el.on(
+ "dragover.pat-sortable",
+ function (ev) {
+ ev.preventDefault();
+ if (this.$el.is(":animated")) return;
+
+ var pos = ev.originalEvent.clientY + $("body").scrollTop();
+ if (pos - this.$el.safeOffset().top < 32)
+ this.$el.animate(
+ { scrollTop: this.$el.scrollTop() - 32 },
+ 50,
+ "linear"
+ );
+ else if (this.$el.safeOffset().top + this.$el.height() - pos < 32)
+ this.$el.animate(
+ { scrollTop: this.$el.scrollTop() + 32 },
+ 50,
+ "linear"
+ );
+ }.bind(this)
+ );
+
+ this.$sortables.on(
+ "dragover.pat-sortable",
+ function (ev) {
+ // list elements are only drop targets when one element of the
+ // list is being dragged. avoids dragging between lists.
+ var $dropTarget = $(ev.target).closest(that.options.selector),
+ midlineY =
+ $dropTarget.safeOffset().top -
+ $(document).scrollTop() +
+ $dropTarget.height() / 2;
+
+ if ($dropTarget.is($dragged)) {
+ return;
+ }
+ $dropTarget.removeClass("drop-target-above drop-target-below");
+ if (ev.originalEvent.clientY > midlineY)
+ $dropTarget.addClass("drop-target-below");
+ else $dropTarget.addClass("drop-target-above");
+ ev.preventDefault();
+ }.bind(this)
+ );
+
+ this.$sortables.on(
+ "dragleave.pat-sortable",
+ function () {
+ this.$sortables.removeClass("drop-target-above drop-target-below");
+ }.bind(this)
+ );
+
+ this.$sortables.on("drop.pat-sortable", function (ev) {
+ var $dropTarget = $(ev.target).closest(that.options.selector);
+ if ($dropTarget.is($dragged)) {
+ return;
+ }
+ if ($dropTarget.hasClass("drop-target-below")) {
+ $dropTarget.after($dragged);
+ } else {
+ $dropTarget.before($dragged);
+ }
+ $dropTarget.removeClass("drop-target-above drop-target-below");
+ ev.preventDefault();
+ });
+ }
+}
+
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/sortable/sortable--implementation.test.js b/src/pat/sortable/sortable--implementation.test.js
new file mode 100644
index 000000000..d194cffb0
--- /dev/null
+++ b/src/pat/sortable/sortable--implementation.test.js
@@ -0,0 +1,373 @@
+import events from "../../core/events";
+import utils from "../../core/utils";
+import $ from "jquery";
+import Sortable from "./sortable--implementation";
+import { jest } from "@jest/globals";
+
+describe("pat-sortable", function () {
+ afterEach(function () {
+ document.body.innerHTML = "";
+ });
+
+ it("1 - adds class on drag start", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-sortable");
+ const sortable = new Sortable(el);
+ await events.await_pattern_init(sortable);
+ const dragged = el.querySelector("li");
+ const handle = dragged.querySelector(".sortable-handle");
+ handle.dispatchEvent(new Event("dragstart"));
+ expect(dragged.classList.contains(sortable.options.dragClass)).toBe(true);
+ });
+
+ it("2 - adds a sortable handle to sortable elements", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-sortable");
+ const sortable = new Sortable(el);
+ await events.await_pattern_init(sortable);
+ const handles = el.querySelectorAll("li a.sortable-handle");
+ expect(handles.length).toBe(3);
+ expect(handles[0].getAttribute("draggable")).toBe("true");
+ expect(handles[1].getAttribute("draggable")).toBe("true");
+ expect(handles[2].getAttribute("draggable")).toBe("true");
+ });
+
+ it("3 - submits a form if there is a .sortable-amount input and .sortable-button-(up|down) buttons", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-sortable");
+ const sortable = new Sortable(el);
+ await events.await_pattern_init(sortable);
+ const handles = el.querySelectorAll("li a.sortable-handle");
+ expect(handles.length).toBe(3);
+
+ const form = document.querySelector("form");
+
+ $("#item3").prependTo($("ol")); // Simulate dragging it to the top.
+ const submitCallback = jest.fn();
+ submitCallback.mockReturnValue(false);
+ form.addEventListener("submit", submitCallback);
+ document
+ .querySelector("#item3 a.sortable-handle")
+ .dispatchEvent(events.dragend_event());
+ expect(document.querySelector(".sortable-amount").getAttribute("value")).toBe(
+ "2"
+ );
+ expect(submitCallback).toHaveBeenCalled();
+ });
+
+ it("4 - Triggers pat-update on drag end", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-sortable");
+ const sortable = new Sortable(el);
+ await events.await_pattern_init(sortable);
+ const dragging_element = el.querySelector("li");
+ const handle = dragging_element.querySelector("a.sortable-handle");
+
+ let data = null;
+ $(el).on("pat-update", (e, d) => {
+ data = d;
+ });
+
+ handle.dispatchEvent(events.dragend_event());
+
+ expect(data.pattern).toBe("sortable");
+ expect(data.action).toBe("changed");
+ expect(data.dom).toBe(dragging_element);
+ });
+
+ it("5 - Initializes sorting behavior on pat-clone'd elements.", async function () {
+ const Clone = (await import("../clone/clone--implementation")).default;
+
+ document.body.innerHTML = `
+
+ Clone
+
+ item
+
+ `;
+ const el = document.querySelector(".pat-sortable");
+ const sortable = new Sortable(el);
+ await events.await_pattern_init(sortable);
+ new Clone(el);
+ await utils.timeout(1);
+
+ const clone_trigger = document.querySelector(".clone-trigger");
+ clone_trigger.click();
+
+ const cloned = el.querySelector("li");
+ expect(cloned).toBeTruthy();
+
+ const drag_handle = cloned.querySelector(".sortable-handle");
+ expect(drag_handle).toBeTruthy();
+ drag_handle.dispatchEvent(new Event("dragstart"));
+
+ expect(cloned.classList.contains(sortable.options.dragClass)).toBe(true);
+ });
+
+ it("6 - Initializes sorting behavior on pat-injected elements.", async function () {
+ const Inject = (await import("../inject/inject")).default;
+
+ document.body.innerHTML = `
+
+ Inject
+
+ item
+
+ `;
+ const el = document.querySelector(".pat-sortable");
+ const sortable = new Sortable(el);
+ await events.await_pattern_init(sortable);
+ const el_inject = document.querySelector(".pat-inject");
+ Inject.init($(el_inject));
+ await utils.timeout(1); // wait a tick for async to settle.
+
+ el_inject.click();
+ await utils.timeout(1);
+
+ const injected = el.querySelector("li");
+ expect(injected).toBeTruthy();
+
+ const drag_handle = injected.querySelector(".sortable-handle");
+ expect(drag_handle).toBeTruthy();
+ drag_handle.dispatchEvent(new Event("dragstart"));
+
+ expect(injected.classList.contains(sortable.options.dragClass)).toBe(true);
+ });
+
+ it("7 - Initializes sorting behavior with existing handles.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-sortable");
+ const sortable = new Sortable(el);
+ await events.await_pattern_init(sortable);
+
+ const item = el.querySelector("li");
+ const drag_handle = item.querySelector(".sortable-handle");
+ drag_handle.dispatchEvent(new Event("dragstart"));
+
+ expect(item.classList.contains(sortable.options.dragClass)).toBe(true);
+ });
+
+ it("8 - Sortable item itself can be the handle.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-sortable");
+ const sortable = new Sortable(el);
+ await events.await_pattern_init(sortable);
+
+ const item = el.querySelector("li");
+ item.dispatchEvent(new Event("dragstart"));
+
+ expect(item.classList.contains(sortable.options.dragClass)).toBe(true);
+ });
+
+ it("9 - Nested sortables handle their own items.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const outer = document.querySelector(".outer");
+ const inner = document.querySelector(".inner");
+ const outer_item = document.querySelector(".outer-item");
+ const inner_item = document.querySelector(".inner-item");
+
+ // Patterns are initialized inside-out.
+ const instance_inner = new Sortable(inner);
+ await events.await_pattern_init(instance_inner);
+ const instance_outer = new Sortable(outer);
+ await events.await_pattern_init(instance_outer);
+
+ // The outer item gets its own handle.
+ const outer_handle = [...outer_item.querySelectorAll(".sortable-handle")].find(
+ (it) => it.parentElement === outer_item
+ );
+ expect(outer_handle).toBeTruthy();
+ expect(inner_item.querySelectorAll(".sortable-handle").length).toBe(1);
+
+ const spy_inner = jest.spyOn(instance_inner, "onDragStart");
+ const spy_outer = jest.spyOn(instance_outer, "onDragStart");
+
+ inner_item.querySelector(".sortable-handle").dispatchEvent(new Event("dragstart"));
+ expect(spy_inner).toHaveBeenCalledTimes(1);
+ expect(spy_outer).not.toHaveBeenCalled();
+ expect(inner_item.classList.contains("dragged")).toBe(true);
+ expect(outer_item.classList.contains("dragged")).toBe(false);
+
+ outer_handle.dispatchEvent(new Event("dragstart"));
+ expect(spy_inner).toHaveBeenCalledTimes(1);
+ expect(spy_outer).toHaveBeenCalledTimes(1);
+ expect(outer_item.classList.contains("dragged")).toBe(true);
+ });
+
+ it("10 - Calls the drop callback passed as option.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-sortable");
+ const drop = jest.fn();
+ const sortable = new Sortable(el, { drop: drop });
+ await events.await_pattern_init(sortable);
+
+ el.querySelector(".sortable-handle").dispatchEvent(events.dragend_event());
+ expect(drop).toHaveBeenCalledTimes(1);
+ expect(drop.mock.calls[0][0][0]).toBe(el.querySelector("li"));
+ });
+
+ describe("11 - Destroy", function () {
+ it("11.1 - removes the event listeners.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-sortable");
+ const sortable = new Sortable(el);
+ await events.await_pattern_init(sortable);
+
+ const item = el.querySelector("li");
+ const handle = item.querySelector(".sortable-handle");
+ handle.dispatchEvent(new Event("dragstart"));
+ expect(item.classList.contains("dragged")).toBe(true);
+ item.classList.remove("dragged");
+
+ const spy_record_positions = jest.spyOn(sortable, "recordPositions");
+ const spy_drag_end = jest.spyOn(sortable, "onDragEnd");
+
+ sortable.destroy();
+ expect(el["pattern-sortable"]).toBeUndefined();
+
+ // No handlers for drag events anymore.
+ handle.dispatchEvent(new Event("dragstart"));
+ handle.dispatchEvent(events.dragend_event());
+ expect(item.classList.contains("dragged")).toBe(false);
+ expect(spy_drag_end).not.toHaveBeenCalled();
+ expect($._data(el, "events")).toBeUndefined();
+ expect($._data(item, "events")).toBeUndefined();
+
+ // No handlers for update events anymore.
+ $(el).triggerHandler("pat-update", { pattern: "clone", action: "added" });
+ $(el).triggerHandler("patterns-injected");
+ expect(spy_record_positions).not.toHaveBeenCalled();
+ });
+
+ it("11.2 - is destroyed when the element is removed from the DOM.", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-sortable");
+ const sortable = new Sortable(el);
+ await events.await_pattern_init(sortable);
+
+ el.remove();
+ await utils.timeout(1);
+ expect(sortable.destroyed).toBe(true);
+ });
+ });
+});
diff --git a/src/pat/sortable/sortable.js b/src/pat/sortable/sortable.js
index 2dc4c9c44..dba40e6ae 100644
--- a/src/pat/sortable/sortable.js
+++ b/src/pat/sortable/sortable.js
@@ -1,246 +1,20 @@
-import $ from "jquery";
-import Base from "../../core/base";
-import dom from "../../core/dom";
-import events from "../../core/events";
-import Parser from "../../core/parser";
-
-export const parser = new Parser("sortable");
-parser.addArgument("selector", "li");
-parser.addArgument("drag-class", "dragged"); // Class to apply to item that is being dragged.
-parser.addArgument("drop"); // Callback function for when item is dropped (null)
-
-// BBB for the mockup sortable pattern.
-parser.addAlias("dragClass", "drag-class");
-
-export default Base.extend({
+/**
+ * pat-sortable 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:
+ * ./sortable--implementation.js
+ */
+import create_lazy_pattern from "../../core/lazy-pattern";
+import registry from "../../core/registry";
+
+const Pattern = create_lazy_pattern({
name: "sortable",
trigger: ".pat-sortable",
-
- init: function () {
- if (window.__patternslib_import_styles) {
- import("./_sortable.scss");
- }
- this.$form = this.$el.closest("form");
- this.options = parser.parse(this.$el, false);
- this.recordPositions().initScrolling();
- this.$el.on("pat-update", this.onPatternUpdate.bind(this));
- this.$el.on("patterns-injected", this.recordPositions.bind(this));
- },
-
- onPatternUpdate: function (ev, data) {
- /* Handler which gets called when pat-update is triggered within
- * the .pat-sortable element.
- */
- if (data?.pattern !== "clone" || data?.action !== "added") {
- // Nothing to do.
- return;
- }
- this.recordPositions();
- },
-
- recordPositions: function () {
- // use only direct descendants to support nested lists
- this.$sortables = this.$el.children().filter(this.options.selector);
- this.$sortables.each(function (idx) {
- $(this).data("patterns.sortable", { position: idx });
- // Add `.sortable-item` class to each sortable.
- this.classList.add("sortable-item");
- });
- this.addHandles();
- return this;
- },
-
- addHandles: function () {
- for (const sortable of this.$sortables) {
- const handles = dom.querySelectorAllAndMe(sortable, ".sortable-handle");
- if (handles.length === 0) {
- // TODO: we should change to a .
- const handle = document.createElement("a");
- handle.textContent = "⇕";
- handle.classList.add("sortable-handle");
- handle.setAttribute("draggable", "true");
- handle.setAttribute("href", "#");
- //handle.setAttribute("title", "Drag to reorder"); // TODO: specify if that should be kept.
- handle.setAttribute("aria-label", "Drag to reorder");
- sortable.appendChild(handle);
- handles.push(handle);
- }
-
- for (const handle of handles) {
- // TODO: remove when element is a button.
- events.add_event_listener(
- handle,
- "click",
- "pat-sortable--click",
- (e) => {
- e.preventDefault();
- }
- );
- events.add_event_listener(
- handle,
- "dragstart",
- "pat-sortable--dragstart",
- this.onDragStart.bind(this)
- );
- events.add_event_listener(
- handle,
- "dragend",
- "pat-sortable--dragend",
- this.onDragEnd.bind(this)
- );
- }
- }
- },
-
- initScrolling: function () {
- // invisible scroll activation areas
- var scrollup = $('
'),
- scrolldn = $('
'),
- scroll = $().add(scrollup).add(scrolldn);
- scrollup.css({ top: 0 });
- scrolldn.css({ bottom: 0 });
- scroll.css({
- position: "fixed",
- zIndex: 999999,
- height: 32,
- left: 0,
- right: 0,
- });
- scroll.on("dragover", function (ev) {
- ev.preventDefault();
- if ($("html,body").is(":animated")) {
- return;
- }
- var newpos =
- $(window).scrollTop() +
- ($(this).attr("id") === "pat-scroll-up" ? -32 : 32);
- $("html,body").animate({ scrollTop: newpos }, 50, "linear");
- });
- return this;
- },
-
- onDragEnd: function (ev) {
- const $dragged = $(ev.target.closest(this.options.selector));
- $dragged.removeClass(this.options.dragClass);
- this.$sortables.off(".pat-sortable");
- this.$el.off(".pat-sortable");
- $("#pat-scroll-up, #pat-scroll-dn").detach();
- var change = this.submitChangedAmount(
- $(ev.target).closest(this.options.selector)
- );
- // Call the optionally passed-in callback function
- if (this.options.drop) {
- this.options.drop($dragged, change);
- }
- // Inform other patterns about sorting changes
- $dragged.trigger("pat-update", {
- pattern: "sortable",
- action: "changed",
- dom: $dragged[0],
- });
- },
-
- submitChangedAmount: function ($dragged) {
- /* If we are in a form, then submit the form with the right amount
- * that the sortable element was moved up or down.
- */
- var $amount_input = this.$form.find(".sortable-amount");
- if ($amount_input.length === 0) {
- return;
- }
- var old_position = $dragged.data("patterns.sortable").position;
- this.recordPositions();
- var new_position = $dragged.data("patterns.sortable").position;
- var change = Math.abs(new_position - old_position);
- var direction = (new_position > old_position && "down") || "up";
- if (this.$form.length > 0) {
- $amount_input.val(change);
- if (direction == "up") {
- $dragged.find(".sortable-button-up").click();
- } else {
- $dragged.find(".sortable-button-down").click();
- }
- }
- return change;
- },
-
- onDragStart: function (ev) {
- const $dragged = $(ev.target.closest(this.options.selector));
- var that = this;
- if (ev.dataTransfer) {
- // Firefox seems to need this set to any value
- ev.dataTransfer.setData("Text", "");
- ev.dataTransfer.effectAllowed = ["move"];
- if ("setDragImage" in ev.dataTransfer) {
- ev.dataTransfer.setDragImage($dragged[0], 0, 0);
- }
- }
- $dragged.addClass(this.options.dragClass);
-
- // Scroll the list if near the borders
- this.$el.on(
- "dragover.pat-sortable",
- function (ev) {
- ev.preventDefault();
- if (this.$el.is(":animated")) return;
-
- var pos = ev.originalEvent.clientY + $("body").scrollTop();
- if (pos - this.$el.safeOffset().top < 32)
- this.$el.animate(
- { scrollTop: this.$el.scrollTop() - 32 },
- 50,
- "linear"
- );
- else if (this.$el.safeOffset().top + this.$el.height() - pos < 32)
- this.$el.animate(
- { scrollTop: this.$el.scrollTop() + 32 },
- 50,
- "linear"
- );
- }.bind(this)
- );
-
- this.$sortables.on(
- "dragover.pat-sortable",
- function (ev) {
- // list elements are only drop targets when one element of the
- // list is being dragged. avoids dragging between lists.
- var $dropTarget = $(ev.target).closest(that.options.selector),
- midlineY =
- $dropTarget.safeOffset().top -
- $(document).scrollTop() +
- $dropTarget.height() / 2;
-
- if ($dropTarget.is($dragged)) {
- return;
- }
- $dropTarget.removeClass("drop-target-above drop-target-below");
- if (ev.originalEvent.clientY > midlineY)
- $dropTarget.addClass("drop-target-below");
- else $dropTarget.addClass("drop-target-above");
- ev.preventDefault();
- }.bind(this)
- );
-
- this.$sortables.on(
- "dragleave.pat-sortable",
- function () {
- this.$sortables.removeClass("drop-target-above drop-target-below");
- }.bind(this)
- );
-
- this.$sortables.on("drop.pat-sortable", function (ev) {
- var $dropTarget = $(ev.target).closest(that.options.selector);
- if ($dropTarget.is($dragged)) {
- return;
- }
- if ($dropTarget.hasClass("drop-target-below")) {
- $dropTarget.after($dragged);
- } else {
- $dropTarget.before($dragged);
- }
- $dropTarget.removeClass("drop-target-above drop-target-below");
- ev.preventDefault();
- });
- },
+ load: () => import("./sortable--implementation"),
});
+
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/sortable/sortable.test.js b/src/pat/sortable/sortable.test.js
index 8cbbc0857..4c9555f05 100644
--- a/src/pat/sortable/sortable.test.js
+++ b/src/pat/sortable/sortable.test.js
@@ -1,248 +1,15 @@
-import events from "../../core/events";
-import utils from "../../core/utils";
-import $ from "jquery";
-import Sortable from "./sortable";
+import Pattern from "./sortable";
+import Implementation from "./sortable--implementation";
-describe("pat-sortable", function () {
- afterEach(function () {
- document.body.innerHTML = "";
+describe("pat-sortable 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);
});
- it("1 - adds class on drag start", function () {
- document.body.innerHTML = `
-
- `;
- const el = document.querySelector(".pat-sortable");
- const sortable = new Sortable(el);
- const dragged = el.querySelector("li");
- const handle = dragged.querySelector(".sortable-handle");
- handle.dispatchEvent(new Event("dragstart"));
- expect(dragged.classList.contains(sortable.options.dragClass)).toBe(true);
- });
-
- it("2 - adds a sortable handle to sortable elements", function () {
- document.body.innerHTML = `
-
- `;
- const el = document.querySelector(".pat-sortable");
- new Sortable(el);
- const handles = el.querySelectorAll("li a.sortable-handle");
- expect(handles.length).toBe(3);
- expect(handles[0].getAttribute("draggable")).toBe("true");
- expect(handles[1].getAttribute("draggable")).toBe("true");
- expect(handles[2].getAttribute("draggable")).toBe("true");
- });
-
- it("3 - submits a form if there is a .sortable-amount input and .sortable-button-(up|down) buttons", function () {
- document.body.innerHTML = `
-
- `;
- const el = document.querySelector(".pat-sortable");
- new Sortable(el);
- const handles = el.querySelectorAll("li a.sortable-handle");
- expect(handles.length).toBe(3);
-
- const form = document.querySelector("form");
-
- $("#item3").prependTo($("ol")); // Simulate dragging it to the top.
- const submitCallback = jest.fn();
- submitCallback.mockReturnValue(false);
- form.addEventListener("submit", submitCallback);
- document
- .querySelector("#item3 a.sortable-handle")
- .dispatchEvent(events.dragend_event());
- expect(document.querySelector(".sortable-amount").getAttribute("value")).toBe(
- "2"
- );
- expect(submitCallback).toHaveBeenCalled();
- });
-
- it("4 - Triggers pat-update on drag end", function () {
- document.body.innerHTML = `
-
- `;
- const el = document.querySelector(".pat-sortable");
- new Sortable(el);
- const dragging_element = el.querySelector("li");
- const handle = dragging_element.querySelector("a.sortable-handle");
-
- let data = null;
- $(el).on("pat-update", (e, d) => {
- data = d;
- });
-
- handle.dispatchEvent(events.dragend_event());
-
- expect(data.pattern).toBe("sortable");
- expect(data.action).toBe("changed");
- expect(data.dom).toBe(dragging_element);
- });
-
- it("5 - Initializes sorting behavior on pat-clone'd elements.", async function () {
- const Clone = (await import("../clone/clone")).default;
-
- document.body.innerHTML = `
-
- Clone
-
- item
-
- `;
- const el = document.querySelector(".pat-sortable");
- const sortable = new Sortable(el);
- new Clone(el);
-
- const clone_trigger = document.querySelector(".clone-trigger");
- clone_trigger.click();
-
- const cloned = el.querySelector("li");
- expect(cloned).toBeTruthy();
-
- const drag_handle = cloned.querySelector(".sortable-handle");
- expect(drag_handle).toBeTruthy();
- drag_handle.dispatchEvent(new Event("dragstart"));
-
- expect(cloned.classList.contains(sortable.options.dragClass)).toBe(true);
- });
-
- it("6 - Initializes sorting behavior on pat-injected elements.", async function () {
- const Inject = (await import("../inject/inject")).default;
-
- document.body.innerHTML = `
-
- Inject
-
- item
-
- `;
- const el = document.querySelector(".pat-sortable");
- const sortable = new Sortable(el);
- const el_inject = document.querySelector(".pat-inject");
- Inject.init($(el_inject));
- await utils.timeout(1); // wait a tick for async to settle.
-
- el_inject.click();
- await utils.timeout(1);
-
- const injected = el.querySelector("li");
- expect(injected).toBeTruthy();
-
- const drag_handle = injected.querySelector(".sortable-handle");
- expect(drag_handle).toBeTruthy();
- drag_handle.dispatchEvent(new Event("dragstart"));
-
- expect(injected.classList.contains(sortable.options.dragClass)).toBe(true);
- });
-
- it("7 - Initializes sorting behavior with existing handles.", function () {
- document.body.innerHTML = `
-
- `;
- const el = document.querySelector(".pat-sortable");
- const sortable = new Sortable(el);
-
- const item = el.querySelector("li");
- const drag_handle = item.querySelector(".sortable-handle");
- drag_handle.dispatchEvent(new Event("dragstart"));
-
- expect(item.classList.contains(sortable.options.dragClass)).toBe(true);
- });
-
- it("8 - Sortable item itself can be the handle.", function () {
- document.body.innerHTML = `
-
- `;
- const el = document.querySelector(".pat-sortable");
- const sortable = new Sortable(el);
-
- const item = el.querySelector("li");
- item.dispatchEvent(new Event("dragstart"));
-
- expect(item.classList.contains(sortable.options.dragClass)).toBe(true);
+ it("loads the implementation.", async function () {
+ expect(await Pattern.load()).toBe(Implementation);
});
});
diff --git a/src/pat/subform/subform.js b/src/pat/subform/subform.js
index ac2f3e3f8..df27ce612 100644
--- a/src/pat/subform/subform.js
+++ b/src/pat/subform/subform.js
@@ -5,31 +5,31 @@
*/
import $ from "jquery";
import ajax from "../ajax/ajax";
-import Base from "../../core/base";
+import { BasePattern } from "../../core/basepattern";
import events from "../../core/events";
import inject from "../inject/inject";
import logging from "../../core/logging";
+import registry from "../../core/registry";
const log = logging.getLogger("subform");
-export default Base.extend({
- name: "subform",
- trigger: ".pat-subform",
+class Pattern extends BasePattern {
+ static name = "subform";
+ static trigger = ".pat-subform";
- init($el) {
- events.add_event_listener(
- $el[0],
- "submit",
- "pat-subform--submit",
- this.submit.bind(this)
- );
- $el.find("input").on("keyup keypress keydown", this.keyboard_handler.bind(this));
- $el.find("button[type=submit]").on("click", this.submitClicked.bind(this));
- },
-
- destroy($el) {
- events.remove_event_listener($el[0], "pat-subform--submit");
- },
+ init() {
+ this.add_event_listener(this.el, "submit", "submit", (e) => this.submit(e));
+ for (const input of this.el.querySelectorAll("input")) {
+ this.add_event_listener(input, "keydown", "keyboard", (e) =>
+ this.keyboard_handler(e)
+ );
+ }
+ for (const button of this.el.querySelectorAll("button[type=submit]")) {
+ this.add_event_listener(button, "click", "submit-click", (e) =>
+ this.submitClicked(e)
+ );
+ }
+ }
scopedSubmit($el) {
const $form = $el.parents("form");
@@ -59,7 +59,7 @@ export default Base.extend({
$(this).attr("name", names[i]);
}
});
- },
+ }
submit(ev) {
ev.stopPropagation();
@@ -70,7 +70,7 @@ export default Base.extend({
} else {
this.scopedSubmit($this);
}
- },
+ }
keyboard_handler(ev) {
// If the user presses the enter key and
@@ -82,15 +82,20 @@ export default Base.extend({
if (!$subform.is(".pat-autosubmit")) {
return;
}
+ // Prevent the implicit submission of the surrounding form by the
+ // browser. Only the subform is submitted.
+ ev.preventDefault();
$subform[0].dispatchEvent(events.submit_event());
- },
+ }
submitClicked(ev) {
ev.preventDefault();
ev.stopPropagation();
ajax.onClickSubmit(ev); // make sure the submitting button is sent with the form
- const $button = $(ev.target);
+ // Use the element the listener is registered on and not the
+ // eventually clicked child element of the button.
+ const $button = $(ev.currentTarget);
const $sub = $button.parents(".pat-subform").first();
const formaction = $button.attr("formaction");
@@ -115,5 +120,9 @@ export default Base.extend({
} else {
this.scopedSubmit($sub);
}
- },
-});
+ }
+}
+
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/subform/subform.test.js b/src/pat/subform/subform.test.js
index 29950e246..12929d930 100644
--- a/src/pat/subform/subform.test.js
+++ b/src/pat/subform/subform.test.js
@@ -1,84 +1,325 @@
+import Pattern from "./subform";
+import events from "../../core/events";
+import inject from "../inject/inject";
import registry from "../../core/registry";
-import $ from "jquery";
-import pattern from "./subform";
+import utils from "../../core/utils";
import { jest } from "@jest/globals";
-describe("subform base tests", function () {
- describe("Triggering of the pattern", function () {
- it("happens when a fieldset has the pat-subform class", function () {
- var $form = $(
- '"
- );
- var spy_init = jest.spyOn(pattern, "init");
- registry.scan($form);
+const enter_event = (type = "keydown") => {
+ return new KeyboardEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ keyCode: 13,
+ key: "Enter",
+ });
+};
+
+describe("pat-subform", function () {
+ afterEach(function () {
+ document.body.innerHTML = "";
+ jest.restoreAllMocks();
+ });
+
+ describe("1 - Triggering of the pattern", function () {
+ it("1.1 - happens when a fieldset has the pat-subform 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();
});
});
- describe("Entering a return", function () {
- it("does nothing if the pat-autosubmit class is missing", function () {
- var $form = $(
- '"
- );
- const pat = new pattern($(".pat-subform", $form));
- const spy_keyboard_handler = jest.spyOn(pat.__proto__, "keyboard_handler");
- const spy_submit = jest.spyOn(pat.__proto__, "submit");
- registry.scan($form);
- $form.find("[name=q]").trigger({
- type: "keydown",
- keyCode: 13,
- });
+ describe("2 - Entering a return", function () {
+ it("2.1 - does nothing if the pat-autosubmit class is missing", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const spy_keyboard_handler = jest.spyOn(Pattern.prototype, "keyboard_handler");
+ const spy_submit = jest.spyOn(Pattern.prototype, "submit");
+
+ const pattern_el = document.querySelector(".pat-subform");
+ const instance = new Pattern(pattern_el);
+ await events.await_pattern_init(instance);
+
+ document.querySelector("[name=q]").dispatchEvent(enter_event());
+
expect(spy_keyboard_handler).toHaveBeenCalled();
expect(spy_submit).not.toHaveBeenCalled();
});
- it("submits the subform when the pat-autosubmit class is present", function () {
- var $form = $(
- '"
- );
- const pat = new pattern($(".pat-subform", $form));
- const spy_keyboard_handler = jest.spyOn(pat.__proto__, "keyboard_handler");
- const spy_submit = jest.spyOn(pat.__proto__, "submit");
- registry.scan($form);
- $form.find("[name=q]").trigger({
- type: "keydown",
- keyCode: 13,
- });
+
+ it("2.2 - submits the subform when the pat-autosubmit class is present", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const spy_keyboard_handler = jest.spyOn(Pattern.prototype, "keyboard_handler");
+ const spy_submit = jest.spyOn(Pattern.prototype, "submit");
+ const spy_scoped_submit = jest
+ .spyOn(Pattern.prototype, "scopedSubmit")
+ .mockImplementation(() => {});
+
+ const pattern_el = document.querySelector(".pat-subform");
+ const instance = new Pattern(pattern_el);
+ await events.await_pattern_init(instance);
+
+ document.querySelector("[name=q]").dispatchEvent(enter_event());
+
expect(spy_keyboard_handler).toHaveBeenCalled();
- expect(spy_submit).toHaveBeenCalled();
+ expect(spy_submit).toHaveBeenCalledTimes(1);
+ expect(spy_scoped_submit).toHaveBeenCalledTimes(1);
});
- it("does not submit the parent autosubmit form when the pat-autosubmit class is present on both", function () {
- var $form = $(
- '"
- );
- const pat = new pattern($(".pat-subform", $form));
- const spy_keyboard_handler = jest.spyOn(pat.__proto__, "keyboard_handler");
- const spy_submit = jest.spyOn(pat.__proto__, "submit");
- const spy_formsubmit = jest.spyOn($form, "submit");
- registry.scan($form);
- $form.find("[name=q]").trigger({
- type: "keydown",
- keyCode: 13,
- });
+
+ it("2.3 - does not submit the parent form when the pat-autosubmit class is present on both", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const spy_keyboard_handler = jest.spyOn(Pattern.prototype, "keyboard_handler");
+ const spy_submit = jest.spyOn(Pattern.prototype, "submit");
+ jest.spyOn(Pattern.prototype, "scopedSubmit").mockImplementation(() => {});
+
+ const form = document.querySelector("form");
+ const form_submit_handler = jest.fn();
+ form.addEventListener("submit", form_submit_handler);
+
+ const pattern_el = document.querySelector(".pat-subform");
+ const instance = new Pattern(pattern_el);
+ await events.await_pattern_init(instance);
+
+ document.querySelector("[name=q]").dispatchEvent(enter_event());
+
expect(spy_keyboard_handler).toHaveBeenCalled();
expect(spy_submit).toHaveBeenCalled();
- expect(spy_formsubmit).not.toHaveBeenCalled();
+ expect(form_submit_handler).not.toHaveBeenCalled();
+ });
+
+ it("2.4 - submits the subform only once per return key press", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const spy_submit = jest.spyOn(Pattern.prototype, "submit");
+ jest.spyOn(Pattern.prototype, "scopedSubmit").mockImplementation(() => {});
+
+ const pattern_el = document.querySelector(".pat-subform");
+ const instance = new Pattern(pattern_el);
+ await events.await_pattern_init(instance);
+
+ const input = document.querySelector("[name=q]");
+ input.dispatchEvent(enter_event("keydown"));
+ input.dispatchEvent(enter_event("keypress"));
+ input.dispatchEvent(enter_event("keyup"));
+
+ expect(spy_submit).toHaveBeenCalledTimes(1);
+ });
+
+ it("2.5 - prevents the implicit submission of the surrounding form", async function () {
+ document.body.innerHTML = `
+
+ `;
+ jest.spyOn(Pattern.prototype, "scopedSubmit").mockImplementation(() => {});
+
+ for (const el of document.querySelectorAll(".pat-subform")) {
+ await events.await_pattern_init(new Pattern(el));
+ }
+
+ const autosubmit_event = enter_event();
+ document.querySelector("[name=q]").dispatchEvent(autosubmit_event);
+ expect(autosubmit_event.defaultPrevented).toBe(true);
+
+ // Subforms without pat-autosubmit keep the browser's behavior.
+ const plain_event = enter_event();
+ document.querySelector("[name=r]").dispatchEvent(plain_event);
+ expect(plain_event.defaultPrevented).toBe(false);
+ });
+ });
+
+ describe("3 - Submitting", function () {
+ it("3.1 - submits only the subform's inputs", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const form = document.querySelector("form");
+ let names = null;
+ jest.spyOn(form, "submit").mockImplementation(() => {
+ names = [...form.querySelectorAll("input")].map((it) => it.name);
+ });
+
+ const pattern_el = document.querySelector(".pat-subform");
+ const instance = new Pattern(pattern_el);
+ await events.await_pattern_init(instance);
+
+ const form_submit_handler = jest.fn();
+ form.addEventListener("submit", form_submit_handler);
+
+ pattern_el.dispatchEvent(events.submit_event());
+
+ // The outer input is made unsuccessful while submitting.
+ expect(names).toEqual(["", "inner"]);
+ // The names are restored afterwards.
+ expect(form.querySelector("input").name).toBe("outer");
+ // The submit event does not bubble up to the form.
+ expect(form_submit_handler).not.toHaveBeenCalled();
+ });
+
+ it("3.2 - submits to an injection on a .pat-inject subform", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const spy_submit_subform = jest
+ .spyOn(inject, "submitSubform")
+ .mockImplementation(() => {});
+
+ const pattern_el = document.querySelector(".pat-subform");
+ const instance = new Pattern(pattern_el);
+ await events.await_pattern_init(instance);
+
+ pattern_el.dispatchEvent(events.submit_event());
+
+ expect(spy_submit_subform).toHaveBeenCalledTimes(1);
+ expect(spy_submit_subform.mock.calls[0][0][0]).toBe(pattern_el);
+ });
+
+ it("3.3 - uses the formaction of a clicked submit button", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const form = document.querySelector("form");
+ const spy_form_submit = jest
+ .spyOn(form, "submit")
+ .mockImplementation(() => {});
+
+ const pattern_el = document.querySelector(".pat-subform");
+ const instance = new Pattern(pattern_el);
+ await events.await_pattern_init(instance);
+
+ // Click on a child element of the button.
+ document.querySelector(".icon").click();
+
+ expect(form.getAttribute("action")).toBe("subform.html");
+ expect(spy_form_submit).toHaveBeenCalledTimes(1);
+ });
+
+ it("3.4 - clicks a formaction button on submit", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const form = document.querySelector("form");
+ const spy_form_submit = jest
+ .spyOn(form, "submit")
+ .mockImplementation(() => {});
+
+ const pattern_el = document.querySelector(".pat-subform");
+ const instance = new Pattern(pattern_el);
+ await events.await_pattern_init(instance);
+
+ pattern_el.dispatchEvent(events.submit_event());
+
+ expect(form.getAttribute("action")).toBe("subform.html");
+ expect(spy_form_submit).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe("4 - Destroy", function () {
+ it("4.1 - removes the event listeners", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const spy_keyboard_handler = jest.spyOn(Pattern.prototype, "keyboard_handler");
+ const spy_submit = jest.spyOn(Pattern.prototype, "submit");
+ const spy_submit_clicked = jest.spyOn(Pattern.prototype, "submitClicked");
+ jest.spyOn(Pattern.prototype, "scopedSubmit").mockImplementation(() => {});
+
+ const form = document.querySelector("form");
+ const form_submit_handler = jest.fn((e) => e.preventDefault());
+ form.addEventListener("submit", form_submit_handler);
+
+ const pattern_el = document.querySelector(".pat-subform");
+ const instance = new Pattern(pattern_el);
+ await events.await_pattern_init(instance);
+
+ instance.destroy();
+ expect(pattern_el["pattern-subform"]).toBeUndefined();
+
+ document.querySelector("[name=q]").dispatchEvent(enter_event());
+ pattern_el.dispatchEvent(events.submit_event());
+ document.querySelector("button").click();
+
+ expect(spy_keyboard_handler).not.toHaveBeenCalled();
+ expect(spy_submit).not.toHaveBeenCalled();
+ expect(spy_submit_clicked).not.toHaveBeenCalled();
+ // Without the subform, the submit events reach the form.
+ expect(form_submit_handler).toHaveBeenCalled();
+ });
+
+ it("4.2 - is destroyed when the element is removed from the DOM", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const pattern_el = document.querySelector(".pat-subform");
+ const instance = new Pattern(pattern_el);
+ await events.await_pattern_init(instance);
+
+ pattern_el.remove();
+ await utils.timeout(1);
+ expect(instance.destroyed).toBe(true);
});
});
});
+
diff --git a/src/pat/switch/switch.js b/src/pat/switch/switch.js
index 39a4cc83b..5c12c296b 100644
--- a/src/pat/switch/switch.js
+++ b/src/pat/switch/switch.js
@@ -1,9 +1,9 @@
// Patterns switch - toggle classes on click
import $ from "jquery";
-import Base from "../../core/base";
+import { BasePattern } from "../../core/basepattern";
import Parser from "../../core/parser";
-import events from "../../core/events";
import logging from "../../core/logging";
+import registry from "../../core/registry";
import store from "../../core/store";
import utils from "../../core/utils";
@@ -15,16 +15,18 @@ parser.addArgument("remove");
parser.addArgument("add");
parser.addArgument("store", "none", ["none", "session", "local"]);
-export default Base.extend({
- name: "switch",
- trigger: ".pat-switch",
+class Pattern extends BasePattern {
+ static name = "switch";
+ static trigger = ".pat-switch";
+ static parser = parser;
+
+ parser_multiple = true;
init() {
- this.options = this._validateOptions(parser.parse(this.el, this.options, true));
+ this.options = this._validateOptions(this.options);
- events.add_event_listener(this.el, "click", "pat-switch--on-click", (e) => {
- // TODO: e.target.tagName
- if (e.tagName === "A") {
+ this.add_event_listener(this.el, "click", "on-click", (e) => {
+ if (this.el.tagName === "A") {
e.preventDefault();
}
this._go();
@@ -40,16 +42,12 @@ export default Base.extend({
this._update(option.selector, state.remove, state.add);
}
}
- },
-
- destroy() {
- events.remove_event_listener(this.el, "pat-switch--on-click");
- },
+ }
execute() {
- // jQuery API to toggle a switch
+ // API to toggle a switch
this._go();
- },
+ }
_go() {
for (const option of this.options) {
@@ -61,9 +59,9 @@ export default Base.extend({
});
}
$(this.el).trigger("resize"); // See: https://github.com/Patternslib/Patterns/pull/539
- },
+ }
- _validateOptions: function (options) {
+ _validateOptions(options) {
var correct = [];
let logged_error = false;
@@ -85,9 +83,9 @@ export default Base.extend({
}
return correct;
- },
+ }
- _update: function (selector, remove, add) {
+ _update(selector, remove, add) {
const targets = document.querySelectorAll(selector);
for (const target of targets) {
if (remove) {
@@ -104,5 +102,9 @@ export default Base.extend({
dom: target,
});
}
- },
-});
+ }
+}
+
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/switch/switch.test.js b/src/pat/switch/switch.test.js
index fb6b15645..f1fef3266 100644
--- a/src/pat/switch/switch.test.js
+++ b/src/pat/switch/switch.test.js
@@ -1,15 +1,13 @@
-import pattern from "./switch";
+import Pattern from "./switch";
import $ from "jquery";
import { jest } from "@jest/globals";
-import utils from "../../core/utils";
+import events from "../../core/events";
describe("pat-switch", function () {
- beforeEach(function () {
- $("
", { id: "lab" }).appendTo(document.body);
- });
-
afterEach(function () {
document.body.innerHTML = "";
+ window.localStorage.clear();
+ jest.restoreAllMocks();
});
describe("When the switch is clicked", function () {
@@ -20,21 +18,19 @@ describe("pat-switch", function () {
href=""
class="pat-switch"
data-pat-switch="#lab on off">test
+
`;
const el = document.querySelector("a");
- const instance = new pattern(el);
- await utils.timeout(1);
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
const spy_go = jest.spyOn(instance, "_go");
- const ev = new Event("click");
- ev.tagName = "A";
- const spy_preventDefault = jest.spyOn(ev, "preventDefault");
-
+ const ev = new Event("click", { cancelable: true });
el.dispatchEvent(ev);
expect(spy_go).toHaveBeenCalled();
- expect(spy_preventDefault).toHaveBeenCalled();
+ expect(ev.defaultPrevented).toBe(true);
});
});
@@ -44,34 +40,50 @@ describe("pat-switch", function () {
test
+
`;
const el = document.querySelector("button");
- const instance = new pattern(el);
- await utils.timeout(1);
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
const spy_go = jest.spyOn(instance, "_go");
- const ev = new Event("click");
- ev.tagName = "BUTTON";
- const spy_preventDefault = jest.spyOn(ev, "preventDefault");
-
+ const ev = new Event("click", { cancelable: true });
el.dispatchEvent(ev);
expect(spy_go).toHaveBeenCalled();
- expect(spy_preventDefault).not.toHaveBeenCalled();
+ expect(ev.defaultPrevented).toBe(false);
});
});
+
+ it("adds and removes the classes", async function () {
+ document.body.innerHTML = `
+ test
+
+ `;
+ const el = document.querySelector("button");
+ const target = document.querySelector("#target");
+
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ el.click();
+ expect(target.classList.contains("foo")).toBe(false);
+ expect(target.classList.contains("bar")).toBe(true);
+ });
});
describe("_validateOptions", function () {
it("Bad options", function () {
- const instance = new pattern(document.createElement("div"));
+ const instance = new Pattern(document.createElement("div"));
const options = instance._validateOptions([{}]);
expect(options).toEqual([]);
});
it("Mix valid and invalid options", function () {
- const instance = new pattern(document.createElement("div"));
+ const instance = new Pattern(document.createElement("div"));
const options = instance._validateOptions([
{ selector: "#valid", add: "purple" },
{},
@@ -89,7 +101,7 @@ describe("pat-switch", function () {
document.body.innerHTML = `
`;
- const instance = new pattern(document.createElement("div"));
+ const instance = new Pattern(document.createElement("div"));
instance._update("body div", "on");
expect(document.querySelector("body div").classList.contains("on")).toBe(
false
@@ -100,14 +112,14 @@ describe("pat-switch", function () {
document.body.innerHTML = `
`;
- const instance = new pattern(document.createElement("div"));
+ const instance = new Pattern(document.createElement("div"));
instance._update("body div", "icon-*");
expect(document.querySelector("body div").getAttribute("class")).toBeFalsy();
});
it("Add class", function () {
document.body.innerHTML = "
";
- const instance = new pattern(document.createElement("div"));
+ const instance = new Pattern(document.createElement("div"));
instance._update("body div", null, "icon-alert");
expect(
document.querySelector("body div").classList.contains("icon-alert")
@@ -117,7 +129,7 @@ describe("pat-switch", function () {
it("Send pat-update event", function () {
document.body.innerHTML = "
";
const target = document.querySelector("body div");
- const instance = new pattern(document.createElement("div"));
+ const instance = new Pattern(document.createElement("div"));
const spy_trigger = jest.spyOn($.fn, "trigger");
instance._update("body div", null, "icon-alert");
expect(target.classList.contains("icon-alert")).toBe(true);
@@ -129,65 +141,57 @@ describe("pat-switch", function () {
});
});
- describe("jQuery plugin usage", function () {
- describe("Initialise via jQuery", function () {
- it("Specify defaults via API", async function () {
- document.body.innerHTML = `
- Click me
- `;
- $("body button").patternSwitch({
- selector: "#target",
- add: "pink",
- });
- await utils.timeout(1);
- const $trigger = $("body button");
- const instance = $trigger.data("pattern-switch");
- expect(instance.options).toEqual([
- { store: "none", selector: "#target", add: "pink" },
- ]);
- });
+ describe("JavaScript API usage", function () {
+ it("Specify defaults via API", async function () {
+ document.body.innerHTML = `
+ Click me
+ `;
+ const el = document.querySelector("button");
+ const instance = new Pattern(el, { selector: "#target", add: "pink" });
+ await events.await_pattern_init(instance);
+ expect(el["pattern-switch"]).toBe(instance);
+ expect(instance.options).toEqual([
+ { store: "none", selector: "#target", add: "pink" },
+ ]);
+ });
- it("Invalid defaults via API", async function () {
- document.body.innerHTML = `
- Click me
- `;
- $("body button").patternSwitch({ selector: "#target" });
- await utils.timeout(1);
- const $trigger = $("body button");
- const instance = $trigger.data("pattern-switch");
- expect(instance.options).toEqual([]);
- });
+ it("Invalid defaults via API", async function () {
+ document.body.innerHTML = `
+ Click me
+ `;
+ const el = document.querySelector("button");
+ const instance = new Pattern(el, { selector: "#target" });
+ await events.await_pattern_init(instance);
+ expect(instance.options).toEqual([]);
+ });
- it("Parse defaults from DOM", async function () {
- document.body.innerHTML = `
- Click me
- `;
- $("body button").patternSwitch();
- await utils.timeout(1);
- const $trigger = $("body button");
- const instance = $trigger.data("pattern-switch");
- expect(instance.options).toEqual([
- {
- store: "none",
- selector: "#target",
- remove: "foo",
- add: "bar",
- },
- ]);
- });
+ it("Parse defaults from DOM", async function () {
+ document.body.innerHTML = `
+ Click me
+ `;
+ const el = document.querySelector("button");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+ expect(instance.options).toEqual([
+ {
+ store: "none",
+ selector: "#target",
+ remove: "foo",
+ add: "bar",
+ },
+ ]);
+ });
- it("Setup click event handler", async function () {
- document.body.innerHTML = `
- Click me
- `;
- $("body button").patternSwitch();
- await utils.timeout(1);
- const $trigger = $("body button");
- const instance = $trigger.data("pattern-switch");
- const spy_go = jest.spyOn(instance, "_go").mockImplementation(() => {});
- $trigger.click();
- expect(spy_go).toHaveBeenCalled();
- });
+ it("Setup click event handler", async function () {
+ document.body.innerHTML = `
+ Click me
+ `;
+ const el = document.querySelector("button");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+ const spy_go = jest.spyOn(instance, "_go").mockImplementation(() => {});
+ el.click();
+ expect(spy_go).toHaveBeenCalled();
});
it("Execute changes via 'execute' API", async function () {
@@ -195,10 +199,10 @@ describe("pat-switch", function () {
Click me
ok
`;
- $("body button").patternSwitch();
- await utils.timeout(1);
- const $trigger = $("body button");
- $trigger.patternSwitch("execute");
+ const el = document.querySelector("button");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+ instance.execute();
expect($("#target").hasClass("foo")).toBe(false);
expect($("#target").hasClass("bar")).toBe(true);
});
@@ -208,13 +212,37 @@ describe("pat-switch", function () {
Click me
ok
`;
- $("body button").patternSwitch();
- await utils.timeout(1);
- const $trigger = $("body button");
- $trigger.patternSwitch("destroy");
- $trigger.click();
+ const el = document.querySelector("button");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+ instance.destroy();
+ expect(el["pattern-switch"]).toBeUndefined();
+ el.click();
expect($("#target").hasClass("foo")).toBe(true);
expect($("#target").hasClass("bar")).toBe(true);
});
});
+
+ describe("State storage", function () {
+ it("Restores the stored state on initialization.", async function () {
+ const markup = `
+ Click me
+
+ `;
+ document.body.innerHTML = markup;
+ let instance = new Pattern(document.querySelector("button"));
+ await events.await_pattern_init(instance);
+ document.querySelector("button").click();
+ expect(document.querySelector("#target").className).toBe("bar");
+
+ // Simulate a page reload.
+ document.body.innerHTML = markup;
+ instance = new Pattern(document.querySelector("button"));
+ await events.await_pattern_init(instance);
+ expect(document.querySelector("#target").className).toBe("bar");
+ });
+ });
});
diff --git a/src/pat/syntax-highlight/syntax-highlight--implementation.js b/src/pat/syntax-highlight/syntax-highlight--implementation.js
new file mode 100644
index 000000000..8b5e66c9e
--- /dev/null
+++ b/src/pat/syntax-highlight/syntax-highlight--implementation.js
@@ -0,0 +1,103 @@
+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("syntax-highlight");
+parser.addArgument("language", "html");
+parser.addArgument("theme", "dark", ["dark", "light"]);
+parser.addArgument("features", null, ["line-highlight", "line-numbers"], true);
+
+class Pattern extends BasePattern {
+ static name = "syntax-highlight";
+ static trigger = ".pat-syntax-highlight";
+ static parser = parser;
+
+ async init() {
+ let _el = this.el;
+ const code_el = [...this.el.children].filter((it) => it.tagName === "CODE")?.[0];
+ if (code_el) {
+ _el = code_el;
+ }
+
+ let theme;
+ if (
+ this.options.theme === "light" ||
+ _el.classList.contains("light-bg") ||
+ this.el.classList.contains("light-bg")
+ ) {
+ theme = "stackoverflow-light";
+ } else if (this.options.theme === "dark") {
+ theme = "stackoverflow-dark";
+ } else {
+ theme = this.options.theme;
+ }
+
+ // Map both spellings to one stylesheet so Webpack emits it once.
+ const theme_name = String(theme).replace(/\.min$/, "");
+ // Only top-level themes, no `base16/` subdirectory. Every file which
+ // could match becomes a chunk listed in the entry point's runtime.
+ import(
+ /* webpackInclude: /styles\/[^/]+\.css$/ */
+ /* webpackExclude: /\.min\.css$/ */
+ `highlight.js/styles/${theme_name}.css`
+ );
+ const hljs = (await import("highlight.js/lib/core")).default;
+
+ // Get the language
+ let language = [..._el.classList, ...this.el.classList]
+ .filter((it) => {
+ return it.startsWith("language-") || it.startsWith("lang-");
+ })?.[0]
+ ?.replace("language-", "")
+ ?.replace("lang-", "");
+ // CSS class language always win.
+ language = language || this.options.language || "html";
+ // Set the language on the code element (ignored if already set)
+ this.el.classList.add(`language-${language}`);
+ _el.classList.add(`language-${language}`);
+ _el.classList.add("hljs");
+
+ let high;
+ const value = utils.unescape_html(_el.innerHTML).trim();
+ if (language) {
+ try {
+ // language to import path mapping
+ const import_path_mapping = {
+ atom: "xml",
+ html: "xml",
+ plist: "xml",
+ rss: "xml",
+ svg: "xml",
+ wsf: "xml",
+ xhtml: "xml",
+ xjb: "xml",
+ xsd: "xml",
+ xsl: "xml",
+ };
+ const lang_file = import_path_mapping[language] || language;
+ const hljs_language = (
+ await import(
+ // Only the languages of highlight.js' "common" build.
+ // Every file which could match becomes a chunk listed
+ // in the entry point's runtime. Other languages fall
+ // back to `highlightAuto`.
+ /* webpackInclude: /languages\/(xml|bash|c|cpp|csharp|css|markdown|diff|ruby|go|graphql|ini|java|javascript|json|kotlin|less|lua|makefile|perl|objectivec|php|php-template|plaintext|python|python-repl|r|rust|scss|shell|sql|swift|yaml|typescript|vbnet|wasm)\.js$/ */
+ `highlight.js/lib/languages/${lang_file}`
+ )
+ ).default;
+ hljs.registerLanguage(language, hljs_language);
+ high = hljs.highlight(value, { language: language }).value;
+ } catch {
+ high = hljs.highlightAuto(value).value;
+ }
+ } else {
+ high = hljs.highlightAuto(value).value;
+ }
+ _el.innerHTML = high;
+ }
+}
+
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/syntax-highlight/syntax-highlight--implementation.test.js b/src/pat/syntax-highlight/syntax-highlight--implementation.test.js
new file mode 100644
index 000000000..41755b983
--- /dev/null
+++ b/src/pat/syntax-highlight/syntax-highlight--implementation.test.js
@@ -0,0 +1,56 @@
+import pattern from "./syntax-highlight--implementation";
+import utils from "../../core/utils";
+
+describe("pat-markdown", function () {
+ beforeEach(function () {
+ document.body.innerHTML = "";
+ });
+
+ afterEach(function () {
+ document.body.innerHTML = "";
+ });
+
+ describe("when initialized", function () {
+ it("it does syntax highlighting.", async function () {
+ document.body.innerHTML = `def foo():\n pass `;
+ new pattern(document.querySelector(".pat-syntax-highlight"));
+ await utils.timeout(1);
+ expect(
+ document.querySelector(".pat-syntax-highlight code .hljs-keyword")
+ ).toBeTruthy();
+ // Also adds the .hljs class to the wrapper
+ expect(
+ document.querySelector(".pat-syntax-highlight code.hljs")
+ ).toBeTruthy();
+ });
+
+ it("it does syntax highlighting on any element.", async function () {
+ document.body.innerHTML = `def foo():\n pass`;
+ new pattern(document.querySelector(".pat-syntax-highlight"));
+ await utils.timeout(1);
+ expect(
+ document.querySelector(".pat-syntax-highlight .hljs-keyword")
+ ).toBeTruthy();
+ // Also adds the .hljs class to the wrapper
+ expect(document.querySelector(".pat-syntax-highlight.hljs")).toBeTruthy();
+ });
+
+ it("it does syntax highlighting for html.", async function () {
+ // html code should be escaped for `<`,`>` and `&`.
+ document.body.innerHTML = `
+
+ <h1>foo</h1>
+
+ `;
+ new pattern(document.querySelector(".pat-syntax-highlight"));
+ await utils.timeout(1);
+ expect(
+ document.querySelector(".pat-syntax-highlight code .hljs-tag")
+ ).toBeTruthy();
+ // Also adds the .hljs class to the wrapper
+ expect(
+ document.querySelector(".pat-syntax-highlight code.hljs")
+ ).toBeTruthy();
+ });
+ });
+});
diff --git a/src/pat/syntax-highlight/syntax-highlight.js b/src/pat/syntax-highlight/syntax-highlight.js
index 8b5e66c9e..2862d6982 100644
--- a/src/pat/syntax-highlight/syntax-highlight.js
+++ b/src/pat/syntax-highlight/syntax-highlight.js
@@ -1,102 +1,19 @@
-import { BasePattern } from "../../core/basepattern";
-import Parser from "../../core/parser";
+/**
+ * pat-syntax-highlight 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:
+ * ./syntax-highlight--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("syntax-highlight");
-parser.addArgument("language", "html");
-parser.addArgument("theme", "dark", ["dark", "light"]);
-parser.addArgument("features", null, ["line-highlight", "line-numbers"], true);
-
-class Pattern extends BasePattern {
- static name = "syntax-highlight";
- static trigger = ".pat-syntax-highlight";
- static parser = parser;
-
- async init() {
- let _el = this.el;
- const code_el = [...this.el.children].filter((it) => it.tagName === "CODE")?.[0];
- if (code_el) {
- _el = code_el;
- }
-
- let theme;
- if (
- this.options.theme === "light" ||
- _el.classList.contains("light-bg") ||
- this.el.classList.contains("light-bg")
- ) {
- theme = "stackoverflow-light";
- } else if (this.options.theme === "dark") {
- theme = "stackoverflow-dark";
- } else {
- theme = this.options.theme;
- }
-
- // Map both spellings to one stylesheet so Webpack emits it once.
- const theme_name = String(theme).replace(/\.min$/, "");
- // Only top-level themes, no `base16/` subdirectory. Every file which
- // could match becomes a chunk listed in the entry point's runtime.
- import(
- /* webpackInclude: /styles\/[^/]+\.css$/ */
- /* webpackExclude: /\.min\.css$/ */
- `highlight.js/styles/${theme_name}.css`
- );
- const hljs = (await import("highlight.js/lib/core")).default;
-
- // Get the language
- let language = [..._el.classList, ...this.el.classList]
- .filter((it) => {
- return it.startsWith("language-") || it.startsWith("lang-");
- })?.[0]
- ?.replace("language-", "")
- ?.replace("lang-", "");
- // CSS class language always win.
- language = language || this.options.language || "html";
- // Set the language on the code element (ignored if already set)
- this.el.classList.add(`language-${language}`);
- _el.classList.add(`language-${language}`);
- _el.classList.add("hljs");
-
- let high;
- const value = utils.unescape_html(_el.innerHTML).trim();
- if (language) {
- try {
- // language to import path mapping
- const import_path_mapping = {
- atom: "xml",
- html: "xml",
- plist: "xml",
- rss: "xml",
- svg: "xml",
- wsf: "xml",
- xhtml: "xml",
- xjb: "xml",
- xsd: "xml",
- xsl: "xml",
- };
- const lang_file = import_path_mapping[language] || language;
- const hljs_language = (
- await import(
- // Only the languages of highlight.js' "common" build.
- // Every file which could match becomes a chunk listed
- // in the entry point's runtime. Other languages fall
- // back to `highlightAuto`.
- /* webpackInclude: /languages\/(xml|bash|c|cpp|csharp|css|markdown|diff|ruby|go|graphql|ini|java|javascript|json|kotlin|less|lua|makefile|perl|objectivec|php|php-template|plaintext|python|python-repl|r|rust|scss|shell|sql|swift|yaml|typescript|vbnet|wasm)\.js$/ */
- `highlight.js/lib/languages/${lang_file}`
- )
- ).default;
- hljs.registerLanguage(language, hljs_language);
- high = hljs.highlight(value, { language: language }).value;
- } catch {
- high = hljs.highlightAuto(value).value;
- }
- } else {
- high = hljs.highlightAuto(value).value;
- }
- _el.innerHTML = high;
- }
-}
+const Pattern = create_lazy_pattern({
+ name: "syntax-highlight",
+ trigger: ".pat-syntax-highlight",
+ load: () => import("./syntax-highlight--implementation"),
+});
registry.register(Pattern);
export default Pattern;
diff --git a/src/pat/syntax-highlight/syntax-highlight.test.js b/src/pat/syntax-highlight/syntax-highlight.test.js
index 22cd45fef..4391ea13a 100644
--- a/src/pat/syntax-highlight/syntax-highlight.test.js
+++ b/src/pat/syntax-highlight/syntax-highlight.test.js
@@ -1,56 +1,15 @@
-import pattern from "./syntax-highlight";
-import utils from "../../core/utils";
-
-describe("pat-markdown", function () {
- beforeEach(function () {
- document.body.innerHTML = "";
- });
-
- afterEach(function () {
- document.body.innerHTML = "";
+import Pattern from "./syntax-highlight";
+import Implementation from "./syntax-highlight--implementation";
+
+describe("pat-syntax-highlight 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("when initialized", function () {
- it("it does syntax highlighting.", async function () {
- document.body.innerHTML = `
def foo():\n pass`;
- new pattern(document.querySelector(".pat-syntax-highlight"));
- await utils.timeout(1);
- expect(
- document.querySelector(".pat-syntax-highlight code .hljs-keyword")
- ).toBeTruthy();
- // Also adds the .hljs class to the wrapper
- expect(
- document.querySelector(".pat-syntax-highlight code.hljs")
- ).toBeTruthy();
- });
-
- it("it does syntax highlighting on any element.", async function () {
- document.body.innerHTML = `
def foo():\n pass`;
- new pattern(document.querySelector(".pat-syntax-highlight"));
- await utils.timeout(1);
- expect(
- document.querySelector(".pat-syntax-highlight .hljs-keyword")
- ).toBeTruthy();
- // Also adds the .hljs class to the wrapper
- expect(document.querySelector(".pat-syntax-highlight.hljs")).toBeTruthy();
- });
-
- it("it does syntax highlighting for html.", async function () {
- // html code should be escaped for `<`,`>` and `&`.
- document.body.innerHTML = `
-
- <h1>foo</h1>
-
- `;
- new pattern(document.querySelector(".pat-syntax-highlight"));
- await utils.timeout(1);
- expect(
- document.querySelector(".pat-syntax-highlight code .hljs-tag")
- ).toBeTruthy();
- // Also adds the .hljs class to the wrapper
- expect(
- document.querySelector(".pat-syntax-highlight code.hljs")
- ).toBeTruthy();
- });
+ it("loads the implementation.", async function () {
+ expect(await Pattern.load()).toBe(Implementation);
});
});
diff --git a/src/pat/tabs/tabs.js b/src/pat/tabs/tabs.js
index b94384b5a..7949a0c32 100644
--- a/src/pat/tabs/tabs.js
+++ b/src/pat/tabs/tabs.js
@@ -1,6 +1,7 @@
import $ from "jquery";
-import Base from "../../core/base";
+import { BasePattern } from "../../core/basepattern";
import logging from "../../core/logging";
+import registry from "../../core/registry";
import utils from "../../core/utils";
import dom from "../../core/dom";
@@ -9,11 +10,11 @@ export const DEBOUNCE_TIMEOUT = 10;
//logger.setLevel(logging.Level.DEBUG);
-export default Base.extend({
- name: "tabs",
- trigger: ".pat-tabs",
- jquery_plugin: true,
- allowed_update_patterns: [
+class Pattern extends BasePattern {
+ static name = "tabs";
+ static trigger = ".pat-tabs";
+
+ allowed_update_patterns = [
"stacks",
"switch",
"auto-scale",
@@ -21,14 +22,17 @@ export default Base.extend({
"equaliser",
"masonry",
"zoom",
- ],
+ ];
+
+ resize_observer = null;
init() {
// debounce_resize to cancel previous runs of adjust_tabs
- const debounced_resize = utils.debounce(
- this.adjust_tabs.bind(this),
- DEBOUNCE_TIMEOUT
- );
+ const debounced_resize = utils.debounce(() => {
+ if (!this.destroyed) {
+ this.adjust_tabs();
+ }
+ }, DEBOUNCE_TIMEOUT);
// ResizeObserver allows for calling the adjust_tabs method after an
// animation is done, e.g. a menu is slided in. At the end of the
@@ -49,7 +53,10 @@ export default Base.extend({
// Also listen for ``pat-update`` event for cases where no resize but
// an immediate display of the element is done.
- $("body").on("pat-update", (e, data) => {
+ // ``pat-update`` is mostly triggered via jQuery, so we need a jQuery
+ // event handler. Use an instance specific namespace to be able to
+ // remove it on destroy.
+ $("body").on(`pat-update.pat-tabs--${this.uuid}`, (e, data) => {
if (this.allowed_update_patterns.includes(data?.pattern)) {
logger.debug("pat-update received.");
debounced_resize();
@@ -57,7 +64,13 @@ export default Base.extend({
});
debounced_resize();
- },
+ }
+
+ destroy() {
+ this.resize_observer?.disconnect();
+ $("body").off(`pat-update.pat-tabs--${this.uuid}`);
+ super.destroy();
+ }
async adjust_tabs() {
logger.debug("Entering adjust_tabs");
@@ -70,7 +83,7 @@ export default Base.extend({
this.dimensions = this._get_dimensions();
await this._adjust_tabs();
this.el.classList.add("tabs-ready");
- },
+ }
_flatten_tabs() {
// Remove the extra-tabs structure and place all tabs directly under .pat-tabs
@@ -79,7 +92,7 @@ export default Base.extend({
this.el.append(...extra_wrapper.children);
extra_wrapper.remove();
}
- },
+ }
_get_dimensions() {
const bounds = utils.get_bounds(this.el);
@@ -108,9 +121,13 @@ export default Base.extend({
logger.debug(dimensions);
return dimensions;
- },
+ }
async _adjust_tabs() {
+ if (this.destroyed) {
+ // Stop when the pattern was destroyed in the meantime.
+ return;
+ }
logger.debug("Entering _adjust_tabs");
const children = [...this.el.children].filter(
(it) =>
@@ -200,5 +217,9 @@ export default Base.extend({
await utils.animation_frame();
await this._adjust_tabs();
- },
-});
+ }
+}
+
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/tabs/tabs.test.js b/src/pat/tabs/tabs.test.js
index 990744f4e..c49553075 100644
--- a/src/pat/tabs/tabs.test.js
+++ b/src/pat/tabs/tabs.test.js
@@ -1,7 +1,24 @@
-import pattern, { DEBOUNCE_TIMEOUT } from "./tabs";
+import $ from "jquery";
+import Pattern, { DEBOUNCE_TIMEOUT } from "./tabs";
+import events from "../../core/events";
import utils from "../../core/utils";
describe("pat-tabs", function () {
+ const OriginalResizeObserver = global.ResizeObserver;
+
+ beforeAll(function () {
+ // The ResizeObserver mock from @patternslib/dev has no disconnect method.
+ global.ResizeObserver = class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ };
+ });
+
+ afterAll(function () {
+ global.ResizeObserver = OriginalResizeObserver;
+ });
+
afterEach(function () {
jest.restoreAllMocks();
document.body.innerHTML = "";
@@ -28,7 +45,8 @@ describe("pat-tabs", function () {
jest.spyOn(tabs[3], "getBoundingClientRect").mockImplementation(() => { return { x: 100, width: 40 }; }); // prettier-ignore
expect(nav.classList.contains("tabs-ready")).toBeFalsy();
- pattern.init(nav);
+ const instance = new Pattern(nav);
+ await events.await_pattern_init(instance);
await utils.timeout(DEBOUNCE_TIMEOUT);
expect(nav.querySelector(".extra-tabs")).toBeTruthy();
@@ -69,7 +87,8 @@ describe("pat-tabs", function () {
jest.spyOn(tabs[3], "getBoundingClientRect").mockImplementation(() => { return { x: 400, width: 40 }; }); // prettier-ignore
expect(nav.classList.contains("tabs-ready")).toBeFalsy();
- pattern.init(nav);
+ const instance = new Pattern(nav);
+ await events.await_pattern_init(instance);
await utils.timeout(DEBOUNCE_TIMEOUT);
expect(nav.querySelector(".extra-tabs")).toBeTruthy();
@@ -108,7 +127,8 @@ describe("pat-tabs", function () {
jest.spyOn(tabs[3], "getBoundingClientRect").mockImplementation(() => { return { x: 400, width: 40 }; }); // prettier-ignore
expect(nav.classList.contains("tabs-ready")).toBeFalsy();
- pattern.init(nav);
+ const instance = new Pattern(nav);
+ await events.await_pattern_init(instance);
await utils.timeout(DEBOUNCE_TIMEOUT);
expect(nav.querySelector(".extra-tabs")).toBeFalsy();
@@ -137,7 +157,8 @@ describe("pat-tabs", function () {
jest.spyOn(tabs[3], "getBoundingClientRect").mockImplementation(() => { return { x: 100, width: 40 }; }); // prettier-ignore
expect(nav.classList.contains("tabs-ready")).toBeFalsy();
- pattern.init(nav);
+ const instance = new Pattern(nav);
+ await events.await_pattern_init(instance);
await utils.timeout(DEBOUNCE_TIMEOUT);
expect(nav.querySelector(".extra-tabs")).toBeTruthy();
@@ -176,7 +197,8 @@ describe("pat-tabs", function () {
jest.spyOn(tabs[0], "getBoundingClientRect").mockImplementation(() => { return { x: 100, width: 40 }; }); // prettier-ignore
jest.spyOn(tabs[1], "getBoundingClientRect").mockImplementation(() => { return { x: 100, width: 40 }; }); // prettier-ignore
- pattern.init(nav);
+ const instance = new Pattern(nav);
+ await events.await_pattern_init(instance);
await utils.timeout(DEBOUNCE_TIMEOUT);
const extra_tabs = nav.querySelector(".extra-tabs");
@@ -209,7 +231,8 @@ describe("pat-tabs", function () {
jest.spyOn(tabs[0], "getBoundingClientRect").mockImplementation(() => { return { x: 100, width: 40 }; }); // prettier-ignore
jest.spyOn(tabs[1], "getBoundingClientRect").mockImplementation(() => { return { x: 200, width: 40 }; }); // prettier-ignore
- pattern.init(nav);
+ const instance = new Pattern(nav);
+ await events.await_pattern_init(instance);
await utils.timeout(DEBOUNCE_TIMEOUT);
const extra_tabs = nav.querySelector(".extra-tabs");
@@ -222,7 +245,8 @@ describe("pat-tabs", function () {
document.body.innerHTML = `
`;
const nav = document.querySelector(".pat-tabs");
- const pat = pattern.init(nav);
+ const pat = new Pattern(nav);
+ await events.await_pattern_init(pat);
const spy_adjust_tabs = jest
.spyOn(pat, "adjust_tabs")
.mockImplementation(() => {});
@@ -259,7 +283,8 @@ describe("pat-tabs", function () {
jest.spyOn(tabs[3], "getBoundingClientRect").mockImplementation(() => { return { x: 100, width: 40 }; }); // prettier-ignore
expect(nav.classList.contains("tabs-ready")).toBeFalsy();
- const pat = pattern.init(nav);
+ const pat = new Pattern(nav);
+ await events.await_pattern_init(pat);
const spy_get_dimensions = jest.spyOn(pat, "_get_dimensions");
await utils.timeout(DEBOUNCE_TIMEOUT);
@@ -306,7 +331,8 @@ describe("pat-tabs", function () {
jest.spyOn(tabs[3], "getBoundingClientRect").mockImplementation(() => { return { x: 100, width: 200 }; }); // prettier-ignore
expect(nav.classList.contains("tabs-ready")).toBeFalsy();
- const pat = pattern.init(nav);
+ const pat = new Pattern(nav);
+ await events.await_pattern_init(pat);
await utils.timeout(DEBOUNCE_TIMEOUT);
// make .extra-tabs wider than available space, which result in an infinite loop in a previous version of this code.
@@ -327,8 +353,8 @@ describe("pat-tabs", function () {
let thrown = false;
try {
- pattern.init(el.querySelector("div"));
- await utils.timeout(1);
+ const instance = new Pattern(el.querySelector("div"));
+ await events.await_pattern_init(instance);
document.body.dispatchEvent(new Event("pat-update"));
await utils.timeout(1);
} catch (e) {
@@ -340,4 +366,81 @@ describe("pat-tabs", function () {
}
expect(thrown).toBe(false);
});
+
+ describe("11 - Destroy", () => {
+ it("11.1 - Reacts on pat-update events until destroyed.", async () => {
+ document.body.innerHTML = `
`;
+ const nav = document.querySelector(".pat-tabs");
+
+ const instance = new Pattern(nav);
+ await events.await_pattern_init(instance);
+ await utils.timeout(DEBOUNCE_TIMEOUT);
+
+ const spy_adjust_tabs = jest.spyOn(instance, "adjust_tabs");
+
+ $(document.body).trigger("pat-update", { pattern: "switch" });
+ await utils.timeout(DEBOUNCE_TIMEOUT);
+ expect(spy_adjust_tabs).toHaveBeenCalledTimes(1);
+
+ // Not allowed pattern.
+ $(document.body).trigger("pat-update", { pattern: "toggle" });
+ await utils.timeout(DEBOUNCE_TIMEOUT);
+ expect(spy_adjust_tabs).toHaveBeenCalledTimes(1);
+
+ instance.destroy();
+ expect(nav["pattern-tabs"]).toBeUndefined();
+
+ $(document.body).trigger("pat-update", { pattern: "switch" });
+ await utils.timeout(DEBOUNCE_TIMEOUT);
+ expect(spy_adjust_tabs).toHaveBeenCalledTimes(1);
+ });
+
+ it("11.2 - Does not remove the pat-update handlers of other instances.", async () => {
+ document.body.innerHTML = `
+
+
+ `;
+ const instance1 = new Pattern(document.querySelector(".tabs1"));
+ const instance2 = new Pattern(document.querySelector(".tabs2"));
+ await events.await_pattern_init(instance1);
+ await events.await_pattern_init(instance2);
+ await utils.timeout(DEBOUNCE_TIMEOUT);
+
+ const spy_adjust_tabs_2 = jest.spyOn(instance2, "adjust_tabs");
+ instance1.destroy();
+
+ $(document.body).trigger("pat-update", { pattern: "switch" });
+ await utils.timeout(DEBOUNCE_TIMEOUT);
+ expect(spy_adjust_tabs_2).toHaveBeenCalledTimes(1);
+ });
+
+ it("11.3 - Disconnects the ResizeObserver.", async () => {
+ document.body.innerHTML = `
`;
+ const nav = document.querySelector(".pat-tabs");
+
+ const instance = new Pattern(nav);
+ await events.await_pattern_init(instance);
+ const spy_disconnect = jest.spyOn(instance.resize_observer, "disconnect");
+
+ nav.remove();
+ await utils.timeout(1);
+
+ expect(instance.destroyed).toBe(true);
+ expect(spy_disconnect).toHaveBeenCalled();
+ });
+
+ it("11.4 - Does not adjust the tabs after being destroyed.", async () => {
+ document.body.innerHTML = `
`;
+ const nav = document.querySelector(".pat-tabs");
+
+ const instance = new Pattern(nav);
+ const spy_adjust_tabs = jest.spyOn(instance, "adjust_tabs");
+ await events.await_pattern_init(instance);
+
+ // The initial adjustment is debounced and not yet run.
+ instance.destroy();
+ await utils.timeout(DEBOUNCE_TIMEOUT);
+ expect(spy_adjust_tabs).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/src/pat/toggle/toggle.js b/src/pat/toggle/toggle.js
index 5a75fa879..285f0bbc2 100644
--- a/src/pat/toggle/toggle.js
+++ b/src/pat/toggle/toggle.js
@@ -4,9 +4,10 @@
* Copyright 2012-2014 Simplon B.V. - Wichert Akkerman
*/
import $ from "jquery";
-import Base from "../../core/base";
+import { BasePattern } from "../../core/basepattern";
import logging from "../../core/logging";
import Parser from "../../core/parser";
+import registry from "../../core/registry";
import store from "../../core/store";
import utils from "../../core/utils";
@@ -90,12 +91,16 @@ AttributeToggler.prototype.next = function (value) {
return !value;
};
-export default Base.extend({
- name: "toggle",
- trigger: ".pat-toggle",
+class Pattern extends BasePattern {
+ static name = "toggle";
+ static trigger = ".pat-toggle";
+ static parser = parser;
+
+ parser_multiple = true;
init() {
- const options = this._validateOptions(parser.parse(this.$el, true));
+ this.$el = $(this.el);
+ const options = this._validateOptions(this.options);
this.options = options;
if (!options.length) {
@@ -129,14 +134,23 @@ export default Base.extend({
// Using debounce, we prevent double-toggle which would result in
// toggling having no effect.
this.click_debouncer = utils.debounce(() => {
+ if (this.destroyed) {
+ return;
+ }
this._onClick();
}, 1);
+ // Keep jQuery event handling, so that events triggered via jQuery
+ // (e.g. custom events) are still handled.
this.$el
.off(".toggle")
- .on(`${event_name || "click"}.toggle`, () => this.click_debouncer())
- .on("keypress.toggle", this._onKeyPress.bind(this));
- },
+ .on(`${event_name || "click"}.toggle`, () => this.click_debouncer());
+ }
+
+ destroy() {
+ this.$el?.off(".toggle");
+ super.destroy();
+ }
_makeToggler(option) {
if (option.attr === "class") {
@@ -146,7 +160,7 @@ export default Base.extend({
} else {
return new AttributeToggler(option.attr);
}
- },
+ }
_validateOptions(options) {
const correct = [];
@@ -195,7 +209,7 @@ export default Base.extend({
correct.push(option);
}
return correct;
- },
+ }
_onClick() {
for (const option of this.options) {
@@ -212,12 +226,9 @@ export default Base.extend({
option.value_storage.set(next_state);
}
}
- },
+ }
+}
- _onKeyPress(event) {
- const keycode = event.keyCode ? event.keyCode : event.which;
- if (keycode === "13") {
- this.$el.trigger("click");
- }
- },
-});
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/toggle/toggle.test.js b/src/pat/toggle/toggle.test.js
index 715c48d00..b7a60ea94 100644
--- a/src/pat/toggle/toggle.test.js
+++ b/src/pat/toggle/toggle.test.js
@@ -1,5 +1,6 @@
import $ from "jquery";
import Pattern, { ClassToggler, AttributeToggler } from "./toggle";
+import events from "../../core/events";
import utils from "../../core/utils";
describe("pat-toggle", function () {
@@ -206,7 +207,7 @@ describe("Pattern implementation", function () {
});
describe("2 - When clicking on a toggle", function () {
- var lab, trigger, victims;
+ let lab, trigger, victims;
beforeEach(function () {
lab = document.createElement("div");
@@ -216,8 +217,8 @@ describe("Pattern implementation", function () {
trigger.className = "pat-toggle";
lab.appendChild(trigger);
victims = [];
- for (var i = 1; i < 3; i++) {
- var v = document.createElement("input");
+ for (let i = 1; i < 3; i++) {
+ const v = document.createElement("input");
v.id = "victim" + i;
v.className = "victim";
lab.appendChild(v);
@@ -227,14 +228,15 @@ describe("Pattern implementation", function () {
});
afterEach(function () {
- document.body.removeChild(lab);
+ document.body.innerHTML = "";
});
it("2.1 - the class is toggled", async function () {
- var $trigger = $(trigger);
+ const $trigger = $(trigger);
$(victims).addClass("foo");
trigger.dataset.patToggle = ".victim; value: foo bar";
- new Pattern($trigger);
+ const instance = new Pattern(trigger);
+ await events.await_pattern_init(instance);
$trigger.click();
await utils.timeout(1);
expect(victims[0].className).toBe("victim bar");
@@ -244,9 +246,10 @@ describe("Pattern implementation", function () {
});
it("2.2 - attributes are updated", async function () {
- var $trigger = $(trigger);
+ const $trigger = $(trigger);
trigger.dataset.patToggle = ".victim; attr: disabled";
- new Pattern($trigger);
+ const instance = new Pattern(trigger);
+ await events.await_pattern_init(instance);
$trigger.click();
await utils.timeout(1);
expect(victims[0].disabled).toBe(true);
@@ -256,9 +259,10 @@ describe("Pattern implementation", function () {
});
it("2.3 - attributes are updated - use the alias", async function () {
- var $trigger = $(trigger);
+ const $trigger = $(trigger);
trigger.dataset.patToggle = ".victim; attribute: disabled";
- new Pattern($trigger);
+ const instance = new Pattern(trigger);
+ await events.await_pattern_init(instance);
$trigger.click();
await utils.timeout(1);
expect(victims[0].disabled).toBe(true);
@@ -266,24 +270,41 @@ describe("Pattern implementation", function () {
await utils.timeout(1);
expect(victims[0].disabled).toBe(false);
});
+
+ it("2.4 - multiple toggles can be defined", async function () {
+ trigger.dataset.patToggle =
+ ".victim; value: foo && #victim1; attr: disabled";
+ const instance = new Pattern(trigger);
+ await events.await_pattern_init(instance);
+ expect(instance.options.length).toBe(2);
+ trigger.click();
+ await utils.timeout(1);
+ expect(victims[0].classList.contains("foo")).toBe(true);
+ expect(victims[1].classList.contains("foo")).toBe(true);
+ expect(victims[0].disabled).toBe(true);
+ expect(victims[1].disabled).toBe(false);
+ });
});
describe("3 - Toggle event triggers", function () {
+ afterEach(function () {
+ document.body.innerHTML = "";
+ });
+
it("3.1 - by default on click event", async function () {
- $(
- "" +
- '
"
- ).appendTo(document.body);
+ document.body.innerHTML = `
+
+ `;
expect($(".toggled").length).toEqual(0);
- new Pattern($(".pat-toggle"));
+ const instance = new Pattern(document.querySelector(".pat-toggle"));
+ await events.await_pattern_init(instance);
expect($(".toggled").length).toEqual(0);
$(".pat-toggle").click();
@@ -295,21 +316,19 @@ describe("Pattern implementation", function () {
});
it("3.2 - can also listen to custom event", async function () {
- $(
- "" +
- '
"
- ).appendTo(document.body);
+ document.body.innerHTML = `
+
+ `;
expect($(".toggled").length).toEqual(0);
- new Pattern($(".pat-toggle"));
- await utils.timeout(1);
+ const instance = new Pattern(document.querySelector(".pat-toggle"));
+ await events.await_pattern_init(instance);
expect($(".toggled").length).toEqual(0);
$(".pat-toggle").trigger("onmouseenter");
@@ -331,8 +350,8 @@ describe("Pattern implementation", function () {
-
-
+
+
`;
const pattern_checklist = (await import("../checklist/checklist")).default;
@@ -341,9 +360,10 @@ describe("Pattern implementation", function () {
const el_target = document.querySelector("#target");
const el_checkbox = document.querySelector("input");
- new Pattern(el_label);
- new pattern_checklist(el_label);
- await utils.timeout(1);
+ const instance_toggle = new Pattern(el_label);
+ const instance_checklist = new pattern_checklist(el_label);
+ await events.await_pattern_init(instance_toggle);
+ await events.await_pattern_init(instance_checklist);
$(el_label).click();
await utils.timeout(1);
@@ -360,4 +380,88 @@ describe("Pattern implementation", function () {
expect(el_checkbox.checked).toBe(false);
});
});
+
+ describe("5 - State storage", function () {
+ afterEach(function () {
+ document.body.innerHTML = "";
+ window.localStorage.clear();
+ });
+
+ it("5.1 - stores the state and restores it on initialization.", async function () {
+ const markup = `
+
toggle
+
+ `;
+ document.body.innerHTML = markup;
+
+ let instance = new Pattern(document.querySelector(".pat-toggle"));
+ await events.await_pattern_init(instance);
+ document.querySelector(".pat-toggle").click();
+ await utils.timeout(1);
+ expect(document.querySelector("#target").classList.contains("open")).toBe(
+ true
+ );
+
+ // Simulate a page reload.
+ document.body.innerHTML = markup;
+ expect(document.querySelector("#target").classList.contains("open")).toBe(
+ false
+ );
+ instance = new Pattern(document.querySelector(".pat-toggle"));
+ await events.await_pattern_init(instance);
+ expect(document.querySelector("#target").classList.contains("open")).toBe(
+ true
+ );
+ });
+ });
+
+ describe("6 - Destroy", function () {
+ afterEach(function () {
+ document.body.innerHTML = "";
+ });
+
+ it("6.1 - does not toggle anymore after being destroyed.", async function () {
+ document.body.innerHTML = `
+
toggle
+
+ `;
+ const el = document.querySelector(".pat-toggle");
+ const target = document.querySelector("#target");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+ expect(el["pattern-toggle"]).toBe(instance);
+
+ instance.destroy();
+ expect(el["pattern-toggle"]).toBeUndefined();
+ el.click();
+ await utils.timeout(1);
+ expect(target.classList.contains("open")).toBe(false);
+ });
+
+ it("6.2 - does not run a pending toggle after being destroyed.", async function () {
+ document.body.innerHTML = `
+
toggle
+
+ `;
+ const el = document.querySelector(".pat-toggle");
+ const target = document.querySelector("#target");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ el.click();
+ instance.destroy();
+ await utils.timeout(1);
+ expect(target.classList.contains("open")).toBe(false);
+ });
+ });
});
diff --git a/src/pat/tooltip/tooltip.js b/src/pat/tooltip/tooltip.js
index 516780d7a..870aa400f 100644
--- a/src/pat/tooltip/tooltip.js
+++ b/src/pat/tooltip/tooltip.js
@@ -458,7 +458,8 @@ class Pattern extends BasePattern {
return text;
}
- const instance = new Markdown($("
"));
+ // Await the instance, as the pattern might be loaded lazily.
+ const instance = await new Markdown($("
"));
await events.await_pattern_init(instance);
const cfg = { url };
diff --git a/src/pat/tooltip/tooltip.test.js b/src/pat/tooltip/tooltip.test.js
index 1c56b9dfd..32d917a75 100644
--- a/src/pat/tooltip/tooltip.test.js
+++ b/src/pat/tooltip/tooltip.test.js
@@ -1,5 +1,5 @@
import $ from "jquery";
-import autosubmit from "../auto-submit/auto-submit";
+import autosubmit from "../auto-submit/auto-submit--implementation";
import { BasePattern } from "../../core/basepattern";
import events, { event_listener_map } from "../../core/events";
import lifecycle from "../../core/lifecycle";
@@ -1677,7 +1677,8 @@ this will be extracted.
const instance = new Pattern($el);
await events.await_pattern_init(instance);
- const instance2 = new autosubmit($(form));
+ const instance2 = new autosubmit(form);
+ await events.await_pattern_init(instance2);
const spy_handler1 = jest.spyOn(instance2, "refreshListeners");
const spy_handler2 = jest.spyOn(instance2, "onInputChange");
diff --git a/src/pat/validation/validation.test.js b/src/pat/validation/validation.test.js
index 5159a35b6..7c00fb695 100644
--- a/src/pat/validation/validation.test.js
+++ b/src/pat/validation/validation.test.js
@@ -351,7 +351,7 @@ describe("pat-validation", function () {
it("1.15 - Prevents pat-modal closing with a pat-inject when invalid.", async function () {
await import("../close-panel/close-panel");
const pat_inject = (await import("../inject/inject")).default;
- const pat_modal = (await import("../modal/modal")).default;
+ const pat_modal = (await import("../modal/modal--implementation")).default;
const registry = (await import("../../core/registry")).default;
document.body.innerHTML = `
@@ -365,7 +365,7 @@ describe("pat-validation", function () {
const el = document.querySelector("form");
const spy_inject_submit = jest.spyOn(pat_inject, "onTrigger");
- const spy_destroy_modal = jest.spyOn(pat_modal.prototype, "destroy");
+ const spy_close_modal = jest.spyOn(pat_modal.prototype, "close");
registry.scan(document.body);
await utils.timeout(1); // wait a tick for async to settle.
@@ -375,12 +375,12 @@ describe("pat-validation", function () {
expect(el.querySelectorAll("em.warning").length).toBe(1);
expect(spy_inject_submit).not.toHaveBeenCalled();
- expect(spy_destroy_modal).not.toHaveBeenCalled();
+ expect(spy_close_modal).not.toHaveBeenCalled();
});
it("1.16 - Prevents pat-modal closing when invalid.", async function () {
await import("../close-panel/close-panel");
- const pat_modal = (await import("../modal/modal")).default;
+ const pat_modal = (await import("../modal/modal--implementation")).default;
const registry = (await import("../../core/registry")).default;
document.body.innerHTML = `
@@ -393,7 +393,7 @@ describe("pat-validation", function () {
`;
const el = document.querySelector("form");
- const spy_destroy_modal = jest.spyOn(pat_modal.prototype, "destroy");
+ const spy_close_modal = jest.spyOn(pat_modal.prototype, "close");
registry.scan(document.body);
await utils.timeout(1); // wait a tick for async to settle.
@@ -403,15 +403,15 @@ describe("pat-validation", function () {
await utils.timeout(1); // wait a tick for async to settle.
expect(el.querySelectorAll("em.warning").length).toBe(1);
- expect(spy_destroy_modal).not.toHaveBeenCalled();
+ expect(spy_close_modal).not.toHaveBeenCalled();
});
it("1.17 - Prevents pat-modal closing when invalid with custom validation rule.", async function () {
await import("../close-panel/close-panel");
- const pat_modal = (await import("../modal/modal")).default;
+ const pat_modal = (await import("../modal/modal--implementation")).default;
const registry = (await import("../../core/registry")).default;
- const spy_destroy_modal = jest.spyOn(pat_modal.prototype, "destroy");
+ const spy_close_modal = jest.spyOn(pat_modal.prototype, "close");
document.body.innerHTML = `
@@ -435,13 +435,13 @@ describe("pat-validation", function () {
await utils.timeout(1); // wait a tick for async to settle.
expect(el.querySelectorAll("em.warning").length).toBe(1);
- expect(spy_destroy_modal).not.toHaveBeenCalled();
+ expect(spy_close_modal).not.toHaveBeenCalled();
// A non-submit close-panel button does not check for validity.
el.querySelector("button.cancel").click();
await utils.timeout(1); // wait a tick for async to settle.
- expect(spy_destroy_modal).toHaveBeenCalled();
+ expect(spy_close_modal).toHaveBeenCalled();
});
it("1.18 - validates all inputs after submit", async function () {
diff --git a/src/pat/zoom/zoom.js b/src/pat/zoom/zoom.js
index 57bc863af..9334b887c 100644
--- a/src/pat/zoom/zoom.js
+++ b/src/pat/zoom/zoom.js
@@ -1,4 +1,4 @@
-import $ from "jquery";
+import { BasePattern } from "../../core/basepattern";
import registry from "../../core/registry";
import Parser from "../../core/parser";
@@ -6,32 +6,37 @@ export const parser = new Parser("zoom");
parser.addArgument("min", 0);
parser.addArgument("max", 2);
-var zoom = {
- name: "zoom",
- trigger: ".pat-zoom",
+class Pattern extends BasePattern {
+ static name = "zoom";
+ static trigger = ".pat-zoom";
+ static parser = parser;
- init: function ($el, opts) {
- return $el.each(function () {
- const $block = $(this);
- const options = parser.parse($block, opts);
+ slider = null;
- const $slider = $("
", {
- type: "range",
- step: "any",
- value: 1,
- min: options.min,
- max: options.max,
- });
+ init() {
+ this.slider = document.createElement("input");
+ this.slider.type = "range";
+ this.slider.step = "any";
+ this.slider.min = this.options.min;
+ this.slider.max = this.options.max;
+ this.slider.value = 1;
+ this.el.before(this.slider);
- $slider.insertBefore($block).on("change input", null, $block, zoom.onZoom);
- });
- },
+ for (const event_type of ["change", "input"]) {
+ this.add_event_listener(
+ this.slider,
+ event_type,
+ `zoom-on-${event_type}`,
+ () => this.zoom(),
+ );
+ }
+ }
- onZoom: function (event) {
- const $block = event.data;
- $block.css("zoom", this.value);
- },
-};
+ zoom() {
+ this.el.style.zoom = this.slider.value;
+ }
+}
-registry.register(zoom);
-export default zoom;
+registry.register(Pattern);
+export default Pattern;
+export { Pattern };
diff --git a/src/pat/zoom/zoom.test.js b/src/pat/zoom/zoom.test.js
index 9c1133d52..266087630 100644
--- a/src/pat/zoom/zoom.test.js
+++ b/src/pat/zoom/zoom.test.js
@@ -1,48 +1,88 @@
-import pattern from "./zoom";
-import $ from "jquery";
+import Pattern from "./zoom";
+import events from "../../core/events";
+import utils from "../../core/utils";
describe("pat-zoom", function () {
- beforeEach(function () {
- $("
", { id: "lab" }).appendTo(document.body);
- });
-
afterEach(function () {
- $("#lab").remove();
+ document.body.innerHTML = "";
});
describe("init", function () {
- it("Create default range input", function () {
- $("#lab").append("
");
- var $block = $("#lab div");
- pattern.init($block);
- var $range = $block.prev();
- expect($range.length).toBe(1);
- expect($range[0].min).toBe("0");
- expect($range[0].max).toBe("2");
- expect($range[0].value).toBe("1");
+ it("Create default range input", async function () {
+ document.body.innerHTML = `
`;
+ const el = document.querySelector(".pat-zoom");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ expect(el["pattern-zoom"]).toBe(instance);
+ const range = el.previousElementSibling;
+ expect(range).toBe(instance.slider);
+ expect(range.type).toBe("range");
+ expect(range.step).toBe("any");
+ expect(range.min).toBe("0");
+ expect(range.max).toBe("2");
+ expect(range.value).toBe("1");
});
- it("Tweak ranges", function () {
- $("#lab").append("
");
- var $block = $("#lab div");
- pattern.init($block, { min: 0.5, max: 5 });
- var $range = $block.prev();
- expect($range[0].min).toBe("0.5");
- expect($range[0].max).toBe("5");
- expect($range[0].value).toBe("1");
+ it("Tweak ranges via options", async function () {
+ document.body.innerHTML = `
`;
+ const el = document.querySelector(".pat-zoom");
+ const instance = new Pattern(el, { min: 0.5, max: 5 });
+ await events.await_pattern_init(instance);
+
+ const range = el.previousElementSibling;
+ expect(range.min).toBe("0.5");
+ expect(range.max).toBe("5");
+ expect(range.value).toBe("1");
+ });
+
+ it("Tweak ranges via data attributes", async function () {
+ document.body.innerHTML = `
+
+ `;
+ const el = document.querySelector(".pat-zoom");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ const range = el.previousElementSibling;
+ expect(range.min).toBe("1");
+ expect(range.max).toBe("3");
});
});
describe("Integration tests", function () {
- it("Zoom in", function () {
- $("#lab").append("
");
- var $block = $("#lab div");
- pattern.init($block);
- var $range = $block.prev();
- $range.val("1.5");
- $range.trigger("change");
- // Fairly lax test so it passes in different browsers.
- expect($block.css("zoom")).toBe("1.5");
+ it("Zoom in on change and input events", async function () {
+ document.body.innerHTML = `
`;
+ const el = document.querySelector(".pat-zoom");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ const range = el.previousElementSibling;
+ range.value = "1.5";
+ range.dispatchEvent(new Event("change"));
+ expect(el.style.zoom).toBe("1.5");
+
+ range.value = "1.75";
+ range.dispatchEvent(new Event("input"));
+ expect(el.style.zoom).toBe("1.75");
+ });
+
+ it("Does not zoom anymore after destroy", async function () {
+ document.body.innerHTML = `
`;
+ const el = document.querySelector(".pat-zoom");
+ const instance = new Pattern(el);
+ await events.await_pattern_init(instance);
+
+ const range = instance.slider;
+ el.remove();
+ await utils.timeout(1); // wait for the automatic destroy.
+
+ expect(instance.destroyed).toBe(true);
+ expect(el["pattern-zoom"]).toBeUndefined();
+
+ range.value = "1.5";
+ range.dispatchEvent(new Event("input"));
+ expect(el.style.zoom).not.toBe("1.5");
});
});
});