1708 lines
88 KiB
HTML
1708 lines
88 KiB
HTML
<!doctype html>
|
|
<html>
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<title>Kanzi — Kindle annotations to Zotero</title>
|
|
<style>
|
|
/* Design Tokens — F (Cleaned D+B) — unified with chess tool 2026-09-21 */
|
|
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap');
|
|
:root {
|
|
font-family: 'iA Writer Duo', 'iA Writer Duos', 'JetBrains Mono', ui-monospace, monospace;
|
|
color: #111;
|
|
background: #f8f8f8;
|
|
--bg: #f8f8f8;
|
|
--panel: #ffffff;
|
|
--panel-soft: #f0f0f0;
|
|
--line: #ddd;
|
|
--line-strong: #bbb;
|
|
--text: #111;
|
|
--muted: #666;
|
|
--faint: #999;
|
|
--accent: #111;
|
|
--accent-2: #111;
|
|
--accent-soft: #f0f0f0;
|
|
--danger: #a00;
|
|
--danger-soft: #fff0f0;
|
|
--shadow: 0 1px 4px rgba(0,0,0,.06);
|
|
--shadow-strong: 0 4px 12px rgba(0,0,0,.08);
|
|
--radius: 8px;
|
|
--pill-radius: 8px;
|
|
}
|
|
* { box-sizing: border-box; }
|
|
body { margin: 0; background: var(--bg); }
|
|
#root { padding: 0 24px 24px; max-width: 1280px; margin: 0 auto; background: var(--bg); color: var(--text); line-height: 1.5; }
|
|
h1 { margin: 0 0 4px; font-size: 28px; font-weight: 700; letter-spacing: -0.02em; font-family: inherit; color: var(--text); }
|
|
h2 { margin: 24px 0 10px; border-bottom: 1px solid var(--line); padding-bottom: 6px; font-size: 16px; font-weight: 600; letter-spacing: -0.01em; color: var(--text); }
|
|
.tabs { display: flex; gap: 4px; margin: 16px 0 0; flex-wrap: wrap; border-bottom: 1px solid var(--line); }
|
|
.tab-button { padding: 12px 16px 10px; border: 0; border-bottom: 2px solid transparent; background: transparent; color: var(--muted); cursor: pointer; font-family: inherit; font-size: 13px; font-weight: 600; letter-spacing: 0.02em; }
|
|
.tab-button.active { color: var(--accent); border-bottom-color: var(--accent); background: transparent; }
|
|
.tab-button:hover { color: var(--text); }
|
|
.tab { display: none; }
|
|
.tab.active { display: block; padding-top: 16px; }
|
|
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }
|
|
.card { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px; box-shadow: var(--shadow); }
|
|
.card strong { display: block; font-size: 22px; font-weight: 700; color: var(--text); }
|
|
.card span { color: var(--muted); font-size: 12px; }
|
|
label { display: block; margin: 9px 0 3px; font-weight: 600; font-size: 12px; color: var(--text); }
|
|
input, textarea, select { width: 100%; box-sizing: border-box; padding: 8px 10px; font-family: inherit; border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel); color: var(--text); }
|
|
input:focus, textarea:focus, select:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px rgba(17,17,17,.06); }
|
|
textarea { min-height: 72px; }
|
|
table { width: 100%; border-collapse: collapse; background: var(--panel); table-layout: fixed; border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; box-shadow: var(--shadow); }
|
|
th, td { text-align: left; vertical-align: top; border-bottom: 1px solid var(--line); padding: 10px 12px; font-size: 12.5px; overflow-wrap: anywhere; user-select: text; position: relative; }
|
|
th { background: var(--panel-soft); color: var(--muted); position: sticky; top: 0; font-weight: 600; font-family: 'JetBrains Mono', monospace; text-transform: uppercase; letter-spacing: .06em; font-size: 10px; border-bottom: 1px solid var(--line); z-index: 1; }
|
|
th .resizer { position: absolute; top: 0; right: -3px; width: 6px; height: 100%; cursor: col-resize; user-select: none; }
|
|
th .resizer:hover { background: var(--accent); opacity: 0.15; }
|
|
th:nth-child(1), td:nth-child(1) { width: 10%; }
|
|
th:nth-child(2), td:nth-child(2) { width: 9%; }
|
|
th:nth-child(3), td:nth-child(3) { width: 6%; }
|
|
th:nth-child(4), td:nth-child(4) { width: 24%; }
|
|
th:nth-child(5), td:nth-child(5) { width: 21%; }
|
|
th:nth-child(6), td:nth-child(6) { width: 30%; }
|
|
#tab-integrated table { table-layout: fixed; }
|
|
#tab-integrated th:nth-child(1), #tab-integrated td:nth-child(1) { width: 18%; }
|
|
#tab-integrated th:nth-child(2), #tab-integrated td:nth-child(2) { width: 12%; }
|
|
#tab-integrated th:nth-child(3), #tab-integrated td:nth-child(3) { width: 36%; }
|
|
#tab-integrated th:nth-child(4), #tab-integrated td:nth-child(4) { width: 11%; }
|
|
#tab-integrated th:nth-child(5), #tab-integrated td:nth-child(5) { width: 11%; }
|
|
#tab-integrated th:nth-child(6), #tab-integrated td:nth-child(6) { width: 12%; }
|
|
.pill { display: inline-block; background: var(--accent); color: white; border-radius: var(--pill-radius); padding: 3px 8px; font-size: 10px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; border: 1px solid var(--accent); }
|
|
.row-actions button, .row-actions .row-btn { margin: 2px; padding: 6px 10px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel); color: var(--text); cursor: pointer; font-size: 12px; font-family: inherit; transition: all .12s; }
|
|
.row-actions button:hover, .row-actions .row-btn:hover { border-color: var(--line-strong); background: var(--panel-soft); }
|
|
.candidate-list { display: flex; flex-direction: column; gap: 6px; margin: 6px 0; }
|
|
.candidate-option { display: flex; align-items: center; justify-content: space-between; gap: 8px; border: 1px solid var(--line); border-radius: var(--radius); padding: 8px 10px; background: var(--panel); font-size: 12px; line-height: 1.3; box-shadow: var(--shadow); }
|
|
.candidate-option:hover { background: var(--panel-soft); border-color: var(--line-strong); }
|
|
.candidate-option span { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text); }
|
|
.candidate-option button { flex-shrink: 0; padding: 4px 10px; font-size: 11px; border-radius: var(--pill-radius); border: 1px solid var(--accent); background: var(--accent); color: white; cursor: pointer; font-family: 'JetBrains Mono', monospace; text-transform: uppercase; letter-spacing: .06em; }
|
|
.candidate-option button:hover { background: var(--panel); color: var(--accent); }
|
|
.manual-row { display: flex; gap: 6px; margin-top: 8px; }
|
|
.manual-row input { flex: 1; min-width: 0; font-size: 12px; }
|
|
.manual-row button { white-space: nowrap; flex-shrink: 0; padding: 8px 12px; border-radius: var(--radius); border: 1px solid var(--accent); background: var(--accent); color: white; cursor: pointer; font-weight: 600; }
|
|
.manual-row button:hover { background: var(--panel); color: var(--accent); }
|
|
.notice { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 12px 14px; margin: 10px 0; font-size: 13px; box-shadow: var(--shadow); }
|
|
.run-panel { background: var(--panel); color: var(--text); border: 1px solid var(--line); border-radius: 14px; padding: 18px; margin: 16px 0; box-shadow: var(--shadow); }
|
|
.file-button { display: inline-block; min-width: 240px; padding: 11px 16px; margin-bottom: 8px; font-size: 13px; font-weight: 600; text-align: center; color: white; background: var(--accent); border: 1px solid var(--accent); border-radius: var(--radius); cursor: pointer; font-family: inherit; letter-spacing: 0.02em; box-shadow: 0 2px 10px rgba(0,0,0,.12); transition: all .12s; }
|
|
.file-button:hover, .file-button:focus { background: #1a1a1a; transform: translateY(-1px); box-shadow: var(--shadow-strong); outline: none; }
|
|
.file-button.disabled { opacity: 0.4; cursor: wait; transform: none; }
|
|
.run-panel progress { width: 100%; height: 6px; margin: 12px 0 5px; accent-color: var(--accent); border-radius: 999px; }
|
|
.run-meta { display: flex; justify-content: space-between; gap: 12px; color: var(--muted); font-size: 11px; font-family: 'JetBrains Mono', monospace; text-transform: uppercase; letter-spacing: .06em; }
|
|
.ok { color: var(--accent); }
|
|
.err { color: var(--danger); }
|
|
.muted { color: var(--muted); font-size: 12px; }
|
|
.highlight-text { max-width: 520px; white-space: pre-wrap; word-break: break-word; font-size: 12px; line-height: 1.45; font-family: inherit; }
|
|
.integrated-meta { font-size: 10.5px; color: var(--muted); font-family: 'JetBrains Mono', monospace; }
|
|
.pagination { display: flex; align-items: center; justify-content: flex-end; gap: 8px; margin: 10px 0; color: var(--muted); font-size: 11px; }
|
|
.pagination button, .pagination select { width: auto; padding: 5px 8px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel); color: var(--text); font: inherit; }
|
|
.pagination button:disabled { color: var(--faint); background: var(--panel-soft); cursor: not-allowed; }
|
|
::selection { background: var(--accent); color: white; }
|
|
</style>
|
|
<script>
|
|
var KindleManager = {
|
|
io: null,
|
|
plugin: null,
|
|
settings: null,
|
|
data: null,
|
|
rows: [],
|
|
running: false,
|
|
startedAt: null,
|
|
timer: null,
|
|
lastClippingsPath: null,
|
|
integratedPage: 0,
|
|
integratedPageSize: 50,
|
|
conflictsPage: 0,
|
|
conflictsPageSize: 50,
|
|
mappingsPage: 0,
|
|
mappingsPageSize: 50,
|
|
|
|
initSafe() {
|
|
try {
|
|
this.init();
|
|
} catch (error) {
|
|
const root = document.getElementById('root');
|
|
root.textContent = '';
|
|
const h1 = document.createElement('h1');
|
|
h1.textContent = 'Kanzi';
|
|
const sub = document.createElement('div');
|
|
sub.className = 'muted';
|
|
sub.textContent = 'Kindle annotations to Zotero — My Clippings.txt → native annotations';
|
|
root.appendChild(h1);
|
|
root.appendChild(sub);
|
|
const div = document.createElement('div');
|
|
div.className = 'notice err';
|
|
div.textContent = 'Manager failed to load: ' + String(error) + '\n' + (error.stack || '');
|
|
root.appendChild(div);
|
|
}
|
|
},
|
|
|
|
init() {
|
|
this.io = window.arguments && window.arguments[0];
|
|
if (!this.io || !this.io.plugin) throw new Error('Plugin connection was not provided');
|
|
this.plugin = this.io.plugin;
|
|
this.settings = this.io.settings;
|
|
this.data = this.io.data;
|
|
this.rows = this.conflictRows();
|
|
this.render();
|
|
},
|
|
|
|
async chooseAndImport() {
|
|
if (this.running) return;
|
|
try {
|
|
await this.plugin.runManagedImport(this);
|
|
} catch (e) {
|
|
Zotero.logError(e);
|
|
this.failRun(String(e && e.stack ? e.stack : e));
|
|
}
|
|
},
|
|
|
|
beginRun(path) {
|
|
this.running = true;
|
|
this.lastClippingsPath = path;
|
|
this.startedAt = Date.now();
|
|
const btn = document.getElementById('run-button');
|
|
if (btn) btn.classList.add('disabled');
|
|
const fileEl = document.getElementById('run-file');
|
|
if (fileEl) fileEl.textContent = path;
|
|
const resultsEl = document.getElementById('run-results');
|
|
if (resultsEl) resultsEl.textContent = '';
|
|
const bar = document.getElementById('reimport-bar');
|
|
if (bar) bar.style.display = 'none';
|
|
this.updateProgress(1, 'Starting import', 'Preparing pipeline');
|
|
clearInterval(this.timer);
|
|
this.timer = setInterval(() => this.updateElapsed(), 1000);
|
|
},
|
|
|
|
updateElapsed() {
|
|
if (!this.startedAt) return;
|
|
const seconds = Math.floor((Date.now() - this.startedAt) / 1000);
|
|
const minutes = Math.floor(seconds / 60);
|
|
const el = document.getElementById('elapsed');
|
|
if (el) el.textContent = `${minutes}:${String(seconds % 60).padStart(2, '0')} elapsed`;
|
|
},
|
|
|
|
async collectorCredentials() {
|
|
let anonId = '';
|
|
let token = '';
|
|
try { anonId = Services.prefs.getCharPref("extensions.kindleZoteroImporter.collectorAnonId"); } catch(e) {}
|
|
try { token = Services.prefs.getCharPref("extensions.kindleZoteroImporter.collectorToken"); } catch(e) {}
|
|
if (anonId && token) return {anonId, token};
|
|
const response = await fetch("https://annotation.utkubilen.de/register", {method: "POST"});
|
|
if (!response.ok) throw new Error(`Collector registration returned HTTP ${response.status}`);
|
|
const credentials = await response.json();
|
|
if (!credentials.anonId || !credentials.token) throw new Error('Collector registration was incomplete');
|
|
Services.prefs.setCharPref("extensions.kindleZoteroImporter.collectorAnonId", credentials.anonId);
|
|
Services.prefs.setCharPref("extensions.kindleZoteroImporter.collectorToken", credentials.token);
|
|
return credentials;
|
|
},
|
|
|
|
collectorBatches(anonId, data) {
|
|
const batches = [];
|
|
let current = [];
|
|
for (const item of data) {
|
|
const candidate = current.concat(item);
|
|
const bytes = new TextEncoder().encode(JSON.stringify({anonId, data: candidate})).length;
|
|
if (!current.length && bytes > 1500000) {
|
|
throw new Error('One annotation exceeds the collector request limit');
|
|
}
|
|
if (current.length && (current.length >= 200 || bytes > 1500000)) {
|
|
batches.push(current);
|
|
current = [item];
|
|
} else {
|
|
current = candidate;
|
|
}
|
|
}
|
|
if (current.length) batches.push(current);
|
|
return batches;
|
|
},
|
|
|
|
updateProgress(percent, stage, detail) {
|
|
const prog = document.getElementById('progress');
|
|
if (prog) prog.value = Math.max(0, Math.min(100, Number(percent) || 0));
|
|
const stageEl = document.getElementById('stage');
|
|
if (stageEl) stageEl.textContent = stage || 'Working';
|
|
const detailEl = document.getElementById('detail');
|
|
if (detailEl) detailEl.textContent = detail || '';
|
|
const pctEl = document.getElementById('percent');
|
|
if (pctEl) pctEl.textContent = `${Math.round(Number(percent) || 0)}%`;
|
|
},
|
|
|
|
async completeRun(summary, results, data) {
|
|
this.running = false;
|
|
clearInterval(this.timer);
|
|
this.updateProgress(100, 'Import complete', 'Annotations have been checked and saved in Zotero');
|
|
const btn = document.getElementById('run-button');
|
|
if (btn) {
|
|
btn.classList.remove('disabled');
|
|
btn.textContent = 'Choose another clippings file';
|
|
}
|
|
const resultsEl = document.getElementById('run-results');
|
|
if (resultsEl) {
|
|
resultsEl.textContent = '';
|
|
const h2 = document.createElement('h2');
|
|
h2.textContent = 'Result';
|
|
resultsEl.appendChild(h2);
|
|
const grid = document.createElement('div');
|
|
grid.className = 'grid';
|
|
const makeCard = (value, label) => {
|
|
const card = document.createElement('div');
|
|
card.className = 'card';
|
|
const strong = document.createElement('strong');
|
|
strong.textContent = String(value);
|
|
const span = document.createElement('span');
|
|
span.textContent = label;
|
|
card.appendChild(strong);
|
|
card.appendChild(span);
|
|
return card;
|
|
};
|
|
grid.appendChild(makeCard(results.created, 'created'));
|
|
grid.appendChild(makeCard(results.skippedExisting, 'already present'));
|
|
grid.appendChild(makeCard(results.updatedComments + results.updatedSortIndex, 'updated'));
|
|
grid.appendChild(makeCard(results.failed.length, 'failed'));
|
|
resultsEl.appendChild(grid);
|
|
const consentVersion = 2;
|
|
let acceptedVersion = 0;
|
|
try { acceptedVersion = Services.prefs.getIntPref("extensions.kindleZoteroImporter.shareConsentVersion"); } catch(e) {}
|
|
if (acceptedVersion < consentVersion && (data.finalPlan?.annotations || []).length) {
|
|
const accepted = confirm("Share annotation data with the Kanzi developer?\n\nThis sends a random pseudonymous installation ID, publication metadata, raw highlight text and comments, hashes, colour, and dates to annotation.utkubilen.de. Free text may contain identifying information. The dashboard is private, but this data is not anonymous.\n\nChoose OK to opt in, or Cancel to keep sharing disabled. You can change this later in Settings.");
|
|
Services.prefs.setBoolPref("extensions.kindleZoteroImporter.shareAnonymized", accepted);
|
|
Services.prefs.setBoolPref("extensions.kindleZoteroImporter.askedAnonymizedShare", true);
|
|
Services.prefs.setIntPref("extensions.kindleZoteroImporter.shareConsentVersion", consentVersion);
|
|
}
|
|
}
|
|
this.data = data;
|
|
this.rows = this.conflictRows();
|
|
this.refreshRows();
|
|
this.refreshIntegrated();
|
|
this.refreshMappings();
|
|
const bar = document.getElementById('reimport-bar');
|
|
if (bar) bar.style.display = 'none';
|
|
this.status(`${summary.counts.final_annotations || 0} positioned annotations processed; ${this.rows.length} review rows remain.`, results.failed.length > 0);
|
|
// Pseudonymous sharing after explicit consent.
|
|
try {
|
|
let share = false;
|
|
try { share = Services.prefs.getBoolPref("extensions.kindleZoteroImporter.shareAnonymized"); } catch(e) {}
|
|
if (share) {
|
|
const {anonId, token} = await this.collectorCredentials();
|
|
const anonData = (data.finalPlan?.annotations || []).map(a => ({
|
|
citation_key: (a.citation_key || '').slice(0, 512) || null,
|
|
doi: (a.doi || '').slice(0, 512) || null,
|
|
isbn: (a.isbn || '').slice(0, 512) || null,
|
|
issn: (a.issn || '').slice(0, 512) || null,
|
|
publication_title: (a.publication_title || '').slice(0, 1000) || null,
|
|
clipping_id_hash: (a.clipping_id || '').slice(0, 128) || null,
|
|
norm_hash: (a.norm_hash || '').slice(0, 256) || null,
|
|
fuzzy_hash: (a.fuzzy_hash || '').slice(0, 256) || null,
|
|
text: (a.annotation?.text || '').slice(0, 2000),
|
|
color: a.annotation?.color,
|
|
has_comment: !!(a.annotation?.comment),
|
|
comment: (a.annotation?.comment || '').slice(0, 2000),
|
|
comment_hash: null,
|
|
clipping_added_on_iso: (a.clipping_added_on_iso || '').slice(0, 64) || null,
|
|
integrated_at: (a.integrated_at || '').slice(0, 64) || null
|
|
}));
|
|
for (const batch of this.collectorBatches(anonId, anonData)) {
|
|
const response = await fetch("https://annotation.utkubilen.de/highlights", {
|
|
method: "POST",
|
|
headers: {"Content-Type":"application/json", "Authorization": `Bearer ${token}`},
|
|
body: JSON.stringify({anonId, data: batch})
|
|
});
|
|
if (!response.ok) throw new Error(`Collector returned HTTP ${response.status}`);
|
|
}
|
|
}
|
|
} catch(e) {
|
|
this.status(`Import succeeded, but annotation sharing failed: ${e}`, true);
|
|
}
|
|
},
|
|
|
|
failRun(message) {
|
|
this.running = false;
|
|
clearInterval(this.timer);
|
|
const btn = document.getElementById('run-button');
|
|
if (btn) btn.classList.remove('disabled');
|
|
this.updateProgress(0, 'Import failed', message);
|
|
this.status(message, true);
|
|
},
|
|
|
|
getFullReimport() {
|
|
const cb = document.getElementById('full-reimport-check');
|
|
return !!(cb && cb.checked);
|
|
},
|
|
|
|
getRetryUnresolved() {
|
|
const cb = document.getElementById('retry-unresolved-check');
|
|
return !!(cb && cb.checked);
|
|
},
|
|
|
|
updateInfobox() {
|
|
const box = document.getElementById('infobox');
|
|
if (!box) return;
|
|
const pending = (this.data.persistentOverrides?.overrides || []).length;
|
|
const integrated = this.data.finalPlan?.annotation_count || 0;
|
|
const conflicts = this.rows.length;
|
|
const hasPendingReimport = document.getElementById('reimport-bar')?.style.display !== 'none';
|
|
let html = `<div style="font-weight:600; margin-bottom:6px;">Ready to re-run</div>`;
|
|
html += `<div>${integrated} integrated · ${conflicts} conflicts · ${pending} mappings</div>`;
|
|
if (hasPendingReimport) {
|
|
const info = document.getElementById('reimport-info')?.textContent || 'New mapping saved';
|
|
html += `<div style="margin-top:6px; padding-top:6px; border-top:1px solid var(--line); color:var(--text);">${this.esc(info)}</div>`;
|
|
html += `<div style="margin-top:6px;"><button onclick="KindleManager.reimportWithOverrides()" style="width:100%; padding:8px; border:1px solid var(--accent); background:var(--accent); color:white; cursor:pointer; font-family:inherit; border-radius:var(--radius); font-weight:600;">↻ Re-import now</button></div>`;
|
|
} else {
|
|
html += `<div style="margin-top:6px; color:var(--muted);">No pending mappings — choose a candidate in Conflicts or delete in Mappings, then re-import.</div>`;
|
|
}
|
|
html += `<div style="margin-top:10px; padding-top:8px; border-top:1px dashed var(--line); text-align:center;"><button onclick="try{Zotero.launchURL('https://github.com/sponsors/UtkuBilenDemir')}catch(e){window.open('https://github.com/sponsors/UtkuBilenDemir','_blank')}" style="padding:10px 22px; border:1px solid var(--accent); background:var(--accent); color:white; cursor:pointer; font-family:inherit; font-size:13px; border-radius:0; font-weight:700; letter-spacing:.02em;">please give me money+</button></div>`;
|
|
box.innerHTML = html;
|
|
box.style.display = 'block';
|
|
},
|
|
|
|
showReimportReady(title, count) {
|
|
const bar = document.getElementById('reimport-bar');
|
|
const info = document.getElementById('reimport-info');
|
|
if (bar) {
|
|
bar.style.display = 'block';
|
|
if (info) info.textContent = `Saved override for “${title}” (${count} highlight(s)). Click Re-import to integrate pending annotations for this article.`;
|
|
}
|
|
this.updateInfobox();
|
|
},
|
|
|
|
async reimportWithOverrides() {
|
|
if (this.running) return;
|
|
const isFull = this.getFullReimport();
|
|
const mode = isFull ? "FULL re-import from scratch (all highlights)" : "incremental (only new/changed/removed)";
|
|
if (this.lastClippingsPath) {
|
|
if (!confirm(`Re-import with saved overrides using last file?\n\n${this.lastClippingsPath}\n\nMode: ${mode}\nThis will re-run matching, positioning, and Zotero writing.`)) return;
|
|
await this.plugin.runManagedImportWithPath(this, this.lastClippingsPath, isFull);
|
|
} else {
|
|
await this.chooseAndImport();
|
|
}
|
|
},
|
|
|
|
esc(value) {
|
|
return String(value ?? '')
|
|
.replaceAll('&', '&')
|
|
.replaceAll('<', '<')
|
|
.replaceAll('>', '>')
|
|
.replaceAll('"', '"')
|
|
.replaceAll("'", ''');
|
|
},
|
|
|
|
setTab(name) {
|
|
for (const el of document.querySelectorAll('.tab')) el.classList.toggle('active', el.id === `tab-${name}`);
|
|
for (const el of document.querySelectorAll('.tab-button')) el.classList.toggle('active', el.dataset.tab === name);
|
|
},
|
|
|
|
counts(items, key = 'status') {
|
|
const counts = {};
|
|
for (const item of items || []) counts[item[key] || 'unknown'] = (counts[item[key] || 'unknown'] || 0) + 1;
|
|
return counts;
|
|
},
|
|
|
|
cards(counts) {
|
|
return Object.entries(counts || {})
|
|
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
|
|
.map(([k, v]) => `<div class="card"><strong>${this.esc(v)}</strong><span>${this.esc(k)}</span></div>`)
|
|
.join('') || '<div class="card">No data</div>';
|
|
},
|
|
|
|
conflictRows() {
|
|
const rows = [];
|
|
for (const match of this.data.matches?.matches || []) {
|
|
if (['matched', 'ignored'].includes(match.status)) continue;
|
|
rows.push({ source: 'Title match', title: match.clipping_title, status: match.status, count: match.clipping_count, candidates: match.candidates || [] });
|
|
}
|
|
for (const override of this.data.generatedOverrides?.overrides || []) {
|
|
const s = override.review?.status || 'review';
|
|
if (['matched','ignored'].includes(s)) continue;
|
|
rows.push({ source: 'Override suggestion', title: override.clipping_title, status: s, count: override.review?.clipping_count || '', candidates: override.candidates || [], generated: override });
|
|
}
|
|
for (const item of this.data.positionedPlan?.items || []) {
|
|
if (['positioned', 'ignored-title'].includes(item.status)) continue;
|
|
rows.push({ source: 'Attachment/position', title: item.clipping?.title || '(missing title)', status: item.status || 'unknown', count: 1, detail: (item.problems || []).join('; ') || 'Needs review', candidates: [] });
|
|
}
|
|
return rows;
|
|
},
|
|
|
|
async saveCandidate(index) {
|
|
const row = this.rows[index];
|
|
const select = document.getElementById(`candidate-${index}`);
|
|
if (!select) return this.status('No candidate menu found', true);
|
|
const candidate = row.candidates?.[Number(select.value)];
|
|
if (!candidate) return this.status('No candidate selected', true);
|
|
if (!confirm(`Map Kindle title to ${candidate.citation_key || candidate.key || candidate.item_id}?\n\n${row.title}\n→ ${candidate.title}`)) return;
|
|
let resolution;
|
|
if (candidate.citation_key) resolution = { citation_key: candidate.citation_key };
|
|
else if (candidate.key) resolution = { zotero_key: candidate.key };
|
|
else resolution = { zotero_item_id: candidate.item_id };
|
|
await this.plugin.saveOverride({
|
|
clipping_title: row.title,
|
|
clipping_count: row.count,
|
|
resolution,
|
|
review: { status: row.status, clipping_count: row.count || 0 },
|
|
});
|
|
this.status(`Saved override for ${row.title} → ${candidate.citation_key || candidate.key}. Click Re-import to integrate ${row.count} pending highlight(s).`, false);
|
|
this.showReimportReady(row.title, row.count);
|
|
this.data.persistentOverrides = await this.plugin.readJsonArtifact("match-overrides.json");
|
|
this.refreshMappings();
|
|
// Immediately hide mapped titles from Conflicts view
|
|
const mappedTitles = new Set([row.title, ...otherRows.map(r=>r.title)]);
|
|
this.rows = this.rows.filter(r => !mappedTitles.has(r.title));
|
|
this.refreshRows();
|
|
},
|
|
|
|
async saveCandidateAt(rowIndex, candIndex) {
|
|
const row = this.rows[rowIndex];
|
|
const candidate = row.candidates?.[candIndex];
|
|
if (!candidate) return this.status('No candidate selected', true);
|
|
const targetKey = candidate.citation_key || candidate.key || String(candidate.item_id);
|
|
// Find other titles that share this same candidate
|
|
const otherRows = this.rows.filter((r, idx) => idx !== rowIndex && (r.candidates || []).some(c => (c.citation_key || c.key || String(c.item_id)) === targetKey));
|
|
let extraMsg = "";
|
|
if (otherRows.length) extraMsg = `\n\nAlso apply to ${otherRows.length} other title(s) with same candidate ${targetKey}?\n` + otherRows.map(r => `• ${r.title.slice(0,60)}`).join("\n");
|
|
if (!confirm(`Map Kindle title to ${candidate.citation_key || candidate.key || candidate.item_id}?\n\n${row.title}\n→ ${candidate.title}${extraMsg}`)) return;
|
|
let resolution;
|
|
if (candidate.citation_key) resolution = { citation_key: candidate.citation_key };
|
|
else if (candidate.key) resolution = { zotero_key: candidate.key };
|
|
else resolution = { zotero_item_id: candidate.item_id };
|
|
await this.plugin.saveOverride({
|
|
clipping_title: row.title,
|
|
clipping_count: row.count,
|
|
resolution,
|
|
review: { status: row.status, clipping_count: row.count || 0 },
|
|
});
|
|
let appliedTitles = [row.title];
|
|
if (otherRows.length && confirm(`Apply same mapping ${targetKey} to ${otherRows.length} other title(s)?`)) {
|
|
for (const other of otherRows) {
|
|
await this.plugin.saveOverride({
|
|
clipping_title: other.title,
|
|
clipping_count: other.count,
|
|
resolution: { ...resolution },
|
|
review: { status: other.status, clipping_count: other.count || 0 },
|
|
});
|
|
}
|
|
appliedTitles = [row.title, ...otherRows.map(r=>r.title)];
|
|
this.status(`Saved override for ${row.title} + ${otherRows.length} similar titles → ${targetKey}. Click Re-import to integrate.`, false);
|
|
this.showReimportReady(`${row.title} + ${otherRows.length} others`, row.count + otherRows.reduce((s,r)=>s+(r.count||0),0));
|
|
} else {
|
|
this.status(`Saved override for ${row.title} → ${targetKey}. Click Re-import to integrate ${row.count} pending highlight(s).`, false);
|
|
this.showReimportReady(row.title, row.count);
|
|
}
|
|
this.data.persistentOverrides = await this.plugin.readJsonArtifact("match-overrides.json");
|
|
this.refreshMappings();
|
|
// Immediately hide mapped titles from Conflicts view
|
|
const mappedSet = new Set(appliedTitles);
|
|
this.rows = this.rows.filter(r => !mappedSet.has(r.title));
|
|
this.refreshRows();
|
|
},
|
|
|
|
makeTableResizable(table) {
|
|
if (!table || table.dataset.resizable) return;
|
|
table.dataset.resizable = "1";
|
|
const ths = table.querySelectorAll('th');
|
|
ths.forEach(th => {
|
|
const resizer = document.createElement('div');
|
|
resizer.className = 'resizer';
|
|
th.appendChild(resizer);
|
|
let startX, startWidth;
|
|
const onMouseMove = (e) => {
|
|
const dx = e.clientX - startX;
|
|
th.style.width = (startWidth + dx) + 'px';
|
|
};
|
|
const onMouseUp = () => {
|
|
document.removeEventListener('mousemove', onMouseMove);
|
|
document.removeEventListener('mouseup', onMouseUp);
|
|
};
|
|
resizer.addEventListener('mousedown', (e) => {
|
|
startX = e.clientX;
|
|
startWidth = th.offsetWidth;
|
|
document.addEventListener('mousemove', onMouseMove);
|
|
document.addEventListener('mouseup', onMouseUp);
|
|
e.preventDefault();
|
|
});
|
|
});
|
|
},
|
|
|
|
makeTableSortable(table) {
|
|
if (!table || table.dataset.sortable) return;
|
|
table.dataset.sortable = "1";
|
|
const ths = table.querySelectorAll('th');
|
|
let sortCol = -1;
|
|
let sortAsc = true;
|
|
ths.forEach((th, idx) => {
|
|
th.style.cursor = 'pointer';
|
|
th.title = 'Click to sort';
|
|
th.addEventListener('click', (e) => {
|
|
if (e.target.classList.contains('resizer')) return;
|
|
const tbody = table.querySelector('tbody');
|
|
if (!tbody) return;
|
|
const rows = Array.from(tbody.querySelectorAll('tr'));
|
|
// Ignore placeholder rows with colspan
|
|
if (rows.length && rows[0].querySelector('td[colspan]')) return;
|
|
if (sortCol === idx) sortAsc = !sortAsc;
|
|
else { sortCol = idx; sortAsc = true; }
|
|
ths.forEach(h => h.textContent = h.textContent.replace(/ [▲▼]$/, ''));
|
|
th.textContent = th.textContent + (sortAsc ? ' ▲' : ' ▼');
|
|
rows.sort((a,b) => {
|
|
const getText = (row, col) => (row.children[col]?.textContent || '').toLowerCase().trim();
|
|
const va = getText(a, idx);
|
|
const vb = getText(b, idx);
|
|
// Try numeric compare if both look numeric
|
|
const na = parseFloat(va);
|
|
const nb = parseFloat(vb);
|
|
if (!isNaN(na) && !isNaN(nb) && va !== '' && vb !== '') {
|
|
if (na < nb) return sortAsc ? -1 : 1;
|
|
if (na > nb) return sortAsc ? 1 : -1;
|
|
}
|
|
if (va < vb) return sortAsc ? -1 : 1;
|
|
if (va > vb) return sortAsc ? 1 : -1;
|
|
return 0;
|
|
});
|
|
rows.forEach(r => tbody.appendChild(r));
|
|
});
|
|
});
|
|
},
|
|
|
|
async saveManualCandidate(index) {
|
|
const row = this.rows[index];
|
|
const input = document.getElementById(`manual-${index}`);
|
|
const raw = (input?.value || '').trim();
|
|
if (!raw) return this.status('Enter a citation key, Zotero key, or item ID', true);
|
|
let resolution;
|
|
if (/^\d+$/.test(raw)) {
|
|
resolution = { zotero_item_id: Number(raw) };
|
|
} else if (/^[A-Z0-9]{8}$/.test(raw)) {
|
|
resolution = { zotero_key: raw.toUpperCase() };
|
|
} else {
|
|
resolution = { citation_key: raw };
|
|
}
|
|
const hasValue = Object.values(resolution).some(v => v !== '' && v != null);
|
|
if (!hasValue) return this.status('Invalid key', true);
|
|
// Find other titles that could use same custom key (share candidate or similar title)
|
|
const otherRows = this.rows.filter((r, idx) => idx !== index && (r.candidates || []).some(c => (c.citation_key || c.key) === raw || String(c.item_id) === raw));
|
|
let extra = otherRows.length ? `\n\nAlso apply "${raw}" to ${otherRows.length} other title(s) that have this candidate?\n` + otherRows.map(r=>`• ${r.title.slice(0,55)}`).join("\n") : "";
|
|
if (!confirm(`Map Kindle title to custom key "${raw}"?\n\n${row.title}\n→ ${raw}${extra}\n\nYou can enter any citation key (e.g. deleuze1987), Zotero key (8 chars), or numeric item ID.`)) return;
|
|
await this.plugin.saveOverride({
|
|
clipping_title: row.title,
|
|
clipping_count: row.count,
|
|
resolution,
|
|
review: { status: row.status, clipping_count: row.count || 0 },
|
|
});
|
|
if (otherRows.length && confirm(`Apply same custom key "${raw}" to ${otherRows.length} other title(s)?`)) {
|
|
for (const other of otherRows) {
|
|
await this.plugin.saveOverride({
|
|
clipping_title: other.title,
|
|
clipping_count: other.count,
|
|
resolution: { ...resolution },
|
|
review: { status: other.status, clipping_count: other.count || 0 },
|
|
});
|
|
}
|
|
this.status(`Saved custom override for ${row.title} + ${otherRows.length} others → ${raw}. Click Re-import.`, false);
|
|
this.showReimportReady(`${row.title} + ${otherRows.length} others`, row.count + otherRows.reduce((s,r)=>s+(r.count||0),0));
|
|
const mappedTitles = new Set([row.title, ...otherRows.map(r=>r.title)]);
|
|
this.rows = this.rows.filter(r => !mappedTitles.has(r.title));
|
|
} else {
|
|
this.status(`Saved custom override for ${row.title} → ${raw}. Click Re-import to integrate ${row.count} pending highlight(s).`, false);
|
|
this.showReimportReady(row.title, row.count);
|
|
this.rows = this.rows.filter(r => r.title !== row.title);
|
|
}
|
|
this.data.persistentOverrides = await this.plugin.readJsonArtifact("match-overrides.json");
|
|
this.refreshMappings();
|
|
this.refreshRows();
|
|
input.value = '';
|
|
},
|
|
|
|
async ignore(index) {
|
|
const row = this.rows[index];
|
|
if (!confirm(`Ignore all Kindle clippings for this title?\n\n${row.title}`)) return;
|
|
await this.plugin.saveOverride({
|
|
clipping_title: row.title,
|
|
clipping_count: row.count,
|
|
resolution: { ignore: true },
|
|
review: { status: row.status, clipping_count: row.count || 0 },
|
|
});
|
|
this.status(`Saved ignore override for ${row.title}. Click Re-import to apply.`, false);
|
|
this.showReimportReady(row.title, row.count);
|
|
this.data.persistentOverrides = await this.plugin.readJsonArtifact("match-overrides.json");
|
|
this.refreshMappings();
|
|
},
|
|
|
|
status(message, error) {
|
|
const el = document.getElementById('status');
|
|
if (el) {
|
|
if (!message) {
|
|
el.style.display = 'none';
|
|
el.textContent = '';
|
|
return;
|
|
}
|
|
el.style.display = 'block';
|
|
el.className = 'notice';
|
|
el.style.borderLeft = error ? '4px solid var(--danger)' : '4px solid var(--accent)';
|
|
el.style.background = error ? 'var(--danger-soft)' : 'var(--panel-soft)';
|
|
el.textContent = message;
|
|
}
|
|
},
|
|
|
|
formatDate(iso) {
|
|
if (!iso) return '—';
|
|
try {
|
|
const d = new Date(iso);
|
|
if (isNaN(d)) return iso.slice(0,10);
|
|
return d.toISOString().slice(0,10);
|
|
} catch { return String(iso).slice(0,10); }
|
|
},
|
|
|
|
paginate(items, pageKey, pageSizeKey) {
|
|
const totalPages = Math.max(1, Math.ceil(items.length / this[pageSizeKey]));
|
|
if (this[pageKey] >= totalPages) this[pageKey] = totalPages - 1;
|
|
if (this[pageKey] < 0) this[pageKey] = 0;
|
|
const start = this[pageKey] * this[pageSizeKey];
|
|
return { rows: items.slice(start, start + this[pageSizeKey]), totalPages };
|
|
},
|
|
|
|
refreshPagination(containerId, pageKey, pageSizeKey, totalPages, refresh) {
|
|
const container = document.getElementById(containerId);
|
|
if (!container) return;
|
|
container.textContent = '';
|
|
const button = (label, disabled, action) => {
|
|
const el = document.createElement('button');
|
|
el.textContent = label;
|
|
el.disabled = disabled;
|
|
if (!disabled) el.addEventListener('click', action);
|
|
return el;
|
|
};
|
|
container.appendChild(button('Previous', this[pageKey] === 0, () => {
|
|
this[pageKey] -= 1;
|
|
refresh();
|
|
}));
|
|
const status = document.createElement('span');
|
|
status.textContent = `Page ${this[pageKey] + 1} of ${totalPages}`;
|
|
container.appendChild(status);
|
|
container.appendChild(button('Next', this[pageKey] >= totalPages - 1, () => {
|
|
this[pageKey] += 1;
|
|
refresh();
|
|
}));
|
|
const select = document.createElement('select');
|
|
for (const size of [25, 50, 100, 200]) {
|
|
const option = document.createElement('option');
|
|
option.value = size;
|
|
option.textContent = `${size} per page`;
|
|
option.selected = size === this[pageSizeKey];
|
|
select.appendChild(option);
|
|
}
|
|
select.addEventListener('change', () => {
|
|
this[pageSizeKey] = Number(select.value);
|
|
this[pageKey] = 0;
|
|
refresh();
|
|
});
|
|
container.appendChild(select);
|
|
},
|
|
|
|
getIntegratedHighlights() {
|
|
const anns = this.data.finalPlan?.all_annotations || this.data.finalPlan?.annotations || [];
|
|
return anns.slice().sort((a,b) => (a.clipping_title || '').localeCompare(b.clipping_title || '') || (a.annotation?.text || '').localeCompare(b.annotation?.text || ''));
|
|
},
|
|
|
|
buildClippingDateMap() {
|
|
const map = new Map();
|
|
const items = this.data.positionedPlan?.items || [];
|
|
for (const it of items) {
|
|
const c = it.clipping;
|
|
if (c && c.id) map.set(c.id, { added_on: c.added_on, added_on_iso: c.added_on_iso });
|
|
}
|
|
return map;
|
|
},
|
|
|
|
refreshIntegrated(resetPage = false) {
|
|
const tbody = document.getElementById('integrated-rows');
|
|
const countEl = document.getElementById('integrated-count');
|
|
if (!tbody) return;
|
|
tbody.textContent = '';
|
|
const needle = (document.getElementById('integrated-search')?.value || '').toLowerCase();
|
|
const all = this.getIntegratedHighlights();
|
|
const dateMap = this.buildClippingDateMap();
|
|
const filtered = needle ? all.filter(a => `${a.clipping_title} ${a.annotation?.text || ''} ${a.citation_key || ''} ${a.annotation?.pageLabel || ''} ${a.clipping_added_on_iso || ''} ${a.integrated_at || ''}`.toLowerCase().includes(needle)) : all;
|
|
if (resetPage) this.integratedPage = 0;
|
|
const page = this.paginate(filtered, 'integratedPage', 'integratedPageSize');
|
|
const totalPages = page.totalPages;
|
|
const toShow = page.rows;
|
|
if (countEl) countEl.textContent = `${filtered.length} of ${all.length} — page ${this.integratedPage + 1}/${totalPages} (${this.integratedPageSize} per page)`;
|
|
this.refreshPagination('integrated-pagination', 'integratedPage', 'integratedPageSize', totalPages, () => this.refreshIntegrated());
|
|
if (!toShow.length) {
|
|
const tr = document.createElement('tr');
|
|
const td = document.createElement('td');
|
|
td.colSpan = 6;
|
|
td.textContent = all.length ? 'No highlights match the filter.' : 'No integrated highlights yet — run an import.';
|
|
tr.appendChild(td);
|
|
tbody.appendChild(tr);
|
|
return;
|
|
}
|
|
for (const ann of toShow) {
|
|
const tr = document.createElement('tr');
|
|
const tdTitle = document.createElement('td');
|
|
tdTitle.textContent = ann.clipping_title || '';
|
|
tr.appendChild(tdTitle);
|
|
const tdCite = document.createElement('td');
|
|
tdCite.textContent = ann.citation_key || ann.parent_key || '—';
|
|
tdCite.style.fontFamily='ui-monospace, monospace';
|
|
tdCite.style.fontSize='12px';
|
|
tr.appendChild(tdCite);
|
|
const tdText = document.createElement('td');
|
|
tdText.className = 'highlight-text';
|
|
let text = ann.annotation?.text || '';
|
|
if (text.length > 380) text = text.slice(0,380) + '…';
|
|
tdText.textContent = text;
|
|
tr.appendChild(tdText);
|
|
const tdAdded = document.createElement('td');
|
|
const addedIso = ann.clipping_added_on_iso || dateMap.get(ann.clipping_id)?.added_on_iso || '';
|
|
tdAdded.textContent = this.formatDate(addedIso);
|
|
tdAdded.title = ann.clipping_added_on || addedIso || '';
|
|
tdAdded.style.fontSize='12px';
|
|
tr.appendChild(tdAdded);
|
|
const tdIntegrated = document.createElement('td');
|
|
tdIntegrated.textContent = this.formatDate(ann.integrated_at);
|
|
tdIntegrated.title = ann.integrated_at || '';
|
|
tdIntegrated.style.fontSize='12px';
|
|
tr.appendChild(tdIntegrated);
|
|
const tdPage = document.createElement('td');
|
|
tdPage.textContent = ann.annotation?.pageLabel || '—';
|
|
const swatch = document.createElement('span');
|
|
swatch.style.display='inline-block';
|
|
swatch.style.width='10px';
|
|
swatch.style.height='10px';
|
|
swatch.style.borderRadius='2px';
|
|
swatch.style.border='1px solid #999';
|
|
swatch.style.background = ann.annotation?.color || '#ffd400';
|
|
swatch.style.marginLeft='4px';
|
|
swatch.style.verticalAlign='middle';
|
|
tdPage.appendChild(swatch);
|
|
tr.appendChild(tdPage);
|
|
tbody.appendChild(tr);
|
|
}
|
|
},
|
|
|
|
refreshMappings(resetPage = false) {
|
|
const tbody = document.getElementById('mappings-rows');
|
|
const countEl = document.getElementById('mappings-count');
|
|
if (!tbody) return;
|
|
tbody.textContent = '';
|
|
const needle = (document.getElementById('mappings-search')?.value || '').toLowerCase();
|
|
const overrides = this.data.persistentOverrides?.overrides || [];
|
|
const filtered = needle ? overrides.filter(o => `${o.clipping_title} ${o.resolution?.citation_key || ''} ${o.resolution?.zotero_key || ''} ${o.resolution?.ignore ? 'ignored' : ''}`.toLowerCase().includes(needle)) : overrides;
|
|
if (resetPage) this.mappingsPage = 0;
|
|
const page = this.paginate(filtered, 'mappingsPage', 'mappingsPageSize');
|
|
if (countEl) countEl.textContent = `${filtered.length} of ${overrides.length} mappings — page ${this.mappingsPage + 1}/${page.totalPages}`;
|
|
this.refreshPagination('mappings-pagination', 'mappingsPage', 'mappingsPageSize', page.totalPages, () => this.refreshMappings());
|
|
if (!filtered.length) {
|
|
const tr = document.createElement('tr');
|
|
const td = document.createElement('td');
|
|
td.colSpan = 6;
|
|
td.textContent = overrides.length ? 'No mappings match the filter.' : 'No established mappings yet — approve a candidate in Conflicts and Re-import.';
|
|
tr.appendChild(td);
|
|
tbody.appendChild(tr);
|
|
return;
|
|
}
|
|
for (const entry of page.rows) {
|
|
const tr = document.createElement('tr');
|
|
const tdTitle = document.createElement('td');
|
|
tdTitle.textContent = entry.clipping_title;
|
|
tdTitle.title = entry.clipping_title;
|
|
tr.appendChild(tdTitle);
|
|
const tdRes = document.createElement('td');
|
|
if (entry.resolution?.ignore) {
|
|
tdRes.textContent = 'Ignored';
|
|
tdRes.style.fontStyle = 'italic';
|
|
tdRes.style.color = '#a00';
|
|
} else if (entry.resolution?.citation_key) {
|
|
tdRes.textContent = entry.resolution.citation_key;
|
|
tdRes.style.fontFamily = "'iA Writer Duo', ui-monospace, monospace";
|
|
tdRes.style.fontWeight = '600';
|
|
} else if (entry.resolution?.zotero_key) {
|
|
tdRes.textContent = entry.resolution.zotero_key;
|
|
tdRes.style.fontFamily = "'iA Writer Duo', ui-monospace, monospace";
|
|
} else if (entry.resolution?.zotero_item_id) {
|
|
tdRes.textContent = String(entry.resolution.zotero_item_id);
|
|
} else {
|
|
tdRes.textContent = '—';
|
|
}
|
|
tr.appendChild(tdRes);
|
|
const tdStatus = document.createElement('td');
|
|
tdStatus.textContent = entry.review?.status || '—';
|
|
tdStatus.style.fontSize = '11px';
|
|
tr.appendChild(tdStatus);
|
|
const tdCount = document.createElement('td');
|
|
tdCount.textContent = String(entry.review?.clipping_count ?? '—');
|
|
tr.appendChild(tdCount);
|
|
const tdDate = document.createElement('td');
|
|
const dateVal = entry.updated_at || entry.created_at || '';
|
|
tdDate.textContent = this.formatDate(dateVal);
|
|
tdDate.title = dateVal || '';
|
|
tdDate.style.fontSize = '11px';
|
|
tdDate.style.fontFamily = "'iA Writer Duo', ui-monospace, monospace";
|
|
tr.appendChild(tdDate);
|
|
const tdAction = document.createElement('td');
|
|
const delBtn = document.createElement('button');
|
|
delBtn.textContent = 'Delete';
|
|
delBtn.title = 'Remove this override and return to Conflicts';
|
|
delBtn.style.padding = '4px 10px';
|
|
delBtn.style.border = '1px solid var(--danger)';
|
|
delBtn.style.background = 'var(--panel)';
|
|
delBtn.style.color = 'var(--danger)';
|
|
delBtn.style.cursor = 'pointer';
|
|
delBtn.style.fontFamily = 'inherit';
|
|
delBtn.style.fontSize = '11px';
|
|
delBtn.style.borderRadius = 'var(--radius)';
|
|
delBtn.addEventListener('click', () => this.deleteMapping(entry.clipping_title));
|
|
tdAction.appendChild(delBtn);
|
|
tr.appendChild(tdAction);
|
|
tbody.appendChild(tr);
|
|
}
|
|
},
|
|
|
|
async deleteMapping(title) {
|
|
if (!confirm(`Delete override for “${title}”?\n\nIt will return to Conflicts on next Re-import.`)) return;
|
|
try {
|
|
await this.plugin.deleteOverride(title);
|
|
this.status(`Deleted override for ${title}. Re-import to restore it as a conflict.`, false);
|
|
this.data.persistentOverrides = await this.plugin.readJsonArtifact("match-overrides.json");
|
|
this.refreshMappings();
|
|
this.showReimportReady(title, 0);
|
|
} catch (e) {
|
|
this.status(String(e), true);
|
|
}
|
|
},
|
|
|
|
async saveSettings() {
|
|
// collect colour map from table
|
|
const colourMap = {};
|
|
const tbody = document.getElementById('colour-map-rows');
|
|
if (tbody) {
|
|
for (const tr of tbody.querySelectorAll('tr')) {
|
|
const keyInp = tr.querySelector('.colour-key-input');
|
|
const hexInp = tr.querySelector('.colour-hex-input');
|
|
if (!keyInp || !hexInp) continue;
|
|
const raw = (keyInp.value || '').trim().toLowerCase();
|
|
const v = (hexInp.value || '').trim();
|
|
if (!raw || !/^#[0-9a-fA-F]{6}$/.test(v)) continue;
|
|
for (const k of raw.split(',').map(s=>s.trim()).filter(Boolean)) {
|
|
colourMap[k] = v;
|
|
}
|
|
}
|
|
}
|
|
const newSettings = {
|
|
projectDir: document.getElementById('setting-projectDir')?.value?.trim(),
|
|
pythonPath: document.getElementById('setting-pythonPath')?.value?.trim(),
|
|
zoteroDbPath: document.getElementById('setting-zoteroDbPath')?.value?.trim(),
|
|
zoteroStorageRoot: document.getElementById('setting-zoteroStorageRoot')?.value?.trim(),
|
|
colourMap: Object.keys(colourMap).length ? colourMap : undefined,
|
|
};
|
|
const shareAnonymized = !!document.getElementById('setting-shareAnonymized')?.checked;
|
|
try {
|
|
await this.plugin.saveSettingsFromManager(newSettings);
|
|
this.settings = { ...this.settings, ...newSettings };
|
|
Services.prefs.setBoolPref("extensions.kindleZoteroImporter.shareAnonymized", shareAnonymized);
|
|
Services.prefs.setBoolPref("extensions.kindleZoteroImporter.askedAnonymizedShare", true);
|
|
Services.prefs.setIntPref("extensions.kindleZoteroImporter.shareConsentVersion", 2);
|
|
if (shareAnonymized) {
|
|
try {
|
|
Services.prefs.getCharPref("extensions.kindleZoteroImporter.anonId");
|
|
} catch(e) {
|
|
const anonId = Math.random().toString(36).slice(2,10) + Date.now().toString(36);
|
|
Services.prefs.setCharPref("extensions.kindleZoteroImporter.anonId", anonId);
|
|
}
|
|
}
|
|
this.status('Settings saved.', false);
|
|
} catch (e) {
|
|
this.status(String(e), true);
|
|
}
|
|
},
|
|
|
|
render() {
|
|
const root = document.getElementById('root');
|
|
root.textContent = '';
|
|
const headerWrap = document.createElement('div');
|
|
headerWrap.style.display = 'flex';
|
|
headerWrap.style.justifyContent = 'space-between';
|
|
headerWrap.style.alignItems = 'flex-start';
|
|
headerWrap.style.gap = '12px';
|
|
const headerLeft = document.createElement('div');
|
|
const h1 = document.createElement('h1');
|
|
h1.textContent = 'Kanzi';
|
|
const sub = document.createElement('div');
|
|
sub.style.fontSize = '12px';
|
|
sub.style.color = 'var(--muted)';
|
|
sub.style.marginTop = '2px';
|
|
sub.textContent = 'Kindle annotations to Zotero';
|
|
headerLeft.appendChild(h1);
|
|
headerLeft.appendChild(sub);
|
|
const muted = document.createElement('div');
|
|
muted.className = 'muted';
|
|
muted.textContent = 'My Clippings.txt → native Zotero annotations. Formerly Kindle Zotero Importer.';
|
|
headerLeft.appendChild(muted);
|
|
headerWrap.appendChild(headerLeft);
|
|
const infobox = document.createElement('div');
|
|
infobox.id = 'infobox';
|
|
infobox.style.minWidth = '260px';
|
|
infobox.style.maxWidth = '380px';
|
|
infobox.style.border = '1px solid var(--line)';
|
|
infobox.style.background = 'var(--panel)';
|
|
infobox.style.padding = '10px';
|
|
infobox.style.fontSize = '12px';
|
|
infobox.style.lineHeight = '1.4';
|
|
infobox.style.display = 'none';
|
|
infobox.style.borderRadius = 'var(--radius)';
|
|
infobox.style.boxShadow = 'var(--shadow)';
|
|
headerWrap.appendChild(infobox);
|
|
root.appendChild(headerWrap);
|
|
const panel = document.createElement('div');
|
|
panel.className = 'run-panel';
|
|
const runButton = document.createElement('div');
|
|
runButton.id = 'run-button';
|
|
runButton.className = 'file-button';
|
|
runButton.setAttribute('role', 'button');
|
|
runButton.tabIndex = 0;
|
|
runButton.textContent = 'Choose My Clippings.txt';
|
|
runButton.addEventListener('click', () => this.chooseAndImport());
|
|
runButton.addEventListener('keydown', (e) => {
|
|
if (e.key === 'Enter' || e.key === ' ') {
|
|
e.preventDefault();
|
|
this.chooseAndImport();
|
|
}
|
|
});
|
|
panel.appendChild(runButton);
|
|
const runFile = document.createElement('div');
|
|
runFile.id = 'run-file';
|
|
runFile.className = 'muted';
|
|
runFile.textContent = 'No file selected';
|
|
runFile.style.color = '#d7e0e3';
|
|
panel.appendChild(runFile);
|
|
const progress = document.createElement('progress');
|
|
progress.id = 'progress';
|
|
progress.max = 100;
|
|
progress.value = 0;
|
|
panel.appendChild(progress);
|
|
const meta = document.createElement('div');
|
|
meta.className = 'run-meta';
|
|
const stage = document.createElement('strong');
|
|
stage.id = 'stage';
|
|
stage.textContent = 'Ready';
|
|
meta.appendChild(stage);
|
|
const pctWrap = document.createElement('span');
|
|
const pct = document.createElement('span');
|
|
pct.id = 'percent';
|
|
pct.textContent = '0%';
|
|
pctWrap.appendChild(pct);
|
|
pctWrap.appendChild(document.createTextNode(' · '));
|
|
const elapsed = document.createElement('span');
|
|
elapsed.id = 'elapsed';
|
|
elapsed.textContent = '0:00 elapsed';
|
|
pctWrap.appendChild(elapsed);
|
|
meta.appendChild(pctWrap);
|
|
panel.appendChild(meta);
|
|
const detail = document.createElement('div');
|
|
detail.id = 'detail';
|
|
detail.textContent = 'Select your cumulative Kindle clippings file to begin.';
|
|
panel.appendChild(detail);
|
|
const fullRow = document.createElement('div');
|
|
fullRow.style.marginTop = '8px';
|
|
fullRow.style.display = 'flex';
|
|
fullRow.style.alignItems = 'center';
|
|
fullRow.style.gap = '6px';
|
|
const fullCheck = document.createElement('input');
|
|
fullCheck.type = 'checkbox';
|
|
fullCheck.id = 'full-reimport-check';
|
|
fullCheck.style.width = 'auto';
|
|
fullRow.appendChild(fullCheck);
|
|
const fullLabel = document.createElement('label');
|
|
fullLabel.htmlFor = 'full-reimport-check';
|
|
fullLabel.textContent = 'Full re-import from scratch (ignore incremental, re-process all)';
|
|
fullLabel.style.margin = '0';
|
|
fullLabel.style.fontSize = '12px';
|
|
fullLabel.style.color = 'var(--muted)';
|
|
fullLabel.title = 'When checked, re-processes all 2379 clippings from scratch (slow). Unchecked = incremental (only new/changed highlights, fast).';
|
|
fullRow.appendChild(fullLabel);
|
|
panel.appendChild(fullRow);
|
|
const retryRow = document.createElement('div');
|
|
retryRow.style.marginTop = '6px';
|
|
retryRow.style.display = 'flex';
|
|
retryRow.style.alignItems = 'center';
|
|
retryRow.style.gap = '6px';
|
|
const retryCheck = document.createElement('input');
|
|
retryCheck.type = 'checkbox';
|
|
retryCheck.id = 'retry-unresolved-check';
|
|
retryCheck.style.width = 'auto';
|
|
retryRow.appendChild(retryCheck);
|
|
const retryLabel = document.createElement('label');
|
|
retryLabel.htmlFor = 'retry-unresolved-check';
|
|
retryLabel.textContent = 'Retry unresolved attachments and positions';
|
|
retryLabel.style.margin = '0';
|
|
retryLabel.style.fontSize = '12px';
|
|
retryLabel.style.color = 'var(--muted)';
|
|
retryLabel.title = 'Retries prior matching and positioning failures without rebuilding annotations that already succeeded.';
|
|
retryRow.appendChild(retryLabel);
|
|
panel.appendChild(retryRow);
|
|
root.appendChild(panel);
|
|
|
|
const resultsDiv = document.createElement('div');
|
|
resultsDiv.id = 'run-results';
|
|
root.appendChild(resultsDiv);
|
|
|
|
const tabs = document.createElement('div');
|
|
tabs.className = 'tabs';
|
|
const tabNames = [['summary','Summary'],['integrated','Integrated'],['conflicts','Conflicts'],['mappings','Mappings'],['settings','Settings'],['artifacts','Artifacts']];
|
|
for (const [id,label] of tabNames) {
|
|
const btn = document.createElement('div');
|
|
btn.className = 'tab-button' + (id==='summary' ? ' active' : '');
|
|
btn.dataset.tab = id;
|
|
btn.textContent = label;
|
|
btn.setAttribute('role','button');
|
|
btn.tabIndex = 0;
|
|
btn.addEventListener('click', () => this.setTab(id));
|
|
btn.addEventListener('keydown', (e)=>{ if(e.key==='Enter'||e.key===' '){e.preventDefault(); this.setTab(id);} });
|
|
tabs.appendChild(btn);
|
|
}
|
|
root.appendChild(tabs);
|
|
|
|
const summaryTab = document.createElement('div');
|
|
summaryTab.id = 'tab-summary';
|
|
summaryTab.className = 'tab active';
|
|
const matchCounts = this.counts(this.data.matches?.matches || []);
|
|
const planCounts = this.data.positionedPlan?.status_counts || this.counts(this.data.positionedPlan?.items || []);
|
|
const finalCount = this.data.finalPlan?.annotation_count || 0;
|
|
summaryTab.innerHTML = `
|
|
<h2>Import Summary</h2>
|
|
<div class="grid">
|
|
<div class="card"><strong>${this.esc(this.data.summary?.counts?.clippings || '-')}</strong><span>clippings</span></div>
|
|
<div class="card"><strong>${this.esc(this.data.summary?.counts?.unique_titles || '-')}</strong><span>unique titles</span></div>
|
|
<div class="card"><strong>${this.esc(finalCount)}</strong><span>final annotations</span></div>
|
|
<div class="card"><strong>${this.esc(this.rows.length)}</strong><span>conflict rows</span></div>
|
|
</div>
|
|
<h2>Match Statuses</h2><div class="grid">${this.cards(matchCounts)}</div>
|
|
<h2>Plan Statuses</h2><div class="grid">${this.cards(planCounts)}</div>
|
|
<div class="notice">Unresolved title and positioning cases remain available under Conflicts. They do not prevent positioned annotations from importing. Check Integrated for highlights that were included.</div>`;
|
|
root.appendChild(summaryTab);
|
|
|
|
const integratedTab = document.createElement('div');
|
|
integratedTab.id = 'tab-integrated';
|
|
integratedTab.className = 'tab';
|
|
const iH2 = document.createElement('h2');
|
|
iH2.textContent = 'Last Integrated Highlights';
|
|
integratedTab.appendChild(iH2);
|
|
const iDesc = document.createElement('div');
|
|
iDesc.className='muted';
|
|
iDesc.textContent = 'Highlights from the last successful pipeline run (import-plan.final.json). Filter by title, text, or citation key. After saving custom overrides, rerun the import to update this list.';
|
|
integratedTab.appendChild(iDesc);
|
|
const iSearchWrap = document.createElement('div');
|
|
iSearchWrap.style.display = 'flex';
|
|
iSearchWrap.style.justifyContent = 'flex-end';
|
|
iSearchWrap.style.margin = '8px 0';
|
|
const iSearch = document.createElement('input');
|
|
iSearch.id = 'integrated-search';
|
|
iSearch.placeholder = 'Filter integrated highlights by title, text, citekey...';
|
|
iSearch.style.width = '320px';
|
|
iSearch.style.maxWidth = '50%';
|
|
iSearch.addEventListener('input', () => this.refreshIntegrated(true));
|
|
iSearchWrap.appendChild(iSearch);
|
|
integratedTab.appendChild(iSearchWrap);
|
|
const iCount = document.createElement('div');
|
|
iCount.id='integrated-count';
|
|
iCount.className='muted';
|
|
iCount.style.margin='6px 0';
|
|
integratedTab.appendChild(iCount);
|
|
const iTable = document.createElement('table');
|
|
const iThead = document.createElement('thead');
|
|
iThead.innerHTML = '<tr><th>Kindle Title</th><th>Citekey</th><th>Highlight Text</th><th>Added On</th><th>Integrated</th><th>Page</th></tr>';
|
|
iTable.appendChild(iThead);
|
|
const iTbody = document.createElement('tbody');
|
|
iTbody.id='integrated-rows';
|
|
iTable.appendChild(iTbody);
|
|
integratedTab.appendChild(iTable);
|
|
const iPagination = document.createElement('div');
|
|
iPagination.id = 'integrated-pagination';
|
|
iPagination.className = 'pagination';
|
|
integratedTab.appendChild(iPagination);
|
|
root.appendChild(integratedTab);
|
|
|
|
const conflictsTab = document.createElement('div');
|
|
conflictsTab.id = 'tab-conflicts';
|
|
conflictsTab.className = 'tab';
|
|
const cH2 = document.createElement('h2');
|
|
cH2.textContent = 'Conflicts';
|
|
conflictsTab.appendChild(cH2);
|
|
const cDesc = document.createElement('div');
|
|
cDesc.className='muted';
|
|
cDesc.textContent='Pick a suggested candidate or enter any citation key / Zotero key / item ID manually. Each candidate row has a dedicated Use button. “Use Custom” saves your manual entry. After saving, use Re-import to integrate pending highlights.';
|
|
conflictsTab.appendChild(cDesc);
|
|
const reimportBar = document.createElement('div');
|
|
reimportBar.id = 'reimport-bar';
|
|
reimportBar.style.display = 'none';
|
|
reimportBar.style.border = '1px solid var(--accent)';
|
|
reimportBar.style.background = 'var(--panel-soft)';
|
|
reimportBar.style.color = 'var(--text)';
|
|
reimportBar.style.padding = '10px';
|
|
reimportBar.style.margin = '10px 0';
|
|
reimportBar.style.borderRadius = 'var(--radius)';
|
|
const reimportText = document.createElement('span');
|
|
reimportText.id = 'reimport-info';
|
|
reimportText.textContent = 'Override saved — click to re-import.';
|
|
reimportBar.appendChild(reimportText);
|
|
const reimportBtn = document.createElement('button');
|
|
reimportBtn.textContent = '↻ Re-import with saved overrides';
|
|
reimportBtn.style.marginLeft = '10px';
|
|
reimportBtn.style.background = 'var(--accent)';
|
|
reimportBtn.style.color = 'white';
|
|
reimportBtn.style.border = '1px solid var(--accent)';
|
|
reimportBtn.style.padding = '6px 12px';
|
|
reimportBtn.style.cursor = 'pointer';
|
|
reimportBtn.style.fontFamily = 'inherit';
|
|
reimportBtn.style.borderRadius = 'var(--pill-radius)';
|
|
reimportBtn.style.fontWeight = '600';
|
|
reimportBtn.addEventListener('click', () => this.reimportWithOverrides());
|
|
reimportBar.appendChild(reimportBtn);
|
|
conflictsTab.appendChild(reimportBar);
|
|
const searchWrap = document.createElement('div');
|
|
searchWrap.style.display = 'flex';
|
|
searchWrap.style.justifyContent = 'flex-end';
|
|
searchWrap.style.margin = '8px 0';
|
|
const search = document.createElement('input');
|
|
search.id = 'search';
|
|
search.placeholder = 'Filter conflicts by title, status, candidate, citekey...';
|
|
search.style.width = '320px';
|
|
search.style.maxWidth = '50%';
|
|
search.addEventListener('input', () => this.refreshRows(true));
|
|
searchWrap.appendChild(search);
|
|
conflictsTab.appendChild(searchWrap);
|
|
const table = document.createElement('table');
|
|
const thead = document.createElement('thead');
|
|
thead.innerHTML = '<tr><th>Source</th><th>Status</th><th>Count</th><th>Kindle Title</th><th>Candidates / Detail</th><th>Action</th></tr>';
|
|
table.appendChild(thead);
|
|
const tbody = document.createElement('tbody');
|
|
tbody.id = 'rows';
|
|
table.appendChild(tbody);
|
|
conflictsTab.appendChild(table);
|
|
const cPagination = document.createElement('div');
|
|
cPagination.id = 'conflicts-pagination';
|
|
cPagination.className = 'pagination';
|
|
conflictsTab.appendChild(cPagination);
|
|
root.appendChild(conflictsTab);
|
|
|
|
const mappingsTab = document.createElement('div');
|
|
mappingsTab.id = 'tab-mappings';
|
|
mappingsTab.className = 'tab';
|
|
const mH2 = document.createElement('h2');
|
|
mH2.textContent = 'Established Mappings';
|
|
mappingsTab.appendChild(mH2);
|
|
const mDesc = document.createElement('div');
|
|
mDesc.className = 'muted';
|
|
mDesc.textContent = 'Overrides you have approved (mapped or ignored). Delete any entry to send it back to Conflicts. After deleting, Re-import to restore it as a conflict.';
|
|
mappingsTab.appendChild(mDesc);
|
|
const mSearchWrap = document.createElement('div');
|
|
mSearchWrap.style.display = 'flex';
|
|
mSearchWrap.style.justifyContent = 'flex-end';
|
|
mSearchWrap.style.margin = '8px 0';
|
|
const mSearch = document.createElement('input');
|
|
mSearch.id = 'mappings-search';
|
|
mSearch.placeholder = 'Filter mappings by title, citekey...';
|
|
mSearch.style.width = '320px';
|
|
mSearch.style.maxWidth = '50%';
|
|
mSearch.addEventListener('input', () => this.refreshMappings(true));
|
|
mSearchWrap.appendChild(mSearch);
|
|
mappingsTab.appendChild(mSearchWrap);
|
|
const mCount = document.createElement('div');
|
|
mCount.id = 'mappings-count';
|
|
mCount.className = 'muted';
|
|
mCount.style.margin = '6px 0';
|
|
mappingsTab.appendChild(mCount);
|
|
const mTable = document.createElement('table');
|
|
const mThead = document.createElement('thead');
|
|
mThead.innerHTML = '<tr><th>Kindle Title</th><th>Resolution</th><th>Status</th><th>Count</th><th>Date</th><th>Action</th></tr>';
|
|
mTable.appendChild(mThead);
|
|
const mTbody = document.createElement('tbody');
|
|
mTbody.id = 'mappings-rows';
|
|
mTable.appendChild(mTbody);
|
|
mappingsTab.appendChild(mTable);
|
|
const mPagination = document.createElement('div');
|
|
mPagination.id = 'mappings-pagination';
|
|
mPagination.className = 'pagination';
|
|
mappingsTab.appendChild(mPagination);
|
|
root.appendChild(mappingsTab);
|
|
|
|
const settingsTab = document.createElement('div');
|
|
settingsTab.id = 'tab-settings';
|
|
settingsTab.className = 'tab';
|
|
const sH2 = document.createElement('h2');
|
|
sH2.textContent = 'Settings';
|
|
settingsTab.appendChild(sH2);
|
|
const sForm = document.createElement('div');
|
|
const makeSettingField = (label, id, value) => {
|
|
const l = document.createElement('label');
|
|
l.textContent = label;
|
|
sForm.appendChild(l);
|
|
const inp = document.createElement('input');
|
|
inp.id = id;
|
|
inp.value = value || '';
|
|
sForm.appendChild(inp);
|
|
};
|
|
makeSettingField('Project directory', 'setting-projectDir', this.settings.projectDir);
|
|
makeSettingField('Python executable', 'setting-pythonPath', this.settings.pythonPath);
|
|
makeSettingField('Zotero DB', 'setting-zoteroDbPath', this.settings.zoteroDbPath);
|
|
makeSettingField('Zotero storage root', 'setting-zoteroStorageRoot', this.settings.zoteroStorageRoot);
|
|
const shareRow = document.createElement('div');
|
|
shareRow.style.display = 'flex';
|
|
shareRow.style.alignItems = 'center';
|
|
shareRow.style.gap = '8px';
|
|
shareRow.style.marginTop = '12px';
|
|
const shareCheck = document.createElement('input');
|
|
shareCheck.type = 'checkbox';
|
|
shareCheck.id = 'setting-shareAnonymized';
|
|
try { shareCheck.checked = Services.prefs.getBoolPref("extensions.kindleZoteroImporter.shareAnonymized"); } catch(e) { shareCheck.checked = false; }
|
|
shareRow.appendChild(shareCheck);
|
|
const shareLabel = document.createElement('label');
|
|
shareLabel.htmlFor = 'setting-shareAnonymized';
|
|
shareLabel.textContent = 'Share annotation data to help future development (opt in: pseudonymous ID, publication metadata, raw highlight text and comments, hashes, colour, and dates)';
|
|
shareLabel.style.margin = '0';
|
|
shareLabel.style.fontSize = '12px';
|
|
shareRow.appendChild(shareLabel);
|
|
sForm.appendChild(shareRow);
|
|
|
|
// Highlight colours — editable bracket → hex map (British spelling)
|
|
const colourSection = document.createElement('div');
|
|
colourSection.style.marginTop = '18px';
|
|
colourSection.style.padding = '12px';
|
|
colourSection.style.border = '1px solid var(--line)';
|
|
colourSection.style.borderRadius = 'var(--radius)';
|
|
colourSection.style.background = 'var(--panel-soft)';
|
|
const cH3 = document.createElement('div');
|
|
cH3.textContent = 'Highlight colours';
|
|
cH3.style.fontWeight = '600';
|
|
cH3.style.marginBottom = '4px';
|
|
colourSection.appendChild(cH3);
|
|
const colDesc = document.createElement('div');
|
|
colDesc.className = 'muted';
|
|
colDesc.style.marginBottom = '8px';
|
|
colDesc.textContent = 'Use [code] at the start of a highlight to set its colour. All codes are single letters (y, o, r, e, g, b, p, m) — e.g. [o] orange, [r] red, [e] grey. Full names ([orange], [red], [grey]) also work and the bracket is stripped. Example: [o] This will be orange → orange highlight.';
|
|
colourSection.appendChild(colDesc);
|
|
const colourTable = document.createElement('table');
|
|
colourTable.style.marginBottom = '8px';
|
|
const cThead = document.createElement('thead');
|
|
cThead.innerHTML = '<tr><th>Bracket code</th><th>Hex colour</th><th>Preview</th></tr>';
|
|
colourTable.appendChild(cThead);
|
|
const cTbody = document.createElement('tbody');
|
|
cTbody.id = 'colour-map-rows';
|
|
colourTable.appendChild(cTbody);
|
|
colourSection.appendChild(colourTable);
|
|
const colourDefs = [
|
|
{ name: 'yellow', codes: 'y, yellow', hex: '#ffd400' },
|
|
{ name: 'orange', codes: 'o, orange', hex: '#ff8c00' },
|
|
{ name: 'red', codes: 'r, red', hex: '#ff6666' },
|
|
{ name: 'grey', codes: 'e, grey, gray', hex: '#8a8a8a' },
|
|
{ name: 'green', codes: 'g, green', hex: '#5fb236' },
|
|
{ name: 'blue', codes: 'b, blue, bl', hex: '#2ea8e5' },
|
|
{ name: 'purple', codes: 'p, purple', hex: '#a28ae5' },
|
|
{ name: 'magenta', codes: 'm, magenta, pink', hex: '#e56eee' },
|
|
];
|
|
const colourDefaults = {};
|
|
for (const d of colourDefs) for (const c of d.codes.split(',').map(s=>s.trim().toLowerCase()).filter(Boolean)) colourDefaults[c] = d.hex;
|
|
const currentMap = this.settings.colourMap || this.settings.colorMap || colourDefaults;
|
|
// group currentMap by hex for display (one bar per colour)
|
|
const byHex = {};
|
|
for (const [k,v] of Object.entries(currentMap)) {
|
|
const hv = v.toLowerCase();
|
|
if (!byHex[hv]) byHex[hv] = [];
|
|
byHex[hv].push(k);
|
|
}
|
|
// ensure all default hexes have an entry
|
|
for (const d of colourDefs) if (!byHex[d.hex.toLowerCase()]) byHex[d.hex.toLowerCase()] = d.codes.split(',').map(s=>s.trim().toLowerCase());
|
|
this.plugin.loadColourMap().then(m => {
|
|
if (m && JSON.stringify(m) !== JSON.stringify(currentMap)) {
|
|
this.settings.colourMap = m;
|
|
}
|
|
}).catch(()=>{});
|
|
for (const def of colourDefs) {
|
|
const hx = def.hex.toLowerCase();
|
|
const codes = (byHex[hx] || def.codes.split(',').map(s=>s.trim().toLowerCase())).join(', ');
|
|
const tr = document.createElement('tr');
|
|
const tdCode = document.createElement('td');
|
|
const inpCode = document.createElement('input');
|
|
inpCode.value = codes;
|
|
inpCode.placeholder = 'e.g. b, blue, bl';
|
|
inpCode.style.fontFamily = 'JetBrains Mono, monospace';
|
|
inpCode.style.fontSize = '12px';
|
|
inpCode.dataset.colourCodes = hx;
|
|
inpCode.className = 'colour-key-input';
|
|
inpCode.title = 'Comma-separated codes for this colour — e.g. b, blue, bl';
|
|
tdCode.appendChild(inpCode);
|
|
tr.appendChild(tdCode);
|
|
const tdHex = document.createElement('td');
|
|
const inpHex = document.createElement('input');
|
|
inpHex.type = 'color';
|
|
inpHex.value = hx;
|
|
// try to use currentMap's hex if user changed it
|
|
const actualHex = (byHex[hx] ? hx : def.hex);
|
|
// if user changed hex for this colour, use that
|
|
let displayHex = def.hex;
|
|
// find if any of the codes in this row has a different hex in currentMap (custom)
|
|
// For now just use def.hex, but if currentMap has different, it will be in byHex key
|
|
// So displayHex is hx
|
|
displayHex = hx;
|
|
inpHex.value = displayHex;
|
|
inpHex.style.height = '28px';
|
|
inpHex.style.padding = '2px';
|
|
inpHex.dataset.colourHex = hx;
|
|
inpHex.className = 'colour-hex-input';
|
|
const txtHex = document.createElement('input');
|
|
txtHex.value = displayHex;
|
|
txtHex.style.fontFamily = 'JetBrains Mono, monospace';
|
|
txtHex.style.fontSize = '11px';
|
|
txtHex.style.marginLeft = '6px';
|
|
txtHex.style.width = '80px';
|
|
txtHex.dataset.colourHexTxt = hx;
|
|
inpHex.addEventListener('input', () => { txtHex.value = inpHex.value; });
|
|
txtHex.addEventListener('input', () => { if (/^#[0-9a-fA-F]{6}$/.test(txtHex.value)) inpHex.value = txtHex.value; });
|
|
tdHex.appendChild(inpHex);
|
|
tdHex.appendChild(txtHex);
|
|
tr.appendChild(tdHex);
|
|
const tdPrev = document.createElement('td');
|
|
const sw = document.createElement('span');
|
|
sw.style.display = 'inline-block';
|
|
sw.style.width = '20px';
|
|
sw.style.height = '12px';
|
|
sw.style.borderRadius = '2px';
|
|
sw.style.border = '1px solid var(--line)';
|
|
sw.style.background = displayHex;
|
|
inpHex.addEventListener('input', () => sw.style.background = inpHex.value);
|
|
txtHex.addEventListener('input', () => { if (/^#[0-9a-fA-F]{6}$/.test(txtHex.value)) sw.style.background = txtHex.value; });
|
|
tdPrev.appendChild(sw);
|
|
tr.appendChild(tdPrev);
|
|
cTbody.appendChild(tr);
|
|
}
|
|
// also add any custom hexes not in defaults (user added new colour)
|
|
for (const [hx, codes] of Object.entries(byHex)) {
|
|
if (colourDefs.some(d => d.hex.toLowerCase() === hx)) continue;
|
|
const tr = document.createElement('tr');
|
|
const tdCode = document.createElement('td');
|
|
const inpCode = document.createElement('input');
|
|
inpCode.value = codes.join(', ');
|
|
inpCode.className = 'colour-key-input';
|
|
inpCode.dataset.colourCodes = hx;
|
|
inpCode.style.fontFamily = 'JetBrains Mono, monospace';
|
|
tdCode.appendChild(inpCode);
|
|
tr.appendChild(tdCode);
|
|
const tdHex = document.createElement('td');
|
|
const inpHex = document.createElement('input');
|
|
inpHex.type = 'color';
|
|
inpHex.value = hx;
|
|
inpHex.className = 'colour-hex-input';
|
|
inpHex.dataset.colourHex = hx;
|
|
tdHex.appendChild(inpHex);
|
|
const txtHex = document.createElement('input');
|
|
txtHex.value = hx;
|
|
tdHex.appendChild(txtHex);
|
|
tr.appendChild(tdHex);
|
|
const tdPrev = document.createElement('td');
|
|
const sw = document.createElement('span');
|
|
sw.style.background = hx;
|
|
tdPrev.appendChild(sw);
|
|
tr.appendChild(tdPrev);
|
|
cTbody.appendChild(tr);
|
|
}
|
|
// Add row button
|
|
const addRow = document.createElement('button');
|
|
addRow.textContent = '+ Add mapping';
|
|
addRow.style.marginTop = '6px';
|
|
addRow.style.padding = '4px 8px';
|
|
addRow.style.border = '1px solid var(--line)';
|
|
addRow.style.background = 'var(--panel)';
|
|
addRow.style.borderRadius = 'var(--radius)';
|
|
addRow.style.cursor = 'pointer';
|
|
addRow.style.fontSize = '11px';
|
|
addRow.addEventListener('click', () => {
|
|
const tr = document.createElement('tr');
|
|
const tdCode = document.createElement('td');
|
|
const inpCode = document.createElement('input');
|
|
inpCode.placeholder = 'e.g. teal';
|
|
inpCode.style.fontFamily = 'JetBrains Mono, monospace';
|
|
inpCode.className = 'colour-key-input';
|
|
tdCode.appendChild(inpCode);
|
|
tr.appendChild(tdCode);
|
|
const tdHex = document.createElement('td');
|
|
const inpHex = document.createElement('input');
|
|
inpHex.type = 'color';
|
|
inpHex.value = '#ffd400';
|
|
inpHex.className = 'colour-hex-input';
|
|
const txtHex = document.createElement('input');
|
|
txtHex.value = '#ffd400';
|
|
txtHex.style.fontFamily = 'JetBrains Mono, monospace';
|
|
txtHex.style.fontSize = '11px';
|
|
txtHex.style.marginLeft = '6px';
|
|
txtHex.style.width = '80px';
|
|
tdHex.appendChild(inpHex);
|
|
tdHex.appendChild(txtHex);
|
|
tr.appendChild(tdHex);
|
|
const tdPrev = document.createElement('td');
|
|
const sw = document.createElement('span');
|
|
sw.style.display = 'inline-block';
|
|
sw.style.width = '20px';
|
|
sw.style.height = '12px';
|
|
sw.style.border = '1px solid var(--line)';
|
|
sw.style.background = '#ffd400';
|
|
tdPrev.appendChild(sw);
|
|
tr.appendChild(tdPrev);
|
|
cTbody.appendChild(tr);
|
|
});
|
|
colourSection.appendChild(addRow);
|
|
const resetBtn = document.createElement('button');
|
|
resetBtn.textContent = 'Reset to defaults';
|
|
resetBtn.style.marginLeft = '6px';
|
|
resetBtn.style.padding = '4px 8px';
|
|
resetBtn.style.border = '1px solid var(--line)';
|
|
resetBtn.style.background = 'var(--panel)';
|
|
resetBtn.style.borderRadius = 'var(--radius)';
|
|
resetBtn.style.cursor = 'pointer';
|
|
resetBtn.style.fontSize = '11px';
|
|
resetBtn.addEventListener('click', async () => {
|
|
if (!confirm('Reset colours to defaults (grey = [e], red = [r])?')) return;
|
|
cTbody.textContent = '';
|
|
for (const k of Object.keys(colourDefaults).sort()) {
|
|
const tr = document.createElement('tr');
|
|
const tdCode = document.createElement('td');
|
|
const inpCode = document.createElement('input');
|
|
inpCode.value = k;
|
|
inpCode.className = 'colour-key-input';
|
|
tdCode.appendChild(inpCode);
|
|
tr.appendChild(tdCode);
|
|
const tdHex = document.createElement('td');
|
|
const inpHex = document.createElement('input');
|
|
inpHex.type = 'color';
|
|
inpHex.value = colourDefaults[k];
|
|
inpHex.className = 'colour-hex-input';
|
|
const txtHex = document.createElement('input');
|
|
txtHex.value = colourDefaults[k];
|
|
tdHex.appendChild(inpHex);
|
|
tdHex.appendChild(txtHex);
|
|
tr.appendChild(tdHex);
|
|
const tdPrev = document.createElement('td');
|
|
const sw = document.createElement('span');
|
|
sw.style.display = 'inline-block';
|
|
sw.style.width = '20px';
|
|
sw.style.height = '12px';
|
|
sw.style.background = colourDefaults[k];
|
|
tdPrev.appendChild(sw);
|
|
tr.appendChild(tdPrev);
|
|
cTbody.appendChild(tr);
|
|
}
|
|
});
|
|
colourSection.appendChild(resetBtn);
|
|
sForm.appendChild(colourSection);
|
|
|
|
const sSaveBtn = document.createElement('button');
|
|
sSaveBtn.textContent = 'Save Settings';
|
|
sSaveBtn.style.marginTop = '12px';
|
|
sSaveBtn.style.padding = '8px 14px';
|
|
sSaveBtn.style.border = '1px solid var(--accent)';
|
|
sSaveBtn.style.background = 'var(--accent)';
|
|
sSaveBtn.style.color = 'white';
|
|
sSaveBtn.style.cursor = 'pointer';
|
|
sSaveBtn.style.fontFamily = 'inherit';
|
|
sSaveBtn.style.borderRadius = 'var(--radius)';
|
|
sSaveBtn.style.fontWeight = '600';
|
|
sSaveBtn.addEventListener('click', () => this.saveSettings());
|
|
sForm.appendChild(sSaveBtn);
|
|
const sNotice = document.createElement('div');
|
|
sNotice.className = 'notice';
|
|
sNotice.style.marginTop = '12px';
|
|
sNotice.textContent = 'Saves to prefs and plugin-config.json in the project directory. No restart required.';
|
|
sForm.appendChild(sNotice);
|
|
settingsTab.appendChild(sForm);
|
|
root.appendChild(settingsTab);
|
|
|
|
const artifactsTab = document.createElement('div');
|
|
artifactsTab.id = 'tab-artifacts';
|
|
artifactsTab.className = 'tab';
|
|
const aH2 = document.createElement('h2');
|
|
aH2.textContent = 'Artifacts';
|
|
artifactsTab.appendChild(aH2);
|
|
const aDesc = document.createElement('div');
|
|
aDesc.className = 'muted';
|
|
aDesc.textContent = 'Generated files from the last pipeline run. Open to view, Reveal to show in Finder.';
|
|
artifactsTab.appendChild(aDesc);
|
|
const artifacts = [
|
|
['Mismatch review', 'docs/mismatch-review.md'],
|
|
['Persistent overrides', 'match-overrides.json'],
|
|
['Generated suggestions', 'match-overrides.generated.json'],
|
|
['Positioned plan', 'import-plan.positioned.json'],
|
|
['Final writer plan', 'import-plan.final.json'],
|
|
['Plugin summary', 'plugin-summary.json'],
|
|
];
|
|
for (const [label, rel] of artifacts) {
|
|
const row = document.createElement('div');
|
|
row.style.display = 'flex';
|
|
row.style.justifyContent = 'space-between';
|
|
row.style.alignItems = 'center';
|
|
row.style.border = '1px solid var(--line)';
|
|
row.style.padding = '8px 12px';
|
|
row.style.margin = '6px 0';
|
|
row.style.background = 'var(--panel)';
|
|
row.style.borderRadius = 'var(--radius)';
|
|
row.style.boxShadow = 'var(--shadow)';
|
|
const left = document.createElement('div');
|
|
left.style.fontFamily = "'iA Writer Duo', ui-monospace, monospace";
|
|
left.style.fontSize = '12px';
|
|
left.textContent = `${label}: ${this.plugin.artifactPath(rel)}`;
|
|
row.appendChild(left);
|
|
const right = document.createElement('div');
|
|
right.style.display = 'flex';
|
|
right.style.gap = '4px';
|
|
const openBtn = document.createElement('button');
|
|
openBtn.textContent = 'Open';
|
|
openBtn.style.padding = '4px 10px';
|
|
openBtn.style.border = '1px solid var(--line)';
|
|
openBtn.style.background = 'var(--panel)';
|
|
openBtn.style.cursor = 'pointer';
|
|
openBtn.style.fontFamily = 'inherit';
|
|
openBtn.style.borderRadius = 'var(--radius)';
|
|
openBtn.style.fontSize = '12px';
|
|
openBtn.addEventListener('click', () => this.plugin.openArtifact(rel));
|
|
right.appendChild(openBtn);
|
|
const revealBtn = document.createElement('button');
|
|
revealBtn.textContent = 'Reveal';
|
|
revealBtn.style.padding = '4px 10px';
|
|
revealBtn.style.border = '1px solid var(--accent)';
|
|
revealBtn.style.background = 'var(--accent)';
|
|
revealBtn.style.color = 'white';
|
|
revealBtn.style.cursor = 'pointer';
|
|
revealBtn.style.fontFamily = 'inherit';
|
|
revealBtn.style.borderRadius = 'var(--radius)';
|
|
revealBtn.style.fontSize = '12px';
|
|
revealBtn.style.fontWeight = '600';
|
|
revealBtn.addEventListener('click', () => this.plugin.revealFile(this.plugin.artifactPath(rel)));
|
|
right.appendChild(revealBtn);
|
|
row.appendChild(right);
|
|
artifactsTab.appendChild(row);
|
|
}
|
|
root.appendChild(artifactsTab);
|
|
|
|
const statusDiv = document.createElement('div');
|
|
statusDiv.id = 'status';
|
|
statusDiv.className = 'notice';
|
|
statusDiv.style.display = 'none';
|
|
statusDiv.style.marginTop = '16px';
|
|
statusDiv.style.borderLeft = '4px solid var(--accent)';
|
|
statusDiv.style.background = 'var(--panel-soft)';
|
|
root.appendChild(statusDiv);
|
|
|
|
this.refreshRows();
|
|
this.refreshIntegrated();
|
|
this.refreshMappings();
|
|
this.updateInfobox();
|
|
this.makeTableResizable(document.querySelector('#tab-conflicts table'));
|
|
this.makeTableResizable(document.querySelector('#tab-integrated table'));
|
|
this.makeTableResizable(document.querySelector('#tab-mappings table'));
|
|
},
|
|
|
|
refreshRows(resetPage = false) {
|
|
const tbody = document.getElementById('rows');
|
|
if (!tbody) return;
|
|
tbody.textContent = '';
|
|
const needle = (document.getElementById('search')?.value || '').toLowerCase();
|
|
const filtered = this.rows.filter(row => `${row.source} ${row.status} ${row.title} ${row.detail || ''} ${(row.candidates || []).map(c => `${c.citation_key} ${c.title}`).join(' ')}`.toLowerCase().includes(needle));
|
|
if (resetPage) this.conflictsPage = 0;
|
|
const page = this.paginate(filtered, 'conflictsPage', 'conflictsPageSize');
|
|
this.refreshPagination('conflicts-pagination', 'conflictsPage', 'conflictsPageSize', page.totalPages, () => this.refreshRows());
|
|
if (!filtered.length) {
|
|
const tr = document.createElement('tr');
|
|
const td = document.createElement('td');
|
|
td.colSpan = 6;
|
|
td.textContent = 'No conflicts match the filter.';
|
|
tr.appendChild(td);
|
|
tbody.appendChild(tr);
|
|
return;
|
|
}
|
|
for (let idx = 0; idx < page.rows.length; idx++) {
|
|
const row = page.rows[idx];
|
|
const globalIndex = this.rows.indexOf(row);
|
|
const tr = document.createElement('tr');
|
|
const tdSource = document.createElement('td');
|
|
tdSource.textContent = row.source;
|
|
tr.appendChild(tdSource);
|
|
const tdStatus = document.createElement('td');
|
|
const pill = document.createElement('span');
|
|
pill.className = 'pill';
|
|
pill.textContent = row.status;
|
|
tdStatus.appendChild(pill);
|
|
tr.appendChild(tdStatus);
|
|
const tdCount = document.createElement('td');
|
|
tdCount.textContent = String(row.count);
|
|
tr.appendChild(tdCount);
|
|
const tdTitle = document.createElement('td');
|
|
tdTitle.textContent = row.title;
|
|
tdTitle.title = row.title;
|
|
tr.appendChild(tdTitle);
|
|
const tdDetail = document.createElement('td');
|
|
if (row.detail) {
|
|
tdDetail.textContent = row.detail;
|
|
} else if (row.candidates && row.candidates.length) {
|
|
const top = row.candidates[0];
|
|
const cite = top.citation_key || top.key || top.item_id || '';
|
|
tdDetail.textContent = `${row.candidates.length} suggestion(s) — top: ${cite} (${top.score ? Math.round(top.score*100)+'%' : '—'})`;
|
|
tdDetail.title = row.candidates.slice(0,4).map(c=> `${c.citation_key||c.key}: ${c.title}`).join('\n');
|
|
} else {
|
|
tdDetail.textContent = 'No candidates';
|
|
}
|
|
tdDetail.style.fontSize='11px';
|
|
tdDetail.style.color='#444';
|
|
tr.appendChild(tdDetail);
|
|
const tdActions = document.createElement('td');
|
|
tdActions.className = 'row-actions';
|
|
tdActions.style.minWidth='260px';
|
|
if (row.candidates && row.candidates.length) {
|
|
const list = document.createElement('div');
|
|
list.className = 'candidate-list';
|
|
for (let i=0;i<row.candidates.length;i++) {
|
|
const c = row.candidates[i];
|
|
const opt = document.createElement('div');
|
|
opt.className = 'candidate-option';
|
|
const span = document.createElement('span');
|
|
span.textContent = `${c.citation_key || c.key || c.item_id} · ${c.title || ''} ${c.score ? `(${Math.round(c.score*100)}%)` : ''}`;
|
|
span.title = `${c.citation_key || c.key || c.item_id}: ${c.title || ''} — ${c.reason || ''}`;
|
|
const btn = document.createElement('button');
|
|
btn.textContent = 'Use';
|
|
btn.title = `Use ${c.citation_key || c.key}`;
|
|
btn.addEventListener('click', () => this.saveCandidateAt(globalIndex, i));
|
|
opt.appendChild(span);
|
|
opt.appendChild(btn);
|
|
list.appendChild(opt);
|
|
}
|
|
tdActions.appendChild(list);
|
|
} else {
|
|
const noCand = document.createElement('div');
|
|
noCand.className='muted';
|
|
noCand.style.fontSize='11px';
|
|
noCand.textContent='No suggestions — enter custom key below.';
|
|
tdActions.appendChild(noCand);
|
|
}
|
|
const manualRow = document.createElement('div');
|
|
manualRow.className='manual-row';
|
|
const manualInput = document.createElement('input');
|
|
manualInput.id=`manual-${globalIndex}`;
|
|
manualInput.placeholder='or enter any citekey / Zotero key / ID';
|
|
manualInput.title='Examples: deleuze1987 | JTDWDKRH | 51395';
|
|
manualRow.appendChild(manualInput);
|
|
const btnManual = document.createElement('button');
|
|
btnManual.textContent='Use Custom';
|
|
btnManual.className='row-btn';
|
|
btnManual.addEventListener('click', () => this.saveManualCandidate(globalIndex));
|
|
manualRow.appendChild(btnManual);
|
|
tdActions.appendChild(manualRow);
|
|
const btnIgnore = document.createElement('button');
|
|
btnIgnore.textContent = 'Ignore Title';
|
|
btnIgnore.className = 'row-btn';
|
|
btnIgnore.style.marginTop='6px';
|
|
btnIgnore.addEventListener('click', () => this.ignore(globalIndex));
|
|
tdActions.appendChild(btnIgnore);
|
|
tr.appendChild(tdActions);
|
|
tbody.appendChild(tr);
|
|
}
|
|
},
|
|
};
|
|
</script>
|
|
</head>
|
|
<body onload="KindleManager.initSafe()">
|
|
<div id="root">Loading Kanzi...</div>
|
|
</body>
|
|
</html>
|