Files
wekan/client/components/main/globalSearch.js
T
Lauri Ojansivu 3cb089b8ca Checklist from description, action items, and search phrases.
The last three of the features other kanban apps call AI, done with plain
code (docs/Features/General/Assistants/Assistants.md):

- Checklists -> From description: the list lines of a card's description
  ("- ", "* ", "1. ", task boxes; never inside code blocks) previewed, then
  made into a checklist - ticked where the line was [x] - or into subtasks
  through addSubtaskCard.
- Create cards from action items, on a comment and in the card menu for its
  description: "TODO: ...", "- [ ] ..." and "@user ..." lines become cards
  at the top of the card's list, linking back to it, with the mentioned
  user as member when they are an active board member.
- Global search understands plain phrases in the reader's language - "my
  overdue cards", "due this week", "unassigned cards" and seven more - and
  runs them as its operators, saying which; a query with an operator in it
  is never rewritten.

Checklist from description and Action items are Show on Card rows of Board
Settings / Card and of the Admin Panel's Card fields; Search phrases is an
Admin Panel / Settings / Visibility / Features tick. Translated in every
language.

Thanks to xet7 !
2026-10-17 16:25:51 +03:00

644 lines
21 KiB
JavaScript

import { TAPi18n } from '/imports/i18n';
import { CardSearchPaged } from '../../lib/cardSearch';
import { LABEL_COLORS } from '/models/metadata/colors';
import { Query, QueryErrors } from '../../../config/query-classes';
import { OPERATOR_USER } from '/config/search-const';
import { ReactiveCache } from '/imports/reactiveCache';
import { Utils } from '/client/lib/utils';
import { allowFeature } from '/client/lib/instanceFeatures';
// docs/Features/Pages/Search-Phrases.md
const { rewriteSearchPhrases } = require('/models/lib/searchPhrases');
// const subManager = new SubsManager();
// #3392-adjacent: "my cards / all cards" toggle for global search (mirrors the
// due-cards view toggle). When "me", the current user is injected as a `user:`
// predicate (member OR assignee), reusing the existing search logic.
Template.globalSearchControls.helpers({
globalSearchView() {
return Utils.globalSearchView();
},
});
Template.globalSearchControls.events({
'click .js-global-search-view-change': Popup.open('globalSearchViewChange'),
});
Template.globalSearchViewChangePopup.events({
'click .js-global-search-view-me'() {
Utils.setGlobalSearchView('me');
Popup.back();
},
'click .js-global-search-view-all'() {
Utils.setGlobalSearchView('all');
Popup.back();
},
});
Template.globalSearch.onCreated(function () {
const search = new CardSearchPaged(this);
this.search = search;
// The operators a plain-language phrase became, shown above the results.
this.phrasedQuery = new ReactiveVar('');
this.myLists = new ReactiveVar([]);
this.myLabelNames = new ReactiveVar([]);
this.myBoardNames = new ReactiveVar([]);
this.parsingErrors = new QueryErrors();
this.queryParams = null;
Meteor.call('myLists', (err, data) => {
if (!err) {
this.myLists.set(data);
}
});
Meteor.call('myLabelNames', (err, data) => {
if (!err) {
this.myLabelNames.set(data);
}
});
Meteor.call('myBoardNames', (err, data) => {
if (!err) {
this.myBoardNames.set(data);
}
});
});
Template.globalSearch.onRendered(function () {
Meteor.subscribe('setting');
const tpl = this;
// Re-run the search reactively when the query OR the "my/all" view changes,
// so toggling the view filters immediately without a page reload.
this.autorun(() => {
const view = Utils.globalSearchView(); // reactive dependency
const queryText = Session.get('globalQuery'); // reactive dependency
if (queryText || view === 'me') {
searchAllBoards(tpl, queryText || '');
}
});
// #6034 (MVP): make search-result cards draggable so they can be dropped
// into a board list/column. Re-wire whenever the results change.
this.autorun(() => {
tpl.search.results.get(); // reactive dependency: re-run when results render
Tracker.afterFlush(() => setupResultDrag(tpl));
});
});
// #6034 (MVP): drag-and-drop search results into board columns.
//
// We make each `.global-search-results-list` result item a jquery-ui
// `draggable` (clone helper), and make every board list's `.js-minicards`
// container a `droppable`. On drop we resolve the dragged card and call the
// existing `card.move(boardId, swimlaneId, listId, sort)` model method - the
// same method the in-board card sortable uses - so the move stays consistent
// with normal card drag-drop and is persisted + reactively re-rendered.
//
// LIMITATION / TODO: this MVP drops the card at the END of the target list
// (sort = list cards length) rather than at the exact pixel-precise insertion
// index used by the in-board minicard sortable. Pixel-precise positioning and
// multi-select drag are intentionally out of scope here; wiring those would
// require modifying the (non-owned) list/minicard sortable `receive` handler.
// Drag is only enabled when the board is editable and a board is open.
function setupResultDrag(tpl) {
try {
if (typeof window === 'undefined' || !window.jQuery) return;
const $ = window.jQuery;
const $items = tpl.$('.global-search-results-list .result-card-wrapper');
if (!$items.length || typeof $items.draggable !== 'function') return;
// Only allow DnD when we are inside a board the user can modify.
const boardId = Session.get('currentBoard');
if (!boardId) return;
const canModify =
Utils && typeof Utils.canModifyBoard === 'function'
? Utils.canModifyBoard()
: false;
if (!canModify) return;
$items.each(function () {
const el = this;
// Avoid double-initialising the same element.
if ($(el).data('uiDraggable')) return;
$(el).draggable({
helper: 'clone',
appendTo: 'body',
revert: 'invalid',
revertDuration: 150,
cursor: 'grabbing',
zIndex: 1000,
start(evt, ui) {
ui.helper.addClass('global-search-result-drag-helper');
ui.helper.css('width', $(el).width());
},
});
});
// Make board lists accept the dropped result card.
const $lists = $('.list .js-minicards');
if (!$lists.length || typeof $lists.droppable !== 'function') return;
$lists.each(function () {
const listEl = this;
if ($(listEl).data('uiDroppable')) return;
$(listEl).droppable({
accept: '.result-card-wrapper',
tolerance: 'pointer',
hoverClass: 'global-search-drop-hover',
drop(evt, ui) {
onResultDroppedOnList(listEl, ui.draggable.get(0));
},
});
});
} catch (e) {
console.error('Error wiring search-result drag-and-drop (#6034):', e);
}
}
// Resolve the dragged result card + target list and perform the move using the
// existing card model `move()` method (mirrors the in-board card sortable).
function onResultDroppedOnList(listEl, draggedEl) {
try {
if (!listEl || !draggedEl) return;
// Card data from the dragged result item (Blaze data on the result wrapper,
// falling back to the inner minicard).
let cardData = Blaze.getData(draggedEl);
if (!cardData || !cardData._id) {
const inner = draggedEl.querySelector('.js-minicard');
if (inner) cardData = Blaze.getData(inner);
}
if (!cardData || !cardData._id) return;
const card = ReactiveCache.getCard(cardData._id);
if (!card || typeof card.move !== 'function') return;
// Target list / swimlane / board from the drop target.
const listData = Blaze.getData(listEl.closest('.list') || listEl);
if (!listData || !listData._id) return;
const listId = listData._id;
const currentBoard = Utils.getCurrentBoard();
if (!currentBoard) return;
let swimlaneId = listData.swimlaneId;
if (!swimlaneId) {
const swimlaneEl = listEl.closest('.swimlane');
if (swimlaneEl) {
const swimlaneData = Blaze.getData(swimlaneEl);
swimlaneId = swimlaneData && swimlaneData._id;
}
}
if (!swimlaneId) {
const def = currentBoard.getDefaultSwimline && currentBoard.getDefaultSwimline();
swimlaneId = (def && def._id) || card.swimlaneId;
}
// MVP: append to the end of the target list.
let sort = 0;
try {
const existing = ReactiveCache.getCards(
{ listId, archived: false },
{ sort: { sort: -1 }, limit: 1 },
);
if (existing && existing.length && typeof existing[0].sort === 'number') {
sort = existing[0].sort + 1;
}
} catch (e) {
sort = 0;
}
card.move(currentBoard._id, swimlaneId, listId, sort);
} catch (e) {
console.error('Error moving dropped search result (#6034):', e);
}
}
function searchAllBoards(tpl, queryText) {
const search = tpl.search;
queryText = (queryText || '').trim();
search.query.set(queryText);
search.resetSearch();
tpl.parsingErrors = new QueryErrors();
const mine = Utils.globalSearchView() === 'me';
// Nothing to search: empty query and not restricting to the current user.
if (!queryText && !mine) {
return;
}
search.searching.set(true);
// Search phrases: "my overdue cards printer" runs as its operators, and the
// page says so. A query with an operator in it is never rewritten.
let parsedText = queryText;
tpl.phrasedQuery.set('');
if (allowFeature('search-phrases')) {
const phrased = rewriteSearchPhrases(queryText, {
translate: key => TAPi18n.__(key),
username: (ReactiveCache.getCurrentUser() || {}).username || '',
});
if (phrased.matched) {
parsedText = phrased.query;
tpl.phrasedQuery.set(phrased.query);
}
}
const query = new Query();
query.buildParams(parsedText);
const queryParams = query.getQueryParams();
// "My cards": restrict to cards where the current user is member or assignee.
if (mine) {
const currentUser = ReactiveCache.getCurrentUser();
if (currentUser && currentUser.username) {
queryParams.addPredicate(OPERATOR_USER, currentUser.username);
}
}
tpl.queryParams = queryParams.getParams();
if (query.hasErrors()) {
search.searching.set(false);
search.queryErrors = query.errors();
search.hasResults.set(true);
search.hasQueryErrors.set(true);
return;
}
search.runGlobalSearch(queryParams);
}
function errorMessages(tpl) {
if (tpl.parsingErrors.hasErrors()) {
return tpl.parsingErrors.errorMessages();
}
return tpl.search.queryErrorMessages();
}
Template.globalSearch.helpers({
phrasedQuery() {
return Template.instance().phrasedQuery.get();
},
userId() {
return Meteor.userId();
},
// Return ReactiveVar values so Blaze can use them
searching() {
const val = Template.instance().search.searching.get();
return val;
},
hasResults() {
const val = Template.instance().search.hasResults.get();
return val;
},
hasQueryErrors() {
const val = Template.instance().search.hasQueryErrors.get();
return val;
},
serverError() {
const val = Template.instance().search.serverError.get();
return val;
},
query() {
return Template.instance().search.query;
},
debug() {
const val = Template.instance().search.debug.get();
return val;
},
resultsHeading() {
const rv = Template.instance().search.resultsHeading;
return rv ? rv.get() : '';
},
results() {
const rv = Template.instance().search.results;
return rv ? rv.get() : [];
},
hasNextPage() {
const rv = Template.instance().search.hasNextPage;
return rv ? rv.get() : false;
},
hasPreviousPage() {
const rv = Template.instance().search.hasPreviousPage;
return rv ? rv.get() : false;
},
sessionData() {
return Template.instance().search.sessionData;
},
getSearchHref() {
return Template.instance().search.getSearchHref();
},
myLists() {
const rv = Template.instance().myLists;
return rv ? rv.get() : [];
},
myLabelNames() {
const rv = Template.instance().myLabelNames;
return rv ? rv.get() : [];
},
myBoardNames() {
const rv = Template.instance().myBoardNames;
return rv ? rv.get() : [];
},
errorMessages() {
return errorMessages(Template.instance());
},
getSearchData() {
return Template.instance().search;
},
boardColorClass() {
const boardId = Session.get('currentBoard');
const board = boardId ? ReactiveCache.getBoard(boardId) : null;
return board ? board.colorClass() : 'board-color-belize';
},
searchInstructions() {
try {
const tags = {
operator_board: TAPi18n.__('operator-board'),
operator_list: TAPi18n.__('operator-list'),
operator_swimlane: TAPi18n.__('operator-swimlane'),
operator_comment: TAPi18n.__('operator-comment'),
operator_label: TAPi18n.__('operator-label'),
operator_label_abbrev: TAPi18n.__('operator-label-abbrev'),
operator_user: TAPi18n.__('operator-user'),
operator_user_abbrev: TAPi18n.__('operator-user-abbrev'),
operator_member: TAPi18n.__('operator-member'),
operator_member_abbrev: TAPi18n.__('operator-member-abbrev'),
operator_assignee: TAPi18n.__('operator-assignee'),
operator_assignee_abbrev: TAPi18n.__('operator-assignee-abbrev'),
operator_creator: TAPi18n.__('operator-creator'),
operator_due: TAPi18n.__('operator-due'),
operator_created: TAPi18n.__('operator-created'),
operator_modified: TAPi18n.__('operator-modified'),
operator_status: TAPi18n.__('operator-status'),
operator_has: TAPi18n.__('operator-has'),
operator_sort: TAPi18n.__('operator-sort'),
operator_limit: TAPi18n.__('operator-limit'),
operator_debug: TAPi18n.__('operator-debug'),
operator_org: TAPi18n.__('operator-org'),
operator_team: TAPi18n.__('operator-team'),
operator_number: TAPi18n.__('operator-number'),
predicate_overdue: TAPi18n.__('predicate-overdue'),
predicate_archived: TAPi18n.__('predicate-archived'),
predicate_all: TAPi18n.__('predicate-all'),
predicate_ended: TAPi18n.__('predicate-ended'),
predicate_week: TAPi18n.__('predicate-week'),
predicate_month: TAPi18n.__('predicate-month'),
predicate_quarter: TAPi18n.__('predicate-quarter'),
predicate_year: TAPi18n.__('predicate-year'),
predicate_attachment: TAPi18n.__('predicate-attachment'),
predicate_description: TAPi18n.__('predicate-description'),
predicate_checklist: TAPi18n.__('predicate-checklist'),
predicate_public: TAPi18n.__('predicate-public'),
predicate_private: TAPi18n.__('predicate-private'),
predicate_due: TAPi18n.__('predicate-due'),
predicate_created: TAPi18n.__('predicate-created'),
predicate_modified: TAPi18n.__('predicate-modified'),
predicate_start: TAPi18n.__('predicate-start'),
predicate_end: TAPi18n.__('predicate-end'),
predicate_assignee: TAPi18n.__('predicate-assignee'),
predicate_member: TAPi18n.__('predicate-member'),
predicate_selector: TAPi18n.__('predicate-selector'),
predicate_projection: TAPi18n.__('predicate-projection'),
};
let text = '';
[
['# ', 'globalSearch-instructions-heading'],
['\n', 'globalSearch-instructions-description'],
['\n\n', 'globalSearch-instructions-operators'],
['\n- ', 'globalSearch-instructions-operator-board'],
['\n- ', 'globalSearch-instructions-operator-list'],
['\n- ', 'globalSearch-instructions-operator-swimlane'],
['\n- ', 'globalSearch-instructions-operator-comment'],
['\n- ', 'globalSearch-instructions-operator-label'],
['\n- ', 'globalSearch-instructions-operator-hash'],
['\n- ', 'globalSearch-instructions-operator-user'],
['\n- ', 'globalSearch-instructions-operator-at'],
['\n- ', 'globalSearch-instructions-operator-member'],
['\n- ', 'globalSearch-instructions-operator-assignee'],
['\n- ', 'globalSearch-instructions-operator-creator'],
['\n- ', 'globalSearch-instructions-operator-org'],
['\n- ', 'globalSearch-instructions-operator-team'],
['\n- ', 'globalSearch-instructions-operator-number'],
['\n- ', 'globalSearch-instructions-operator-due'],
['\n- ', 'globalSearch-instructions-operator-created'],
['\n- ', 'globalSearch-instructions-operator-modified'],
['\n- ', 'globalSearch-instructions-operator-status'],
['\n - ', 'globalSearch-instructions-status-archived'],
['\n - ', 'globalSearch-instructions-status-public'],
['\n - ', 'globalSearch-instructions-status-private'],
['\n - ', 'globalSearch-instructions-status-all'],
['\n - ', 'globalSearch-instructions-status-ended'],
['\n- ', 'globalSearch-instructions-operator-has'],
['\n- ', 'globalSearch-instructions-operator-sort'],
['\n- ', 'globalSearch-instructions-operator-limit'],
['\n## ', 'heading-notes'],
['\n- ', 'globalSearch-instructions-notes-1'],
['\n- ', 'globalSearch-instructions-notes-2'],
['\n- ', 'globalSearch-instructions-notes-3'],
['\n- ', 'globalSearch-instructions-notes-3-2'],
['\n- ', 'globalSearch-instructions-notes-4'],
['\n- ', 'globalSearch-instructions-notes-5'],
].forEach(([prefix, instruction]) => {
text += `${prefix}${TAPi18n.__(instruction, tags)}`
// Replace *<text>* with `<text>` so markdown shows correctly
.replace(/\*\</, '`<')
.replace(/\>\*/, '\>\`');
});
return text;
} catch (e) {
console.error('Error building searchInstructions:', e);
return '';
}
},
labelColors() {
try {
if (!LABEL_COLORS) return [];
return LABEL_COLORS.map(
color => {
return { color, name: TAPi18n.__(`color-${color}`) };
},
);
} catch (e) {
console.error('Error building labelColors:', e);
return [];
}
},
});
Template.globalSearch.events({
'click input.global-search-query-input'(evt) {
evt.preventDefault();
evt.stopPropagation();
},
'focus input.global-search-query-input'(evt) {
evt.preventDefault();
evt.stopPropagation();
},
'keyup input.global-search-query-input'(evt, tpl) {
evt.preventDefault();
evt.stopPropagation();
// Store the query value
tpl.search.query.set(evt.target.value);
},
'keydown input.global-search-query-input'(evt, tpl) {
// Allow normal key behavior but capture Enter key
if (evt.key === 'Enter') {
evt.preventDefault();
evt.stopPropagation();
searchAllBoards(tpl, evt.target.value);
}
},
'submit .js-search-query-form'(evt, tpl) {
evt.preventDefault();
searchAllBoards(tpl, evt.target.searchQuery.value);
},
'click .js-label-color'(evt, tpl) {
evt.preventDefault();
const input = document.getElementById('global-search-input');
tpl.search.query.set(
`${input.value} ${TAPi18n.__('operator-label')}:"${
evt.currentTarget.textContent
}"`,
);
document.getElementById('global-search-input').focus();
},
'click .js-board-title'(evt, tpl) {
evt.preventDefault();
const input = document.getElementById('global-search-input');
tpl.search.query.set(
`${input.value} ${TAPi18n.__('operator-board')}:"${
evt.currentTarget.textContent
}"`,
);
document.getElementById('global-search-input').focus();
},
'click .js-list-title'(evt, tpl) {
evt.preventDefault();
const input = document.getElementById('global-search-input');
tpl.search.query.set(
`${input.value} ${TAPi18n.__('operator-list')}:"${
evt.currentTarget.textContent
}"`,
);
document.getElementById('global-search-input').focus();
},
'click .js-label-name'(evt, tpl) {
evt.preventDefault();
const input = document.getElementById('global-search-input');
tpl.search.query.set(
`${input.value} ${TAPi18n.__('operator-label')}:"${
evt.currentTarget.textContent
}"`,
);
document.getElementById('global-search-input').focus();
},
'click .js-new-search'(evt, tpl) {
evt.preventDefault();
const input = document.getElementById('global-search-input');
input.value = '';
tpl.search.query.set('');
tpl.search.hasResults.set(false);
},
'click .js-next-page'(evt, tpl) {
evt.preventDefault();
tpl.search.nextPage();
},
'click .js-previous-page'(evt, tpl) {
evt.preventDefault();
tpl.search.previousPage();
},
});
// resultsPaged template helpers - receives search data context from parent template.
Template.resultsPaged.helpers({
resultsHeading() {
const data = Template.currentData();
if (data && data.resultsHeading) {
const rv = data.resultsHeading;
return rv && typeof rv.get === 'function' ? rv.get() : rv;
}
return '';
},
results() {
const data = Template.currentData();
if (data && data.results) {
const rv = data.results;
return rv && typeof rv.get === 'function' ? rv.get() : rv;
}
return [];
},
getSearchHref() {
const data = Template.currentData();
if (data && typeof data.getSearchHref === 'function') {
return data.getSearchHref();
}
return '';
},
hasPreviousPage() {
const data = Template.currentData();
if (data && data.hasPreviousPage) {
const rv = data.hasPreviousPage;
return rv && typeof rv.get === 'function' ? rv.get() : rv;
}
return false;
},
hasNextPage() {
const data = Template.currentData();
if (data && data.hasNextPage) {
const rv = data.hasNextPage;
return rv && typeof rv.get === 'function' ? rv.get() : rv;
}
return false;
},
});
Template.resultsPaged.events({
'click .js-next-page'(evt) {
evt.preventDefault();
// Walk up to find the search instance
let view = Template.instance().view;
while (view) {
const tplInst = view.templateInstance && view.templateInstance();
if (tplInst && tplInst.search) {
tplInst.search.nextPage();
return;
}
view = view.parentView;
}
},
'click .js-previous-page'(evt) {
evt.preventDefault();
let view = Template.instance().view;
while (view) {
const tplInst = view.templateInstance && view.templateInstance();
if (tplInst && tplInst.search) {
tplInst.search.previousPage();
return;
}
view = view.parentView;
}
},
});