1
0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo.git synced 2025-10-10 19:32:02 +00:00

fix: use another method for suggestions

This commit is contained in:
Maxim Slipenko 2025-06-07 18:21:41 +03:00
parent 3d4372c8bf
commit 6e2c72cd70
9 changed files with 122 additions and 102 deletions

View file

@ -1,30 +1,29 @@
import {matchEmoji, matchMention, matchIssue} from '../../utils/match.js';
import {emojiString} from '../emoji.js';
import {getIssueIcon, getIssueColor} from '../issue.js'
import {parseIssueHref} from '../../utils.js'
import {getIssueIcon, getIssueColor,isIssueSuggestionsLoaded, fetchIssueSuggestions} from '../issue.js'
import {svg} from '../../svg.js'
import {createElementFromHTML} from '../../utils/dom.js';
import {debounce} from 'perfect-debounce';
import { GET } from '../../modules/fetch.js';
const debouncedSuggestIssues = debounce((key, text) => new Promise(
async (resolve, reject) => {
const {owner, repo, index} = parseIssueHref(window.location.href);
const matches = await matchIssue(owner, repo, index, text);
if (!matches.length) return resolve({matched: false});
async function issueSuggestions(text) {
const key = '#';
const matches = matchIssue(text);
if (!matches.length) return {matched: false};
const ul = document.createElement('ul');
ul.classList.add('suggestions');
for (const issue of matches) {
const li = document.createElement('li');
li.setAttribute('role', 'option');
li.setAttribute('data-value', `${key}${issue.id}`);
li.setAttribute('data-value', `${key}${issue.number}`);
li.classList.add('tw-flex', 'tw-gap-2')
const icon = svg(getIssueIcon(issue), 16, ['text', getIssueColor(issue)].join(' '));
li.append(createElementFromHTML(icon));
const id = document.createElement('span');
id.textContent = issue.id.toString();
id.textContent = issue.number.toString();
li.append(id);
const nameSpan = document.createElement('span');
@ -34,10 +33,14 @@ const debouncedSuggestIssues = debounce((key, text) => new Promise(
ul.append(li);
}
resolve({matched: true, fragment: ul});
}), 100)
return {matched: true, fragment: ul};
}
export function initTextExpander(expander) {
if (!expander) return;
const textarea = expander.querySelector('textarea');
expander?.addEventListener('text-expander-change', ({detail: {key, provide, text}}) => {
if (key === ':') {
const matches = matchEmoji(text);
@ -86,7 +89,11 @@ export function initTextExpander(expander) {
provide({matched: true, fragment: ul});
} else if (key === '#') {
provide(debouncedSuggestIssues(key, text));
if (!isIssueSuggestionsLoaded()) {
provide(fetchIssueSuggestions().then(() => issueSuggestions(text)));
} else {
provide(issueSuggestions(text));
}
}
});
expander?.addEventListener('text-expander-value', ({detail}) => {

View file

@ -1,3 +1,6 @@
import { GET } from '../modules/fetch.js';
import {parseIssueHref, parseRepoOwnerPathInfo} from '../utils.js'
export function getIssueIcon(issue) {
if (issue.pull_request) {
if (issue.state === 'open') {
@ -15,16 +18,37 @@ export function getIssueIcon(issue) {
return 'octicon-issue-closed'; // Closed Issue
}
export function getIssueColor(issue) {
if (issue.pull_request) {
if (issue.pull_request.draft === true) {
return 'grey'; // WIP PR
} else if (issue.pull_request.merged === true) {
return 'purple'; // Merged PR
}
export function getIssueColor(issue) {
if (issue.pull_request) {
if (issue.pull_request.draft === true) {
return 'grey'; // WIP PR
} else if (issue.pull_request.merged === true) {
return 'purple'; // Merged PR
}
if (issue.state === 'open') {
return 'green'; // Open Issue
}
return 'red'; // Closed Issue
}
}
if (issue.state === 'open') {
return 'green'; // Open Issue
}
return 'red'; // Closed Issue
}
export function isIssueSuggestionsLoaded() {
return !!window.config.issueValues
}
async function fetchIssueSuggestions() {
const issuePathInfo = parseIssueHref(window.location.href);
if (!issuePathInfo.ownerName) {
const repoOwnerPathInfo = parseRepoOwnerPathInfo(window.location.pathname);
issuePathInfo.ownerName = repoOwnerPathInfo.ownerName;
issuePathInfo.repoName = repoOwnerPathInfo.repoName;
// then no issuePathInfo.indexString here, it is only used to exclude the current issue when "matchIssue"
}
if (!issuePathInfo.ownerName) {
throw new Error('unexpected');
}
const res = await GET(`${window.config.appSubUrl}/${issuePathInfo.ownerName}/${issuePathInfo.repoName}/issues/suggestions`);
const issues = await res.json();
window.config.issueValues = issues;
}

View file

@ -34,6 +34,13 @@ export function parseIssueHref(href) {
return {owner, repo, type, index};
}
export function parseRepoOwnerPathInfo(pathname) {
const appSubUrl = window.config.appSubUrl;
if (appSubUrl && pathname.startsWith(appSubUrl)) pathname = pathname.substring(appSubUrl.length);
const [_, ownerName, repoName] = /([^/]+)\/([^/]+)/.exec(pathname) || [];
return {ownerName, repoName};
}
// parse a URL, either relative '/path' or absolute 'https://localhost/path'
export function parseUrl(str) {
return new URL(str, str.startsWith('http') ? undefined : window.location.origin);

View file

@ -76,6 +76,16 @@ test('parseIssueHref', () => {
expect(parseIssueHref('')).toEqual({owner: undefined, repo: undefined, type: undefined, index: undefined});
});
test('parseRepoOwnerPathInfo', () => {
expect(parseRepoOwnerPathInfo('/owner/repo/issues/new')).toEqual({ownerName: 'owner', repoName: 'repo'});
expect(parseRepoOwnerPathInfo('/owner/repo/releases')).toEqual({ownerName: 'owner', repoName: 'repo'});
expect(parseRepoOwnerPathInfo('/other')).toEqual({});
window.config.appSubUrl = '/sub';
expect(parseRepoOwnerPathInfo('/sub/owner/repo/issues/new')).toEqual({ownerName: 'owner', repoName: 'repo'});
expect(parseRepoOwnerPathInfo('/sub/owner/repo/compare/feature/branch-1...fix/branch-2')).toEqual({ownerName: 'owner', repoName: 'repo'});
window.config.appSubUrl = '';
});
test('parseUrl', () => {
expect(parseUrl('').pathname).toEqual('/');
expect(parseUrl('/path').pathname).toEqual('/path');

View file

@ -44,12 +44,45 @@ export function matchMention(queryText) {
return sortAndReduce(results);
}
export async function matchIssue(owner, repo, issueIndexStr, query) {
const res = await GET(`${window.config.appSubUrl}/${owner}/${repo}/issues/suggestions?q=${encodeURIComponent(query)}`);
export function matchIssue(queryText) {
const issues = window.config.issueValues ?? [];
const query = queryText.toLowerCase().trim();
const issues = await res.json();
const issueIndex = parseInt(issueIndexStr);
if (!query) {
// Return latest 5 issues/prs sorted by number descending
return [...issues]
.sort((a, b) => b.number - a.number)
.slice(0, 5);
}
// filter out issue with same id
return issues.filter((i) => i.id !== issueIndex);
const isDigital = /^\d+$/.test(query);
const results = [];
if (isDigital) {
// Find issues/prs with number starting with the query (prefix), sorted by number ascending
const prefixMatches = issues.filter(issue =>
String(issue.number).startsWith(query)
).sort((a, b) => a.number - b.number);
results.push(...prefixMatches);
}
if (!isDigital || results.length < 5) {
// Fallback: find by title match, sorted by number descending
const titleMatches = issues
.filter(issue =>
issue.title.toLowerCase().includes(query)
)
.sort((a, b) => b.number - a.number);
// Add only those not already in the result set
for (const match of titleMatches) {
if (!results.includes(match)) {
results.push(match);
if (results.length >= 5) break;
}
}
}
return results.slice(0, 5);
}