{{template "repo/header" .}}
diff --git a/tests/integration/repo_tag_test.go b/tests/integration/repo_tag_test.go index d649f041ccf..0cd49ee4cd3 100644 --- a/tests/integration/repo_tag_test.go +++ b/tests/integration/repo_tag_test.go @@ -4,17 +4,20 @@ package integration import ( + "fmt" "net/http" "net/url" "testing" "code.gitea.io/gitea/models" + auth_model "code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/db" git_model "code.gitea.io/gitea/models/git" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/git" + api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/services/release" "code.gitea.io/gitea/tests" @@ -117,3 +120,47 @@ func TestCreateNewTagProtected(t *testing.T) { assert.NoError(t, err) } } + +func TestRepushTag(t *testing.T) { + onGiteaRun(t, func(t *testing.T, u *url.URL) { + repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) + owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) + session := loginUser(t, owner.LowerName) + token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) + + httpContext := NewAPITestContext(t, owner.Name, repo.Name) + + dstPath := t.TempDir() + + u.Path = httpContext.GitPath() + u.User = url.UserPassword(owner.Name, userPassword) + + doGitClone(dstPath, u)(t) + + // create and push a tag + _, _, err := git.NewCommand(git.DefaultContext, "tag", "v2.0").RunStdString(&git.RunOpts{Dir: dstPath}) + assert.NoError(t, err) + _, _, err = git.NewCommand(git.DefaultContext, "push", "origin", "--tags", "v2.0").RunStdString(&git.RunOpts{Dir: dstPath}) + assert.NoError(t, err) + // create a release for the tag + createdRelease := createNewReleaseUsingAPI(t, token, owner, repo, "v2.0", "", "Release of v2.0", "desc") + assert.False(t, createdRelease.IsDraft) + // delete the tag + _, _, err = git.NewCommand(git.DefaultContext, "push", "origin", "--delete", "v2.0").RunStdString(&git.RunOpts{Dir: dstPath}) + assert.NoError(t, err) + // query the release by API and it should be a draft + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", owner.Name, repo.Name, "v2.0")) + resp := MakeRequest(t, req, http.StatusOK) + var respRelease *api.Release + DecodeJSON(t, resp, &respRelease) + assert.True(t, respRelease.IsDraft) + // re-push the tag + _, _, err = git.NewCommand(git.DefaultContext, "push", "origin", "--tags", "v2.0").RunStdString(&git.RunOpts{Dir: dstPath}) + assert.NoError(t, err) + // query the release by API and it should not be a draft + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", owner.Name, repo.Name, "v2.0")) + resp = MakeRequest(t, req, http.StatusOK) + DecodeJSON(t, resp, &respRelease) + assert.False(t, respRelease.IsDraft) + }) +} diff --git a/web_src/css/home.css b/web_src/css/home.css index 28992ef31f3..77d2ecf92be 100644 --- a/web_src/css/home.css +++ b/web_src/css/home.css @@ -73,7 +73,7 @@ margin-left: 5px; } -.page-footer .ui.dropdown.language .menu { +.page-footer .ui.dropdown .menu.language-menu { max-height: min(500px, calc(100vh - 60px)); overflow-y: auto; margin-bottom: 10px; diff --git a/web_src/css/repo.css b/web_src/css/repo.css index 85f33f858e2..61aa99d531f 100644 --- a/web_src/css/repo.css +++ b/web_src/css/repo.css @@ -62,23 +62,6 @@ } } -.repository .issue-content-right .ui.list .dependency { - padding: 0; - white-space: nowrap; -} - -.repository .issue-content-right .ui.list .title { - overflow: hidden; - text-overflow: ellipsis; -} - -.repository .issue-content-right #deadlineForm input { - width: 12.8rem; - border-radius: var(--border-radius) 0 0 var(--border-radius); - border-right: 0; - white-space: nowrap; -} - .repository .issue-content-right .filter.menu { max-height: 500px; overflow-x: auto; diff --git a/web_src/js/features/common-page.ts b/web_src/js/features/common-page.ts index 77fe2cc1ca7..beec92d152b 100644 --- a/web_src/js/features/common-page.ts +++ b/web_src/js/features/common-page.ts @@ -1,6 +1,7 @@ -import $ from 'jquery'; import {GET} from '../modules/fetch.ts'; import {showGlobalErrorMessage} from '../bootstrap.ts'; +import {fomanticQuery} from '../modules/fomantic/base.ts'; +import {queryElems} from '../utils/dom.ts'; const {appUrl} = window.config; @@ -17,18 +18,18 @@ export function initHeadNavbarContentToggle() { } export function initFootLanguageMenu() { - async function linkLanguageAction() { - const $this = $(this); - await GET($this.data('url')); + document.querySelector('.ui.dropdown .menu.language-menu')?.addEventListener('click', async (e) => { + const item = (e.target as HTMLElement).closest('.item'); + if (!item) return; + e.preventDefault(); + await GET(item.getAttribute('data-url')); window.location.reload(); - } - - $('.language-menu a[lang]').on('click', linkLanguageAction); + }); } export function initGlobalDropdown() { // Semantic UI modules. - const $uiDropdowns = $('.ui.dropdown'); + const $uiDropdowns = fomanticQuery('.ui.dropdown'); // do not init "custom" dropdowns, "custom" dropdowns are managed by their own code. $uiDropdowns.filter(':not(.custom)').dropdown(); @@ -46,14 +47,14 @@ export function initGlobalDropdown() { }, onHide() { this._tippy?.enable(); + // eslint-disable-next-line unicorn/no-this-assignment + const elDropdown = this; // hide all tippy elements of items after a while. eg: use Enter to click "Copy Link" in the Issue Context Menu setTimeout(() => { - const $dropdown = $(this); + const $dropdown = fomanticQuery(elDropdown); if ($dropdown.dropdown('is hidden')) { - $(this).find('.menu > .item').each((_, item) => { - item._tippy?.hide(); - }); + queryElems(elDropdown, '.menu > .item', (el) => el._tippy?.hide()); } }, 2000); }, @@ -71,7 +72,7 @@ export function initGlobalDropdown() { } export function initGlobalTabularMenu() { - $('.ui.menu.tabular:not(.custom) .item').tab({autoTabActivation: false}); + fomanticQuery('.ui.menu.tabular:not(.custom) .item').tab({autoTabActivation: false}); } /** diff --git a/web_src/js/features/imagediff.ts b/web_src/js/features/imagediff.ts index a6b1f48fb38..cd61888f83b 100644 --- a/web_src/js/features/imagediff.ts +++ b/web_src/js/features/imagediff.ts @@ -1,14 +1,14 @@ -import $ from 'jquery'; import {GET} from '../modules/fetch.ts'; import {hideElem, loadElem, queryElemChildren, queryElems} from '../utils/dom.ts'; import {parseDom} from '../utils.ts'; +import {fomanticQuery} from '../modules/fomantic/base.ts'; function getDefaultSvgBoundsIfUndefined(text, src) { const defaultSize = 300; const maxSize = 99999; const svgDoc = parseDom(text, 'image/svg+xml'); - const svg = svgDoc.documentElement; + const svg = (svgDoc.documentElement as unknown) as SVGSVGElement; const width = svg?.width?.baseVal; const height = svg?.height?.baseVal; if (width === undefined || height === undefined) { @@ -68,12 +68,14 @@ function createContext(imageAfter, imageBefore) { } class ImageDiff { - async init(containerEl) { + containerEl: HTMLElement; + diffContainerWidth: number; + + async init(containerEl: HTMLElement) { this.containerEl = containerEl; containerEl.setAttribute('data-image-diff-loaded', 'true'); - // the only jQuery usage in this file - $(containerEl).find('.ui.menu.tabular .item').tab({autoTabActivation: false}); + fomanticQuery(containerEl).find('.ui.menu.tabular .item').tab({autoTabActivation: false}); // the container may be hidden by "viewed" checkbox, so use the parent's width for reference this.diffContainerWidth = Math.max(containerEl.closest('.diff-file-box').clientWidth - 300, 100); @@ -81,12 +83,12 @@ class ImageDiff { const imageInfos = [{ path: containerEl.getAttribute('data-path-after'), mime: containerEl.getAttribute('data-mime-after'), - images: containerEl.querySelectorAll('img.image-after'), // matches 3 + images: containerEl.querySelectorAll('img.image-after'), // matches 3 boundsInfo: containerEl.querySelector('.bounds-info-after'), }, { path: containerEl.getAttribute('data-path-before'), mime: containerEl.getAttribute('data-mime-before'), - images: containerEl.querySelectorAll('img.image-before'), // matches 3 + images: containerEl.querySelectorAll('img.image-before'), // matches 3 boundsInfo: containerEl.querySelector('.bounds-info-before'), }]; @@ -102,8 +104,8 @@ class ImageDiff { const bounds = getDefaultSvgBoundsIfUndefined(text, info.path); if (bounds) { for (const el of info.images) { - el.setAttribute('width', bounds.width); - el.setAttribute('height', bounds.height); + el.setAttribute('width', String(bounds.width)); + el.setAttribute('height', String(bounds.height)); } hideElem(info.boundsInfo); } @@ -151,7 +153,7 @@ class ImageDiff { const boundsInfoBeforeHeight = this.containerEl.querySelector('.bounds-info-before .bounds-info-height'); if (boundsInfoBeforeHeight) { boundsInfoBeforeHeight.textContent = `${sizes.imageBefore.naturalHeight}px`; - boundsInfoBeforeHeight.classList.add('red', heightChanged); + boundsInfoBeforeHeight.classList.toggle('red', heightChanged); } } @@ -205,7 +207,7 @@ class ImageDiff { } // extra height for inner "position: absolute" elements - const swipe = this.containerEl.querySelector('.diff-swipe'); + const swipe = this.containerEl.querySelector('.diff-swipe'); if (swipe) { swipe.style.width = `${sizes.maxSize.width * factor + 2}px`; swipe.style.height = `${sizes.maxSize.height * factor + 30}px`; @@ -225,7 +227,7 @@ class ImageDiff { const rect = swipeFrame.getBoundingClientRect(); const value = Math.max(0, Math.min(e.clientX - rect.left, width)); swipeBar.style.left = `${value}px`; - this.containerEl.querySelector('.swipe-container').style.width = `${swipeFrame.clientWidth - value}px`; + this.containerEl.querySelector('.swipe-container').style.width = `${swipeFrame.clientWidth - value}px`; }; const removeEventListeners = () => { document.removeEventListener('mousemove', onSwipeMouseMove); @@ -264,11 +266,11 @@ class ImageDiff { overlayFrame.style.height = `${sizes.maxSize.height * factor + 2}px`; } - const rangeInput = this.containerEl.querySelector('input[type="range"]'); + const rangeInput = this.containerEl.querySelector('input[type="range"]'); function updateOpacity() { if (sizes.imageAfter) { - sizes.imageAfter.parentNode.style.opacity = `${rangeInput.value / 100}`; + sizes.imageAfter.parentNode.style.opacity = `${Number(rangeInput.value) / 100}`; } } @@ -278,7 +280,7 @@ class ImageDiff { } export function initImageDiff() { - for (const el of queryElems('.image-diff:not([data-image-diff-loaded])')) { + for (const el of queryElems(document, '.image-diff:not([data-image-diff-loaded])')) { (new ImageDiff()).init(el); // it is async, but we don't need to await for it } } diff --git a/web_src/js/features/repo-common.ts b/web_src/js/features/repo-common.ts index c7d84de9f09..c246d5b4b05 100644 --- a/web_src/js/features/repo-common.ts +++ b/web_src/js/features/repo-common.ts @@ -31,7 +31,7 @@ async function onDownloadArchive(e) { } export function initRepoArchiveLinks() { - queryElems('a.archive-link[href]', (el) => el.addEventListener('click', onDownloadArchive)); + queryElems(document, 'a.archive-link[href]', (el) => el.addEventListener('click', onDownloadArchive)); } export function initRepoActivityTopAuthorsChart() { diff --git a/web_src/js/features/repo-editor.ts b/web_src/js/features/repo-editor.ts index e4d179d3aea..6ea9347eba4 100644 --- a/web_src/js/features/repo-editor.ts +++ b/web_src/js/features/repo-editor.ts @@ -45,17 +45,17 @@ export function initRepoEditor() { const dropzoneUpload = document.querySelector('.page-content.repository.editor.upload .dropzone'); if (dropzoneUpload) initDropzone(dropzoneUpload); - const editArea = document.querySelector('.page-content.repository.editor textarea#edit_area'); + const editArea = document.querySelector('.page-content.repository.editor textarea#edit_area'); if (!editArea) return; - for (const el of queryElems('.js-quick-pull-choice-option')) { + for (const el of queryElems(document, '.js-quick-pull-choice-option')) { el.addEventListener('input', () => { if (el.value === 'commit-to-new-branch') { showElem('.quick-pull-branch-name'); - document.querySelector('.quick-pull-branch-name input').required = true; + document.querySelector('.quick-pull-branch-name input').required = true; } else { hideElem('.quick-pull-branch-name'); - document.querySelector('.quick-pull-branch-name input').required = false; + document.querySelector('.quick-pull-branch-name input').required = false; } document.querySelector('#commit-button').textContent = el.getAttribute('data-button-text'); }); @@ -71,13 +71,13 @@ export function initRepoEditor() { if (filenameInput.value) { parts.push(filenameInput.value); } - document.querySelector('#tree_path').value = parts.join('/'); + document.querySelector('#tree_path').value = parts.join('/'); } filenameInput.addEventListener('input', function () { const parts = filenameInput.value.split('/'); const links = Array.from(document.querySelectorAll('.breadcrumb span.section')); const dividers = Array.from(document.querySelectorAll('.breadcrumb .breadcrumb-divider')); - let warningDiv = document.querySelector('.ui.warning.message.flash-message.flash-warning.space-related'); + let warningDiv = document.querySelector('.ui.warning.message.flash-message.flash-warning.space-related'); let containSpace = false; if (parts.length > 1) { for (let i = 0; i < parts.length; ++i) { @@ -110,14 +110,14 @@ export function initRepoEditor() { filenameInput.value = value; } this.setSelectionRange(0, 0); - containSpace |= (trimValue !== value && trimValue !== ''); + containSpace = containSpace || (trimValue !== value && trimValue !== ''); } } - containSpace |= Array.from(links).some((link) => { + containSpace = containSpace || Array.from(links).some((link) => { const value = link.querySelector('a').textContent; return value.trim() !== value; }); - containSpace |= parts[parts.length - 1].trim() !== parts[parts.length - 1]; + containSpace = containSpace || parts[parts.length - 1].trim() !== parts[parts.length - 1]; if (containSpace) { if (!warningDiv) { warningDiv = document.createElement('div'); @@ -135,8 +135,8 @@ export function initRepoEditor() { joinTreePath(); }); filenameInput.addEventListener('keydown', function (e) { - const sections = queryElems('.breadcrumb span.section'); - const dividers = queryElems('.breadcrumb .breadcrumb-divider'); + const sections = queryElems(document, '.breadcrumb span.section'); + const dividers = queryElems(document, '.breadcrumb .breadcrumb-divider'); // Jump back to last directory once the filename is empty if (e.code === 'Backspace' && filenameInput.selectionStart === 0 && sections.length > 0) { e.preventDefault(); @@ -159,7 +159,7 @@ export function initRepoEditor() { // Using events from https://github.com/codedance/jquery.AreYouSure#advanced-usage // to enable or disable the commit button - const commitButton = document.querySelector('#commit-button'); + const commitButton = document.querySelector('#commit-button'); const $editForm = $('.ui.edit.form'); const dirtyFileClass = 'dirty-file'; diff --git a/web_src/js/features/repo-issue-content.ts b/web_src/js/features/repo-issue-content.ts index 7aaf9765eec..88672cc2553 100644 --- a/web_src/js/features/repo-issue-content.ts +++ b/web_src/js/features/repo-issue-content.ts @@ -3,8 +3,8 @@ import {svg} from '../svg.ts'; import {showErrorToast} from '../modules/toast.ts'; import {GET, POST} from '../modules/fetch.ts'; import {showElem} from '../utils/dom.ts'; +import {parseIssuePageInfo} from '../utils.ts'; -const {appSubUrl} = window.config; let i18nTextEdited; let i18nTextOptions; let i18nTextDeleteFromHistory; @@ -121,15 +121,14 @@ function showContentHistoryMenu(issueBaseUrl, $item, commentId) { } export async function initRepoIssueContentHistory() { - const issueIndex = $('#issueIndex').val(); - if (!issueIndex) return; + const issuePageInfo = parseIssuePageInfo(); + if (!issuePageInfo.issueNumber) return; const $itemIssue = $('.repository.issue .timeline-item.comment.first'); // issue(PR) main content const $comments = $('.repository.issue .comment-list .comment'); // includes: issue(PR) comments, review comments, code comments if (!$itemIssue.length && !$comments.length) return; - const repoLink = $('#repolink').val(); - const issueBaseUrl = `${appSubUrl}/${repoLink}/issues/${issueIndex}`; + const issueBaseUrl = `${issuePageInfo.repoLink}/issues/${issuePageInfo.issueNumber}`; try { const response = await GET(`${issueBaseUrl}/content-history/overview`); diff --git a/web_src/js/features/repo-issue.ts b/web_src/js/features/repo-issue.ts index 392af776f88..721a746aa2c 100644 --- a/web_src/js/features/repo-issue.ts +++ b/web_src/js/features/repo-issue.ts @@ -4,7 +4,7 @@ import {createTippy, showTemporaryTooltip} from '../modules/tippy.ts'; import {hideElem, showElem, toggleElem} from '../utils/dom.ts'; import {setFileFolding} from './file-fold.ts'; import {ComboMarkdownEditor, getComboMarkdownEditor, initComboMarkdownEditor} from './comp/ComboMarkdownEditor.ts'; -import {toAbsoluteUrl} from '../utils.ts'; +import {parseIssuePageInfo, toAbsoluteUrl} from '../utils.ts'; import {GET, POST} from '../modules/fetch.ts'; import {showErrorToast} from '../modules/toast.ts'; import {initRepoIssueSidebar} from './repo-issue-sidebar.ts'; @@ -57,13 +57,11 @@ function excludeLabel(item) { } export function initRepoIssueSidebarList() { - const repolink = $('#repolink').val(); - const repoId = $('#repoId').val(); + const issuePageInfo = parseIssuePageInfo(); const crossRepoSearch = $('#crossRepoSearch').val(); - const tp = $('#type').val(); - let issueSearchUrl = `${appSubUrl}/${repolink}/issues/search?q={query}&type=${tp}`; + let issueSearchUrl = `${issuePageInfo.repoLink}/issues/search?q={query}&type=${issuePageInfo.issueDependencySearchType}`; if (crossRepoSearch === 'true') { - issueSearchUrl = `${appSubUrl}/issues/search?q={query}&priority_repo_id=${repoId}&type=${tp}`; + issueSearchUrl = `${appSubUrl}/issues/search?q={query}&priority_repo_id=${issuePageInfo.repoId}&type=${issuePageInfo.issueDependencySearchType}`; } $('#new-dependency-drop-list') .dropdown({ diff --git a/web_src/js/features/repo-settings.ts b/web_src/js/features/repo-settings.ts index 34a3b635b24..72213f794a4 100644 --- a/web_src/js/features/repo-settings.ts +++ b/web_src/js/features/repo-settings.ts @@ -8,7 +8,7 @@ const {appSubUrl, csrfToken} = window.config; function initRepoSettingsCollaboration() { // Change collaborator access mode - for (const dropdownEl of queryElems('.page-content.repository .ui.dropdown.access-mode')) { + for (const dropdownEl of queryElems(document, '.page-content.repository .ui.dropdown.access-mode')) { const textEl = dropdownEl.querySelector(':scope > .text'); $(dropdownEl).dropdown({ async action(text, value) { diff --git a/web_src/js/modules/fomantic/base.ts b/web_src/js/modules/fomantic/base.ts index 7574fdd25cc..10b5ed014f9 100644 --- a/web_src/js/modules/fomantic/base.ts +++ b/web_src/js/modules/fomantic/base.ts @@ -1,3 +1,4 @@ +import $ from 'jquery'; let ariaIdCounter = 0; export function generateAriaId() { @@ -16,3 +17,6 @@ export function linkLabelAndInput(label, input) { label.setAttribute('for', id); } } + +// eslint-disable-next-line no-jquery/variable-pattern +export const fomanticQuery = $; diff --git a/web_src/js/modules/tippy.ts b/web_src/js/modules/tippy.ts index d75015f69ef..7948e3ecbcd 100644 --- a/web_src/js/modules/tippy.ts +++ b/web_src/js/modules/tippy.ts @@ -179,11 +179,9 @@ export function initGlobalTooltips() { } export function showTemporaryTooltip(target: Element, content: Content) { - // if the target is inside a dropdown, don't show the tooltip because when the dropdown - // closes, the tippy would be pushed unsightly to the top-left of the screen like seen - // on the issue comment menu. - if (target.closest('.ui.dropdown > .menu')) return; - + // if the target is inside a dropdown, the menu will be hidden soon + // so display the tooltip on the dropdown instead + target = target.closest('.ui.dropdown') || target; const tippy = target._tippy ?? attachTooltip(target, content); tippy.setContent(content); if (!tippy.state.isShown) tippy.show(); diff --git a/web_src/js/types.ts b/web_src/js/types.ts index 9c601456bd9..f5c4a40bcac 100644 --- a/web_src/js/types.ts +++ b/web_src/js/types.ts @@ -37,6 +37,13 @@ export type IssuePathInfo = { indexString?: string, } +export type IssuePageInfo = { + repoLink: string, + repoId: number, + issueNumber: number, + issueDependencySearchType: string, +} + export type Issue = { id: number; number: number; diff --git a/web_src/js/utils.ts b/web_src/js/utils.ts index 066a7c7b546..4fed74e20f0 100644 --- a/web_src/js/utils.ts +++ b/web_src/js/utils.ts @@ -1,5 +1,5 @@ -import {encode, decode} from 'uint8-to-base64'; -import type {IssuePathInfo} from './types.ts'; +import {decode, encode} from 'uint8-to-base64'; +import type {IssuePageInfo, IssuePathInfo} from './types.ts'; // transform /path/to/file.ext to file.ext export function basename(path: string): string { @@ -43,6 +43,16 @@ export function parseIssueNewHref(href: string): IssuePathInfo { return {ownerName, repoName, pathType, indexString}; } +export function parseIssuePageInfo(): IssuePageInfo { + const el = document.querySelector('#issue-page-info'); + return { + issueNumber: parseInt(el?.getAttribute('data-issue-index')), + issueDependencySearchType: el?.getAttribute('data-issue-dependency-search-type') || '', + repoId: parseInt(el?.getAttribute('data-issue-repo-id')), + repoLink: el?.getAttribute('data-issue-repo-link') || '', + }; +} + // parse a URL, either relative '/path' or absolute 'https://localhost/path' export function parseUrl(str: string): URL { return new URL(str, str.startsWith('http') ? undefined : window.location.origin); diff --git a/web_src/js/utils/dom.ts b/web_src/js/utils/dom.ts index e2a4c60e84a..79ce05a7adb 100644 --- a/web_src/js/utils/dom.ts +++ b/web_src/js/utils/dom.ts @@ -5,7 +5,7 @@ import type $ from 'jquery'; type ElementArg = Element | string | NodeListOf | Array | ReturnType; type ElementsCallback = (el: Element) => Promisable; type ElementsCallbackWithArgs = (el: Element, ...args: any[]) => Promisable; -type IterableElements = NodeListOf | Array; +type ArrayLikeIterable = ArrayLike & Iterable; // for NodeListOf and Array function elementsCall(el: ElementArg, func: ElementsCallbackWithArgs, ...args: any[]) { if (typeof el === 'string' || el instanceof String) { @@ -15,7 +15,7 @@ function elementsCall(el: ElementArg, func: ElementsCallbackWithArgs, ...args: a func(el, ...args); } else if (el.length !== undefined) { // this works for: NodeList, HTMLCollection, Array, jQuery - for (const e of (el as IterableElements)) { + for (const e of (el as ArrayLikeIterable)) { func(e, ...args); } } else { @@ -58,7 +58,7 @@ export function isElemHidden(el: ElementArg) { return res[0]; } -function applyElemsCallback(elems: IterableElements, fn?: ElementsCallback) { +function applyElemsCallback(elems: ArrayLikeIterable, fn?: ElementsCallback): ArrayLikeIterable { if (fn) { for (const el of elems) { fn(el); @@ -67,19 +67,22 @@ function applyElemsCallback(elems: IterableElements, fn?: ElementsCallback) { return elems; } -export function queryElemSiblings(el: Element, selector = '*', fn?: ElementsCallback) { - return applyElemsCallback(Array.from(el.parentNode.children).filter((child: Element) => { +export function queryElemSiblings(el: Element, selector = '*', fn?: ElementsCallback): ArrayLikeIterable { + const elems = Array.from(el.parentNode.children) as T[]; + return applyElemsCallback(elems.filter((child: Element) => { return child !== el && child.matches(selector); }), fn); } // it works like jQuery.children: only the direct children are selected -export function queryElemChildren(parent: Element | ParentNode, selector = '*', fn?: ElementsCallback) { - return applyElemsCallback(parent.querySelectorAll(`:scope > ${selector}`), fn); +export function queryElemChildren(parent: Element | ParentNode, selector = '*', fn?: ElementsCallback): ArrayLikeIterable { + return applyElemsCallback(parent.querySelectorAll(`:scope > ${selector}`), fn); } -export function queryElems(selector: string, fn?: ElementsCallback) { - return applyElemsCallback(document.querySelectorAll(selector), fn); +// it works like parent.querySelectorAll: all descendants are selected +// in the future, all "queryElems(document, ...)" should be refactored to use a more specific parent +export function queryElems(parent: Element | ParentNode, selector: string, fn?: ElementsCallback): ArrayLikeIterable { + return applyElemsCallback(parent.querySelectorAll(selector), fn); } export function onDomReady(cb: () => Promisable) { @@ -92,7 +95,7 @@ export function onDomReady(cb: () => Promisable) { // checks whether an element is owned by the current document, and whether it is a document fragment or element node // if it is, it means it is a "normal" element managed by us, which can be modified safely. -export function isDocumentFragmentOrElementNode(el: Element | Node) { +export function isDocumentFragmentOrElementNode(el: Node) { try { return el.ownerDocument === document && el.nodeType === Node.ELEMENT_NODE || el.nodeType === Node.DOCUMENT_FRAGMENT_NODE; } catch {