PromucFlow_constructor/app/client/src/utils/hooks/useWidgetFocus/tabbable.ts

313 lines
8.4 KiB
TypeScript
Raw Normal View History

export const CANVAS_WIDGET = '[type="CANVAS_WIDGET"]';
// NOTE: This is a hack to exclude the current canvas from the query selector
// because when we use.closest, it returns the current element too
export const CANVAS_WIDGET_EXCLUDING_SCOPE =
'[type="CANVAS_WIDGET"]:not(:scope)';
export const CONTAINER_SELECTOR =
":is(.t--widget-containerwidget, .t--widget-formwidget)";
const NON_FOCUSABLE_WIDGET_CLASS =
".t--widget-textwidget, .t--widget-ratewidget, [disabled], [data-hidden]";
export const JSONFORM_WIDGET = ".t--widget-jsonformwidget";
export const MODAL_WIDGET = ".t--modal-widget";
export const CHECKBOXGROUP_WIDGET = ".t--widget-checkboxgroupwidget";
export const SWITCHGROUP_WIDGET = ".t--widget-switchgroupwidget";
export const BUTTONGROUP_WIDGET = ".t--widget-buttongroupwidget";
export const FOCUS_SELECTOR =
":is(a, input, select, textarea, button, object, audio, video, [tabindex='-1']):not([data-tabbable='false'])";
export const WIDGET_SELECTOR = `.positioned-widget:is(:not(${NON_FOCUSABLE_WIDGET_CLASS}))`;
/**
* returns the tabbable descendants of the current node
*
* @param currentNode
* @param shiftKey
* @returns
*/
export function getTabbableDescendants(
currentNode: HTMLElement,
shiftKey = false,
): HTMLElement[] {
const activeWidget = currentNode.closest(WIDGET_SELECTOR) as HTMLElement;
if (!activeWidget) {
const modal = currentNode.closest(MODAL_WIDGET) as HTMLElement;
// if we are in modal, we have to trap the focus within the modal
if (modal) {
const tabbableDescendants = Array.from(
modal.querySelectorAll(WIDGET_SELECTOR),
) as HTMLElement[];
const domRect = modal.getBoundingClientRect();
const sortedTabbableDescendants = sortWidgetsByPosition(
{
top: shiftKey ? domRect.bottom : domRect.top,
left: shiftKey ? domRect.right : domRect.left,
},
tabbableDescendants,
shiftKey,
);
return sortedTabbableDescendants;
}
// this case means the focus on the main container canvas
if (currentNode.matches(CANVAS_WIDGET)) {
const tabbableDescendants = Array.from(
currentNode.querySelectorAll(WIDGET_SELECTOR),
) as HTMLElement[];
const domRect = currentNode.getBoundingClientRect();
const sortedTabbableDescendants = sortWidgetsByPosition(
{
top: shiftKey ? domRect.bottom : domRect.top,
left: shiftKey ? domRect.right : domRect.left,
},
tabbableDescendants,
shiftKey,
);
return sortedTabbableDescendants;
}
}
const siblings = getWidgetSiblingsOfNode(activeWidget);
const domRect = activeWidget.getBoundingClientRect();
const sortedSiblings = sortWidgetsByPosition(
{
top: domRect.top,
left: domRect.left,
},
siblings,
shiftKey,
);
if (sortedSiblings.length) return sortedSiblings;
// there are no siblings, which means we are at the end of the tabbable list
// we have to go to next sibling widget of current canvas
const currentCanvas = currentNode.closest(
CANVAS_WIDGET_EXCLUDING_SCOPE,
) as HTMLElement;
if (currentCanvas) {
return getTabbableDescendants(currentCanvas, shiftKey);
}
return [];
}
/**
* returns the next tabbable descendant from the list of descendants
* sorted by position and distance
* if the next tabbable descendant is JSONFORM, it returns the first tabbable
*
* @param descendants
* @param shiftKey
* @returns
*/
export function getNextTabbableDescendant(
descendants: HTMLElement[],
shiftKey = false,
) {
const nextTabbableDescendant = descendants[0];
if (!nextTabbableDescendant) return;
// if nextTabbableDescendant is a container,
if (nextTabbableDescendant.matches(CONTAINER_SELECTOR)) {
const tabbableDescendants = getChildrenWidgetsOfNode(
nextTabbableDescendant,
);
chore: upgrade to prettier v2 + enforce import types (#21013)Co-authored-by: Satish Gandham <hello@satishgandham.com> Co-authored-by: Satish Gandham <satish.iitg@gmail.com> ## Description This PR upgrades Prettier to v2 + enforces TypeScript’s [`import type`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-export) syntax where applicable. It’s submitted as a separate PR so we can merge it easily. As a part of this PR, we reformat the codebase heavily: - add `import type` everywhere where it’s required, and - re-format the code to account for Prettier 2’s breaking changes: https://prettier.io/blog/2020/03/21/2.0.0.html#breaking-changes This PR is submitted against `release` to make sure all new code by team members will adhere to new formatting standards, and we’ll have fewer conflicts when merging `bundle-optimizations` into `release`. (I’ll merge `release` back into `bundle-optimizations` once this PR is merged.) ### Why is this needed? This PR is needed because, for the Lodash optimization from https://github.com/appsmithorg/appsmith/commit/7cbb12af886621256224be0c93e6a465dd710ad3, we need to use `import type`. Otherwise, `babel-plugin-lodash` complains that `LoDashStatic` is not a lodash function. However, just using `import type` in the current codebase will give you this: <img width="962" alt="Screenshot 2023-03-08 at 17 45 59" src="https://user-images.githubusercontent.com/2953267/223775744-407afa0c-e8b9-44a1-90f9-b879348da57f.png"> That’s because Prettier 1 can’t parse `import type` at all. To parse it, we need to upgrade to Prettier 2. ### Why enforce `import type`? Apart from just enabling `import type` support, this PR enforces specifying `import type` everywhere it’s needed. (Developers will get immediate TypeScript and ESLint errors when they forget to do so.) I’m doing this because I believe `import type` improves DX and makes refactorings easier. Let’s say you had a few imports like below. Can you tell which of these imports will increase the bundle size? (Tip: it’s not all of them!) ```ts // app/client/src/workers/Linting/utils.ts import { Position } from "codemirror"; import { LintError as JSHintError, LintOptions } from "jshint"; import { get, isEmpty, isNumber, keys, last, set } from "lodash"; ``` It’s pretty hard, right? What about now? ```ts // app/client/src/workers/Linting/utils.ts import type { Position } from "codemirror"; import type { LintError as JSHintError, LintOptions } from "jshint"; import { get, isEmpty, isNumber, keys, last, set } from "lodash"; ``` Now, it’s clear that only `lodash` will be bundled. This helps developers to see which imports are problematic, but it _also_ helps with refactorings. Now, if you want to see where `codemirror` is bundled, you can just grep for `import \{.*\} from "codemirror"` – and you won’t get any type-only imports. This also helps (some) bundlers. Upon transpiling, TypeScript erases type-only imports completely. In some environment (not ours), this makes the bundle smaller, as the bundler doesn’t need to bundle type-only imports anymore. ## Type of change - Chore (housekeeping or task changes that don't impact user perception) ## How Has This Been Tested? This was tested to not break the build. ### Test Plan > Add Testsmith test cases links that relate to this PR ### Issues raised during DP testing > Link issues raised during DP testing for better visiblity and tracking (copy link from comments dropped on this PR) ## Checklist: ### Dev activity - [x] My code follows the style guidelines of this project - [ ] I have performed a self-review of my own code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] PR is being merged under a feature flag ### QA activity: - [ ] Test plan has been approved by relevant developers - [ ] Test plan has been peer reviewed by QA - [ ] Cypress test cases have been added and approved by either SDET or manual QA - [ ] Organized project review call with relevant stakeholders after Round 1/2 of QA - [ ] Added Test Plan Approved label after reveiwing all Cypress test --------- Co-authored-by: Satish Gandham <hello@satishgandham.com> Co-authored-by: Satish Gandham <satish.iitg@gmail.com>
2023-03-16 11:41:47 +00:00
const { bottom, left, right, top } =
nextTabbableDescendant.getBoundingClientRect();
const sortedTabbableDescendants = sortWidgetsByPosition(
{
top: shiftKey ? bottom : top,
left: shiftKey ? right : left,
},
tabbableDescendants,
shiftKey,
);
return sortedTabbableDescendants[0];
}
// if nextTabbableDescendant is a jsonform widget
if (
nextTabbableDescendant.matches(JSONFORM_WIDGET) ||
nextTabbableDescendant.matches(CHECKBOXGROUP_WIDGET) ||
nextTabbableDescendant.matches(SWITCHGROUP_WIDGET) ||
nextTabbableDescendant.matches(BUTTONGROUP_WIDGET)
) {
const tabbable = Array.from(
nextTabbableDescendant.querySelectorAll<HTMLElement>(FOCUS_SELECTOR),
);
return shiftKey ? tabbable[tabbable.length - 1] : tabbable[0];
}
return nextTabbableDescendant;
}
/**
* returns a focussable element within a widget
*
* @param node
* @returns
*/
export function getFocussableElementOfWidget(node: HTMLElement) {
if (node.matches(FOCUS_SELECTOR)) {
return node;
}
return node.querySelector(FOCUS_SELECTOR) as HTMLElement;
}
/**
* get widgets of a given node
*
* @param node
* @returns
*/
export function getChildrenWidgetsOfNode(node: HTMLElement) {
const widgets = Array.from(
node.querySelectorAll(WIDGET_SELECTOR),
) as HTMLElement[];
return widgets;
}
/**
* get the siblings of the current node's widget
*
* @param node
* @returns
*/
function getWidgetSiblingsOfNode(node: HTMLElement) {
const canvas = node.closest(CANVAS_WIDGET_EXCLUDING_SCOPE) as HTMLElement;
if (!canvas) return [];
const widget = node.closest(WIDGET_SELECTOR) as HTMLElement;
const siblings = Array.from(
canvas.querySelectorAll(`:scope > ${WIDGET_SELECTOR}`),
) as HTMLElement[];
return siblings.filter((sibling) => sibling !== widget);
}
/**
* sorts the descendants by their position in the DOM
*
* @param currentElement
* @param tabbableDescendants
* @param shiftKey
* @returns
*/
export function sortWidgetsByPosition(
boundingClientRect: {
top: number;
left: number;
},
tabbableDescendants: HTMLElement[],
shiftKey = false,
) {
const { left, top } = boundingClientRect;
const isTabbingForward = !shiftKey;
const isTabbingBackward = shiftKey;
let tabbableElementsByPosition = Array.from(tabbableDescendants).map(
(element) => {
chore: upgrade to prettier v2 + enforce import types (#21013)Co-authored-by: Satish Gandham <hello@satishgandham.com> Co-authored-by: Satish Gandham <satish.iitg@gmail.com> ## Description This PR upgrades Prettier to v2 + enforces TypeScript’s [`import type`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-export) syntax where applicable. It’s submitted as a separate PR so we can merge it easily. As a part of this PR, we reformat the codebase heavily: - add `import type` everywhere where it’s required, and - re-format the code to account for Prettier 2’s breaking changes: https://prettier.io/blog/2020/03/21/2.0.0.html#breaking-changes This PR is submitted against `release` to make sure all new code by team members will adhere to new formatting standards, and we’ll have fewer conflicts when merging `bundle-optimizations` into `release`. (I’ll merge `release` back into `bundle-optimizations` once this PR is merged.) ### Why is this needed? This PR is needed because, for the Lodash optimization from https://github.com/appsmithorg/appsmith/commit/7cbb12af886621256224be0c93e6a465dd710ad3, we need to use `import type`. Otherwise, `babel-plugin-lodash` complains that `LoDashStatic` is not a lodash function. However, just using `import type` in the current codebase will give you this: <img width="962" alt="Screenshot 2023-03-08 at 17 45 59" src="https://user-images.githubusercontent.com/2953267/223775744-407afa0c-e8b9-44a1-90f9-b879348da57f.png"> That’s because Prettier 1 can’t parse `import type` at all. To parse it, we need to upgrade to Prettier 2. ### Why enforce `import type`? Apart from just enabling `import type` support, this PR enforces specifying `import type` everywhere it’s needed. (Developers will get immediate TypeScript and ESLint errors when they forget to do so.) I’m doing this because I believe `import type` improves DX and makes refactorings easier. Let’s say you had a few imports like below. Can you tell which of these imports will increase the bundle size? (Tip: it’s not all of them!) ```ts // app/client/src/workers/Linting/utils.ts import { Position } from "codemirror"; import { LintError as JSHintError, LintOptions } from "jshint"; import { get, isEmpty, isNumber, keys, last, set } from "lodash"; ``` It’s pretty hard, right? What about now? ```ts // app/client/src/workers/Linting/utils.ts import type { Position } from "codemirror"; import type { LintError as JSHintError, LintOptions } from "jshint"; import { get, isEmpty, isNumber, keys, last, set } from "lodash"; ``` Now, it’s clear that only `lodash` will be bundled. This helps developers to see which imports are problematic, but it _also_ helps with refactorings. Now, if you want to see where `codemirror` is bundled, you can just grep for `import \{.*\} from "codemirror"` – and you won’t get any type-only imports. This also helps (some) bundlers. Upon transpiling, TypeScript erases type-only imports completely. In some environment (not ours), this makes the bundle smaller, as the bundler doesn’t need to bundle type-only imports anymore. ## Type of change - Chore (housekeeping or task changes that don't impact user perception) ## How Has This Been Tested? This was tested to not break the build. ### Test Plan > Add Testsmith test cases links that relate to this PR ### Issues raised during DP testing > Link issues raised during DP testing for better visiblity and tracking (copy link from comments dropped on this PR) ## Checklist: ### Dev activity - [x] My code follows the style guidelines of this project - [ ] I have performed a self-review of my own code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes - [ ] PR is being merged under a feature flag ### QA activity: - [ ] Test plan has been approved by relevant developers - [ ] Test plan has been peer reviewed by QA - [ ] Cypress test cases have been added and approved by either SDET or manual QA - [ ] Organized project review call with relevant stakeholders after Round 1/2 of QA - [ ] Added Test Plan Approved label after reveiwing all Cypress test --------- Co-authored-by: Satish Gandham <hello@satishgandham.com> Co-authored-by: Satish Gandham <satish.iitg@gmail.com>
2023-03-16 11:41:47 +00:00
const { left: elementLeft, top: elementTop } =
element.getBoundingClientRect();
const topDiff = elementTop - top;
const leftDiff = elementLeft - left;
return {
element,
topDiff,
leftDiff,
top,
left,
elementTop,
elementLeft,
};
},
);
tabbableElementsByPosition = tabbableElementsByPosition.filter((element) => {
// if tabbing forward, only consider elements below and to the right
if (isTabbingForward) {
if (element.topDiff === 0) {
return element.leftDiff > 0;
}
return element.topDiff > 0;
}
// if tabbing backward, only consider elements above and to the left
if (isTabbingBackward) {
if (element.topDiff === 0) {
return element.leftDiff < 0;
}
return element.topDiff < 0;
}
});
tabbableElementsByPosition = tabbableElementsByPosition.sort((a, b) => {
if (isTabbingForward) {
return a.topDiff - b.topDiff || a.leftDiff - b.leftDiff;
}
if (isTabbingBackward) {
return b.topDiff - a.topDiff || b.leftDiff - a.leftDiff;
}
return 0;
});
return tabbableElementsByPosition.map((element) => element.element);
}
/**
* get next item to focus if the current widget has relative positioned children
*
* Note:
* if the user is tabbing out, we need to get the next tabbable descendant of the current widget
* else tabbing will work as expected as widgets inside the widget are regular components
* and will be handled by the default tabbing logic
*
*
* @param currentWidget
* @param shiftKey
* @returns
*/
export function getNextTabbableDescendantForRegularWidgets(
currentWidget: HTMLElement,
shiftKey: boolean,
) {
let nextTabbableDescendant;
const tabbable = Array.from(
currentWidget.querySelectorAll<HTMLElement>(FOCUS_SELECTOR),
);
const currentIndex = tabbable.indexOf(document.activeElement as HTMLElement);
const isTabbingOutOfJSONForm = shiftKey
? currentIndex === 0
: currentIndex === tabbable.length - 1;
if (isTabbingOutOfJSONForm) {
const descendents = getTabbableDescendants(currentWidget, shiftKey);
nextTabbableDescendant = getNextTabbableDescendant(descendents, shiftKey);
}
return nextTabbableDescendant;
}