2527 lines
131 KiB
HTML
2527 lines
131 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.sortable { cursor: pointer; user-select: none; }
|
|
th.sortable:hover { color: var(--text); background: #e9e9e9; }
|
|
th .sort-label { pointer-events: none; }
|
|
th .sort-arrow { pointer-events: none; color: var(--text); }
|
|
th .resizer { position: absolute; top: 0; right: -3px; width: 8px; height: 100%; cursor: col-resize; user-select: none; border-right: 2px solid transparent; }
|
|
th:hover .resizer { border-right-color: var(--line-strong); }
|
|
th .resizer:hover, th .resizer.dragging { border-right-color: var(--accent); background: rgba(17,17,17,.06); }
|
|
.expander { cursor: pointer; border: 1px solid var(--line); background: var(--panel); border-radius: 6px; width: 24px; height: 24px; line-height: 1; font-size: 13px; color: var(--text); padding: 0; }
|
|
.expander:hover { background: var(--panel-soft); border-color: var(--line-strong); }
|
|
tr.detail-row td { background: var(--panel-soft); border-bottom: 1px solid var(--line-strong); padding: 0; }
|
|
.clip-list { display: flex; flex-direction: column; gap: 8px; padding: 10px 12px 12px 38px; }
|
|
.clip-item { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 8px 10px; font-size: 12px; box-shadow: var(--shadow); }
|
|
.clip-item .clip-head { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; color: var(--muted); font-size: 10.5px; font-family: 'JetBrains Mono', monospace; text-transform: uppercase; letter-spacing: .05em; margin-bottom: 4px; }
|
|
.clip-item .clip-text { white-space: pre-wrap; word-break: break-word; line-height: 1.45; }
|
|
.clip-item .clip-problem { margin-top: 4px; color: var(--danger); font-size: 11px; }
|
|
.status-stack { display: flex; gap: 4px; flex-wrap: wrap; }
|
|
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-conflicts th:nth-child(1), #tab-conflicts td:nth-child(1) { width: 36px; }
|
|
#tab-conflicts th:nth-child(2), #tab-conflicts td:nth-child(2) { width: 13%; }
|
|
#tab-conflicts th:nth-child(3), #tab-conflicts td:nth-child(3) { width: 6%; }
|
|
#tab-conflicts th:nth-child(4), #tab-conflicts td:nth-child(4) { width: 24%; }
|
|
#tab-conflicts th:nth-child(5), #tab-conflicts td:nth-child(5) { width: 22%; }
|
|
#tab-conflicts th:nth-child(6), #tab-conflicts 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%; }
|
|
.title-status-wrap { max-height: 520px; overflow: auto; border: 1px solid var(--line); border-radius: var(--radius); }
|
|
#title-status-table { border: 0; box-shadow: none; }
|
|
#title-status-table th:nth-child(1), #title-status-table td:nth-child(1) { width: 13%; }
|
|
#title-status-table th:nth-child(2), #title-status-table td:nth-child(2) { width: 12%; }
|
|
#title-status-table th:nth-child(3), #title-status-table td:nth-child(3),
|
|
#title-status-table th:nth-child(4), #title-status-table td:nth-child(4),
|
|
#title-status-table th:nth-child(5), #title-status-table td:nth-child(5) { width: 8%; }
|
|
#title-status-table th:nth-child(6), #title-status-table td:nth-child(6) { width: 34%; }
|
|
#title-status-table th:nth-child(7), #title-status-table td:nth-child(7) { width: 17%; }
|
|
.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; }
|
|
#pending-review { display: none; background: var(--panel); border: 2px solid var(--accent); border-radius: 14px; padding: 16px 18px; margin: 16px 0; box-shadow: var(--shadow-strong); }
|
|
#pending-review h2 { margin-top: 0; }
|
|
.pending-toolbar { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin: 10px 0; }
|
|
.pending-toolbar button { width: auto; padding: 6px 12px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel); color: var(--text); cursor: pointer; font: inherit; font-size: 12px; }
|
|
.pending-toolbar button:hover { background: var(--panel-soft); border-color: var(--line-strong); }
|
|
.pending-group { border: 1px solid var(--line); border-radius: var(--radius); margin: 8px 0; overflow: hidden; }
|
|
.pending-group-head { display: flex; gap: 8px; align-items: center; padding: 8px 10px; background: var(--panel-soft); font-size: 12.5px; font-weight: 600; }
|
|
.pending-group-head input { width: auto; }
|
|
.pending-group-head .cite { font-family: 'JetBrains Mono', monospace; font-size: 11px; color: var(--muted); font-weight: 400; }
|
|
.pending-items { display: flex; flex-direction: column; }
|
|
.pending-item { display: flex; gap: 8px; align-items: flex-start; padding: 7px 10px 7px 34px; border-top: 1px solid var(--line); font-size: 12px; line-height: 1.45; }
|
|
.pending-item input { width: auto; margin-top: 3px; flex-shrink: 0; }
|
|
.pending-item .swatch { display: inline-block; width: 10px; height: 10px; border-radius: 2px; border: 1px solid #999; flex-shrink: 0; margin-top: 3px; }
|
|
.pending-item .pg { color: var(--muted); font-family: 'JetBrains Mono', monospace; font-size: 10.5px; flex-shrink: 0; }
|
|
.pending-item .txt { white-space: pre-wrap; word-break: break-word; }
|
|
.pending-footer { display: flex; gap: 8px; align-items: center; margin-top: 12px; flex-wrap: wrap; }
|
|
#pending-integrate { width: auto; padding: 10px 18px; border: 1px solid var(--accent); background: var(--accent); color: white; cursor: pointer; font: inherit; font-weight: 700; border-radius: var(--radius); }
|
|
#pending-integrate:disabled { opacity: 0.4; cursor: not-allowed; }
|
|
#pending-integrate:not(:disabled):hover { background: #1a1a1a; }
|
|
#pending-cancel { width: auto; padding: 10px 14px; border: 1px solid var(--line); background: var(--panel); color: var(--text); cursor: pointer; font: inherit; border-radius: var(--radius); }
|
|
#pending-cancel:hover { background: var(--panel-soft); }
|
|
::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,
|
|
expandedTitles: {},
|
|
pendingPlan: null,
|
|
sortState: {
|
|
titles: { column: 'status', direction: 'asc' },
|
|
conflicts: { column: 'count', direction: 'desc' },
|
|
integrated: { column: 'title', direction: 'asc' },
|
|
mappings: { column: 'updated', direction: 'desc' },
|
|
},
|
|
|
|
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();
|
|
this.hidePendingReview();
|
|
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.hidePendingReview();
|
|
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.relationsAdded || 0, 'relations added'));
|
|
grid.appendChild(makeCard(results.commentLinksAdded || 0, 'comment links added'));
|
|
grid.appendChild(makeCard(results.failed.length, 'failed'));
|
|
if ((results.relationFailures || []).length) {
|
|
grid.appendChild(makeCard(results.relationFailures.length, 'relation failures'));
|
|
}
|
|
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.refreshTitleOverview();
|
|
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 || (results.relationFailures || []).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.hidePendingReview();
|
|
this.updateProgress(0, 'Import failed', message);
|
|
this.status(message, true);
|
|
},
|
|
|
|
cancelRun(message) {
|
|
this.running = false;
|
|
clearInterval(this.timer);
|
|
const btn = document.getElementById('run-button');
|
|
if (btn) btn.classList.remove('disabled');
|
|
this.updateProgress(0, 'Ready', message || 'Cancelled.');
|
|
this.status(message || 'Cancelled.', false);
|
|
},
|
|
|
|
// Pure helper (tested): group pending delta annotations by title.
|
|
groupPendingAnnotations(annotations) {
|
|
const byKey = new Map();
|
|
for (const a of annotations || []) {
|
|
const key = a.citation_key || a.clipping_title || '(missing title)';
|
|
if (!byKey.has(key)) {
|
|
byKey.set(key, {
|
|
key, title: a.clipping_title || key,
|
|
citationKey: a.citation_key || '',
|
|
items: [],
|
|
});
|
|
}
|
|
byKey.get(key).items.push({
|
|
id: a.clipping_id,
|
|
text: a.annotation?.text || '',
|
|
page: a.annotation?.pageLabel || '',
|
|
color: a.annotation?.color || '#ffd400',
|
|
});
|
|
}
|
|
const groups = [...byKey.values()];
|
|
groups.sort((x, y) => y.items.length - x.items.length || x.title.localeCompare(y.title));
|
|
return groups;
|
|
},
|
|
|
|
showPendingReview(summary, finalPlan) {
|
|
this.pendingPlan = finalPlan;
|
|
const panel = document.getElementById('pending-review');
|
|
if (!panel) return;
|
|
panel.textContent = '';
|
|
panel.style.display = 'block';
|
|
const delta = finalPlan.annotations || [];
|
|
const deletions = finalPlan.deletions || [];
|
|
const groups = this.groupPendingAnnotations(delta);
|
|
const h2 = document.createElement('h2');
|
|
h2.textContent = `Review & integrate — ${delta.length} new highlight(s) across ${groups.length} title(s)`;
|
|
panel.appendChild(h2);
|
|
const desc = document.createElement('div');
|
|
desc.className = 'muted';
|
|
desc.textContent = 'Untick anything you do not want yet. Skipped highlights are offered again on the next run; nothing is recorded as done until you press Integrate.' + (deletions.length ? ` ${deletions.length} withdrawn highlight(s) will also be removed from Zotero.` : '');
|
|
panel.appendChild(desc);
|
|
const toolbar = document.createElement('div');
|
|
toolbar.className = 'pending-toolbar';
|
|
const mkBtn = (label, fn) => {
|
|
const b = document.createElement('button');
|
|
b.type = 'button';
|
|
b.textContent = label;
|
|
b.addEventListener('click', fn);
|
|
return b;
|
|
};
|
|
toolbar.appendChild(mkBtn('Select all', () => {
|
|
panel.querySelectorAll('input[data-clip-id], input[data-group-key]').forEach(cb => { cb.checked = true; cb.indeterminate = false; });
|
|
this.updatePendingCount();
|
|
}));
|
|
toolbar.appendChild(mkBtn('Select none', () => {
|
|
panel.querySelectorAll('input[data-clip-id], input[data-group-key]').forEach(cb => { cb.checked = false; cb.indeterminate = false; });
|
|
this.updatePendingCount();
|
|
}));
|
|
const count = document.createElement('span');
|
|
count.id = 'pending-count';
|
|
count.className = 'muted';
|
|
toolbar.appendChild(count);
|
|
panel.appendChild(toolbar);
|
|
const list = document.createElement('div');
|
|
list.id = 'pending-groups';
|
|
for (const g of groups) {
|
|
const box = document.createElement('div');
|
|
box.className = 'pending-group';
|
|
const head = document.createElement('label');
|
|
head.className = 'pending-group-head';
|
|
const gcb = document.createElement('input');
|
|
gcb.type = 'checkbox';
|
|
gcb.checked = true;
|
|
gcb.dataset.groupKey = g.key;
|
|
gcb.addEventListener('change', () => {
|
|
box.querySelectorAll('input[data-clip-id]').forEach(cb => { cb.checked = gcb.checked; });
|
|
gcb.indeterminate = false;
|
|
this.updatePendingCount();
|
|
});
|
|
head.appendChild(gcb);
|
|
const t = document.createElement('span');
|
|
t.textContent = `${g.title} (${g.items.length})`;
|
|
head.appendChild(t);
|
|
if (g.citationKey && g.citationKey !== g.title) {
|
|
const cite = document.createElement('span');
|
|
cite.className = 'cite';
|
|
cite.textContent = g.citationKey;
|
|
head.appendChild(cite);
|
|
}
|
|
box.appendChild(head);
|
|
const items = document.createElement('div');
|
|
items.className = 'pending-items';
|
|
for (const it of g.items) {
|
|
const row = document.createElement('label');
|
|
row.className = 'pending-item';
|
|
const cb = document.createElement('input');
|
|
cb.type = 'checkbox';
|
|
cb.checked = true;
|
|
cb.dataset.clipId = it.id;
|
|
cb.addEventListener('change', () => {
|
|
const boxes = [...box.querySelectorAll('input[data-clip-id]')];
|
|
const checked = boxes.filter(b => b.checked).length;
|
|
gcb.checked = checked === boxes.length;
|
|
gcb.indeterminate = checked > 0 && checked < boxes.length;
|
|
this.updatePendingCount();
|
|
});
|
|
row.appendChild(cb);
|
|
const sw = document.createElement('span');
|
|
sw.className = 'swatch';
|
|
sw.style.background = it.color;
|
|
row.appendChild(sw);
|
|
if (it.page) {
|
|
const pg = document.createElement('span');
|
|
pg.className = 'pg';
|
|
pg.textContent = it.page;
|
|
row.appendChild(pg);
|
|
}
|
|
const txt = document.createElement('span');
|
|
txt.className = 'txt';
|
|
let snippet = it.text || '(no text)';
|
|
if (snippet.length > 220) snippet = snippet.slice(0, 220) + '…';
|
|
txt.textContent = snippet;
|
|
txt.title = it.text || '';
|
|
row.appendChild(txt);
|
|
items.appendChild(row);
|
|
}
|
|
box.appendChild(items);
|
|
list.appendChild(box);
|
|
}
|
|
panel.appendChild(list);
|
|
const footer = document.createElement('div');
|
|
footer.className = 'pending-footer';
|
|
const go = document.createElement('button');
|
|
go.id = 'pending-integrate';
|
|
go.textContent = `Integrate selected`;
|
|
go.addEventListener('click', () => this.integrateSelected());
|
|
footer.appendChild(go);
|
|
const cancel = document.createElement('button');
|
|
cancel.id = 'pending-cancel';
|
|
cancel.textContent = 'Cancel (nothing is written)';
|
|
cancel.addEventListener('click', () => this.cancelPendingReview());
|
|
footer.appendChild(cancel);
|
|
panel.appendChild(footer);
|
|
this.updatePendingCount();
|
|
panel.scrollIntoView({ block: 'nearest' });
|
|
},
|
|
|
|
hidePendingReview() {
|
|
this.pendingPlan = null;
|
|
const panel = document.getElementById('pending-review');
|
|
if (panel) {
|
|
panel.style.display = 'none';
|
|
panel.textContent = '';
|
|
}
|
|
},
|
|
|
|
updatePendingCount() {
|
|
const panel = document.getElementById('pending-review');
|
|
if (!panel) return;
|
|
const n = panel.querySelectorAll('input[data-clip-id]:checked').length;
|
|
const total = panel.querySelectorAll('input[data-clip-id]').length;
|
|
const count = document.getElementById('pending-count');
|
|
if (count) count.textContent = `${n} of ${total} selected`;
|
|
const go = document.getElementById('pending-integrate');
|
|
if (go) {
|
|
const deletions = (this.pendingPlan?.deletions || []).length;
|
|
go.disabled = n === 0 && deletions === 0;
|
|
go.textContent = deletions
|
|
? `Integrate selected (${n}) + ${deletions} deletion(s)`
|
|
: `Integrate selected (${n})`;
|
|
}
|
|
},
|
|
|
|
getSelectedClippingIds() {
|
|
const panel = document.getElementById('pending-review');
|
|
if (!panel) return [];
|
|
return [...panel.querySelectorAll('input[data-clip-id]:checked')].map(cb => cb.dataset.clipId);
|
|
},
|
|
|
|
async integrateSelected() {
|
|
const ids = this.getSelectedClippingIds();
|
|
if (!ids.length && !(this.pendingPlan?.deletions || []).length) return;
|
|
const go = document.getElementById('pending-integrate');
|
|
const cancel = document.getElementById('pending-cancel');
|
|
if (go) go.disabled = true;
|
|
if (cancel) cancel.disabled = true;
|
|
try {
|
|
await this.plugin.integratePending(this, ids);
|
|
} catch (e) {
|
|
this.failRun(String(e && e.stack ? e.stack : e));
|
|
}
|
|
},
|
|
|
|
async cancelPendingReview() {
|
|
try {
|
|
await this.plugin.cancelPendingReview(this);
|
|
} catch (e) {
|
|
this.cancelRun(String(e && e.message ? e.message : e));
|
|
}
|
|
},
|
|
|
|
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} source clipping(s)). Click Re-import to process every annotation under this exact title.`;
|
|
}
|
|
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 and positioning. You will review the pending highlights and press Integrate before anything is written to Zotero.`)) 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>';
|
|
},
|
|
|
|
discardedIds() {
|
|
return new Set(this.data.finalPlan?.discarded_clipping_ids || []);
|
|
},
|
|
|
|
sourceTitleStats() {
|
|
const byTitle = new Map();
|
|
const discarded = this.discardedIds();
|
|
for (const clipping of this.data.clippings?.clippings || []) {
|
|
if (clipping.id && discarded.has(clipping.id)) continue;
|
|
const title = clipping.title || '(missing title)';
|
|
if (!byTitle.has(title)) {
|
|
byTitle.set(title, {
|
|
title, count: 0, highlights: 0, notes: 0, bookmarks: 0,
|
|
clippings: [],
|
|
});
|
|
}
|
|
const entry = byTitle.get(title);
|
|
entry.count += 1;
|
|
entry.clippings.push(clipping);
|
|
if (clipping.kind === 'highlight') entry.highlights += 1;
|
|
else if (clipping.kind === 'note') entry.notes += 1;
|
|
else if (clipping.kind === 'bookmark') entry.bookmarks += 1;
|
|
}
|
|
return byTitle;
|
|
},
|
|
|
|
conflictRows() {
|
|
// One row per unique Kindle title. Per-clipping attachment/position
|
|
// failures are grouped under their title and shown via chevron.
|
|
const sourceByTitle = this.sourceTitleStats();
|
|
const byTitle = new Map();
|
|
const ensure = (title) => {
|
|
const key = title || '(missing title)';
|
|
if (!byTitle.has(key)) {
|
|
const source = sourceByTitle.get(key);
|
|
byTitle.set(key, {
|
|
title: key, count: source?.count || 0, status: 'review',
|
|
highlights: source?.highlights || 0,
|
|
notes: source?.notes || 0,
|
|
bookmarks: source?.bookmarks || 0,
|
|
statuses: new Set(), sources: new Set(),
|
|
candidates: [],
|
|
clippings: (source?.clippings || []).map(clipping => ({
|
|
id: clipping.id,
|
|
text: clipping.text || '', kind: clipping.kind || '',
|
|
page: clipping.page || '', location: clipping.location || '',
|
|
added_on: clipping.added_on || clipping.added_on_iso || '',
|
|
status: '', problems: [],
|
|
})),
|
|
positionProblems: new Set(),
|
|
});
|
|
}
|
|
return byTitle.get(key);
|
|
};
|
|
const mergeCandidates = (entry, list) => {
|
|
const seen = new Set(entry.candidates.map(c => (c.citation_key || c.key || String(c.item_id))));
|
|
for (const c of list || []) {
|
|
const k = (c.citation_key || c.key || String(c.item_id));
|
|
if (!k || seen.has(k)) continue;
|
|
seen.add(k);
|
|
entry.candidates.push(c);
|
|
}
|
|
entry.candidates.sort((a, b) => (b.score || 0) - (a.score || 0));
|
|
};
|
|
for (const match of this.data.matches?.matches || []) {
|
|
if (['matched', 'ignored'].includes(match.status)) continue;
|
|
const e = ensure(match.clipping_title);
|
|
e.statuses.add(match.status);
|
|
e.sources.add('Title match');
|
|
if (!sourceByTitle.has(match.clipping_title)) e.count = Math.max(e.count, match.clipping_count || 0);
|
|
mergeCandidates(e, match.candidates);
|
|
if (!e.matchStatus) e.matchStatus = match.status;
|
|
}
|
|
for (const override of this.data.generatedOverrides?.overrides || []) {
|
|
const s = override.review?.status || 'review';
|
|
if (['matched', 'ignored'].includes(s)) continue;
|
|
const e = ensure(override.clipping_title);
|
|
e.statuses.add(s);
|
|
e.sources.add('Override suggestion');
|
|
if (!sourceByTitle.has(override.clipping_title)) e.count = Math.max(e.count, override.review?.clipping_count || e.count);
|
|
mergeCandidates(e, override.candidates);
|
|
if (!e.matchStatus) e.matchStatus = s;
|
|
}
|
|
const discarded = this.discardedIds();
|
|
for (const item of this.data.positionedPlan?.items || []) {
|
|
if (['positioned', 'ignored-title'].includes(item.status)) continue;
|
|
if (item.clipping?.id && discarded.has(item.clipping.id)) continue;
|
|
const title = item.clipping?.title || '(missing title)';
|
|
const e = ensure(title);
|
|
e.statuses.add(item.status);
|
|
e.sources.add('Attachment/position');
|
|
const c = item.clipping || {};
|
|
const clipping = e.clippings.find(entry => entry.id === c.id);
|
|
const details = {
|
|
id: c.id,
|
|
text: c.text || '', kind: c.kind || '',
|
|
page: c.page || '', location: c.location || '',
|
|
added_on: c.added_on || c.added_on_iso || '',
|
|
status: item.status || 'unknown', problems: item.problems || [],
|
|
pageHint: item.page_hint || null,
|
|
};
|
|
if (clipping) Object.assign(clipping, details);
|
|
else e.clippings.push(details);
|
|
for (const p of item.problems || []) e.positionProblems.add(p);
|
|
}
|
|
const rank = (s) => {
|
|
const order = { ambiguous: 0, unmatched: 1, 'unmatched-title': 1, 'matched-title-no-attachment': 2, 'matched-title-ambiguous-attachment': 2, review: 3 };
|
|
return order[s] ?? 4;
|
|
};
|
|
const rows = [];
|
|
const matchByTitle = new Map((this.data.matches?.matches || []).map(m => [m.clipping_title, m]));
|
|
const overrideByTitle = new Map((this.data.persistentOverrides?.overrides || []).map(o => [o.clipping_title, o]));
|
|
for (const e of byTitle.values()) {
|
|
// clippings.json is authoritative when available; older runtimes
|
|
// without it fall back to conflict/position row counts.
|
|
const source = sourceByTitle.get(e.title);
|
|
if (source) e.count = source.count;
|
|
else if (!e.count && e.clippings.length) e.count = e.clippings.length;
|
|
if (!e.count) e.count = e.clippings.length || 1;
|
|
const statuses = [...e.statuses];
|
|
statuses.sort((a, b) => rank(a) - rank(b));
|
|
e.status = statuses[0] || 'review';
|
|
e.statuses = statuses;
|
|
e.sources = [...e.sources];
|
|
e.detail = [...e.positionProblems].join('; ');
|
|
// Already-mapped target for position-failure rows (matched titles
|
|
// are skipped above, so candidates stay empty and look unmatched).
|
|
const match = matchByTitle.get(e.title);
|
|
const override = overrideByTitle.get(e.title);
|
|
const res = override?.resolution || {};
|
|
e.mappedTarget = res.ignore ? 'Ignored'
|
|
: res.citation_key || res.zotero_key || res.zotero_item_id
|
|
|| match?.candidates?.[0]?.citation_key || match?.candidates?.[0]?.key || '';
|
|
e.matchStatusFull = match?.status || '';
|
|
rows.push(e);
|
|
}
|
|
rows.sort((a, b) => (b.count - a.count) || a.title.localeCompare(b.title));
|
|
return rows;
|
|
},
|
|
|
|
conflictAffected(row) {
|
|
const total = row.count || (row.clippings || []).length || 0;
|
|
const positionFailed = (row.clippings || []).filter(c =>
|
|
(c.problems && c.problems.length) || (c.status && c.status !== '' && c.status !== 'positioned')
|
|
).length;
|
|
const hasTitleLevel = (row.statuses || [row.status]).some(s =>
|
|
['ambiguous', 'unmatched', 'unmatched-title', 'review', 'matched-title-no-attachment', 'matched-title-ambiguous-attachment'].includes(s)
|
|
);
|
|
const failed = positionFailed > 0 ? positionFailed : (hasTitleLevel ? total : positionFailed);
|
|
return { failed, total };
|
|
},
|
|
|
|
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 process all ${row.count} source clipping(s) for this title.`, false);
|
|
this.showReimportReady(row.title, row.count);
|
|
this.data.persistentOverrides = await this.plugin.readJsonArtifact("match-overrides.json");
|
|
this.refreshMappings();
|
|
this.refreshTitleOverview();
|
|
// Immediately hide mapped titles from Conflicts view
|
|
this.rows = this.rows.filter(r => r.title !== row.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 process all ${row.count} source clipping(s) for this title.`, false);
|
|
this.showReimportReady(row.title, row.count);
|
|
}
|
|
this.data.persistentOverrides = await this.plugin.readJsonArtifact("match-overrides.json");
|
|
this.refreshMappings();
|
|
this.refreshTitleOverview();
|
|
// 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 => {
|
|
if (th.querySelector(':scope > .resizer')) return;
|
|
const resizer = document.createElement('div');
|
|
resizer.className = 'resizer';
|
|
resizer.title = 'Drag to resize column';
|
|
th.appendChild(resizer);
|
|
let startX, startWidth;
|
|
const onMouseMove = (e) => {
|
|
const dx = e.clientX - startX;
|
|
th.style.width = Math.max(40, startWidth + dx) + 'px';
|
|
table.style.tableLayout = 'fixed';
|
|
};
|
|
const onMouseUp = () => {
|
|
resizer.classList.remove('dragging');
|
|
document.removeEventListener('mousemove', onMouseMove);
|
|
document.removeEventListener('mouseup', onMouseUp);
|
|
};
|
|
resizer.addEventListener('mousedown', (e) => {
|
|
startX = e.clientX;
|
|
startWidth = th.offsetWidth;
|
|
resizer.classList.add('dragging');
|
|
document.addEventListener('mousemove', onMouseMove);
|
|
document.addEventListener('mouseup', onMouseUp);
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
});
|
|
});
|
|
},
|
|
|
|
makeTableSortable(table, opts = {}) {
|
|
if (!table || table.dataset.sortable) return;
|
|
table.dataset.sortable = "1";
|
|
const skipCols = new Set(opts.skipColumns || []);
|
|
const columns = opts.columns || [];
|
|
const descendingColumns = new Set(opts.descendingColumns || []);
|
|
const ths = Array.from(table.querySelectorAll('thead th'));
|
|
// Wrap header labels so sort arrows never wipe the resizer node.
|
|
ths.forEach(th => {
|
|
if (!th.querySelector(':scope > .sort-label')) {
|
|
const label = document.createElement('span');
|
|
label.className = 'sort-label';
|
|
while (th.firstChild && !th.firstChild.classList?.contains('resizer')) {
|
|
label.appendChild(th.firstChild);
|
|
}
|
|
th.insertBefore(label, th.firstChild);
|
|
const arrow = document.createElement('span');
|
|
arrow.className = 'sort-arrow';
|
|
th.insertBefore(arrow, th.querySelector('.resizer'));
|
|
}
|
|
});
|
|
ths.forEach((th, idx) => {
|
|
const column = columns[idx];
|
|
if (skipCols.has(idx) || !column) return;
|
|
th.classList.add('sortable');
|
|
th.title = 'Click to sort';
|
|
th.addEventListener('click', (e) => {
|
|
if (e.target.classList.contains('resizer')) return;
|
|
if (e.target.classList.contains('expander')) return;
|
|
const current = this.sortState[opts.tableKey] || {};
|
|
const direction = current.column === column
|
|
? (current.direction === 'asc' ? 'desc' : 'asc')
|
|
: (descendingColumns.has(column) ? 'desc' : 'asc');
|
|
this.sortState[opts.tableKey] = { column, direction };
|
|
this.updateSortIndicators(table, opts.tableKey, columns);
|
|
if (opts.refresh) opts.refresh();
|
|
});
|
|
});
|
|
this.updateSortIndicators(table, opts.tableKey, columns);
|
|
},
|
|
|
|
updateSortIndicators(table, tableKey, columns) {
|
|
const state = this.sortState[tableKey] || {};
|
|
Array.from(table.querySelectorAll('thead th')).forEach((th, idx) => {
|
|
const arrow = th.querySelector(':scope > .sort-arrow');
|
|
if (arrow) arrow.textContent = columns[idx] === state.column
|
|
? (state.direction === 'asc' ? ' ▲' : ' ▼')
|
|
: '';
|
|
});
|
|
},
|
|
|
|
sortRows(items, tableKey, selectors) {
|
|
const state = this.sortState[tableKey] || {};
|
|
const select = selectors[state.column];
|
|
if (!select) return items.slice();
|
|
const direction = state.direction === 'desc' ? -1 : 1;
|
|
return items.map((item, index) => ({ item, index })).sort((a, b) => {
|
|
const left = select(a.item);
|
|
const right = select(b.item);
|
|
let result = 0;
|
|
if (typeof left === 'number' && typeof right === 'number') result = left - right;
|
|
else result = String(left ?? '').localeCompare(String(right ?? ''), undefined, { numeric: true, sensitivity: 'base' });
|
|
return result ? result * direction : a.index - b.index;
|
|
}).map(entry => entry.item);
|
|
},
|
|
|
|
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 process all ${row.count} source clipping(s) for this title.`, 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.refreshTitleOverview();
|
|
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();
|
|
this.refreshTitleOverview();
|
|
},
|
|
|
|
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();
|
|
},
|
|
|
|
titleOverviewRows() {
|
|
const sources = this.sourceTitleStats();
|
|
const matches = new Map((this.data.matches?.matches || []).map(match => [match.clipping_title, match]));
|
|
const overrides = new Map((this.data.persistentOverrides?.overrides || []).map(entry => [entry.clipping_title, entry]));
|
|
const positioned = new Map();
|
|
const discardedSet = new Set(this.data.finalPlan?.discarded_clipping_ids || []);
|
|
for (const item of this.data.positionedPlan?.items || []) {
|
|
if (item.clipping?.id && discardedSet.has(item.clipping.id)) continue;
|
|
const title = item.clipping?.title || '(missing title)';
|
|
if (!positioned.has(title)) positioned.set(title, { positioned: 0, unresolved: 0 });
|
|
const counts = positioned.get(title);
|
|
if (item.status === 'positioned') counts.positioned += 1;
|
|
else if (item.status !== 'ignored-title') counts.unresolved += 1;
|
|
}
|
|
const integrated = new Map();
|
|
for (const annotation of this.getIntegratedHighlights()) {
|
|
const title = annotation.clipping_title || '(missing title)';
|
|
integrated.set(title, (integrated.get(title) || 0) + 1);
|
|
}
|
|
const deferred = new Set(this.data.finalPlan?.deferred_clipping_ids || []);
|
|
const pendingByTitle = new Map();
|
|
const clippingIdToTitle = new Map();
|
|
for (const source of sources.values()) {
|
|
for (const clipping of source.clippings || []) {
|
|
if (clipping.id) clippingIdToTitle.set(clipping.id, source.title);
|
|
}
|
|
}
|
|
for (const item of this.data.positionedPlan?.items || []) {
|
|
const clipping = item.clipping || {};
|
|
if (clipping.id && deferred.has(clipping.id)) {
|
|
const title = clipping.title || clippingIdToTitle.get(clipping.id) || '(missing title)';
|
|
pendingByTitle.set(title, (pendingByTitle.get(title) || 0) + 1);
|
|
deferred.delete(clipping.id);
|
|
}
|
|
}
|
|
for (const id of deferred) {
|
|
const title = clippingIdToTitle.get(id) || '(missing title)';
|
|
pendingByTitle.set(title, (pendingByTitle.get(title) || 0) + 1);
|
|
}
|
|
const rows = [];
|
|
for (const source of sources.values()) {
|
|
const match = matches.get(source.title);
|
|
const override = overrides.get(source.title);
|
|
const resolution = override?.resolution || {};
|
|
const position = positioned.get(source.title) || { positioned: 0, unresolved: 0 };
|
|
const integratedCount = integrated.get(source.title) || 0;
|
|
const pending = pendingByTitle.get(source.title) || 0;
|
|
let target = '';
|
|
if (resolution.ignore) target = 'Ignored';
|
|
else target = resolution.citation_key || resolution.zotero_key || resolution.zotero_item_id ||
|
|
match?.candidates?.[0]?.citation_key || match?.candidates?.[0]?.key || '';
|
|
let status = 'unmatched';
|
|
if (resolution.ignore || match?.status === 'ignored') status = 'ignored';
|
|
else if (override && match?.status !== 'matched') status = 'mapping saved';
|
|
else if (pending) status = 'pending review';
|
|
else if (position.unresolved) status = 'position issues';
|
|
else if (integratedCount) status = 'integrated';
|
|
else if (match?.status === 'matched') status = 'matched';
|
|
else if (match?.status) status = match.status;
|
|
rows.push({
|
|
...source,
|
|
status,
|
|
target: String(target || '—'),
|
|
integrated: integratedCount,
|
|
pending,
|
|
unresolved: position.unresolved,
|
|
});
|
|
}
|
|
return rows;
|
|
},
|
|
|
|
refreshTitleOverview() {
|
|
const tbody = document.getElementById('title-status-rows');
|
|
const count = document.getElementById('title-status-count');
|
|
if (!tbody) return;
|
|
tbody.textContent = '';
|
|
const rows = this.sortRows(this.titleOverviewRows(), 'titles', {
|
|
status: row => row.status,
|
|
source: row => row.count,
|
|
integrated: row => row.integrated,
|
|
pending: row => row.pending,
|
|
problems: row => row.unresolved,
|
|
title: row => row.title,
|
|
target: row => row.target,
|
|
});
|
|
if (count) count.textContent = `${rows.length} Kindle titles from the current clippings file`;
|
|
for (const row of rows) {
|
|
const tr = document.createElement('tr');
|
|
const values = [
|
|
row.status,
|
|
`${row.count} (${row.highlights}H · ${row.notes}N · ${row.bookmarks}B)`,
|
|
row.integrated,
|
|
row.pending,
|
|
row.unresolved,
|
|
row.title,
|
|
row.target,
|
|
];
|
|
values.forEach((value, index) => {
|
|
const td = document.createElement('td');
|
|
if (index === 0) {
|
|
const pill = document.createElement('span');
|
|
pill.className = 'pill';
|
|
pill.textContent = String(value);
|
|
td.appendChild(pill);
|
|
} else {
|
|
td.textContent = String(value);
|
|
}
|
|
if (index === 1) td.title = `${row.highlights} highlights, ${row.notes} notes, ${row.bookmarks} bookmarks`;
|
|
tr.appendChild(td);
|
|
});
|
|
tbody.appendChild(tr);
|
|
}
|
|
},
|
|
|
|
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;
|
|
const sorted = this.sortRows(filtered, 'integrated', {
|
|
title: annotation => annotation.clipping_title || '',
|
|
citation: annotation => annotation.citation_key || annotation.parent_key || '',
|
|
text: annotation => annotation.annotation?.text || '',
|
|
added: annotation => annotation.clipping_added_on_iso || dateMap.get(annotation.clipping_id)?.added_on_iso || '',
|
|
integrated: annotation => annotation.integrated_at || '',
|
|
page: annotation => annotation.annotation?.pageLabel || '',
|
|
});
|
|
if (resetPage) this.integratedPage = 0;
|
|
const page = this.paginate(sorted, '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 sourceCounts = this.sourceTitleStats();
|
|
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;
|
|
const sorted = this.sortRows(filtered, 'mappings', {
|
|
title: entry => entry.clipping_title || '',
|
|
resolution: entry => entry.resolution?.citation_key || entry.resolution?.zotero_key || entry.resolution?.zotero_item_id || (entry.resolution?.ignore ? 'ignored' : ''),
|
|
status: entry => entry.review?.status || '',
|
|
count: entry => sourceCounts.get(entry.clipping_title)?.count ?? entry.review?.clipping_count ?? 0,
|
|
updated: entry => entry.updated_at || entry.created_at || '',
|
|
});
|
|
if (resetPage) this.mappingsPage = 0;
|
|
const page = this.paginate(sorted, '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(sourceCounts.get(entry.clipping_title)?.count ?? 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.refreshTitleOverview();
|
|
this.showReimportReady(title, 0);
|
|
} catch (e) {
|
|
this.status(String(e), true);
|
|
}
|
|
},
|
|
|
|
async copyClipText(clip) {
|
|
const text = clip.text || '';
|
|
if (!text) return this.status('Nothing to copy — this clipping has no text.', true);
|
|
try {
|
|
if (navigator.clipboard?.writeText) await navigator.clipboard.writeText(text);
|
|
else throw new Error('clipboard unavailable');
|
|
this.status('Clipping text copied — paste it into a Zotero annotation manually. Kanzi will not touch manual annotations.', false);
|
|
} catch (e) {
|
|
this.status(`Copy failed — select the text manually: ${e}`, true);
|
|
}
|
|
},
|
|
|
|
async discardClip(clippingId, title) {
|
|
if (!clippingId) return;
|
|
if (!confirm(`Permanently discard this clipping?\n\nIt will never be retried or shown again.\n${title || ''}`)) return;
|
|
try {
|
|
await this.plugin.discardClip(clippingId);
|
|
this.data.finalPlan = await this.plugin.readJsonArtifact("import-plan.final.json");
|
|
this.rows = this.conflictRows();
|
|
this.refreshRows();
|
|
this.refreshTitleOverview();
|
|
this.status('Clipping discarded — it will not return on future runs.', false);
|
|
} catch (e) {
|
|
this.status(String(e && e.message ? e.message : 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 pendingDiv = document.createElement('div');
|
|
pendingDiv.id = 'pending-review';
|
|
root.appendChild(pendingDiv);
|
|
|
|
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 titles</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>`;
|
|
const titleH2 = document.createElement('h2');
|
|
titleH2.textContent = 'Status by Kindle Title';
|
|
summaryTab.appendChild(titleH2);
|
|
const titleDesc = document.createElement('div');
|
|
titleDesc.className = 'muted';
|
|
titleDesc.textContent = 'Source counts come directly from clippings.json. H = highlights, N = notes, B = bookmarks. Problems are annotations that could not be positioned.';
|
|
summaryTab.appendChild(titleDesc);
|
|
const titleCount = document.createElement('div');
|
|
titleCount.id = 'title-status-count';
|
|
titleCount.className = 'muted';
|
|
titleCount.style.margin = '6px 0';
|
|
summaryTab.appendChild(titleCount);
|
|
const titleWrap = document.createElement('div');
|
|
titleWrap.className = 'title-status-wrap';
|
|
const titleTable = document.createElement('table');
|
|
titleTable.id = 'title-status-table';
|
|
const titleThead = document.createElement('thead');
|
|
titleThead.innerHTML = '<tr><th>Status</th><th>Source</th><th>Integrated</th><th>Pending</th><th>Problems</th><th>Kindle Title</th><th>Target</th></tr>';
|
|
titleTable.appendChild(titleThead);
|
|
const titleTbody = document.createElement('tbody');
|
|
titleTbody.id = 'title-status-rows';
|
|
titleTable.appendChild(titleTbody);
|
|
titleWrap.appendChild(titleTable);
|
|
summaryTab.appendChild(titleWrap);
|
|
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='One row per unique Kindle title. Click ▸ to expand its highlights/notes and positioning problems. Pick a suggested candidate or enter any citation key / Zotero key / item ID manually. 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 cCount = document.createElement('div');
|
|
cCount.id = 'conflicts-count';
|
|
cCount.className = 'muted';
|
|
cCount.style.margin = '6px 0';
|
|
conflictsTab.appendChild(cCount);
|
|
const table = document.createElement('table');
|
|
table.id = 'conflicts-table';
|
|
const thead = document.createElement('thead');
|
|
thead.innerHTML = '<tr><th></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);
|
|
return inp;
|
|
};
|
|
makeSettingField('Project directory', 'setting-projectDir', this.settings.projectDir);
|
|
makeSettingField('Python executable', 'setting-pythonPath', this.settings.pythonPath);
|
|
const pythonHelp = document.createElement('div');
|
|
pythonHelp.className = 'notice';
|
|
pythonHelp.style.margin = '8px 0 12px';
|
|
pythonHelp.style.whiteSpace = 'pre-wrap';
|
|
pythonHelp.style.userSelect = 'text';
|
|
pythonHelp.textContent = this.plugin.isWindows()
|
|
? 'Windows setup (PowerShell):\nwinget install --id Python.Python.3.13 --exact\nwinget install --id oschwartz10612.Poppler --exact\nwinget install --id QPDF.QPDF --exact # optional, for protected PDFs\n\nFully quit and reopen Zotero after installation. Kanzi detects Python automatically; only edit the executable path to override detection.'
|
|
: 'Kanzi detects standard Python 3.11+ installations automatically. Only edit this path to override detection.';
|
|
sForm.appendChild(pythonHelp);
|
|
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.refreshTitleOverview();
|
|
this.refreshIntegrated();
|
|
this.refreshMappings();
|
|
this.updateInfobox();
|
|
this.makeTableResizable(document.querySelector('#title-status-table'));
|
|
this.makeTableResizable(document.querySelector('#tab-conflicts table'));
|
|
this.makeTableResizable(document.querySelector('#tab-integrated table'));
|
|
this.makeTableResizable(document.querySelector('#tab-mappings table'));
|
|
this.makeTableSortable(document.querySelector('#title-status-table'), {
|
|
tableKey: 'titles',
|
|
columns: ['status', 'source', 'integrated', 'pending', 'problems', 'title', 'target'],
|
|
descendingColumns: ['source', 'integrated', 'pending', 'problems'],
|
|
refresh: () => this.refreshTitleOverview(),
|
|
});
|
|
this.makeTableSortable(document.querySelector('#tab-conflicts table'), {
|
|
tableKey: 'conflicts',
|
|
columns: [null, 'status', 'count', 'title', 'detail', null],
|
|
skipColumns: [0, 5],
|
|
descendingColumns: ['count'],
|
|
refresh: () => { this.conflictsPage = 0; this.refreshRows(); },
|
|
});
|
|
this.makeTableSortable(document.querySelector('#tab-integrated table'), {
|
|
tableKey: 'integrated',
|
|
columns: ['title', 'citation', 'text', 'added', 'integrated', 'page'],
|
|
descendingColumns: ['added', 'integrated'],
|
|
refresh: () => { this.integratedPage = 0; this.refreshIntegrated(); },
|
|
});
|
|
this.makeTableSortable(document.querySelector('#tab-mappings table'), {
|
|
tableKey: 'mappings',
|
|
columns: ['title', 'resolution', 'status', 'count', 'updated', null],
|
|
skipColumns: [5],
|
|
descendingColumns: ['count', 'updated'],
|
|
refresh: () => { this.mappingsPage = 0; this.refreshMappings(); },
|
|
});
|
|
},
|
|
|
|
toggleTitle(title) {
|
|
this.expandedTitles[title] = !this.expandedTitles[title];
|
|
this.refreshRows();
|
|
},
|
|
|
|
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.statuses || [row.status]).join(' ')} ${(row.sources || []).join(' ')} ${row.title} ${row.detail || ''} ${(row.candidates || []).map(c => `${c.citation_key} ${c.title}`).join(' ')} ${(row.clippings || []).map(c => c.text).join(' ').slice(0, 4000)}`.toLowerCase().includes(needle));
|
|
const sorted = this.sortRows(filtered, 'conflicts', {
|
|
status: row => row.status || '',
|
|
count: row => this.conflictAffected(row).failed,
|
|
title: row => row.title || '',
|
|
detail: row => `${row.candidates?.[0]?.citation_key || row.candidates?.[0]?.key || ''} ${row.detail || ''}`,
|
|
});
|
|
if (resetPage) this.conflictsPage = 0;
|
|
const page = this.paginate(sorted, 'conflictsPage', 'conflictsPageSize');
|
|
this.refreshPagination('conflicts-pagination', 'conflictsPage', 'conflictsPageSize', page.totalPages, () => this.refreshRows());
|
|
const countNote = document.getElementById('conflicts-count');
|
|
if (countNote) countNote.textContent = `${filtered.length} unique titles — page ${this.conflictsPage + 1}/${page.totalPages}`;
|
|
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 expanded = !!this.expandedTitles[row.title];
|
|
const tr = document.createElement('tr');
|
|
// Chevron cell
|
|
const tdExp = document.createElement('td');
|
|
tdExp.dataset.sortValue = '';
|
|
const clipCount = (row.clippings || []).length;
|
|
if (clipCount) {
|
|
const btn = document.createElement('button');
|
|
btn.className = 'expander';
|
|
btn.textContent = expanded ? '▾' : '▸';
|
|
btn.title = expanded ? `Hide ${clipCount} source clipping(s)` : `Show ${clipCount} source clipping(s)`;
|
|
btn.addEventListener('click', () => this.toggleTitle(row.title));
|
|
tdExp.appendChild(btn);
|
|
} else {
|
|
tdExp.textContent = '';
|
|
tdExp.style.color = 'var(--faint)';
|
|
}
|
|
tr.appendChild(tdExp);
|
|
const tdStatus = document.createElement('td');
|
|
tdStatus.dataset.sortValue = row.status || '';
|
|
const stack = document.createElement('div');
|
|
stack.className = 'status-stack';
|
|
for (const s of (row.statuses || [row.status])) {
|
|
const pill = document.createElement('span');
|
|
pill.className = 'pill';
|
|
pill.textContent = s;
|
|
pill.title = `Sources: ${(row.sources || []).join(', ')}`;
|
|
stack.appendChild(pill);
|
|
}
|
|
tdStatus.appendChild(stack);
|
|
tr.appendChild(tdStatus);
|
|
const tdCount = document.createElement('td');
|
|
const affected = this.conflictAffected(row);
|
|
tdCount.textContent = affected.failed === affected.total
|
|
? String(affected.total)
|
|
: `${affected.failed} / ${affected.total}`;
|
|
tdCount.title = `${affected.failed} with problems out of ${affected.total} source clipping(s)`;
|
|
tdCount.dataset.sortValue = String(affected.failed).padStart(8, '0');
|
|
tr.appendChild(tdCount);
|
|
const tdTitle = document.createElement('td');
|
|
tdTitle.textContent = row.title;
|
|
const affectedTitle = this.conflictAffected(row);
|
|
tdTitle.title = `${row.title}\nSources: ${(row.sources || []).join(', ')}\n${affectedTitle.failed} with problems / ${affectedTitle.total} source clipping(s) — click ▸ to expand`;
|
|
tdTitle.dataset.sortValue = row.title;
|
|
tr.appendChild(tdTitle);
|
|
const tdDetail = document.createElement('td');
|
|
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)+'%' : '—'})${row.detail ? ' · ' + row.detail : ''}`;
|
|
tdDetail.title = row.candidates.slice(0,4).map(c=> `${c.citation_key||c.key}: ${c.title}`).join('\n') + (row.detail ? '\n\nPosition: ' + row.detail : '');
|
|
} else if (row.mappedTarget) {
|
|
tdDetail.textContent = `Mapped to ${row.mappedTarget}${row.detail ? ' · ' + row.detail : ''}`;
|
|
tdDetail.title = `Title already maps to ${row.mappedTarget} (match status: ${row.matchStatusFull || 'n/a'}). These clips need positioning, not a new mapping.${row.detail ? '\n\nPosition: ' + row.detail : ''}`;
|
|
} else if (row.detail) {
|
|
tdDetail.textContent = row.detail;
|
|
} 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 if (row.mappedTarget) {
|
|
const mapped = document.createElement('div');
|
|
mapped.className='muted';
|
|
mapped.style.fontSize='11px';
|
|
const noAttach = (row.statuses || []).includes('matched-title-no-attachment');
|
|
mapped.textContent = noAttach
|
|
? `Already mapped to ${row.mappedTarget} — attach a PDF/EPUB to it in Zotero, then Retry. Remap below only if the target is wrong.`
|
|
: `Already mapped to ${row.mappedTarget} — fix the attachment/position issue, then Retry. Remap below only if the target is wrong.`;
|
|
tdActions.appendChild(mapped);
|
|
} 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 = row.mappedTarget ? 'remap to a different key…' : '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);
|
|
// Expandable detail row with per-highlight text
|
|
if (expanded && clipCount) {
|
|
const dtr = document.createElement('tr');
|
|
dtr.className = 'detail-row';
|
|
const dtd = document.createElement('td');
|
|
dtd.colSpan = 6;
|
|
const list = document.createElement('div');
|
|
list.className = 'clip-list';
|
|
const head = document.createElement('div');
|
|
head.className = 'muted';
|
|
const affectedHead = this.conflictAffected(row);
|
|
head.textContent = affectedHead.failed === affectedHead.total
|
|
? `${affectedHead.total} source clipping(s) for this title:`
|
|
: `${affectedHead.failed} with problems / ${affectedHead.total} source clipping(s) for this title:`;
|
|
list.appendChild(head);
|
|
const affectedClips = (row.clippings || []).filter(c =>
|
|
(c.problems && c.problems.length) || (c.status && c.status !== '' && c.status !== 'positioned')
|
|
);
|
|
const showAll = !affectedClips.length || affectedClips.length === (row.clippings || []).length;
|
|
const clipsToShow = showAll ? (row.clippings || []) : affectedClips;
|
|
for (const clip of clipsToShow.slice(0, 60)) {
|
|
const item = document.createElement('div');
|
|
item.className = 'clip-item';
|
|
const chead = document.createElement('div');
|
|
chead.className = 'clip-head';
|
|
const bits = [];
|
|
if (clip.kind) bits.push(clip.kind);
|
|
if (clip.page) bits.push('p. ' + clip.page);
|
|
if (clip.location) bits.push('loc. ' + clip.location);
|
|
if (clip.status && clip.status !== row.status) bits.push(clip.status);
|
|
chead.textContent = bits.join(' · ') || clip.status || 'highlight';
|
|
item.appendChild(chead);
|
|
const ctext = document.createElement('div');
|
|
ctext.className = 'clip-text';
|
|
let t = clip.text || '(no text)';
|
|
if (t.length > 420) t = t.slice(0, 420) + '…';
|
|
ctext.textContent = t;
|
|
item.appendChild(ctext);
|
|
if (clip.problems && clip.problems.length) {
|
|
const prob = document.createElement('div');
|
|
prob.className = 'clip-problem';
|
|
prob.textContent = clip.problems.join('; ');
|
|
item.appendChild(prob);
|
|
}
|
|
if (clip.pageHint?.text) {
|
|
const hint = document.createElement('div');
|
|
hint.className = 'clip-problem';
|
|
hint.style.color = 'var(--muted)';
|
|
hint.style.whiteSpace = 'pre-wrap';
|
|
let ht = clip.pageHint.text;
|
|
if (ht.length > 900) ht = ht.slice(0, 900) + '…';
|
|
hint.textContent = `Near Kindle p.${clip.pageHint.kindle_page} the PDF reads:\n${ht}`;
|
|
hint.title = 'Extracted PDF text around the Kindle page hint — find the passage and place the highlight manually in Zotero, or Copy text above.';
|
|
item.appendChild(hint);
|
|
}
|
|
if (clip.id) {
|
|
const actions = document.createElement('div');
|
|
actions.style.display = 'flex';
|
|
actions.style.gap = '6px';
|
|
actions.style.marginTop = '6px';
|
|
const copyBtn = document.createElement('button');
|
|
copyBtn.textContent = 'Copy text';
|
|
copyBtn.className = 'row-btn';
|
|
copyBtn.title = 'Copy this clipping text for manual insertion in Zotero';
|
|
copyBtn.addEventListener('click', (ev) => { ev.stopPropagation(); this.copyClipText(clip); });
|
|
actions.appendChild(copyBtn);
|
|
const discardBtn = document.createElement('button');
|
|
discardBtn.textContent = 'Discard';
|
|
discardBtn.className = 'row-btn';
|
|
discardBtn.title = 'Permanently discard this clipping — it will not be retried or shown again';
|
|
discardBtn.addEventListener('click', (ev) => { ev.stopPropagation(); this.discardClip(clip.id, row.title); });
|
|
actions.appendChild(discardBtn);
|
|
item.appendChild(actions);
|
|
}
|
|
list.appendChild(item);
|
|
}
|
|
if (clipsToShow.length > 60) {
|
|
const more = document.createElement('div');
|
|
more.className = 'muted';
|
|
more.textContent = `… and ${clipsToShow.length - 60} more with problems. The rest are integrated — see Integrated tab.`;
|
|
list.appendChild(more);
|
|
} else if (!showAll) {
|
|
const note = document.createElement('div');
|
|
note.className = 'muted';
|
|
note.textContent = `Showing only the ${clipsToShow.length} with problems. The other ${row.clippings.length - clipsToShow.length} for this title are integrated — see Integrated tab.`;
|
|
list.appendChild(note);
|
|
}
|
|
dtd.appendChild(list);
|
|
dtr.appendChild(dtd);
|
|
tbody.appendChild(dtr);
|
|
}
|
|
}
|
|
},
|
|
};
|
|
</script>
|
|
</head>
|
|
<body onload="KindleManager.initSafe()">
|
|
<div id="root">Loading Kanzi...</div>
|
|
</body>
|
|
</html>
|