Kanzi 0.6.7: bracket colours [r]=grey + editable Settings

- src/kindle_zotero_importer/import_plan.py: add DEFAULT_COLOUR_MAP with grey->[r] per request (y/o/r/grey/gray/red/g/b/p/m etc.), _extract_colour() strips leading [code] and maps to hex, _annotation_stub() uses it, build_import_plan() accepts colour_map
- src/kindle_zotero_importer/cli.py: _load_colour_map() from workdir/colour-map.json or plugin-config.json colourMap, passed to build_import_plan (incremental + full)
- plugin/bootstrap.js: saveSettingsFromManager() persists colourMap to plugin-config.json + colour-map.json, getRuntimeSettings() loads it, loadColourMap() helper, label Kanzi
- plugin/manager.html: Settings → Highlight colours editor (table bracket→hex with colour picker, preview, +Add, Reset, grey=[r] note, example [o] orange), saveSettings() collects colourMap, init uses F tokens
- plugin/manifest.json: name Kanzi, 0.6.6→0.6.7, description Kindle annotations to Zotero
- README.md: Kanzi title, Tools → Kanzi…, colours tip with British spelling
- updates.json: add 0.6.7 on top
This commit is contained in:
Utku Bilen Demir 2026-09-22 15:19:27 +02:00
parent f17a2b8bf6
commit 935bc049ce
7 changed files with 346 additions and 30 deletions

View file

@ -2,19 +2,19 @@
> [!CAUTION]
> **This project has been heavily vibecoded.**
# Kindle Zotero Importer
# Kanzi — Kindle annotations to Zotero
Import Kindle `My Clippings.txt` highlights into Zotero as native annotations; directly inside Zotero, no terminal needed.
Import Kindle `My Clippings.txt` highlights into Zotero as native annotations; directly inside Zotero, no terminal needed. Formerly *Kindle Zotero Importer*.
[<img src="https://img.shields.io/badge/please%20give%20me%20money+-red?style=for-the-badge" alt="please give me money+">](https://github.com/sponsors/UtkuBilenDemir)
## Install (30 seconds)
1. Download `kindle-zotero-importer.xpi` from [Releases](../../releases) (latest `0.6.6`, or `0.6.5-beta` for preview).
1. Download `kindle-zotero-importer.xpi` from [Releases](../../releases) (latest `0.6.7`, or `0.6.6-beta` for preview).
2. In Zotero: `Tools → Plugins → gear → Install Plugin From File…` → pick the `.xpi` → restart Zotero.
3. `Tools → Kindle Zotero Importer…` to open the manager.
3. `Tools → Kanzi…` (or `Kindle Zotero Importer…`) to open the manager.
Works with Zotero 7–10; macOS/Windows/Linux; PDF and EPUB.
Works with Zotero 7–10; macOS/Windows/Linux; PDF and EPUB. Colours via bracket: `[o] orange`, `[r] grey` (per request), `[red]` red, `[y]` yellow, etc. — editable in `Settings → Highlight colours`.
## Use
@ -32,6 +32,7 @@ Your choices are saved in `match-overrides.json` in the project folder; back it
- Keep `My Clippings.txt` cumulative (do not clear it on the Kindle); the importer remembers what is already integrated via `kindle-id:<hash>` tags, so re-imports are incremental.
- If a highlight is positioned in the wrong place, check that the Zotero item has the correct PDF/EPUB attached (not a link); `Matched-title-no-attachment` in `Conflicts` means that.
- `Full re-import` is only needed if you changed many mappings at once or want to rebuild from scratch.
- Colours: start a highlight with `[o]`, `[r]` (grey, per request), `[red]`, `[y]`, `[g]`, `[b]`, `[p]`, `[m]` — e.g. `[o] This is orange` → orange. Full names (`[orange]`, `[grey]` etc.) also work. Change mappings in `Settings → Highlight colours` (British spelling).
## For developers / CLI

50
plugin/bootstrap.js vendored
View file

@ -56,13 +56,13 @@ var KindleZoteroImporter = {
const popup = doc.getElementById("menu_ToolsPopup");
if (!popup) {
Zotero.debug("Kindle Zotero Importer: Tools menu not found");
Zotero.debug("Kanzi: Tools menu not found");
return;
}
const managerItem = doc.createXULElement("menuitem");
managerItem.setAttribute("id", "kindle-zotero-importer-manager");
managerItem.setAttribute("label", "Kindle Zotero Importer...");
managerItem.setAttribute("label", "Kanzi...");
managerItem.addEventListener("command", () => this.openManager());
popup.appendChild(managerItem);
this.menuItems.push(managerItem);
@ -130,7 +130,7 @@ var KindleZoteroImporter = {
this.revealFile(path);
} catch (_error) {
this.alert(
"Kindle Zotero Importer",
"Kanzi",
`File not found yet:\n${path}\n\nRun Import Kindle Clippings first to generate review artifacts.`
);
}
@ -151,6 +151,13 @@ var KindleZoteroImporter = {
settings[key] = parsed[key];
}
}
if (parsed.colourMap) settings.colourMap = parsed.colourMap;
if (parsed.colorMap) settings.colourMap = parsed.colorMap;
// also check colour-map.json for Python pipeline
try {
const cmapText = await Zotero.File.getContentsAsync(this.getProjectDir() + "/colour-map.json");
settings.colourMap = JSON.parse(cmapText);
} catch (_e2) {}
} catch (_error) {
// The config file is optional; defaults/preferences are enough for first run.
}
@ -172,7 +179,7 @@ var KindleZoteroImporter = {
notify(message, success) {
try {
const progressWindow = new Zotero.ProgressWindow({ closeOnClick: true });
progressWindow.changeHeadline("Kindle Zotero Importer");
progressWindow.changeHeadline("Kanzi");
const icon = success ? "chrome://zotero/skin/tick.png" : "chrome://zotero/skin/cross.png";
const item = new progressWindow.ItemProgress(icon, message);
item.setProgress(100);
@ -187,7 +194,7 @@ var KindleZoteroImporter = {
createProgress(message) {
try {
const progressWindow = new Zotero.ProgressWindow({ closeOnClick: false });
progressWindow.changeHeadline("Kindle Zotero Importer");
progressWindow.changeHeadline("Kanzi");
progressWindow.progress = new progressWindow.ItemProgress(
"chrome://zotero/skin/treesource-collection.png",
message
@ -301,7 +308,18 @@ var KindleZoteroImporter = {
zoteroDbPath: newSettings.zoteroDbPath || this.getZoteroDbPath(),
zoteroStorageRoot: newSettings.zoteroStorageRoot || this.getZoteroStorageRoot(),
};
if (newSettings.colourMap) {
toSave.colourMap = newSettings.colourMap;
// also write colour-map.json for Python pipeline (mirrors plugin-config)
try {
await Zotero.File.putContentsAsync(
this.getProjectDir() + "/colour-map.json",
JSON.stringify(newSettings.colourMap, null, 2) + "\n"
);
} catch (_e) {}
}
for (const [key, value] of Object.entries(toSave)) {
if (key === "colourMap") continue;
this.setPref(key, value);
}
await Zotero.File.putContentsAsync(
@ -311,6 +329,20 @@ var KindleZoteroImporter = {
return toSave;
},
async loadColourMap() {
try {
const text = await Zotero.File.getContentsAsync(this.getProjectDir() + "/colour-map.json");
return JSON.parse(text);
} catch (_e) {}
try {
const text = await Zotero.File.getContentsAsync(this.getConfigPath());
const parsed = JSON.parse(text);
if (parsed.colourMap) return parsed.colourMap;
if (parsed.colorMap) return parsed.colorMap;
} catch (_e) {}
return null;
},
async readJsonArtifact(relativePath) {
try {
return JSON.parse(await Zotero.File.getContentsAsync(this.artifactPath(relativePath)));
@ -343,7 +375,7 @@ var KindleZoteroImporter = {
} catch (error) {
Zotero.logError(error);
return this.promptForPath(
"Kindle Zotero Importer",
"Kanzi",
"File picker failed. Enter the full path to My Clippings.txt:",
this.defaultClippingsPath
);
@ -472,7 +504,7 @@ var KindleZoteroImporter = {
const choice = Services.prompt.confirmEx(
this.getMainWindow(),
"Kindle Zotero Importer",
"Kanzi",
message,
Services.prompt.BUTTON_POS_0 * Services.prompt.BUTTON_TITLE_IS_STRING +
Services.prompt.BUTTON_POS_1 * Services.prompt.BUTTON_TITLE_IS_STRING +
@ -573,7 +605,7 @@ var KindleZoteroImporter = {
].join("\n");
return Services.prompt.confirm(
this.getMainWindow(),
"Kindle Zotero Importer: Recreate Annotation?",
"Kanzi: Recreate Annotation?",
message
);
},
@ -822,7 +854,7 @@ var KindleZoteroImporter = {
file.initWithPath(path);
file.reveal();
} catch (error) {
this.alert("Kindle Zotero Importer", `Review file written to:\n${path}\n\n${error}`);
this.alert("Kanzi", `Review file written to:\n${path}\n\n${error}`);
}
},

View file

@ -2,7 +2,7 @@
<html>
<head>
<meta charset="utf-8">
<title>Kindle Zotero Importer</title>
<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');
@ -111,8 +111,12 @@
const root = document.getElementById('root');
root.textContent = '';
const h1 = document.createElement('h1');
h1.textContent = 'Kindle Zotero Importer';
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 || '');
@ -754,11 +758,26 @@
},
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 k = (keyInp.value || '').trim().toLowerCase();
const v = (hexInp.value || '').trim();
if (!k || !/^#[0-9a-fA-F]{6}$/.test(v)) continue;
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 {
@ -790,11 +809,17 @@
headerWrap.style.gap = '12px';
const headerLeft = document.createElement('div');
const h1 = document.createElement('h1');
h1.textContent = 'Kindle Zotero Importer';
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 = 'Import Kindle highlights into Zotero and review unresolved items.';
muted.textContent = 'My Clippings.txt → native Zotero annotations. Formerly Kindle Zotero Importer.';
headerLeft.appendChild(muted);
headerWrap.appendChild(headerLeft);
const infobox = document.createElement('div');
@ -1090,6 +1115,187 @@
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. Grey is [r] per request — red is [red]. Edit codes or hexes below. Example: [o] This will be orange → orange highlight, text becomes “This will be orange”.';
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 colourDefaults = {
y: '#ffd400', yellow: '#ffd400',
o: '#ff8c00', orange: '#ff8c00',
r: '#8a8a8a', grey: '#8a8a8a', gray: '#8a8a8a',
red: '#ff6666',
g: '#5fb236', green: '#5fb236',
b: '#2ea8e5', blue: '#2ea8e5',
p: '#a28ae5', purple: '#a28ae5',
m: '#e56eee', magenta: '#e56eee', pink: '#e56eee'
};
const currentMap = this.settings.colourMap || this.settings.colorMap || colourDefaults;
// merge defaults with current to show all keys, but allow editing
const displayKeys = Array.from(new Set([...Object.keys(colourDefaults), ...Object.keys(currentMap || {})])).sort();
// also try to load persisted map async and refresh if different
this.plugin.loadColourMap().then(m => {
if (m && JSON.stringify(m) !== JSON.stringify(currentMap)) {
this.settings.colourMap = m;
// re-render colour table on next Settings open; for now just keep defaults
}
}).catch(()=>{});
for (const k of displayKeys) {
const tr = document.createElement('tr');
const tdCode = document.createElement('td');
const inpCode = document.createElement('input');
inpCode.value = k;
inpCode.style.fontFamily = 'JetBrains Mono, monospace';
inpCode.style.fontSize = '12px';
inpCode.dataset.colourKey = 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 = (currentMap[k] || colourDefaults[k] || '#ffd400');
inpHex.style.height = '28px';
inpHex.style.padding = '2px';
inpHex.dataset.colourHex = k;
inpHex.className = 'colour-hex-input';
const txtHex = document.createElement('input');
txtHex.value = inpHex.value;
txtHex.style.fontFamily = 'JetBrains Mono, monospace';
txtHex.style.fontSize = '11px';
txtHex.style.marginLeft = '6px';
txtHex.style.width = '80px';
txtHex.dataset.colourHexTxt = k;
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 = inpHex.value;
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);
}
// 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 = [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';
@ -1303,6 +1509,6 @@
</script>
</head>
<body onload="KindleManager.initSafe()">
<div id="root">Loading Kindle Zotero Importer...</div>
<div id="root">Loading Kanzi...</div>
</body>
</html>

View file

@ -1,8 +1,8 @@
{
"manifest_version": 2,
"name": "Kindle Zotero Importer",
"version": "0.6.6",
"description": "Import Kindle My Clippings.txt highlights and notes into Zotero as native annotations.",
"name": "Kanzi",
"version": "0.6.7",
"description": "Kindle annotations to Zotero — My Clippings.txt → native annotations.",
"homepage_url": "https://github.com/UtkuBilenDemir/kindle-zotero_importer",
"author": "Utku Bilen Demir",
"applications": {

View file

@ -8,7 +8,7 @@ from pathlib import Path
from .clippings import clippings_to_jsonable, load_clippings
from .epub_position import add_epub_positions
from .final_plan import build_final_writer_plan
from .import_plan import build_import_plan
from .import_plan import DEFAULT_COLOUR_MAP, build_import_plan
from .matcher import build_match_report, load_json
from .mismatch_review import build_mismatch_review
from .overrides import generate_override_skeleton, load_overrides
@ -16,6 +16,29 @@ from .pdf_position import add_pdf_positions
from .zotero_index import build_zotero_index
def _load_colour_map(workdir: Path) -> dict[str, str] | None:
# 1) workdir/colour-map.json (editable via Settings)
p = workdir / "colour-map.json"
if p.exists():
try:
data = json.loads(p.read_text(encoding="utf-8"))
if isinstance(data, dict):
return {str(k).lower(): str(v) for k, v in data.items()}
except Exception:
pass
# 2) plugin-config.json colourMap field
cfg = workdir / "plugin-config.json"
if cfg.exists():
try:
data = json.loads(cfg.read_text(encoding="utf-8"))
m = data.get("colourMap") or data.get("colorMap")
if isinstance(m, dict):
return {str(k).lower(): str(v) for k, v in m.items()}
except Exception:
pass
return None
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
prog="kindle-zotero-importer",
@ -345,6 +368,7 @@ def main(argv: list[str] | None = None) -> int:
overrides_path = Path(args.overrides).expanduser()
if not overrides_path.is_absolute():
overrides_path = workdir / overrides_path
colour_map = _load_colour_map(workdir)
report_progress(2, "Reading clippings", "Parsing My Clippings.txt")
new_clippings_list = load_clippings(args.clippings_file)
@ -433,7 +457,7 @@ def main(argv: list[str] | None = None) -> int:
# For artifact completeness, also build full matches for summary? Use delta matches for now
# But we need full matches for review? Keep delta
report_progress(22, "Building plan", "Selecting attachments (incremental)")
plan = build_import_plan(delta_clippings, zotero_index, matches)
plan = build_import_plan(delta_clippings, zotero_index, matches, colour_map)
report_progress(30, "Positioning EPUB highlights", "Locating highlights in EPUB files (incremental)")
epub_plan = add_epub_positions(plan)
report_progress(55, "Positioning PDF highlights", "Locating highlights in PDF files (incremental)")
@ -464,7 +488,7 @@ def main(argv: list[str] | None = None) -> int:
matches = build_match_report(clippings, zotero_index, overrides)
override_skeleton = generate_override_skeleton(matches)
report_progress(22, "Building plan", "Selecting attachments")
plan = build_import_plan(clippings, zotero_index, matches)
plan = build_import_plan(clippings, zotero_index, matches, colour_map)
report_progress(30, "Positioning EPUB highlights", "Locating highlights in EPUB files")
epub_plan = add_epub_positions(plan)
report_progress(55, "Positioning PDF highlights", "Locating highlights in PDF files; this is usually the longest stage")

View file

@ -6,11 +6,50 @@ from typing import Any
PLAN_FORMAT = "kindle-zotero-importer.import-plan.v1"
# Default bracket → colour map (British spelling in UI, Zotero field stays "color")
# grey is [r] per request — red is only [red] (full name) to avoid clash
DEFAULT_COLOUR_MAP: dict[str, str] = {
"y": "#ffd400",
"yellow": "#ffd400",
"o": "#ff8c00",
"orange": "#ff8c00",
"r": "#8a8a8a",
"grey": "#8a8a8a",
"gray": "#8a8a8a",
"red": "#ff6666",
"g": "#5fb236",
"green": "#5fb236",
"b": "#2ea8e5",
"blue": "#2ea8e5",
"p": "#a28ae5",
"purple": "#a28ae5",
"m": "#e56eee",
"magenta": "#e56eee",
"pink": "#e56eee",
}
def _extract_colour(text: str, colour_map: dict[str, str] | None = None) -> tuple[str, str]:
"""If text starts with [code], return (colour_hex, stripped_text). Case-insensitive."""
if not text:
return "#ffd400", text
cmap = {k.lower(): v for k, v in (colour_map or DEFAULT_COLOUR_MAP).items()}
m = re.match(r"^\s*\[([^\]]+)\]\s*", text)
if not m:
return "#ffd400", text
raw = m.group(1).strip().lower()
# allow palette names and single letters
hex_colour = cmap.get(raw)
if not hex_colour:
return "#ffd400", text
return hex_colour, text[m.end():].lstrip()
def build_import_plan(
clippings_payload: dict[str, Any],
zotero_index: dict[str, Any],
match_report: dict[str, Any],
colour_map: dict[str, str] | None = None,
) -> dict[str, Any]:
items_by_id = {item["item_id"]: item for item in zotero_index["items"]}
matches_by_title = {
@ -22,7 +61,7 @@ def build_import_plan(
}
clippings = _attach_notes_to_highlights(clippings_payload["clippings"])
plan_items = [
_plan_clipping(clipping, matches_by_title, items_by_id, overrides_by_title)
_plan_clipping(clipping, matches_by_title, items_by_id, overrides_by_title, colour_map)
for clipping in clippings
if clipping["kind"] in {"highlight", "note"}
]
@ -48,6 +87,7 @@ def _plan_clipping(
matches_by_title: dict[str, dict[str, Any]],
items_by_id: dict[int, dict[str, Any]],
overrides_by_title: dict[str, dict[str, Any]],
colour_map: dict[str, str] | None = None,
) -> dict[str, Any]:
base = {
"clipping": clipping,
@ -98,7 +138,7 @@ def _plan_clipping(
clipping, zotero_item.get("attachments", [])
),
},
"annotation": _annotation_stub(clipping) if attachment else None,
"annotation": _annotation_stub(clipping, colour_map) if attachment else None,
"problems": problems,
}
@ -193,14 +233,18 @@ def _attachment_from_override(
return None, None
def _annotation_stub(clipping: dict[str, Any]) -> dict[str, Any]:
def _annotation_stub(clipping: dict[str, Any], colour_map: dict[str, str] | None = None) -> dict[str, Any]:
annotation_type = "highlight" if clipping["kind"] == "highlight" else "note"
raw_text = clipping["text"] if annotation_type == "highlight" else ""
colour, cleaned = _extract_colour(raw_text, colour_map)
# For highlights, strip the bracket from text; for notes, keep original but still colour from text
text = cleaned if annotation_type == "highlight" else raw_text
return {
"type": annotation_type,
"text": clipping["text"] if annotation_type == "highlight" else "",
"text": text,
"comment": clipping.get("comment")
or (clipping["text"] if annotation_type == "note" else None),
"color": "#ffd400",
"color": colour,
"pageLabel": clipping.get("page") or "",
"sortIndex": None,
"position": None,

View file

@ -2,6 +2,15 @@
"addons": {
"kindlezoteroimporter@utkubilen.de": {
"updates": [
{
"version": "0.6.7",
"update_link": "https://github.com/UtkuBilenDemir/kindle-zotero_importer/releases/download/v0.6.7/kindle-zotero-importer.xpi",
"applications": {
"zotero": {
"strict_min_version": "6.999"
}
}
},
{
"version": "0.6.6",
"update_link": "https://github.com/UtkuBilenDemir/kindle-zotero_importer/releases/download/v0.6.6/kindle-zotero-importer.xpi",