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

Remove jQuery & Bootstrap #4111

Draft
wants to merge 9 commits into
base: 2.x
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
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
6 changes: 3 additions & 3 deletions framework/core/js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@
"type": "module",
"prettier": "@flarum/prettier-config",
"dependencies": {
"@popperjs/core": "^2.11.8",
"body-scroll-lock": "^4.0.0-beta.0",
"bootstrap": "^3.4.1",
"bootstrap": "^5.3.3",
"clsx": "^1.1.1",
"color-thief-browser": "^2.0.2",
"dayjs": "^1.10.7",
"focus-trap": "^6.7.1",
"format-message": "^6.2.4",
"jquery": "^3.6.0",
"jquery.hotkeys": "^0.1.0",
"mithril": "^2.2",
"nanoid": "^3.1.30",
"punycode": "^2.1.1",
Expand All @@ -24,7 +24,7 @@
"@flarum/jest-config": "^1.0.0",
"@flarum/prettier-config": "^1.0.0",
"@types/body-scroll-lock": "^3.1.0",
"@types/jquery": "^3.5.10",
"@types/bootstrap": "^5.2.10",
"@types/mithril": "^2.0.8",
"@types/punycode": "^2.1.0",
"@types/textarea-caret": "^3.0.1",
Expand Down
8 changes: 8 additions & 0 deletions framework/core/js/src/@types/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,14 @@ declare type VnodeElementTag<Attrs = Record<string, unknown>, C extends Componen
*/
declare const app: import('../common/Application').default;

/**
* @deprecated We are moving away from jQuery.
*/
declare const $: JQueryStatic;
/**
* @deprecated We are moving away from jQuery.
*/
declare const jQuery: JQueryStatic;
declare const m: import('mithril').Static;
declare const dayjs: typeof import('dayjs');

Expand Down
1 change: 1 addition & 0 deletions framework/core/js/src/common/Component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ export default abstract class Component<Attrs extends ComponentAttrs = Component
* @param [selector] a jQuery-compatible selector string
* @returns the jQuery object for the DOM node
* @final
* @deprecated We are moving away from jQuery.
*/
$(selector?: string): JQuery {
const $element = $(this.element) as JQuery<HTMLElement>;
Expand Down
1 change: 1 addition & 0 deletions framework/core/js/src/common/Fragment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export default abstract class Fragment {
* @param [selector] a jQuery-compatible selector string
* @returns the jQuery object for the DOM node
* @final
* @deprecated We are moving away from jQuery.
*/
public $(selector?: string): JQuery {
const $element = $(this.element) as JQuery<HTMLElement>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,12 +86,17 @@ export default abstract class AbstractGlobalSearch<T extends SearchAttrs = Searc
this.searchState = this.attrs.state;
}

blur() {
this.element.querySelector('input')?.blur();
return true;
}

view() {
// Hide the search view if no sources were loaded
if (this.sourceItems().isEmpty()) return <div></div>;

const openSearchModal = () => {
this.$('input').blur() &&
this.blur() &&
app.modal.show(() => import('../../common/components/SearchModal'), { searchState: this.searchState, sources: this.sourceItems().toArray() });
};

Expand All @@ -101,7 +106,7 @@ export default abstract class AbstractGlobalSearch<T extends SearchAttrs = Searc
className="Search"
aria-label={this.attrs.a11yRoleLabel}
onclick={() => {
this.$('input').blur();
this.blur();
setTimeout(() => openSearchModal(), 150);
}}
>
Expand All @@ -124,7 +129,7 @@ export default abstract class AbstractGlobalSearch<T extends SearchAttrs = Searc
onkeydown: (e: KeyboardEvent) => {
if (e.key === 'Enter') {
e.preventDefault();
this.$('input').blur() && openSearchModal();
this.blur() && openSearchModal();
}
},
}}
Expand Down
104 changes: 56 additions & 48 deletions framework/core/js/src/common/components/AutocompleteDropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,35 +84,35 @@ export default abstract class AutocompleteDropdown<
// Highlight the item that is currently selected.
this.setIndex(this.getCurrentNumericIndex());

this.$('.Dropdown-suggestions')
.on('mousedown', (e) => e.preventDefault())
// Whenever the mouse is hovered over a search result, highlight it.
.on('mouseenter', '> li:not(.Dropdown-header)', function () {
component.setIndex(component.selectableItems().index(this));
});
const suggestions = this.element.querySelector('.Dropdown-suggestions')! as HTMLDivElement;
suggestions.addEventListener('mousedown', (e) => e.preventDefault());
// Whenever the mouse is hovered over a search result, highlight it.
suggestions.addEventListener('mouseenter', (e) => {
const el = e.target as HTMLElement;
if (el.parentElement != suggestions || el.tagName != 'LI' || el.classList.contains('Dropdown-header')) return;
component.setIndex(component.selectableItems().indexOf(el as HTMLLIElement));
});

const $input = this.inputElement();
const input = this.inputElement();

this.navigator = new KeyboardNavigatable();
this.navigator
.onUp(() => this.setIndex(this.getCurrentNumericIndex() - 1, true))
.onDown(() => this.setIndex(this.getCurrentNumericIndex() + 1, true))
.onSelect(this.selectSuggestion.bind(this), true)
.bindTo($input);

$input
.on('focus', function () {
component.hasFocus = true;
m.redraw();

$(this)
.one('mouseup', (e) => e.preventDefault())
.trigger('select');
})
.on('blur', function () {
component.hasFocus = false;
m.redraw();
});
.bindTo(input);

input.addEventListener('focus', function() {
component.hasFocus = true;
m.redraw();

this.addEventListener('mouseup', (e) => e.preventDefault(), { once: true });
this.dispatchEvent(new Event('select'));
});
input.addEventListener('blur', () => {
component.hasFocus = false;
m.redraw();
});

this.updateMaxHeightHandler = this.updateMaxHeight.bind(this);
window.addEventListener('resize', this.updateMaxHeightHandler);
Expand All @@ -126,75 +126,83 @@ export default abstract class AutocompleteDropdown<
}
}

selectableItems(): JQuery {
return this.$('.Dropdown-suggestions > li:not(.Dropdown-header)');
selectableItems(): HTMLLIElement[] {
return Array.from(this.element.querySelectorAll('.Dropdown-suggestions > li:not(.Dropdown-header)')) as HTMLLIElement[];
}

inputElement(): JQuery<HTMLInputElement> {
return this.$('input') as JQuery<HTMLInputElement>;
inputElement(): HTMLInputElement {
return this.element.querySelector('input') as HTMLInputElement;
}

selectSuggestion() {
this.getItem(this.index).find('button')[0].click();
this.getItem(this.index).querySelector('button')!.click();
}

/**
* Get the position of the currently selected item.
* Returns zero if not found.
*/
getCurrentNumericIndex(): number {
return Math.max(0, this.selectableItems().index(this.getItem(this.index)));
return Math.max(0, this.selectableItems().indexOf(this.getItem(this.index)));
}

/**
* Get the <li> in the search results with the given index (numeric or named).
*/
getItem(index: number): JQuery {
const $items = this.selectableItems();
let $item = $items.filter(`[data-index="${index}"]`);
getItem(index: number): HTMLLIElement {
const items = this.selectableItems();
const filtered = items.filter((v) => v.getAttribute('data-index') == index.toString());

if (!$item.length) {
$item = $items.eq(index);
if (!filtered.length) {
return items[index];
}

return $item;
return filtered[0];
}

/**
* Set the currently-selected search result item to the one with the given
* index.
*/
setIndex(index: number, scrollToItem: boolean = false) {
const $items = this.selectableItems();
const $dropdown = $items.parent();
const items = this.selectableItems();

let fixedIndex = index;
if (index < 0) {
fixedIndex = $items.length - 1;
} else if (index >= $items.length) {
fixedIndex = items.length - 1;
} else if (index >= items.length) {
fixedIndex = 0;
}

const $item = $items.removeClass('active').eq(fixedIndex).addClass('active');
items.forEach(el => el.classList.remove('active'));
const item = items[fixedIndex];
const dropdown = item.parentElement!;
item.classList.add('active');

this.index = parseInt($item.attr('data-index') as string) || fixedIndex;
this.index = parseInt(item.getAttribute('data-index') as string) || fixedIndex;

if (scrollToItem) {
const dropdownScroll = $dropdown.scrollTop()!;
const dropdownTop = $dropdown.offset()!.top;
const dropdownBottom = dropdownTop + $dropdown.outerHeight()!;
const itemTop = $item.offset()!.top;
const itemBottom = itemTop + $item.outerHeight()!;
const documentScrollTop = document.documentElement.scrollTop;
const dropdownScroll = dropdown.scrollTop!;
const dropdownRect = dropdown.getBoundingClientRect();
const dropdownTop = dropdownRect.top + documentScrollTop;
const dropdownBottom = dropdownTop + dropdownRect.height;
const itemRect = item.getBoundingClientRect();
const itemTop = itemRect.top + documentScrollTop;
const itemBottom = itemTop + itemRect.height;

let scrollTop;
if (itemTop < dropdownTop) {
scrollTop = dropdownScroll - dropdownTop + itemTop - parseInt($dropdown.css('padding-top'), 10);
scrollTop = dropdownScroll - dropdownTop + itemTop - parseInt(dropdown.style.paddingTop, 10);
} else if (itemBottom > dropdownBottom) {
scrollTop = dropdownScroll - dropdownBottom + itemBottom + parseInt($dropdown.css('padding-bottom'), 10);
scrollTop = dropdownScroll - dropdownBottom + itemBottom + parseInt(dropdown.style.paddingBottom, 10);
}

if (typeof scrollTop !== 'undefined') {
$dropdown.stop(true).animate({ scrollTop }, 100);
dropdown.scrollTo({
top: scrollTop,
behavior: 'smooth'
});
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@ export default class ConfirmDocumentUnload extends Component {
super.oncreate(vnode);

this.boundHandler = this.handler.bind(this);
$(window).on('beforeunload', this.boundHandler);
window.addEventListener('beforeunload', this.boundHandler);
}

onremove(vnode) {
super.onremove(vnode);

$(window).off('beforeunload', this.boundHandler);
window.removeEventListener('beforeunload', this.boundHandler);
}

view(vnode) {
Expand Down
39 changes: 14 additions & 25 deletions framework/core/js/src/common/components/Dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ export interface IDropdownAttrs extends ComponentAttrs {
export default class Dropdown<CustomAttrs extends IDropdownAttrs = IDropdownAttrs> extends Component<CustomAttrs> {
protected showing = false;

protected backdropElement: HTMLDivElement | null = null;

static initAttrs(attrs: IDropdownAttrs) {
attrs.className ||= '';
attrs.buttonClassName ||= '';
Expand Down Expand Up @@ -67,7 +69,7 @@ export default class Dropdown<CustomAttrs extends IDropdownAttrs = IDropdownAttr
// When opening the dropdown menu, work out if the menu goes beyond the
// bottom of the viewport. If it does, we will apply class to make it show
// above the toggle button instead of below it.
this.$().on('shown.bs.dropdown', () => {
this.element.addEventListener('shown.bs.dropdown', () => {
const { lazyDraw, onshow } = this.attrs;

this.showing = true;
Expand All @@ -88,38 +90,25 @@ export default class Dropdown<CustomAttrs extends IDropdownAttrs = IDropdownAttr
m.redraw();
}

const $menu = this.$('.Dropdown-menu');
const isRight = $menu.hasClass('Dropdown-menu--right');

const top = $menu.offset()?.top ?? 0;
const height = $menu.height() ?? 0;
const windowSrollTop = $(window).scrollTop() ?? 0;
const windowHeight = $(window).height() ?? 0;

$menu.removeClass('Dropdown-menu--top Dropdown-menu--right');

$menu.toggleClass('Dropdown-menu--top', top + height > windowSrollTop + windowHeight);

if (($menu.offset()?.top || 0) < 0) {
$menu.removeClass('Dropdown-menu--top');
}

const left = $menu.offset()?.left ?? 0;
const width = $menu.width() ?? 0;
const windowScrollLeft = $(window).scrollLeft() ?? 0;
const windowWidth = $(window).width() ?? 0;

$menu.toggleClass('Dropdown-menu--right', isRight || left + width > windowScrollLeft + windowWidth);
// Mithril doesn't really redraw this component sometimes (e.g. Discussion list)
// Bootstrap 5 has removed the open class toggle and the backdrop
// these need to be added manually.
this.element.classList.add('open');
this.backdropElement = document.createElement('div');
this.backdropElement.classList.add('dropdown-backdrop');
this.element.append(this.backdropElement);
});

this.$().on('hidden.bs.dropdown', () => {
this.element.addEventListener('hidden.bs.dropdown', () => {
this.showing = false;

if (this.attrs.onhide) {
this.attrs.onhide();
}

m.redraw();
this.element.classList.remove('open');
this.backdropElement?.remove();
});
}

Expand All @@ -132,7 +121,7 @@ export default class Dropdown<CustomAttrs extends IDropdownAttrs = IDropdownAttr
className={'Dropdown-toggle ' + this.attrs.buttonClassName}
aria-haspopup="menu"
aria-label={this.attrs.accessibleToggleLabel}
data-toggle="dropdown"
data-bs-toggle="dropdown"
onclick={this.attrs.onclick}
{...this.attrs.buttonAttrs}
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ export default class EditUserModal<CustomAttrs extends IEditUserModalAttrs = IEd
const target = e.target as HTMLInputElement;
this.setPassword(target.checked);
m.redraw.sync();
if (target.checked) this.$('[name=password]').select();
if (target.checked) this.element.querySelector('[name=password]')?.dispatchEvent(new Event('select'));
e.redraw = false;
}}
disabled={this.nonAdminEditingAdmin()}
Expand Down
7 changes: 5 additions & 2 deletions framework/core/js/src/common/components/FormModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@ export default abstract class FormModal<ModalAttrs extends IFormModalAttrs = IFo
* @remark Focuses the first input in the modal.
*/
onready(): void {
this.$().find('input, select, textarea').first().trigger('focus').trigger('select');
const input = this.element.querySelector('input, select, textarea') as (HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement);
if (!input) return;
input.focus();
input.dispatchEvent(new Event('select'));
}

/**
Expand All @@ -43,7 +46,7 @@ export default abstract class FormModal<ModalAttrs extends IFormModalAttrs = IFo
m.redraw();

if (error.status === 422 && error.response?.errors) {
this.$('form [name=' + (error.response.errors as any[])[0].source.pointer.replace('/data/attributes/', '') + ']').trigger('select');
this.element.querySelector(`form [name=${(error.response.errors as any[])[0].source.pointer.replace('/data/attributes/', '')}]`)?.dispatchEvent(new Event('select'));
} else {
this.onready();
}
Expand Down
2 changes: 1 addition & 1 deletion framework/core/js/src/common/components/ModalManager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ export default class ModalManager extends Component<IModalManagerAttrs> {
);

requestAnimationFrame(() => {
this.activeDialogElement?.classList.add('in');
this.activeDialogElement?.classList.add('show');
});
}

Expand Down
Loading
Loading