rob-revisited/ide/ui/js/board.js

1231 lines
73 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// The Board window: Kanban (columns, cards, drag and drop, Alt+arrows), notes (Markdown) and an overview of the project.
// Its data is jumphp.net's board for a project linked to the site, else the project's .jumphp/board.json (ide/src/Board,
// commands board.*); a local board can import the issues / pull requests of the project's forge through gh. Changes are
// shown at once (optimistic) and undone with a message when the backend refuses them.
// jumphp.net's board is shared by its members: its live channel (BoardLive: board.live.*) brings the others' changes within a second,
// who is on it (avatars) and which card they edit ("X is editing"); a card saved by someone else meanwhile is merged field by field
// (board-merge.js: the fields both changed are asked), a note paragraph by paragraph (the site).
import { backend } from './backend.js';
import { el, clear, icon, notify, prefs, t, confirm, dialog, prompt, menu, progressBar, debounce, timeAgo } from './ui.js';
import { renderMarkdown } from './markdown.js';
import { parse as parseMd, toDom as mdDom, plainText } from './board-md.js';
import { applyEvents, mergeCard, resolve, presence as whoIsHere } from './board-merge.js';
const PRIORITIES = [['', 'No priority'], ['low', 'Low'], ['medium', 'Medium'], ['high', 'High'], ['urgent', 'Urgent']];
const COLORS = ['#e5534b', '#e0823d', '#c69026', '#57ab5a', '#39c5cf', '#539bf5', '#986ee2', '#e275ad', '#768390'];
const DAY = 86400000;
const today = () => new Date().toISOString().slice(0, 10);
const epoch = (iso) => { const ms = Date.parse(iso || ''); return Number.isNaN(ms) ? 0 : ms / 1000; };
const done = (card) => (card.checklist || []).filter((i) => i.done).length;
/** its own styles (several people on the board), once */
function liveStyles() {
if (document.getElementById('board-live-css')) return;
document.head.append(el('link', { id: 'board-live-css', rel: 'stylesheet', href: new URL('../css/board-live.css', import.meta.url).href }));
}
export class BoardPanel {
constructor(app) {
liveStyles();
this.app = app;
this.node = el('div.board-view');
this.tab = prefs.get('board:tab', 'board');
this.state = { mode: 'local', linked: false };
this.data = null;
this.notes = null;
this.note = null; // the note open in the editor
this.error = null;
this.filter = { text: '', label: '' };
this.busy = false;
this.saveNoteSoon = debounce(() => this.saveNote(), 700);
this.here = { people: [], editing: new Map() }; // who is on jumphp.net's board, what they edit
this.liveState = 'off';
this.live = false;
this.myClient = null;
backend.on('board.live', (m) => this.onLive(m));
backend.on('board.live.presence', (p) => this.onPresence(p));
backend.on('board.live.state', (s) => { this.liveState = s.state; this.renderLive(); });
backend.on('board.live.reload', () => { this.quietReload(); if (this.tab === 'notes') this.loadNotes().then(() => this.render()); });
}
title() { return t('Board'); }
actions() {
return [
el('button', { title: t('Sync the issues and pull requests'), onclick: () => this.sync() }, icon('pull')),
el('button', { title: t('Refresh'), onclick: () => this.load() }, icon('refresh')),
el('button', { title: t('More'), onclick: (e) => this.moreMenu(e.currentTarget) }, icon('more')),
];
}
async shown() {
if (!this.data) await this.load(); else this.render();
}
/** the board (and the notes) from the backend */
async load() {
this.state = await backend.invoke('board.state').catch(() => this.state);
try {
this.data = await backend.invoke('board.get');
this.error = null;
if (this.data.recovered) notify(t('The board file could not be read: it was put aside as {path} and the last good version is used.', { path: this.data.recovered }), 'error', { title: t('Board') });
} catch (e) {
this.error = String(e.message || e);
this.data = this.data || null;
}
if (this.tab === 'notes' || this.notes) await this.loadNotes();
this.render();
if (this.state.mode === 'remote') this.startLive(); else this.stopLive();
return this.data;
}
// ---- Several people on jumphp.net's board ----
startLive() {
if (this.live) return;
this.live = true;
backend.invoke('board.live.start').then((s) => { this.liveState = s.state; this.myClient = s.client; this.renderLive(); }).catch(() => { this.live = false; });
}
stopLive() {
if (!this.live) return;
this.live = false;
this.here = { people: [], editing: new Map() };
backend.invoke('board.live.stop').catch(() => {});
this.renderLive();
}
/** what this window edits now (a card, a note, nothing): the others see "X is editing" */
editing(what) {
if (this.state.mode === 'remote' && this.live) backend.invoke('board.live.editing', { what }).catch(() => {});
}
/** the others' changes: applied (never over a newer version), the open note / card told */
onLive(m) {
if (!this.data) return;
const changed = applyEvents(this.data, m.events, String);
const who = m.by || '?';
if (!m.mine && this.editingCard && changed.cards.has(String(this.editingCard.id))) {
notify(t('{who} just changed this card: when you save, your changes will be merged with theirs.', { who }), 'info', { title: t('Board') });
}
for (const e of changed.notes) this.noteChanged(e, m);
// the project's shared HTTP collections (HTTP Client > Share with the Project's Members): said, the HTTP Client's Sync brings them
const collections = [...new Set(changed.http.map((e) => e.collection).filter(Boolean))];
if (!m.mine && collections.length) notify(t('{who} changed the shared HTTP collection {name}: Sync it in the HTTP Client to get the change.', { who, name: collections.join(', ') }), 'info', { title: 'HTTP Client' });
if (changed.cards.size || changed.columns) { if (this.tab === 'board') this.renderColumns(); else if (this.tab === 'overview') this.render(); }
}
async noteChanged(e, m) {
if (!this.notes) return;
const id = String(e.note?.id ?? e.id);
const i = this.notes.findIndex((n) => String(n.id) === id);
const open = this.note && String(this.note.id) === id;
if (e.type === 'note.deleted') {
if (i >= 0) this.notes.splice(i, 1);
if (open && !m.mine) { this.note = null; this.noteDirty = false; notify(t('This note was deleted by {who}.', { who: m.by || '?' }), 'info', { title: t('Notes') }); }
if (this.tab === 'notes') this.render();
return;
}
if (i < 0) { this.notes.unshift({ ...e.note, body: '', loaded: false }); if (this.tab === 'notes') this.render(); return; }
const n = this.notes[i];
if (m.mine || (n.version ?? 0) >= (e.note.version ?? 0)) return;
Object.assign(n, { title: e.note.title, updatedAt: e.note.updatedAt });
if (!open) { n.loaded = false; if (this.tab === 'notes') this.render(); return; }
if (this.noteDirty) {
notify(t('{who} saved this note: when you save, your changes will be merged with theirs, paragraph by paragraph.', { who: m.by || '?' }), 'info', { title: t('Notes') });
return;
}
// nothing typed here: their text at once
await this.fetchNote(n);
if (this.tab === 'notes' && !this.noteDirty) this.render();
}
onPresence(p) {
this.myClient = p.client || this.myClient;
this.here = whoIsHere(p.people, this.myClient);
this.renderLive();
}
/** the avatars and the live dot of the header, the "is editing" badges of the cards */
renderLive() {
const node = this.node.querySelector('.board-presence');
if (node) {
const people = this.state.mode === 'remote' ? this.here.people : [];
node.replaceChildren(...people.map((person) => {
const label = (person.name && person.name !== person.login ? `${person.name} (@${person.login})` : '@' + person.login) + (person.via.has('ide') ? ' · IDE' : '');
return el('span.board-person' + (person.via.has('ide') ? '.ide' : ''), { title: label },
person.avatar ? el('img', { src: person.avatar, alt: '' }) : el('span', {}, person.login.slice(0, 1).toUpperCase()));
}));
const dot = el('span.board-live-dot.' + this.liveState, { title: t({ live: 'Live: the others\' changes appear at once.', polling: 'Live (every few seconds).', offline: 'Offline: trying again…' }[this.liveState] || 'Local') });
if (this.state.mode === 'remote' && this.liveState !== 'off') node.prepend(dot);
}
this.columnsNode?.querySelectorAll('.board-card').forEach((cardEl) => this.badge(cardEl));
}
badge(cardEl) {
const who = this.here.editing.get('card:' + cardEl.dataset.card) || [];
let b = cardEl.querySelector('.board-editing');
if (!who.length) { b?.remove(); cardEl.classList.remove('edited'); return; }
if (!b) cardEl.append(b = el('div.board-editing'));
b.textContent = '✎ ' + t('{who} is editing', { who: who.map((w) => w.name || w.login).join(', ') });
cardEl.classList.add('edited');
}
/** a note of jumphp.net with its text and version (the list comes without the texts) */
async fetchNote(n) {
const full = await backend.invoke('board.note.get', { id: n.id });
if (full) Object.assign(n, { title: full.title, body: full.body, updatedAt: full.updatedAt, version: full.version, base: full.body, loaded: true });
return n;
}
/** the merge dialog: per field both changed, mine or theirs; null: keep theirs everywhere */
chooseMerge(conflicts) {
const names = { title: 'Title', body: 'Description', labels: 'Labels', assignee: 'Assignee', due: 'Due date', priority: 'Priority', checklist: 'Checklist' };
const show = (field, v) => {
if (v === null || v === undefined || v === '') return '—';
if (field === 'labels') return v.map((l) => l.name).join(', ') || '—';
if (field === 'checklist') return v.map((i) => (i.done ? '☑ ' : '☐ ') + i.text).join('\n') || '—';
return typeof v === 'object' ? JSON.stringify(v) : String(v);
};
const choice = {};
const body = el('div.board-merge', {}, el('p', {}, t('Someone else changed this card while you were editing it. What only you changed is kept; for each field you both changed, choose the version to keep.')),
...conflicts.map((c) => {
choice[c.field] = 'mine';
const option = (side, label, value) => el('label.board-merge-option', {},
el('input', { type: 'radio', name: 'merge-' + c.field, checked: side === 'mine', onchange: () => { choice[c.field] = side; } }), ' ', t(label), el('pre', {}, show(c.field, value)));
return el('fieldset.board-merge-field', {}, el('legend', {}, t(names[c.field] || c.field)), option('mine', 'Keep my version', c.mine), option('theirs', 'Keep theirs', c.theirs));
}));
return new Promise((done) => {
let saved = false;
dialog({ title: 'Merge the changes', body, wide: true, onClose: () => { if (!saved) done(null); },
buttons: [{ label: 'Keep theirs everywhere' }, { label: 'Save the merge', primary: true, action: () => { saved = true; done({ ...choice }); } }] });
});
}
async loadNotes() {
try { this.notes = await backend.invoke('board.notes'); } catch (e) { this.notes = this.notes || []; notify(String(e.message || e), 'error', { title: t('Notes') }); }
if (this.note) this.note = this.notes.find((n) => String(n.id) === String(this.note.id)) || null;
}
setTab(tab) {
this.tab = tab;
prefs.set('board:tab', tab);
if (tab === 'notes' && !this.notes) this.loadNotes().then(() => this.render());
else if (tab === 'overview') { this.render(); this.quietReload(); } // the newest activity
else this.render();
}
render() {
clear(this.node);
const tabs = [['board', 'Board'], ['notes', 'Notes'], ['overview', 'Overview']];
const where = this.state.mode === 'remote' ? el('span.board-where.remote', { title: t('Kept on jumphp.net ({slug})', { slug: this.state.slug || '' }) }, icon('globe'), 'jumphp.net')
: el('span.board-where', { title: this.state.file || '.jumphp/board.json' }, icon('file'), t('Local'));
this.node.append(el('div.cryo-tabs.board-tabs', {}, ...tabs.map(([id, label]) => el('button' + (this.tab === id ? '.on' : ''), { onclick: () => this.setTab(id) }, t(label))), el('span.tw-spacer'),
el('span.board-presence', { title: t('On this board now') }), where));
this.renderLive();
if (this.error) {
this.node.append(el('div.board-error', {}, el('b', {}, t('The board could not be loaded')), el('div', {}, this.error),
el('div.board-row', {}, el('button.btn', { onclick: () => this.load() }, t('Try again')),
this.state.mode === 'remote' ? el('button.btn.primary', { onclick: () => this.setMode('local') }, t('Use the local board')) : null)));
if (!this.data) return;
}
if (!this.data) { this.node.append(el('div.board-empty', {}, t('Loading…'))); return; }
if (this.tab === 'notes') this.renderNotes();
else if (this.tab === 'overview') this.renderOverview();
else this.renderBoard();
}
// ---- Board ----
labels() {
const all = new Map();
for (const c of this.data.cards) for (const l of c.labels || []) if (!all.has(l.name.toLowerCase())) all.set(l.name.toLowerCase(), l);
return [...all.values()].sort((a, b) => a.name.localeCompare(b.name));
}
visible(card) {
const q = this.filter.text.trim().toLowerCase();
if (q && !`${card.title}\n${card.body}\n${card.assignee}\n${card.issue ? '#' + card.issue.number : ''}`.toLowerCase().includes(q)) return false;
if (this.filter.label && !(card.labels || []).some((l) => l.name.toLowerCase() === this.filter.label)) return false;
return true;
}
cardsOf(columnId) {
return this.data.cards.filter((c) => String(c.columnId) === String(columnId)).sort((a, b) => a.position - b.position);
}
renderBoard() {
const search = el('input.input.board-filter', { type: 'search', placeholder: t('Filter cards…'), value: this.filter.text,
oninput: debounce((e) => { this.filter.text = e.target.value; this.renderColumns(); }, 120) });
const labels = this.labels();
const labelSelect = el('select.input.board-label-filter', { onchange: (e) => { this.filter.label = e.target.value; this.renderColumns(); } },
el('option', { value: '' }, t('All labels')), ...labels.map((l) => el('option', { value: l.name.toLowerCase(), selected: this.filter.label === l.name.toLowerCase() }, l.name)));
this.node.append(el('div.board-toolbar', {}, search, labelSelect,
el('button.btn.small', { title: t('Add a column'), onclick: () => this.addColumn() }, icon('plus'), t('Column'))));
this.columnsNode = el('div.board-columns');
this.node.append(this.columnsNode);
this.renderColumns();
}
renderColumns() {
if (!this.columnsNode) return;
const focused = document.activeElement?.dataset?.card;
clear(this.columnsNode);
const columns = [...this.data.columns].sort((a, b) => a.position - b.position);
columns.forEach((column, index) => {
const cards = this.cardsOf(column.id);
const shown = cards.filter((c) => this.visible(c));
const list = el('div.board-cards', { dataset: { column: column.id } });
for (const card of shown) list.append(this.cardNode(card, index === columns.length - 1));
this.dropZone(list, column);
const add = this.composer(column);
this.columnsNode.append(el('div.board-column', { dataset: { column: column.id } },
el('div.board-column-head', { ondblclick: () => this.renameColumn(column) },
el('b', {}, column.name), el('span.board-count', {}, shown.length === cards.length ? String(cards.length) : `${shown.length}/${cards.length}`), el('span.tw-spacer'),
el('button.icon-btn', { title: t('Column actions'), onclick: (e) => this.columnMenu(column, e.currentTarget) }, icon('more'))),
list, add));
});
if (focused) this.columnsNode.querySelector(`[data-card="${CSS.escape(focused)}"]`)?.focus();
}
/**
* "Add a card…" of a column: a title (Enter adds it), and a description of several lines that opens below it once a title
* is typed (Ctrl+Enter adds the card from there). The new card is shown at once, scrolled into view.
*/
composer(column) {
const title = el('input.input.board-quick', { placeholder: t('Add a card…'), maxLength: 500 });
const body = el('textarea.input.board-quick-body', { placeholder: t('Description (optional, several lines)'), rows: 3 });
const box = el('div.board-composer');
const open = (on) => box.classList.toggle('open', on);
const submit = async () => {
const text = title.value.trim();
if (!text) { if (body.value.trim()) { notify(t('A card needs a title.'), 'error', { title: t('Board') }); title.focus(); } return; }
const description = body.value;
title.value = ''; body.value = '';
const card = await this.addCard(column.id, text, description.trim() ? { body: description } : {});
const again = this.columnsNode?.querySelector(`.board-column[data-column="${CSS.escape(String(column.id))}"] .board-quick`);
again?.focus();
if (card) this.reveal(card.id);
};
// opened by typing a title (not by the focus: the cards do not move under a double click)
title.addEventListener('input', () => open(title.value.trim() !== '' || body.value.trim() !== ''));
title.addEventListener('keydown', (e) => {
if (e.key === 'Enter') { e.preventDefault(); submit(); }
if (e.key === 'Escape') { title.value = ''; body.value = ''; open(false); title.blur(); }
});
body.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); submit(); }
if (e.key === 'Escape') { open(false); title.focus(); }
});
box.addEventListener('focusout', (e) => { if (!box.contains(e.relatedTarget) && !title.value.trim() && !body.value.trim()) open(false); });
box.append(title, body, el('div.board-composer-actions', {},
el('span.pub-faint', {}, t('Enter: add · Ctrl+Enter in the description')),
el('button.btn.small.primary', { onmousedown: (e) => e.preventDefault(), onclick: submit }, t('Add'))));
return box;
}
/** a card brought into view and lit for a moment (a new one at the bottom of a long column) */
reveal(id) {
const node = this.columnsNode?.querySelector(`[data-card="${CSS.escape(String(id))}"]`);
if (!node) return;
node.scrollIntoView({ block: 'nearest', inline: 'nearest' });
node.classList.add('fresh');
setTimeout(() => node.classList.remove('fresh'), 1200);
}
cardNode(card, inLast) {
const overdue = card.due && card.due < today() && !inLast;
const total = (card.checklist || []).length;
const node = el(`div.board-card${card.priority ? '.p-' + card.priority : ''}`, {
draggable: true, tabIndex: 0, dataset: { card: card.id },
title: t('Double-click to open, drag or Alt+arrows to move'),
onclick: (e) => { if (!e.target.closest('a, button')) e.currentTarget.focus(); },
ondblclick: (e) => { if (!e.target.closest('a, button')) this.editCard(card); },
ondragstart: (e) => { e.dataTransfer.setData('text/x-board-card', String(card.id)); e.dataTransfer.effectAllowed = 'move'; node.classList.add('dragging'); this.dragging = card.id; },
ondragend: () => { node.classList.remove('dragging'); this.dragging = null; this.columnsNode?.querySelectorAll('.drop-before, .drop-end').forEach((n) => n.classList.remove('drop-before', 'drop-end')); },
onkeydown: (e) => this.cardKey(e, card),
},
(card.labels || []).length ? el('div.board-labels', {}, ...card.labels.map((l) => el('span.board-label', { style: { background: l.color } }, l.name))) : null,
el('div.board-card-title', {}, card.title),
card.body?.trim() ? el('div.board-card-body', {}, excerpt(card.body)) : null,
el('div.board-meta', {},
card.issue ? el('a.board-issue.' + card.issue.state, { href: '#', title: card.issue.url, onclick: (e) => { e.preventDefault(); e.stopPropagation(); if (card.issue.url) this.app.openUrl(card.issue.url); } },
(card.issue.kind === 'pr' ? 'PR ' : '') + '#' + card.issue.number) : null,
card.priority ? el('span.board-priority', {}, t(PRIORITIES.find(([v]) => v === card.priority)?.[1] || card.priority)) : null,
card.due ? el('span.board-due' + (overdue ? '.overdue' : ''), { title: t('Due date') }, card.due) : null,
total ? el('span.board-check' + (done(card) === total ? '.all' : ''), { title: t('Checklist') }, `☑ ${done(card)}/${total}`) : null,
(card.attachments || []).length ? el('span.board-has-files', { title: t('Pictures') }, icon('camera'), String(card.attachments.length)) : null,
card.assignee ? el('span.board-assignee', { title: t('Assignee') }, '@' + card.assignee) : null));
this.badge(node);
return node;
}
/** where a dragged card lands: before the card under the pointer, else at the end */
dropZone(list, column) {
const target = (e) => {
const cards = [...list.querySelectorAll('.board-card:not(.dragging)')];
return cards.find((n) => { const r = n.getBoundingClientRect(); return e.clientY < r.top + r.height / 2; }) || null;
};
list.addEventListener('dragover', (e) => {
if (!e.dataTransfer.types.includes('text/x-board-card')) return;
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
this.columnsNode.querySelectorAll('.drop-before, .drop-end').forEach((n) => n.classList.remove('drop-before', 'drop-end'));
const before = target(e);
if (before) before.classList.add('drop-before'); else list.classList.add('drop-end');
});
list.addEventListener('dragleave', (e) => { if (!list.contains(e.relatedTarget)) list.classList.remove('drop-end'); });
list.addEventListener('drop', (e) => {
const id = e.dataTransfer.getData('text/x-board-card');
if (!id) return;
e.preventDefault();
const before = target(e);
// the position among the column's other cards (filtered ones included: the index of the card it lands before)
const others = this.cardsOf(column.id).filter((c) => String(c.id) !== id);
const position = before ? others.findIndex((c) => String(c.id) === before.dataset.card) : others.length;
this.move(id, column.id, position < 0 ? others.length : position);
});
}
cardKey(e, card) {
if (e.key === 'Enter') { e.preventDefault(); this.editCard(card); return; }
if (e.key === 'Delete') { e.preventDefault(); this.deleteCard(card); return; }
if (!e.altKey || !['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key)) {
if (['ArrowUp', 'ArrowDown'].includes(e.key)) { // move the focus between cards
e.preventDefault();
const all = [...e.currentTarget.parentNode.querySelectorAll('.board-card')];
all[all.indexOf(e.currentTarget) + (e.key === 'ArrowUp' ? -1 : 1)]?.focus();
}
return;
}
e.preventDefault();
const columns = [...this.data.columns].sort((a, b) => a.position - b.position);
const ci = columns.findIndex((c) => String(c.id) === String(card.columnId));
const others = this.cardsOf(card.columnId).filter((c) => c.id !== card.id);
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
const position = Math.max(0, Math.min(others.length, card.position + (e.key === 'ArrowUp' ? -1 : 1)));
if (position !== card.position) this.move(card.id, card.columnId, position);
return;
}
const to = columns[ci + (e.key === 'ArrowLeft' ? -1 : 1)];
if (to) this.move(card.id, to.id, Math.min(card.position, this.cardsOf(to.id).length));
}
/** moved here at once, then told to the backend (undone if it refuses) */
async move(id, columnId, position) {
const card = this.data.cards.find((c) => String(c.id) === String(id));
if (!card) return;
const before = JSON.stringify(this.data.cards);
const from = card.columnId;
const rest = this.cardsOf(columnId).filter((c) => c !== card);
rest.splice(Math.max(0, Math.min(rest.length, position)), 0, card);
card.columnId = columnId;
rest.forEach((c, i) => { c.position = i; });
if (String(from) !== String(columnId)) this.cardsOf(from).forEach((c, i) => { c.position = i; });
this.renderColumns();
this.columnsNode?.querySelector(`[data-card="${CSS.escape(String(id))}"]`)?.focus();
try {
const saved = await backend.invoke('board.card.update', { id, columnId, position: card.position });
Object.assign(card, saved);
if (this.state.mode === 'remote') await this.quietReload();
else if (String(from) !== String(columnId)) this.afterMove(card, from, columnId);
} catch (e) {
this.data.cards = JSON.parse(before);
this.renderColumns();
notify(String(e.message || e), 'error', { title: t('Board') });
}
}
async quietReload() {
try { this.data = await backend.invoke('board.get'); } catch { /* keep what is shown */ }
if (this.tab === 'board') this.renderColumns(); else this.render();
}
async addCard(columnId, title, fields = {}) {
const temp = { id: 'new-' + Date.now(), columnId, position: this.cardsOf(columnId).length, title, body: '', labels: [], assignee: '', due: null, priority: '', checklist: [], issue: null, attachments: [], createdAt: new Date().toISOString(), updatedAt: '', ...fields };
this.data.cards.push(temp);
this.renderColumns();
try {
const card = await backend.invoke('board.card.add', { ...fields, columnId, title });
Object.assign(temp, card);
if (this.state.mode !== 'remote') this.data.activity = (await backend.invoke('board.get').catch(() => this.data)).activity;
this.renderColumns();
return temp;
} catch (e) {
this.data.cards = this.data.cards.filter((c) => c !== temp);
this.renderColumns();
notify(String(e.message || e), 'error', { title: t('Board') });
return null;
}
}
/**
* @param base the card when its editor opened (jumphp.net: someone else's save meanwhile is merged with this one, field by field;
* the fields both changed are asked, never silently overwritten)
*/
async updateCard(card, fields, base = null) {
const before = { ...card };
Object.assign(card, fields);
this.render();
try {
const versioned = base && this.state.mode === 'remote' && base.version !== undefined;
let saved = await backend.invoke('board.card.update', { id: card.id, ...fields, ...(versioned ? { baseVersion: base.version } : {}) });
if (saved?.conflict) {
const theirs = saved.conflict.card;
if (!theirs) throw new Error(saved.conflict.error);
const merge = mergeCard(base, fields, theirs, Object.keys(fields));
const choices = merge.conflicts.length ? await this.chooseMerge(merge.conflicts) : {};
const again = choices === null ? {} : resolve(merge, choices);
saved = Object.keys(again).length ? await backend.invoke('board.card.update', { id: card.id, ...again, baseVersion: theirs.version }) : theirs;
if (saved?.conflict) throw new Error(saved.conflict.error);
}
Object.assign(card, saved);
this.render();
return card;
} catch (e) {
Object.assign(card, before);
this.render();
notify(String(e.message || e), 'error', { title: t('Board') });
return null;
}
}
async deleteCard(card) {
if (!(await confirm(t('Delete the card'), t('Delete “{title}”?', { title: card.title }), { ok: 'Delete', danger: true }))) return;
const index = this.data.cards.indexOf(card);
this.data.cards.splice(index, 1);
this.render();
try { await backend.invoke('board.card.delete', { id: card.id }); } catch (e) {
this.data.cards.splice(index, 0, card);
this.render();
notify(String(e.message || e), 'error', { title: t('Board') });
}
}
async createIssue(card) {
try {
const r = await backend.invoke('board.card.issue', { id: card.id });
if (r?.tokenNeeded) { if (await this.askToken(r.tokenNeeded)) await this.createIssue(card); return; }
Object.assign(card, r.title !== undefined ? r : { issue: r.issue });
this.render();
notify(t('Issue #{number} created.', { number: card.issue?.number ?? '?' }), 'success', { title: t('Board'),
actions: card.issue?.url ? [{ label: 'Open', action: () => this.app.openUrl(card.issue.url) }] : [] });
} catch (e) { notify(String(e.message || e), 'error', { title: t('Create issue') }); }
}
async sync() {
if (this.busy) return;
this.busy = true;
notify(t('Reading the issues and pull requests…'), 'info', { title: t('Board'), timeout: 2500 });
try {
const r = await backend.invoke('board.sync');
if (r?.tokenNeeded) {
this.busy = false;
if (await this.askToken(r.tokenNeeded)) await this.sync();
return;
}
await this.load();
notify(t('{imported} imported, {updated} updated.', { imported: r.imported, updated: r.updated }) + (r.errors?.length ? '\n' + r.errors.join('\n') : ''),
r.errors?.length ? 'error' : 'success', { title: t('Sync') });
} catch (e) { notify(String(e.message || e), 'error', { title: t('Sync') }); } finally { this.busy = false; }
}
/** "Token for {host}": the tracker wants a token (none, or the one set was refused). True when one was saved. */
askToken(info) {
return new Promise((resolve) => {
let saved = false;
const input = el('input.input', { type: 'password', autocomplete: 'off', spellcheck: false, placeholder: t('Paste the token') });
const scopes = { github: t('Scope: repo (or a fine-grained token with Issues: read and write).'), gh: t('Scope: repo (or a fine-grained token with Issues: read and write).'),
gitlab: t('Scope: api (read_api is enough to read).'), forgejo: t('Permissions: issue (read and write), repository (read).') }[info.provider] || '';
dialog({
title: t('Token for {host}', { host: info.host }),
body: el('div.board-token', {},
el('p', {}, info.refused ? t('{host} refused the token set for it: set another one.', { host: info.host }) : t('{host} needs a token to read and change its issues.', { host: info.host })),
info.tokenUrl ? el('p', {}, el('a', { href: '#', onclick: (e) => { e.preventDefault(); this.app.openUrl(info.tokenUrl); } }, t('Create a token on {host}', { host: info.host }))) : null,
scopes ? el('p.pub-faint', {}, scopes) : null,
input,
el('p.pub-faint', {}, t('Kept in the IDE\'s settings on this computer, never in the project, and only sent to {host}.', { host: info.host }))),
buttons: [{ label: 'Cancel' }, { label: 'Save', primary: true, action: async () => {
if (!input.value.trim()) { notify(t('Paste the token'), 'error'); return false; }
await backend.invoke('board.token.set', { host: info.host, token: input.value.trim() });
saved = true; resolve(true);
} }],
onClose: () => { if (!saved) resolve(false); },
});
});
}
/** A card moved: into the last column, its open issue may be closed; out of it, its closed issue reopened (the "close issues when done" setting). */
async afterMove(card, from, to) {
if (this.state.mode === 'remote' || !card.issue || card.issue.kind !== 'issue') return;
const last = this.data.columns[this.data.columns.length - 1];
if (!last) return;
const done = String(to) === String(last.id);
const undone = String(from) === String(last.id) && !done;
const open = card.issue.state === 'open';
if (!((done && open) || (undone && !open))) return;
const policy = this.state.closeWhenDone || 'ask';
if (policy === 'never') return;
if (policy === 'ask') {
const ok = await confirm(done ? t('Close the issue') : t('Reopen the issue'),
done ? t('Close issue #{number} on the tracker too?', { number: card.issue.number }) : t('Reopen issue #{number} on the tracker too?', { number: card.issue.number }),
{ ok: done ? 'Close' : 'Reopen' });
if (!ok) return;
}
try {
const r = await backend.invoke('board.issue.state', { id: card.id, open: !done });
if (r?.tokenNeeded) { if (await this.askToken(r.tokenNeeded)) await this.afterMove(card, from, to); return; }
if (r?.issue) card.issue = r.issue;
this.renderColumns();
notify(done ? t('Issue #{number} closed.', { number: card.issue.number }) : t('Issue #{number} reopened.', { number: card.issue.number }), 'success', { title: t('Board') });
} catch (e) { notify(String(e.message || e), 'error', { title: t('Issue tracker') }); }
}
/** ⋯ > Issue tracker…: which tracker, its API address, the generic tracker's addresses, closing issues when done, the token. */
async trackerDialog() {
let s;
try { s = await backend.invoke('board.tracker'); } catch (e) { notify(String(e.message || e), 'error', { title: t('Issue tracker') }); return; }
const g = s.generic || {};
const f = g.fields || {};
const names = { github: 'GitHub', gitlab: 'GitLab', forgejo: 'Forgejo / Gitea', gh: 'gh', generic: t('Generic') };
const provider = el('select.input', {},
...['auto', 'github', 'gitlab', 'forgejo', 'generic'].filter((k) => !s.svn || k === 'generic' || k === 'auto').map((k) => el('option', { value: k, selected: s.provider === k },
k === 'auto' ? t('Automatic (from the Git remote)') : names[k])));
const api = el('input.input', { value: s.api || '', placeholder: t('Default: the usual address of the forge') });
const field = (value, placeholder) => el('input.input', { value: value || '', placeholder });
const gen = {
issueUrl: field(g.issueUrl, 'https://tracker.example.com/issues/{number}'),
listUrl: field(g.listUrl, 'https://tracker.example.com/api/issues?open=1'),
items: field(g.items, 'issues'),
tokenHeader: field(g.tokenHeader, 'Authorization'),
tokenPrefix: field(g.tokenPrefix ?? 'Bearer ', 'Bearer '),
number: field(f.number, 'number'), title: field(f.title, 'title'), state: field(f.state, 'state'), url: field(f.url, 'url'), body: field(f.body, 'body'),
};
const close = el('select.input', {}, ...[['ask', t('Ask')], ['always', t('Always')], ['never', t('Never')]].map(([v, label]) => el('option', { value: v, selected: (s.closeWhenDone || 'ask') === v }, label)));
const row = (label, input) => el('label.board-field', {}, el('span', {}, label), input);
const genericBox = el('div.board-generic', {},
el('p.pub-faint', {}, t('Any other tracker: the address of an issue ({number} is replaced), and optionally an address answering its issues in JSON, read with this mapping (dot paths).')),
row(t('Issue address'), gen.issueUrl), row(t('List address (JSON)'), gen.listUrl), row(t('List inside the answer'), gen.items),
row(t('Token header'), gen.tokenHeader), row(t('Token prefix'), gen.tokenPrefix),
row(t('Number'), gen.number), row(t('Title'), gen.title), row(t('State'), gen.state), row(t('Address'), gen.url), row(t('Description'), gen.body));
const apiRow = row(t('API address'), api);
const sync = () => { genericBox.hidden = provider.value !== 'generic' && !s.svn && !(provider.value === 'auto' && !s.remote); apiRow.hidden = provider.value === 'generic' || s.svn; };
provider.onchange = sync;
const found = s.error ? el('p.board-error', {}, s.error)
: el('p', {}, t('Syncs with {tracker} ({host}).', { tracker: names[s.detected] || s.detected || '?', host: s.host || '' }),
s.detected === 'gh' ? ' ' + t('No token set: through the gh command, else without a token.') : '');
const tokenRow = s.host ? el('div.board-row', {},
el('button.btn.small', { onclick: async () => { if (await this.askToken({ host: s.host, provider: s.detected, tokenUrl: s.tokenUrl })) { d.close(); this.trackerDialog(); } } },
s.hasToken ? t('Change the token…') : t('Set a token…')),
s.hasToken ? el('button.btn.small.danger', { onclick: async () => {
await backend.invoke('board.token.forget', { host: s.host });
notify(t('The token for {host} was forgotten.', { host: s.host }), 'success', { title: t('Issue tracker') });
d.close(); this.trackerDialog();
} }, t('Forget the token')) : null) : null;
const body = el('div.board-tracker', {},
s.remote ? el('p.pub-faint', {}, t('Git remote: {remote}', { remote: s.remote })) : el('p.pub-faint', {}, s.svn ? t('A Subversion project: only the generic tracker.') : t('No Git remote.')),
found, tokenRow,
row(t('Tracker'), provider), apiRow, genericBox,
row(t('Close the issue when its card is done'), close));
sync();
const d = dialog({
title: t('Issue tracker'), body, wide: true,
buttons: [{ label: 'Cancel' }, { label: 'Save', primary: true, action: async () => {
const generic = { issueUrl: gen.issueUrl.value, listUrl: gen.listUrl.value, items: gen.items.value, tokenHeader: gen.tokenHeader.value, tokenPrefix: gen.tokenPrefix.value,
fields: { number: gen.number.value, title: gen.title.value, state: gen.state.value, url: gen.url.value, body: gen.body.value } };
await backend.invoke('board.tracker.set', { provider: provider.value, api: api.value, closeWhenDone: close.value,
...(provider.value === 'generic' || s.svn || gen.issueUrl.value || gen.listUrl.value ? { generic } : {}) });
this.state.closeWhenDone = close.value;
notify(t('Issue tracker saved.'), 'success', { title: t('Board') });
} }],
});
}
// ---- columns ----
async addColumn() {
const name = (await prompt(t('Add a column'), { label: 'Name', ok: 'Add' }))?.trim();
if (!name) return;
try { this.data.columns.push(await backend.invoke('board.column.add', { name })); this.render(); } catch (e) { notify(String(e.message || e), 'error', { title: t('Board') }); }
}
async renameColumn(column) {
const name = (await prompt(t('Rename the column'), { value: column.name, ok: 'Rename' }))?.trim();
if (!name || name === column.name) return;
const old = column.name;
column.name = name;
this.render();
try { await backend.invoke('board.column.update', { id: column.id, name }); } catch (e) { column.name = old; this.render(); notify(String(e.message || e), 'error', { title: t('Board') }); }
}
async moveColumn(column, delta) {
const columns = [...this.data.columns].sort((a, b) => a.position - b.position);
const i = columns.indexOf(column);
const j = i + delta;
if (j < 0 || j >= columns.length) return;
columns.splice(i, 1);
columns.splice(j, 0, column);
columns.forEach((c, k) => { c.position = k; });
this.render();
try { await backend.invoke('board.column.update', { id: column.id, position: j }); } catch (e) { notify(String(e.message || e), 'error', { title: t('Board') }); await this.load(); }
}
async deleteColumn(column) {
const count = this.cardsOf(column.id).length;
if (this.data.columns.length < 2) { notify(t('The last column cannot be deleted.'), 'error', { title: t('Board') }); return; }
if (!(await confirm(t('Delete the column'), count ? t('Delete the column {name}? Its {count} cards go to the first other column.', { name: column.name, count }) : t('Delete the column {name}?', { name: column.name }), { ok: 'Delete', danger: true }))) return;
try { await backend.invoke('board.column.delete', { id: column.id }); await this.load(); } catch (e) { notify(String(e.message || e), 'error', { title: t('Board') }); }
}
columnMenu(column, at) {
menu([
{ label: 'Add a card…', icon: 'plus', action: () => this.columnsNode.querySelector(`.board-column[data-column="${CSS.escape(String(column.id))}"] .board-quick`)?.focus() },
{ label: 'Rename…', icon: 'edit', action: () => this.renameColumn(column) },
{ label: 'Move left', action: () => this.moveColumn(column, -1) },
{ label: 'Move right', action: () => this.moveColumn(column, 1) },
'-',
{ label: 'Delete the column', icon: 'trash', action: () => this.deleteColumn(column) },
], at);
}
moreMenu(at) {
const items = [];
if (this.state.linked) {
items.push(this.state.mode === 'remote'
? { label: 'Use the local board', icon: 'file', action: () => this.setMode('local') }
: { label: 'Use the jumphp.net board', icon: 'globe', action: () => this.setMode('remote') });
items.push({ label: 'Copy the local board to jumphp.net', icon: 'upload', action: () => this.copyToRemote() });
} else {
items.push({ head: this.state.forge ? t('Issues of {forge}', { forge: this.state.forge }) : t('Local board (.jumphp/board.json)') });
}
items.push({ label: 'Sync the issues and pull requests', icon: 'pull', action: () => this.sync() });
if (this.state.mode !== 'remote') items.push({ label: 'Issue tracker…', icon: 'bug', action: () => this.trackerDialog() });
if (this.state.mode !== 'remote') items.push({ label: 'Open board.json', icon: 'file', action: () => this.app.editors?.open(this.state.file || '.jumphp/board.json') });
menu(items, at);
}
async setMode(mode) {
this.live = false; // the backend stops the channel with the mode; load() starts it again for jumphp.net's board
try { this.state = { ...this.state, ...(await backend.invoke('board.mode', { mode })) }; } catch (e) { notify(String(e.message || e), 'error', { title: t('Board') }); return; }
this.data = null; this.notes = null; this.note = null;
await this.load();
}
async copyToRemote() {
if (!(await confirm(t('Copy the local board to jumphp.net'), t('Its columns, cards and notes are added to the jumphp.net board of this project (what is already there with the same title is skipped).'), { ok: 'Copy' }))) return;
try {
const r = await backend.invoke('board.copyToRemote');
notify(t('{columns} columns, {cards} cards and {notes} notes copied, {skipped} already there.', r) + (r.errors?.length ? '\n' + r.errors.join('\n') : ''), r.errors?.length ? 'error' : 'success', { title: t('Board') });
if (this.state.mode === 'remote') await this.load();
} catch (e) { notify(String(e.message || e), 'error', { title: t('Board') }); }
}
/** the command palette's "Add a Task…": a card in the first column */
async quickAdd() {
if (!this.data) await this.load();
if (!this.data?.columns?.length) { notify(this.error || t('The board has no column.'), 'error', { title: t('Board') }); return; }
const title = (await prompt(t('Add a Task…'), { label: 'Title', ok: 'Add' }))?.trim();
if (!title) return;
const first = [...this.data.columns].sort((a, b) => a.position - b.position)[0];
const card = await this.addCard(first.id, title);
if (card) notify(t('Added to {column}.', { column: first.name }), 'success', { title: t('Board'), actions: [{ label: 'Open the Board', action: () => this.app.showTool('board') }] });
}
// ---- the card editor ----
editCard(card) {
const draft = JSON.parse(JSON.stringify(card));
const base = JSON.parse(JSON.stringify(card));
this.editingCard = card;
this.editing('card:' + card.id);
const columns = [...this.data.columns].sort((a, b) => a.position - b.position);
const titleInput = el('input.input', { value: draft.title, oninput: (e) => { draft.title = e.target.value; } });
const columnSelect = el('select.input', { onchange: (e) => { draft.columnId = e.target.value; } }, ...columns.map((c) => el('option', { value: c.id, selected: String(c.id) === String(draft.columnId) }, c.name)));
const prioritySelect = el('select.input', { onchange: (e) => { draft.priority = e.target.value; } }, ...PRIORITIES.map(([v, l]) => el('option', { value: v, selected: draft.priority === v }, t(l))));
const due = el('input.input', { type: 'date', value: draft.due || '', onchange: (e) => { draft.due = e.target.value || null; } });
const assignee = el('input.input', { value: draft.assignee || '', placeholder: t('Who does it'), oninput: (e) => { draft.assignee = e.target.value; } });
const labelsNode = el('div.board-label-edit');
const known = this.labels();
const renderLabels = () => {
clear(labelsNode);
for (const l of draft.labels) {
labelsNode.append(el('span.board-label.editable', { style: { background: l.color } },
el('input', { type: 'color', value: l.color, title: t('Color'), oninput: (e) => { l.color = e.target.value; renderLabels(); } }), l.name,
el('button', { title: t('Remove'), onclick: () => { draft.labels = draft.labels.filter((x) => x !== l); renderLabels(); } }, '×')));
}
const name = el('input.input.board-label-name', { placeholder: t('New label'), list: 'board-known-labels', onkeydown: (e) => {
if (e.key !== 'Enter' || !e.target.value.trim()) return;
e.preventDefault(); e.stopPropagation();
const n = e.target.value.trim();
if (!draft.labels.some((x) => x.name.toLowerCase() === n.toLowerCase())) {
const existing = known.find((k) => k.name.toLowerCase() === n.toLowerCase());
draft.labels.push({ name: existing?.name || n, color: existing?.color || COLORS[draft.labels.length % COLORS.length] });
}
renderLabels();
labelsNode.querySelector('.board-label-name')?.focus();
} });
labelsNode.append(name, el('datalist', { id: 'board-known-labels' }, ...known.map((k) => el('option', { value: k.name }))));
};
renderLabels();
const checkNode = el('div.board-checklist');
const renderChecklist = () => {
clear(checkNode);
const total = draft.checklist.length;
if (total) checkNode.append(el('div.board-progress', {}, progressBar(draft.checklist.filter((i) => i.done).length / total), el('span', {}, `${draft.checklist.filter((i) => i.done).length}/${total}`)));
draft.checklist.forEach((item, i) => {
checkNode.append(el('div.board-check-item' + (item.done ? '.done' : ''), {},
el('input', { type: 'checkbox', checked: item.done, onchange: (e) => { item.done = e.target.checked; renderChecklist(); } }),
el('input.input', { value: item.text, oninput: (e) => { item.text = e.target.value; } }),
el('button.icon-btn', { title: t('Remove'), onclick: () => { draft.checklist.splice(i, 1); renderChecklist(); } }, icon('close'))));
});
checkNode.append(el('input.input', { placeholder: t('Add an item…'), onkeydown: (e) => {
if (e.key !== 'Enter' || !e.target.value.trim()) return;
e.preventDefault(); e.stopPropagation();
draft.checklist.push({ text: e.target.value.trim(), done: false });
renderChecklist();
checkNode.lastChild.focus();
} }));
};
renderChecklist();
// the description: Markdown (GFM) with a toolbar, its preview rendered safely (board-md.js) with the card's pictures in place
const preview = el('div.md-body.board-preview.board-rich');
const mdHooks = { onLink: (url) => this.app.openUrl(url), picture: (name) => this.picture(card, { name }),
onImage: (img, src) => { const a = src.startsWith('attachment:') ? (card.attachments || []).find((x) => x.name === src.slice(11)) : null; if (a) this.viewPicture(card, a); } };
const showPreview = () => preview.replaceChildren(...(draft.body.trim() ? mdDom(parseMd(draft.body), mdHooks) : [el('span.pub-faint', {}, t('Nothing to preview'))]));
const body = el('textarea.input.board-body', { value: draft.body || '', placeholder: t('Description (Markdown): paste a document, a picture…'), oninput: debounce((e) => { draft.body = e.target.value; showPreview(); }, 150) });
body.addEventListener('input', (e) => { draft.body = e.target.value; });
showPreview();
const insert = (text, { block = false } = {}) => {
const start = body.selectionStart ?? body.value.length;
const end = body.selectionEnd ?? start;
const before = body.value.slice(0, start);
const lead = block && before && !before.endsWith('\n\n') ? (before.endsWith('\n') ? '\n' : '\n\n') : '';
body.focus();
body.setRangeText(lead + text, start, end, 'end');
body.dispatchEvent(new Event('input', { bubbles: true }));
};
const wrap = (left, right = left, empty = '') => {
const [a, b] = [body.selectionStart, body.selectionEnd];
const sel = body.value.slice(a, b) || empty;
body.focus();
body.setRangeText(left + sel + right, a, b, 'select');
body.setSelectionRange(a + left.length, a + left.length + sel.length);
body.dispatchEvent(new Event('input', { bubbles: true }));
};
const prefix = (mark) => {
const v = body.value;
const a = v.lastIndexOf('\n', body.selectionStart - 1) + 1;
let b = v.indexOf('\n', Math.max(body.selectionEnd - 1, a));
if (b < 0) b = v.length;
const lines = v.slice(a, b).split('\n').map((l, k) => (typeof mark === 'function' ? mark(k) : mark) + l);
body.focus();
body.setRangeText(lines.join('\n'), a, b, 'select');
body.dispatchEvent(new Event('input', { bubbles: true }));
};
const pickPicture = () => {
const input = el('input', { type: 'file', accept: 'image/png,image/jpeg,image/gif,image/webp', multiple: true });
input.onchange = () => attachFiles([...input.files], true);
input.click();
};
const tool = (label, title, action) => el('button.btn.small.board-md-tool', { title, onmousedown: (e) => e.preventDefault(), onclick: action }, label);
const toolbar = el('div.board-md-toolbar', {},
tool(el('b', {}, 'B'), t('Bold (Ctrl+B)'), () => wrap('**', '**', t('bold'))),
tool(el('i', {}, 'I'), t('Italic (Ctrl+I)'), () => wrap('*', '*', t('italic'))),
tool(el('u', {}, 'U'), t('Underline (Ctrl+U)'), () => wrap('<u>', '</u>', t('underlined'))),
tool('H', t('Heading'), () => prefix('## ')),
tool('•', t('Bulleted list'), () => prefix('- ')),
tool('1.', t('Numbered list'), () => prefix((k) => `${k + 1}. `)),
tool('❝', t('Quote'), () => prefix('> ')),
tool('</>', t('Code'), () => (body.value.slice(body.selectionStart, body.selectionEnd).includes('\n') ? wrap('```\n', '\n```') : wrap('`', '`', 'code'))),
tool('↗', t('Link'), () => wrap('[', '](https://)', t('text'))),
tool('▦', t('Table'), () => insert(`| ${t('Column')} | ${t('Column')} |\n| --- | --- |\n| | |\n`, { block: true })),
tool(icon('camera'), t('Insert a picture'), pickPicture));
body.addEventListener('keydown', (e) => {
if (!(e.ctrlKey || e.metaKey) || e.altKey || e.shiftKey) return;
const k = e.key.toLowerCase();
if (k === 'b') { e.preventDefault(); wrap('**', '**', t('bold')); }
if (k === 'i') { e.preventDefault(); wrap('*', '*', t('italic')); }
if (k === 'u') { e.preventDefault(); wrap('<u>', '</u>', t('underlined')); }
});
// the pictures: pasted (Ctrl+V) into the description or anywhere in the dialog, kept at once beside the card
const files = el('div.board-files');
const renderFiles = () => {
clear(files);
const list = card.attachments || [];
for (const a of list) {
const img = el('img', { alt: a.name, title: `${a.name} (${Math.max(1, Math.round(a.size / 1024))} KB)`, onclick: () => this.viewPicture(card, a) });
this.picture(card, a).then((url) => { img.src = url; }, () => img.classList.add('broken'));
files.append(el('div.board-file', {}, img,
el('button.board-file-remove', { title: t('Remove the picture'), onclick: async () => {
try { Object.assign(card, await backend.invoke('board.card.detach', { id: card.id, name: a.name })); renderFiles(); this.renderColumns(); } catch (e) { notify(String(e.message || e), 'error', { title: t('Board') }); }
} }, '×')));
}
if (!list.length) files.append(el('span.pub-faint', {}, String(card.id).startsWith('new-') ? t('Save the card first.') : t('Paste a picture (Ctrl+V) into the description to add it.')));
};
renderFiles();
const readFile = (file) => new Promise((resolve, reject) => { const r = new FileReader(); r.onload = () => resolve(String(r.result)); r.onerror = () => reject(r.error); r.readAsDataURL(file); });
const isNew = () => String(card.id).startsWith('new-');
/** pictures attached to the card; inline: also put where the cursor is in the description */
const attachFiles = async (files, inline) => {
if (isNew()) { notify(t('Save the card first.'), 'error', { title: t('Board') }); return; }
for (const file of files) {
if (!/^image\/(png|jpeg|gif|webp)$/.test(file.type)) { notify(t('This is not a picture (PNG, JPEG, GIF or WebP).'), 'error', { title: t('Board') }); continue; }
if (file.size > 5 * 1024 * 1024) { notify(t('A picture is {max} MB at most.', { max: 5 }), 'error', { title: t('Board') }); continue; }
try {
Object.assign(card, await backend.invoke('board.card.attach', { id: card.id, name: file.name && file.name !== 'image.png' ? file.name : '', data: await readFile(file) }));
const last = card.attachments[card.attachments.length - 1];
if (inline && last) insert(`![](attachment:${last.name})`);
renderFiles();
this.renderColumns();
} catch (err) { notify(String(err.message || err), 'error', { title: t('Board') }); }
}
};
// Ctrl+V: a formatted document (HTML: a web page, Word, LibreOffice, Google Docs, an e-mail) becomes Markdown with its pictures
// attached where they were; a picture alone is attached (and put at the cursor in the description); plain text pastes as usual
const paste = async (e) => {
const dt = e.clipboardData;
if (!dt) return;
const files = [...dt.items].filter((i) => i.kind === 'file' && i.type.startsWith('image/')).map((i) => i.getAsFile()).filter(Boolean);
const html = e.target === body ? dt.getData('text/html') : '';
const rich = html && !codeLike(html) && /<(p|div|h[1-6]|ul|ol|li|table|img|b|strong|i|em|u|a|br|blockquote|pre|span)\b/i.test(html) && !isNew();
if (!rich && !files.length) {
// no file in the event: a picture copied in another program (WebKitGTK does not give it to the page): the system's clipboard
if (dt.getData('text/plain') || dt.getData('text/html')) return;
e.preventDefault();
const img = await backend.invoke('clipboard.image', {}).catch(() => null);
if (!img?.base64) { notify(t('No picture on the clipboard.'), 'info', { title: t('Board'), timeout: 2500 }); return; }
const bin = atob(img.base64);
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
await attachFiles([new File([bytes], 'image.png', { type: img.type || 'image/png' })], e.target === body);
return;
}
e.preventDefault();
if (!rich) { await attachFiles(files, e.target === body); return; }
notify(t('Pasting the document…'), 'info', { title: t('Board'), timeout: 1500 });
try {
const list = [];
for (const f of files) if (/^image\/(png|jpeg|gif|webp)$/.test(f.type) && f.size <= 5 * 1024 * 1024) list.push({ name: f.name, data: await readFile(f) });
const r = await backend.invoke('board.card.paste', { id: card.id, html, files: list });
if (Array.isArray(r.card?.attachments)) { card.attachments = r.card.attachments; card.updatedAt = r.card.updatedAt || card.updatedAt; }
if (r.markdown) insert(r.markdown, { block: /\n./.test(r.markdown.trim()) || /^(#|-|\d+\.|>|\||```)/.test(r.markdown) });
renderFiles();
this.renderColumns();
} catch (err) {
notify(String(err.message || err), 'error', { title: t('Board') });
insert(dt.getData('text/plain'));
}
};
const when = (iso) => { const ms = Date.parse(iso || ''); return Number.isNaN(ms) ? '' : new Date(ms).toLocaleString(); };
const dates = el('div.board-dates.pub-faint', {},
when(card.createdAt) ? el('span', {}, t('Created {when}', { when: when(card.createdAt) })) : null,
when(card.updatedAt) ? el('span', {}, t('Updated {when}', { when: when(card.updatedAt) })) : null);
const issue = card.issue
? el('a.board-issue.' + card.issue.state, { href: '#', onclick: (e) => { e.preventDefault(); this.app.openUrl(card.issue.url); } }, `${card.issue.kind === 'pr' ? t('Pull request') : t('Issue')} #${card.issue.number} (${t(card.issue.state)})`)
: el('button.btn.small', { onclick: () => { d.close(); this.createIssue(card); } }, icon('bug'), t('Create issue'));
const field = (label, input) => el('label.board-field', {}, el('span', {}, t(label)), input);
const form = el('div.board-editor', {},
field('Title', titleInput),
dates,
el('div.board-fields', {}, field('Column', columnSelect), field('Priority', prioritySelect), field('Due date', due), field('Assignee', assignee)),
field('Labels', labelsNode),
el('div.board-field', {}, el('span', {}, t('Description')), toolbar, el('div.board-md', {}, body, preview)),
el('div.board-field', {}, el('span', {}, t('Pictures')), files),
el('div.board-field', {}, el('span', {}, t('Checklist')), checkNode),
el('div.board-field', {}, el('span', {}, t('Issue')), el('div', {}, issue)));
form.addEventListener('paste', paste);
const d = dialog({
title: 'Edit the card', body: form, wide: true,
onClose: () => { if (this.editingCard === card) { this.editingCard = null; this.editing(null); } },
buttons: [
{ label: 'Delete', danger: true, action: () => { setTimeout(() => this.deleteCard(card), 0); } },
{ label: 'Cancel' },
{ label: 'Save', primary: true, action: async () => {
if (!draft.title.trim()) { notify(t('A card needs a title.'), 'error'); return false; }
const fields = { title: draft.title.trim(), body: draft.body, labels: draft.labels, assignee: draft.assignee.trim(), due: draft.due, priority: draft.priority,
checklist: draft.checklist.filter((i) => i.text.trim()) };
const moved = String(draft.columnId) !== String(card.columnId);
await this.updateCard(card, fields, base);
if (moved) await this.move(card.id, draft.columnId, this.cardsOf(draft.columnId).length);
return true;
} },
],
});
d.box.classList.add('board-dialog');
}
/** a picture of a card as a data: address (asked once, then kept while the window lives) */
picture(card, a) {
this.pictures ??= new Map();
const key = `${card.id}/${a.name}`;
if (!this.pictures.has(key)) {
this.pictures.set(key, backend.invoke('board.card.file', { id: card.id, name: a.name }).then((f) => `data:${f.type};base64,${f.data}`));
this.pictures.get(key).catch(() => this.pictures.delete(key));
}
return this.pictures.get(key);
}
/** a picture of a card, big */
async viewPicture(card, a) {
const img = el('img.board-picture-big', { alt: a.name });
dialog({ title: a.name, body: el('div.board-picture-view', {}, img), wide: true, buttons: [{ label: 'Close' }] });
try { img.src = await this.picture(card, a); } catch (e) { notify(String(e.message || e), 'error', { title: t('Board') }); }
}
// ---- Notes ----
renderNotes() {
if (!this.notes) { this.node.append(el('div.board-empty', {}, t('Loading…'))); return; }
const q = (this.noteQuery || '').trim().toLowerCase();
const list = el('div.board-note-list');
const shown = this.notes.filter((n) => !q || `${n.title}\n${n.body}`.toLowerCase().includes(q));
for (const n of shown) {
list.append(el('div.board-note-item' + (this.note && String(this.note.id) === String(n.id) ? '.on' : ''), { onclick: () => this.openNote(n) },
el('b', {}, n.title), el('span', {}, n.updatedAt ? timeAgo(epoch(n.updatedAt)) : '')));
}
if (!shown.length) list.append(el('div.board-empty', {}, q ? t('No note matches.') : t('No notes yet.')));
const side = el('div.board-note-side', {},
el('div.board-row', {}, el('input.input', { type: 'search', placeholder: t('Search the notes…'), value: this.noteQuery || '',
oninput: debounce((e) => { this.noteQuery = e.target.value; this.render(); this.node.querySelector('.board-note-side input')?.focus(); }, 150) }),
el('button.btn.small', { title: t('New note'), onclick: () => this.newNote() }, icon('plus'))), list);
this.node.append(el('div.board-notes', {}, side, this.noteEditor()));
}
/** a note opened: on jumphp.net its text and version come with it (the list has none) */
async openNote(n) {
this.flushNote();
this.editing(null);
this.note = n;
if (this.state.mode === 'remote' && !n.loaded && !String(n.id).startsWith('new-')) {
try { await this.fetchNote(n); } catch (e) { notify(String(e.message || e), 'error', { title: t('Notes') }); }
}
this.render();
}
noteEditor() {
const n = this.note;
if (!n) return el('div.board-note-editor.board-empty', {}, t('Choose a note, or make a new one.'));
const preview = el('div.md-body.board-preview');
const show = () => preview.replaceChildren(...(n.body.trim() ? renderMarkdown(n.body, (url) => this.app.openUrl(url)) : [el('span.pub-faint', {}, t('Nothing to preview'))]));
show();
const title = el('input.input.board-note-title', { value: n.title, oninput: (e) => { n.title = e.target.value; this.noteDirty = true; this.saveNoteSoon(); } });
const text = el('textarea.input.board-body', { value: n.body, placeholder: t('Write in Markdown…'), oninput: (e) => { n.body = e.target.value; this.noteDirty = true; show(); this.saveNoteSoon(); },
onfocus: () => this.editing('note:' + n.id), onblur: () => { this.flushNote(); this.editing(null); } });
return el('div.board-note-editor', {},
el('div.board-row', {}, title, el('button.icon-btn', { title: t('Delete the note'), onclick: () => this.deleteNote(n) }, icon('trash'))),
el('div.board-md.tall', {}, text, preview));
}
flushNote() { if (this.noteDirty) this.saveNote(); }
async saveNote() {
const n = this.note;
if (!n || !this.noteDirty) return;
this.noteDirty = false;
try {
const sent = n.body;
const remote = this.state.mode === 'remote' && n.version !== undefined;
// jumphp.net: the version and the text this edit started from; a save made meanwhile by someone else is merged by paragraph
const saved = await backend.invoke('board.note.save', { id: String(n.id).startsWith('new-') ? null : n.id, title: n.title, body: n.body,
...(remote ? { baseVersion: n.version, base: n.base ?? '' } : {}) });
if (saved?.conflict) throw new Error(saved.conflict.error);
n.id = saved.id; n.updatedAt = saved.updatedAt;
if (saved.version !== undefined) { n.version = saved.version; n.base = saved.body; n.loaded = true; }
if (saved.merged) {
notify(saved.merged.conflicts ? t('Someone else had changed this note: both versions are merged; {count} paragraph(s) changed on both sides keep your version.', { count: saved.merged.conflicts })
: t('Someone else had changed this note: your changes and theirs are merged.'), 'info', { title: t('Notes') });
// their paragraphs in the editor, unless the person typed meanwhile (the next save merges again)
if (n.body === sent) {
n.body = saved.body;
const area = this.node.querySelector('.board-note-editor textarea');
if (area && this.note === n) { const at = area.selectionStart; area.value = saved.body; area.selectionStart = area.selectionEnd = Math.min(at, saved.body.length); }
}
}
if (!n.title.trim()) n.title = saved.title;
const item = this.node.querySelector('.board-note-item.on span');
if (item) item.textContent = timeAgo(epoch(n.updatedAt));
const name = this.node.querySelector('.board-note-item.on b');
if (name) name.textContent = n.title;
} catch (e) { this.noteDirty = true; notify(String(e.message || e), 'error', { title: t('Notes') }); }
}
async newNote() {
this.flushNote();
try {
const n = await backend.invoke('board.note.save', { id: null, title: t('New note'), body: '' });
Object.assign(n, { base: n.body, loaded: true });
this.notes.unshift(n);
this.note = n;
this.render();
const input = this.node.querySelector('.board-note-title');
input?.focus(); input?.select();
} catch (e) { notify(String(e.message || e), 'error', { title: t('Notes') }); }
}
async deleteNote(n) {
if (!(await confirm(t('Delete the note'), t('Delete “{title}”?', { title: n.title }), { ok: 'Delete', danger: true }))) return;
try {
await backend.invoke('board.note.delete', { id: n.id });
this.notes = this.notes.filter((x) => x !== n);
this.note = null; this.noteDirty = false;
this.render();
} catch (e) { notify(String(e.message || e), 'error', { title: t('Notes') }); }
}
// ---- Overview ----
renderOverview() {
const columns = [...this.data.columns].sort((a, b) => a.position - b.position);
const cards = this.data.cards;
const last = columns[columns.length - 1];
const finished = last ? this.cardsOf(last.id).length : 0;
const max = Math.max(1, ...columns.map((c) => this.cardsOf(c.id).length));
const open = cards.filter((c) => !last || String(c.columnId) !== String(last.id));
const now = today();
const soon = new Date(Date.now() + 14 * DAY).toISOString().slice(0, 10);
const overdue = open.filter((c) => c.due && c.due < now).sort((a, b) => a.due.localeCompare(b.due));
const upcoming = open.filter((c) => c.due && c.due >= now && c.due <= soon).sort((a, b) => a.due.localeCompare(b.due));
const items = cards.reduce((n, c) => n + (c.checklist || []).length, 0);
const ticked = cards.reduce((n, c) => n + done(c), 0);
const cardLine = (c) => el('div.board-ov-card', { onclick: () => this.editCard(c) }, el('span.board-due' + (c.due < now ? '.overdue' : ''), {}, c.due), ' ', c.title,
el('span.pub-faint', {}, ' · ' + (this.data.columns.find((k) => String(k.id) === String(c.columnId))?.name || '')));
const section = (title, ...children) => el('div.board-ov-section', {}, el('h4', {}, t(title)), ...children);
const activity = (this.data.activity || []).length
? [...this.data.activity].reverse().slice(0, 15).map((a) => el('div.board-ov-act', {}, el('span.pub-faint', {}, timeAgo(epoch(a.at))), ' ', activityText(a)))
: [...cards].filter((c) => c.updatedAt).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).slice(0, 15)
.map((c) => el('div.board-ov-act', {}, el('span.pub-faint', {}, timeAgo(epoch(c.updatedAt))), ' ', t('Updated “{title}”', { title: c.title })));
this.node.append(el('div.board-overview', {},
section('Progress',
el('div.board-progress.big', {}, progressBar(cards.length ? finished / cards.length : 0),
el('span', {}, t('{done} of {total} cards done ({percent}%)', { done: finished, total: cards.length, percent: cards.length ? Math.round(100 * finished / cards.length) : 0 }))),
items ? el('div.board-progress', {}, progressBar(ticked / items), el('span', {}, t('{done} of {total} checklist items', { done: ticked, total: items }))) : null),
section('Cards per column', ...columns.map((c) => {
const n = this.cardsOf(c.id).length;
return el('div.board-ov-bar', {}, el('span.board-ov-name', {}, c.name), el('span.board-ov-track', {}, el('i', { style: { width: `${Math.round(100 * n / max)}%` } })), el('b', {}, String(n)));
})),
section('Overdue', ...(overdue.length ? overdue.map(cardLine) : [el('div.pub-faint', {}, t('Nothing overdue.'))])),
section('Due in the next 14 days', ...(upcoming.length ? upcoming.map(cardLine) : [el('div.pub-faint', {}, t('Nothing due soon.'))])),
section('Recent activity', ...(activity.length ? activity : [el('div.pub-faint', {}, t('No activity yet.'))]))));
}
}
/** the start of a description, as plain text (Markdown marks and pictures left out) */
function excerpt(body) {
const lines = plainText(body).split('\n').map((l) => l.trim()).filter(Boolean);
const short = lines.slice(0, 3).join('\n');
return short.length > 240 ? short.slice(0, 240) + '…' : short;
}
/** HTML of a code editor (VS Code, the IDE, a terminal): pasted as its plain text, not as a coloured document */
function codeLike(html) {
const head = html.slice(0, 1500);
return /white-space:\s*pre|font-family:[^;"]*(mono|consolas|courier|menlo)/i.test(head) && !/<(table|ul|ol|h[1-6]|img)\b/i.test(html);
}
/** an entry of the local board's activity, in words */
function activityText(a) {
const v = { title: a.title || '', from: a.from || '', to: a.to || '', count: a.count ?? '', number: a.number ?? '' };
switch (a.action) {
case 'card.add': return t('Added “{title}” to {to}', v);
case 'card.move': return t('Moved “{title}” from {from} to {to}', v);
case 'card.done': return t('Finished “{title}”', v);
case 'card.edit': return t('Edited “{title}”', v);
case 'card.delete': return t('Deleted “{title}”', v);
case 'column.add': return t('Added the column {title}', v);
case 'column.rename': return t('Renamed the column {from} to {title}', v);
case 'column.delete': return t('Deleted the column {title}', v);
case 'note.add': return t('Wrote the note “{title}”', v);
case 'note.delete': return t('Deleted the note “{title}”', v);
case 'sync': return t('Imported {count} issues from {title}', v);
case 'issue': return t('Created issue #{number} for “{title}”', v);
case 'issue.close': return t('Closed issue #{number} of “{title}”', v);
case 'issue.reopen': return t('Reopened issue #{number} of “{title}”', v);
default: return `${a.action} ${a.title || ''}`;
}
}
// Claude's tools (agent.js): the same board as the window, which shows the changes
export const boardAgentTools = {
async boardPanel() {
const panel = this.app.board;
if (!panel) throw new Error('no Board window here');
if (!panel.data) await panel.load();
if (!panel.data) throw new Error(panel.error || 'the board could not be loaded');
return panel;
},
boardColumn(panel, column) {
const columns = [...panel.data.columns].sort((a, b) => a.position - b.position);
if (column === undefined || column === null || column === '') return columns[0];
const c = columns.find((k) => String(k.id) === String(column)) || columns.find((k) => k.name.toLowerCase() === String(column).toLowerCase());
if (!c) throw new Error(`no column "${column}" (there are: ${columns.map((k) => k.name).join(', ')})`);
return c;
},
boardCard(panel, id) {
const card = panel.data.cards.find((c) => String(c.id) === String(id));
if (!card) throw new Error(`no card ${id} (board_list gives the ids)`);
return card;
},
boardFields(args) {
const f = {};
for (const k of ['title', 'body', 'assignee', 'due', 'priority']) if (args[k] !== undefined) f[k] = args[k];
if (Array.isArray(args.labels)) f.labels = args.labels.map((l) => (typeof l === 'string' ? { name: l } : l));
if (Array.isArray(args.checklist)) f.checklist = args.checklist.map((i) => (typeof i === 'string' ? { text: i, done: false } : { text: String(i.text || ''), done: !!i.done }));
return f;
},
async tool_board_list(args) {
const panel = await this.boardPanel();
const q = String(args.query || '').toLowerCase();
return { backend: panel.state.mode === 'remote' ? `jumphp.net (${panel.state.slug})` : '.jumphp/board.json',
columns: [...panel.data.columns].sort((a, b) => a.position - b.position).map((c) => ({ id: c.id, name: c.name,
cards: panel.cardsOf(c.id).filter((k) => !q || `${k.title}\n${k.body}`.toLowerCase().includes(q)).map((k) => ({ id: k.id, title: k.title, body: k.body, labels: k.labels.map((l) => l.name),
priority: k.priority || undefined, due: k.due || undefined, assignee: k.assignee || undefined,
checklist: k.checklist.length ? k.checklist : undefined, issue: k.issue ? `${k.issue.kind} #${k.issue.number} ${k.issue.state} ${k.issue.url}` : undefined })) })) };
},
async tool_board_add_card(args) {
const panel = await this.boardPanel();
const column = this.boardColumn(panel, args.column);
const fields = this.boardFields(args);
delete fields.title;
const card = await panel.addCard(column.id, String(args.title || '').trim(), fields);
if (!card) throw new Error('the card was not added');
return { id: card.id, column: column.name };
},
async tool_board_move_card(args) {
const panel = await this.boardPanel();
const card = this.boardCard(panel, args.id);
const column = this.boardColumn(panel, args.column ?? card.columnId);
const others = panel.cardsOf(column.id).filter((c) => c !== card);
await panel.move(card.id, column.id, Number.isInteger(args.position) ? args.position : others.length);
return { id: card.id, column: column.name, position: card.position };
},
async tool_board_update_card(args) {
const panel = await this.boardPanel();
const card = this.boardCard(panel, args.id);
const saved = await panel.updateCard(card, this.boardFields(args));
if (!saved) throw new Error('the card was not changed');
return { id: card.id, title: card.title };
},
async tool_notes_list(args) {
const panel = await this.boardPanel();
await panel.loadNotes();
const q = String(args.query || '').toLowerCase();
return panel.notes.filter((n) => !q || `${n.title}\n${n.body}`.toLowerCase().includes(q)).map((n) => ({ id: n.id, title: n.title, body: n.body, updated: n.updatedAt }));
},
async tool_note_save(args) {
const panel = await this.boardPanel();
const n = await backend.invoke('board.note.save', { id: args.id ?? null, title: String(args.title || ''), body: String(args.body || '') });
await panel.loadNotes();
panel.note = panel.notes.find((x) => String(x.id) === String(n.id)) || null;
if (panel.tab === 'notes') panel.render();
return { id: n.id, title: n.title };
},
};