Skip to content

Commit 452a587

Browse files
hydrosquallsimonw
andauthored
JavaScript Plugin API, providing custom panels and column menu items
Thanks, Cameron Yick. #2052 Co-authored-by: Simon Willison <swillison@gmail.com>
1 parent 4b534b8 commit 452a587

6 files changed

Lines changed: 399 additions & 19 deletions

File tree

Lines changed: 210 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
1+
// Custom events for use with the native CustomEvent API
2+
const DATASETTE_EVENTS = {
3+
INIT: "datasette_init", // returns datasette manager instance in evt.detail
4+
};
5+
6+
// Datasette "core" -> Methods/APIs that are foundational
7+
// Plugins will have greater stability if they use the functional hooks- but if they do decide to hook into
8+
// literal DOM selectors, they'll have an easier time using these addresses.
9+
const DOM_SELECTORS = {
10+
/** Should have one match */
11+
jsonExportLink: ".export-links a[href*=json]",
12+
13+
/** Event listeners that go outside of the main table, e.g. existing scroll listener */
14+
tableWrapper: ".table-wrapper",
15+
table: "table.rows-and-columns",
16+
aboveTablePanel: ".above-table-panel",
17+
18+
// These could have multiple matches
19+
/** Used for selecting table headers. Use makeColumnActions if you want to add menu items. */
20+
tableHeaders: `table.rows-and-columns th`,
21+
22+
/** Used to add "where" clauses to query using direct manipulation */
23+
filterRows: ".filter-row",
24+
/** Used to show top available enum values for a column ("facets") */
25+
facetResults: ".facet-results [data-column]",
26+
};
27+
28+
/**
29+
* Monolith class for interacting with Datasette JS API
30+
* Imported with DEFER, runs after main document parsed
31+
* For now, manually synced with datasette/version.py
32+
*/
33+
const datasetteManager = {
34+
VERSION: window.datasetteVersion,
35+
36+
// TODO: Should order of registration matter more?
37+
38+
// Should plugins be allowed to clobber others or is it last-in takes priority?
39+
// Does pluginMetadata need to be serializable, or can we let it be stateful / have functions?
40+
plugins: new Map(),
41+
42+
registerPlugin: (name, pluginMetadata) => {
43+
if (datasetteManager.plugins.has(name)) {
44+
console.warn(`Warning -> plugin ${name} was redefined`);
45+
}
46+
datasetteManager.plugins.set(name, pluginMetadata);
47+
48+
// If the plugin participates in the panel... update the panel.
49+
if (pluginMetadata.makeAboveTablePanelConfigs) {
50+
datasetteManager.renderAboveTablePanel();
51+
}
52+
},
53+
54+
/**
55+
* New DOM elements are created on each click, so the data is not stale.
56+
*
57+
* Items
58+
* - must provide label (text)
59+
* - might provide href (string) or an onclick ((evt) => void)
60+
*
61+
* columnMeta is metadata stored on the column header (TH) as a DOMStringMap
62+
* - column: string
63+
* - columnNotNull: boolean
64+
* - columnType: sqlite datatype enum (text, number, etc)
65+
* - isPk: boolean
66+
*/
67+
makeColumnActions: (columnMeta) => {
68+
let columnActions = [];
69+
70+
// Accept function that returns list of columnActions with keys
71+
// Required: label (text)
72+
// Optional: onClick or href
73+
datasetteManager.plugins.forEach((plugin) => {
74+
if (plugin.makeColumnActions) {
75+
// Plugins can provide multiple columnActions if they want
76+
// If multiple try to create entry with same label, the last one deletes the others
77+
columnActions.push(...plugin.makeColumnActions(columnMeta));
78+
}
79+
});
80+
81+
// TODO: Validate columnAction configs and give informative error message if missing keys.
82+
return columnActions;
83+
},
84+
85+
/**
86+
* In MVP, each plugin can only have 1 instance.
87+
* In future, panels could be repeated. We omit that for now since so many plugins depend on
88+
* shared URL state, so having multiple instances of plugin at same time is problematic.
89+
* Currently, we never destroy any panels, we just hide them.
90+
*
91+
* TODO: nicer panel css, show panel selection state.
92+
* TODO: does this hook need to take any arguments?
93+
*/
94+
renderAboveTablePanel: () => {
95+
const aboveTablePanel = document.querySelector(
96+
DOM_SELECTORS.aboveTablePanel
97+
);
98+
99+
if (!aboveTablePanel) {
100+
console.warn(
101+
"This page does not have a table, the renderAboveTablePanel cannot be used."
102+
);
103+
return;
104+
}
105+
106+
let aboveTablePanelWrapper = aboveTablePanel.querySelector(".panels");
107+
108+
// First render: create wrappers. Otherwise, reuse previous.
109+
if (!aboveTablePanelWrapper) {
110+
aboveTablePanelWrapper = document.createElement("div");
111+
aboveTablePanelWrapper.classList.add("tab-contents");
112+
const panelNav = document.createElement("div");
113+
panelNav.classList.add("tab-controls");
114+
115+
// Temporary: css for minimal amount of breathing room.
116+
panelNav.style.display = "flex";
117+
panelNav.style.gap = "8px";
118+
panelNav.style.marginTop = "4px";
119+
panelNav.style.marginBottom = "20px";
120+
121+
aboveTablePanel.appendChild(panelNav);
122+
aboveTablePanel.appendChild(aboveTablePanelWrapper);
123+
}
124+
125+
datasetteManager.plugins.forEach((plugin, pluginName) => {
126+
const { makeAboveTablePanelConfigs } = plugin;
127+
128+
if (makeAboveTablePanelConfigs) {
129+
const controls = aboveTablePanel.querySelector(".tab-controls");
130+
const contents = aboveTablePanel.querySelector(".tab-contents");
131+
132+
// Each plugin can make multiple panels
133+
const configs = makeAboveTablePanelConfigs();
134+
135+
configs.forEach((config, i) => {
136+
const nodeContentId = `${pluginName}_${config.id}_panel-content`;
137+
138+
// quit if we've already registered this plugin
139+
// TODO: look into whether plugins should be allowed to ask
140+
// parent to re-render, or if they should manage that internally.
141+
if (document.getElementById(nodeContentId)) {
142+
return;
143+
}
144+
145+
// Add tab control button
146+
const pluginControl = document.createElement("button");
147+
pluginControl.textContent = config.label;
148+
pluginControl.onclick = () => {
149+
contents.childNodes.forEach((node) => {
150+
if (node.id === nodeContentId) {
151+
node.style.display = "block";
152+
} else {
153+
node.style.display = "none";
154+
}
155+
});
156+
};
157+
controls.appendChild(pluginControl);
158+
159+
// Add plugin content area
160+
const pluginNode = document.createElement("div");
161+
pluginNode.id = nodeContentId;
162+
config.render(pluginNode);
163+
pluginNode.style.display = "none"; // Default to hidden unless you're ifrst
164+
165+
contents.appendChild(pluginNode);
166+
});
167+
168+
// Let first node be selected by default
169+
if (contents.childNodes.length) {
170+
contents.childNodes[0].style.display = "block";
171+
}
172+
}
173+
});
174+
},
175+
176+
/** Selectors for document (DOM) elements. Store identifier instead of immediate references in case they haven't loaded when Manager starts. */
177+
selectors: DOM_SELECTORS,
178+
179+
// Future API ideas
180+
// Fetch page's data in array, and cache so plugins could reuse it
181+
// Provide knowledge of what datasette JS or server-side via traditional console autocomplete
182+
// State helpers: URL params https://github.com/simonw/datasette/issues/1144 and localstorage
183+
// UI Hooks: command + k, tab manager hook
184+
// Should we notify plugins that have dependencies
185+
// when all dependencies were fulfilled? (leaflet, codemirror, etc)
186+
// https://github.com/simonw/datasette-leaflet -> this way
187+
// multiple plugins can all request the same copy of leaflet.
188+
};
189+
190+
const initializeDatasette = () => {
191+
// Hide the global behind __ prefix. Ideally they should be listening for the
192+
// DATASETTE_EVENTS.INIT event to avoid the habit of reading from the window.
193+
194+
window.__DATASETTE__ = datasetteManager;
195+
console.debug("Datasette Manager Created!");
196+
197+
const initDatasetteEvent = new CustomEvent(DATASETTE_EVENTS.INIT, {
198+
detail: datasetteManager,
199+
});
200+
201+
document.dispatchEvent(initDatasetteEvent);
202+
};
203+
204+
/**
205+
* Main function
206+
* Fires AFTER the document has been parsed
207+
*/
208+
document.addEventListener("DOMContentLoaded", function () {
209+
initializeDatasette();
210+
});

‎datasette/static/table.js‎

Lines changed: 64 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ var DROPDOWN_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="14" heig
1717
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
1818
</svg>`;
1919

20-
(function () {
20+
/** Main initialization function for Datasette Table interactions */
21+
const initDatasetteTable = function (manager) {
2122
// Feature detection
2223
if (!window.URLSearchParams) {
2324
return;
@@ -68,13 +69,11 @@ var DROPDOWN_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="14" heig
6869
menu.style.display = "none";
6970
menu.classList.remove("anim-scale-in");
7071
}
71-
// When page loads, add scroll listener on .table-wrapper
72-
document.addEventListener("DOMContentLoaded", () => {
73-
var tableWrapper = document.querySelector(".table-wrapper");
74-
if (tableWrapper) {
75-
tableWrapper.addEventListener("scroll", closeMenu);
76-
}
77-
});
72+
73+
const tableWrapper = document.querySelector(manager.selectors.tableWrapper);
74+
if (tableWrapper) {
75+
tableWrapper.addEventListener("scroll", closeMenu);
76+
}
7877
document.body.addEventListener("click", (ev) => {
7978
/* was this click outside the menu? */
8079
var target = ev.target;
@@ -85,7 +84,8 @@ var DROPDOWN_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="14" heig
8584
closeMenu();
8685
}
8786
});
88-
function iconClicked(ev) {
87+
88+
function onTableHeaderClick(ev) {
8989
ev.preventDefault();
9090
ev.stopPropagation();
9191
var th = ev.target;
@@ -185,7 +185,40 @@ var DROPDOWN_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="14" heig
185185
menu.style.left = menuLeft + "px";
186186
menu.style.display = "block";
187187
menu.classList.add("anim-scale-in");
188+
189+
// Custom menu items on each render
190+
// Plugin hook: allow adding JS-based additional menu items
191+
const columnActionsPayload = {
192+
columnName: th.dataset.column,
193+
columnNotNull: th.dataset.columnNotNull === '1',
194+
columnType: th.dataset.columnType,
195+
isPk: th.dataset.isPk === '1'
196+
};
197+
const columnItemConfigs = manager.makeColumnActions(columnActionsPayload);
198+
199+
const menuList = menu.querySelector('ul');
200+
columnItemConfigs.forEach(itemConfig => {
201+
// Remove items from previous render. We assume entries have unique labels.
202+
const existingItems = menuList.querySelectorAll(`li`);
203+
Array.from(existingItems).filter(item => item.innerText === itemConfig.label).forEach(node => {
204+
node.remove();
205+
});
206+
207+
const newLink = document.createElement('a');
208+
newLink.textContent = itemConfig.label;
209+
newLink.href = itemConfig.href ?? '#';
210+
if (itemConfig.onClick) {
211+
newLink.onclick = itemConfig.onClick;
212+
}
213+
214+
// Attach new elements to DOM
215+
const menuItem = document.createElement('li');
216+
menuItem.appendChild(newLink);
217+
menuList.appendChild(menuItem);
218+
});
219+
188220
}
221+
189222
var svg = document.createElement("div");
190223
svg.innerHTML = DROPDOWN_ICON_SVG;
191224
svg = svg.querySelector("*");
@@ -197,21 +230,21 @@ var DROPDOWN_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="14" heig
197230
menu.style.display = "none";
198231
document.body.appendChild(menu);
199232

200-
var ths = Array.from(document.querySelectorAll(".rows-and-columns th"));
233+
var ths = Array.from(document.querySelectorAll(manager.selectors.tableHeaders));
201234
ths.forEach((th) => {
202235
if (!th.querySelector("a")) {
203236
return;
204237
}
205238
var icon = svg.cloneNode(true);
206-
icon.addEventListener("click", iconClicked);
239+
icon.addEventListener("click", onTableHeaderClick);
207240
th.appendChild(icon);
208241
});
209-
})();
242+
};
210243

211244
/* Add x buttons to the filter rows */
212-
(function () {
245+
function addButtonsToFilterRows(manager) {
213246
var x = "✖";
214-
var rows = Array.from(document.querySelectorAll(".filter-row")).filter((el) =>
247+
var rows = Array.from(document.querySelectorAll(manager.selectors.filterRow)).filter((el) =>
215248
el.querySelector(".filter-op")
216249
);
217250
rows.forEach((row) => {
@@ -234,13 +267,13 @@ var DROPDOWN_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="14" heig
234267
a.style.display = "none";
235268
}
236269
});
237-
})();
270+
};
238271

239272
/* Set up datalist autocomplete for filter values */
240-
(function () {
273+
function initAutocompleteForFilterValues(manager) {
241274
function createDataLists() {
242275
var facetResults = document.querySelectorAll(
243-
".facet-results [data-column]"
276+
manager.selectors.facetResults
244277
);
245278
Array.from(facetResults).forEach(function (facetResult) {
246279
// Use link text from all links in the facet result
@@ -266,9 +299,21 @@ var DROPDOWN_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="14" heig
266299
document.body.addEventListener("change", function (event) {
267300
if (event.target.name === "_filter_column") {
268301
event.target
269-
.closest(".filter-row")
302+
.closest(manager.selectors.filterRow)
270303
.querySelector(".filter-value")
271304
.setAttribute("list", "datalist-" + event.target.value);
272305
}
273306
});
274-
})();
307+
};
308+
309+
// Ensures Table UI is initialized only after the Manager is ready.
310+
document.addEventListener("datasette_init", function (evt) {
311+
const { detail: manager } = evt;
312+
313+
// Main table
314+
initDatasetteTable(manager);
315+
316+
// Other UI functions with interactive JS needs
317+
addButtonsToFilterRows(manager);
318+
initAutocompleteForFilterValues(manager);
319+
});

‎datasette/templates/_table.html‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
<!-- above-table-panel is a hook node for plugins to attach to . Displays even if no data available -->
2+
<div class="above-table-panel"> </div>
13
{% if display_rows %}
24
<div class="table-wrapper">
35
<table class="rows-and-columns">

‎datasette/templates/base.html‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
{% for url in extra_css_urls %}
88
<link rel="stylesheet" href="{{ url.url }}"{% if url.get("sri") %} integrity="{{ url.sri }}" crossorigin="anonymous"{% endif %}>
99
{% endfor %}
10+
<script>window.datasetteVersion = '{{ datasette_version }}';</script>
11+
<script src="{{ urls.static('datasette-manager.js') }}" defer></script>
1012
{% for url in extra_js_urls %}
1113
<script {% if url.module %}type="module" {% endif %}src="{{ url.url }}"{% if url.get("sri") %} integrity="{{ url.sri }}" crossorigin="anonymous"{% endif %}></script>
1214
{% endfor %}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from datasette import hookimpl
2+
3+
# Test command:
4+
# datasette fixtures.db \ --plugins-dir=demos/plugins/
5+
# \ --static static:demos/plugins/static
6+
7+
# Create a set with view names that qualify for this JS, since plugins won't do anything on other pages
8+
# Same pattern as in Nteract data explorer
9+
# https://github.com/hydrosquall/datasette-nteract-data-explorer/blob/main/datasette_nteract_data_explorer/__init__.py#L77
10+
PERMITTED_VIEWS = {"table", "query", "database"}
11+
12+
13+
@hookimpl
14+
def extra_js_urls(view_name):
15+
print(view_name)
16+
if view_name in PERMITTED_VIEWS:
17+
return [
18+
{
19+
"url": f"/static/table-example-plugins.js",
20+
}
21+
]

0 commit comments

Comments
 (0)