Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upgrade DOM bricks to be root aware #4910

Merged
merged 8 commits into from
Jan 2, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 125 additions & 0 deletions src/blocks/effects/attachAutocomplete.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/*
* Copyright (C) 2022 PixieBrix, Inc.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please update the year

*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

/*
* Copyright (C) 2022 PixieBrix, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

/*
* Copyright (C) 2022 PixieBrix, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import { unsafeAssumeValidArg } from "@/runtime/runtimeTypes";
import ConsoleLogger from "@/utils/ConsoleLogger";
import { uuidSequence } from "@/testUtils/factories";
import { type BlockOptions } from "@/core";
import { AttachAutocomplete } from "@/blocks/effects/attachAutocomplete";

const brick = new AttachAutocomplete();

const logger = new ConsoleLogger({
extensionId: uuidSequence(0),
});

jest.mock("@/utils/injectStylesheet", () => ({
default: jest.fn(),
__esModule: true,
}));

describe("AttachAutocomplete", () => {
beforeEach(() => {
document.body.innerHTML = `
<html>
<body>
<div id="noForm"></div>
<div id="hasForm">
<form>
<input type="text" name="name" value="John Doe" />
</form>
</div>
</body>
</html>
`;
});

test("isRootAware", async () => {
await expect(brick.isRootAware()).resolves.toBe(true);
});

test("it attaches autocomplete", async () => {
await brick.run(unsafeAssumeValidArg({ selector: "[name='name']" }), {
root: document,
logger,
} as unknown as BlockOptions);

expect(
document.querySelector("[name='name']").getAttribute("role")
).toEqual("combobox");
});

test("it is root aware", async () => {
await brick.run(
unsafeAssumeValidArg({ selector: "[name='name']", isRootAware: true }),
{
root: document.querySelector("#noForm"),
logger,
} as unknown as BlockOptions
);

expect(
document.querySelector("[name='name']").getAttribute("role")
).toBeNull();

await brick.run(
unsafeAssumeValidArg({ selector: "[name='name']", isRootAware: true }),
{
root: document.querySelector("#hasForm"),
logger,
} as unknown as BlockOptions
);

expect(
document.querySelector("[name='name']").getAttribute("role")
).toEqual("combobox");
});
});
42 changes: 32 additions & 10 deletions src/blocks/effects/attachAutocomplete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@ import { Effect } from "@/types";
import { type BlockArg, type BlockOptions, type Schema } from "@/core";
import { propertiesToSchema } from "@/validators/generic";
import { type AutocompleteItem } from "autocompleter";

import {
$safeFindElementsWithRootMode,
IS_ROOT_AWARE_BRICK_PROPS,
} from "@/blocks/rootModeHelpers";
import autocompleterStyleUrl from "autocompleter/autocomplete.css?loadAsUrl";
import injectStylesheet from "@/utils/injectStylesheet";
import { $safeFind } from "@/helpers";

export class AttachAutocomplete extends Effect {
constructor() {
Expand All @@ -33,6 +35,10 @@ export class AttachAutocomplete extends Effect {
);
}

override async isRootAware(): Promise<boolean> {
return true;
}

inputSchema: Schema = propertiesToSchema(
{
selector: {
Expand All @@ -45,34 +51,50 @@ export class AttachAutocomplete extends Effect {
type: "string",
},
},
...IS_ROOT_AWARE_BRICK_PROPS,
},
["selector", "options"]
["options"]
);

async effect(
{
selector,
options,
isRootAware = false,
}: BlockArg<{
selector: string;
options: string[];
isRootAware?: boolean;
}>,
{ logger }: BlockOptions
{ logger, root }: BlockOptions
): Promise<void> {
const $elements = $safeFind(selector);
const $elements = $safeFindElementsWithRootMode({
selector,
isRootAware,
root,
blockId: this.id,
});

const inputs = $elements
.toArray()
.filter((x) => !(x instanceof Document) && x.tagName === "INPUT");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NIT: Is !(x instanceof Document) added just to fix a type error?
Looks unnecessary and a little bit confusing.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$elements is a Document or HTMLElement. There's really no way of avoiding putting the check somewhere, and Typescript needs enough confidence that all of the array elements are HTMLElements


if (inputs.length === 0) {
logger.warn("No input elements found", {
selector,
isRootAware,
});

const inputs = $elements.toArray().filter((x) => x.tagName === "INPUT");
// Return early to avoid injecting the stylesheet and loading the module
return;
}

const { default: autocompleter } = await import(
/* webpackChunkName: "autocompleter" */ "autocompleter"
);
// TODO: adjust style to hard-code font color so it works on dark themes that have a light font color by default
await injectStylesheet(autocompleterStyleUrl);

if (inputs.length === 0) {
logger.warn("No input elements found for selector");
}

for (const input of inputs) {
autocompleter({
input: input as HTMLInputElement,
Expand Down
31 changes: 31 additions & 0 deletions src/blocks/effects/cancel.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Copyright (C) 2022 PixieBrix, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import { CancelEffect } from "@/blocks/effects/cancel";
import { unsafeAssumeValidArg } from "@/runtime/runtimeTypes";
import { CancelError } from "@/errors/businessErrors";
import { type BlockOptions } from "@/core";

const brick = new CancelEffect();

describe("CancelEffect", () => {
test("it throws CancelError", async () => {
await expect(
brick.run(unsafeAssumeValidArg({}), {} as BlockOptions)
).rejects.toThrow(CancelError);
});
});
70 changes: 70 additions & 0 deletions src/blocks/effects/customEvent.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* Copyright (C) 2022 PixieBrix, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import { unsafeAssumeValidArg } from "@/runtime/runtimeTypes";
import ConsoleLogger from "@/utils/ConsoleLogger";
import { uuidSequence } from "@/testUtils/factories";
import { type BlockOptions } from "@/core";
import CustomEventEffect from "@/blocks/effects/customEvent";

const brick = new CustomEventEffect();

const logger = new ConsoleLogger({
extensionId: uuidSequence(0),
});

describe("CustomEventEffect", () => {
beforeEach(() => {
document.body.innerHTML = `
<html>
<body>
<div>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NIT: there's one extra space in the indent.

<button>Click me</button>
</div>
</body>
</html>
`;
});

test("isRootAware", async () => {
await expect(brick.isRootAware()).resolves.toBe(true);
});

test("it fires custom event", async () => {
const eventHandler = jest.fn();
document.querySelector("button").addEventListener("foo", eventHandler);

await brick.run(unsafeAssumeValidArg({ eventName: "foo" }), {
root: document.querySelector("button"),
logger,
} as unknown as BlockOptions);

expect(eventHandler).toHaveBeenCalled();
});

test("it bubbles custom event", async () => {
const eventHandler = jest.fn();
document.querySelector("div").addEventListener("foo", eventHandler);

await brick.run(unsafeAssumeValidArg({ eventName: "foo" }), {
root: document.querySelector("button"),
logger,
} as unknown as BlockOptions);

expect(eventHandler).toHaveBeenCalled();
});
});
8 changes: 4 additions & 4 deletions src/blocks/effects/customEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,17 +43,17 @@ class CustomEventEffect extends Effect {
required: ["eventName"],
};

override async isRootAware(): Promise<boolean> {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It wasn't declaring itself as root aware even though it was using the root

return true;
}

async effect(
{
eventName,
data = {},
}: BlockArg<{ eventName: string; data?: UnknownObject }>,
{ root }: BlockOptions
): Promise<void> {
console.debug("Emitting custom event %s", eventName, {
data,
});

const event = new CustomEvent(eventName, { detail: data, bubbles: true });
root.dispatchEvent(event);
}
Expand Down
Loading