4 changed files with 492 additions and 103 deletions
@ -1,31 +1,332 @@
|
||||
import { Plugin } from 'ckeditor5/src/core'; |
||||
import { ButtonView } from 'ckeditor5/src/ui'; |
||||
|
||||
/** |
||||
* Minimal citation picker for Drupal CKEditor5 (sandbox). |
||||
* |
||||
* NOTE: This source file is not used by Drupal unless you build it. |
||||
* The build output lives in ../build/footnotepicker2.js |
||||
*/ |
||||
|
||||
|
||||
export default class FootnotePicker2 extends Plugin { |
||||
init() { |
||||
const editor = this.editor; |
||||
|
||||
editor.ui.componentFactory.add('footnotePicker2', (locale) => { |
||||
const button = new ButtonView(locale); |
||||
button.set({ |
||||
label: 'Reference Footnotes', |
||||
withText: true, |
||||
tooltip: 'Insert reference footnote', |
||||
}); |
||||
|
||||
button.on('execute', () => { |
||||
// Implemented in the built file for now.
|
||||
}); |
||||
|
||||
return button; |
||||
}); |
||||
} |
||||
} |
||||
/* Browser-ready source. Copy to ../build/footnotepicker2.js after changes. */ |
||||
(function () { |
||||
const w = window; |
||||
|
||||
// Guard: CKEditor5 globals must exist.
|
||||
w.CKEditor5 = w.CKEditor5 || {}; |
||||
w.CKEditor5.footnotepicker2 = w.CKEditor5.footnotepicker2 || {}; |
||||
|
||||
const { Plugin, ButtonView, Widget, toWidget, viewToModelPositionOutsideModelElement, DomEventObserver } = w.CKEDITOR || { |
||||
...w.CKEditor5.core, ...w.CKEditor5.ui, ...w.CKEditor5.widget, ...w.CKEditor5.engine |
||||
}; |
||||
|
||||
|
||||
if (!Plugin || !ButtonView || !Widget || !toWidget || !viewToModelPositionOutsideModelElement || !DomEventObserver) { |
||||
// eslint-disable-next-line no-console
|
||||
console.warn('[bibcite_footnotes] CKEditor5 globals not found; FootnotePicker2 not registered.'); |
||||
return; |
||||
} |
||||
// Sanitize ONLY the footnote body (not the article).
|
||||
// Allows: <strong>, <em>, <a href="..."> and plain text.
|
||||
function sanitizeFootnoteHtml(input) { |
||||
if (!input) return ''; |
||||
|
||||
const allowedTags = new Set(['STRONG', 'EM', 'A']); |
||||
const allowedAttrs = { |
||||
A: new Set(['href', 'title', 'target', 'rel']), |
||||
}; |
||||
|
||||
const template = document.createElement('template'); |
||||
template.innerHTML = input; |
||||
|
||||
const cleanNode = (node) => { |
||||
// Remove comments.
|
||||
if (node.nodeType === Node.COMMENT_NODE) { |
||||
node.remove(); |
||||
return; |
||||
} |
||||
|
||||
// Text nodes are fine.
|
||||
if (node.nodeType === Node.TEXT_NODE) return; |
||||
|
||||
// Element nodes.
|
||||
if (node.nodeType === Node.ELEMENT_NODE) { |
||||
// Strip disallowed elements but keep their text content.
|
||||
if (!allowedTags.has(node.tagName)) { |
||||
const textNode = document.createTextNode(node.textContent || ''); |
||||
node.replaceWith(textNode); |
||||
return; |
||||
} |
||||
|
||||
// Strip disallowed attributes.
|
||||
[...node.attributes].forEach((attr) => { |
||||
const name = attr.name.toLowerCase(); |
||||
const ok = allowedAttrs[node.tagName] && allowedAttrs[node.tagName].has(name); |
||||
if (!ok) node.removeAttribute(attr.name); |
||||
}); |
||||
|
||||
// Extra link safety.
|
||||
if (node.tagName === 'A') { |
||||
const href = node.getAttribute('href') || ''; |
||||
// Allow only http(s), mailto, and relative URLs.
|
||||
if (!/^(https?:|mailto:|\/)/i.test(href)) { |
||||
node.removeAttribute('href'); |
||||
} |
||||
node.setAttribute('rel', 'noopener noreferrer'); |
||||
} |
||||
} |
||||
|
||||
// Recurse.
|
||||
[...node.childNodes].forEach(cleanNode); |
||||
}; |
||||
|
||||
[...template.content.childNodes].forEach(cleanNode); |
||||
return template.innerHTML; |
||||
} |
||||
|
||||
|
||||
function openFootnoteDialog(onSubmit, initial = {}) { |
||||
const $ = w.jQuery; |
||||
const Drupal = w.Drupal; |
||||
|
||||
// Fallback: prompt() if dialog isn't available.
|
||||
if (!Drupal || !Drupal.dialog || !$) { |
||||
const reference = w.prompt('Reference ID (optional):', initial.reference || ''); |
||||
const text = w.prompt('Free-form footnote text (optional):', initial.text || ''); |
||||
const page = w.prompt('Page(s) (optional):', initial.page || ''); |
||||
const value = w.prompt('Value (optional):', initial.value || ''); |
||||
if ([reference, text, page, value].some(v => v === null)) return; |
||||
onSubmit({reference: reference.trim(), text: text.trim(), page: page.trim(), value: value.trim()}); |
||||
return; |
||||
} |
||||
|
||||
const $wrapper = $('<div class="reference-footnotes-dialog"></div>'); |
||||
|
||||
// Row 1: reference selector
|
||||
$wrapper.append('<div class="rf-row rf-row--ref"><label class="rf-label"><strong>Reference Footnote item:</strong></label></div>'); |
||||
const $ref = $(` |
||||
<select class="form-select rf-select"> |
||||
<option value="">- None -</option> |
||||
<!-- TODO: populate dynamically / autocomplete later --> |
||||
</select> |
||||
`);
|
||||
const references = w.drupalSettings?.bibcite_footnotes?.references || []; |
||||
for (const [label, id] of references) { |
||||
$ref.append($('<option>').val(String(id)).text(String(label))); |
||||
} |
||||
if (initial.reference && !$ref.find('option').toArray().some(o => o.value === initial.reference)) { |
||||
$ref.append($('<option>').val(initial.reference).text('Reference ' + initial.reference)); |
||||
} |
||||
$ref.val(initial.reference || ''); |
||||
$wrapper.find('.rf-row--ref').append($ref); |
||||
|
||||
// Row 2: free-form textarea
|
||||
$wrapper.append('<div class="rf-row rf-row--or"><div class="rf-or"><strong>Or add free-form footnote text :</strong></div></div>'); |
||||
const $text = $('<textarea class="form-textarea rf-textarea" rows="6"></textarea>'); |
||||
$wrapper.append($('<div class="rf-row rf-row--text"></div>').append($text)); |
||||
|
||||
// Helper line
|
||||
$wrapper.append('<div class="rf-help">HTML tags can be used, e.g., <strong>, <em>, <a href="..."></div>'); |
||||
|
||||
// Row 3: pages + value side-by-side
|
||||
const $grid = $('<div class="rf-grid"></div>'); |
||||
|
||||
const $pageWrap = $(` |
||||
<div class="rf-field"> |
||||
<label class="rf-label">Page(s):</label> |
||||
</div> |
||||
`);
|
||||
const $page = $('<input type="text" class="form-text rf-input" />'); |
||||
$pageWrap.append($page); |
||||
|
||||
const $valueWrap = $(` |
||||
<div class="rf-field"> |
||||
<label class="rf-label">Value :</label> |
||||
</div> |
||||
`);
|
||||
const $value = $('<input type="text" class="form-text rf-input rf-input--value" />'); |
||||
$valueWrap.append($value); |
||||
|
||||
$grid.append($pageWrap, $valueWrap); |
||||
$wrapper.append($grid); |
||||
|
||||
// Hint line
|
||||
$wrapper.append('<div class="rf-hint">Leave blank for an automatic sequential reference number, or enter a custom footnote value</div>'); |
||||
|
||||
$text.val(initial.text || ''); |
||||
$page.val(initial.page || ''); |
||||
$value.val(initial.value || ''); |
||||
const dialog = Drupal.dialog($wrapper.get(0), { |
||||
title: initial.editing ? 'Edit Reference Footnote' : 'Reference Footnotes', |
||||
width: 900, |
||||
close: function () { $wrapper.remove(); }, |
||||
buttons: [ |
||||
{ |
||||
text: 'OK', |
||||
classes: 'button button--primary', |
||||
click: function (event) { |
||||
event.preventDefault(); |
||||
|
||||
|
||||
const reference = ($ref.val() || '').toString().trim(); |
||||
const text = ($text.val() || '').toString().trim(); |
||||
const page = ($page.val() || '').toString().trim(); |
||||
const value = ($value.val() || '').toString().trim(); |
||||
|
||||
|
||||
|
||||
if (!reference && !text) { |
||||
console.warn('[footnotes] blocked: reference + text are empty'); |
||||
$text.trigger('focus'); |
||||
return; |
||||
} |
||||
|
||||
// IMPORTANT: do the work first.
|
||||
|
||||
onSubmit({ reference, text, page, value }); |
||||
|
||||
// Then close/destroy, but never let this prevent insertion.
|
||||
try { dialog.close(); } catch (e) { console.warn('[footnotes] dialog.close failed', e); } |
||||
} |
||||
|
||||
}, |
||||
{ |
||||
text: 'Cancel', |
||||
click: function () { |
||||
dialog.close(); |
||||
|
||||
} |
||||
} |
||||
] |
||||
}); |
||||
|
||||
dialog.showModal(); |
||||
setTimeout(() => $ref.trigger('focus'), 0); |
||||
} |
||||
|
||||
|
||||
const modelName = 'bibciteFootnote'; |
||||
const attributes = ['reference', 'page', 'value', 'body']; |
||||
|
||||
class FootnoteDoubleClickObserver extends DomEventObserver { |
||||
constructor(view) { |
||||
super(view); |
||||
this.domEventType = 'dblclick'; |
||||
} |
||||
onDomEvent(event) { this.fire(event.type, event); } |
||||
} |
||||
|
||||
class FootnotePicker2 extends Plugin { |
||||
static get requires() { return [Widget]; } |
||||
static get pluginName() { return 'FootnotePicker2'; } |
||||
|
||||
init() { |
||||
const editor = this.editor; |
||||
const model = editor.model; |
||||
const view = editor.editing.view; |
||||
model.schema.register(modelName, { |
||||
inheritAllFrom: '$inlineObject', |
||||
allowAttributes: attributes, |
||||
}); |
||||
// Keep the original footnote HTML opaque, including nested formatting.
|
||||
editor.data.processor.registerRawContentMatcher({ name: 'fn' }); |
||||
editor.conversion.for('upcast').elementToElement({ |
||||
view: { name: 'fn' }, |
||||
model: (element, { writer, consumable }) => { |
||||
const attrs = { body: element.getCustomProperty('$rawContent') || '' }; |
||||
for (const key of attributes.slice(0, 3)) { |
||||
if (element.hasAttribute(key)) { |
||||
attrs[key] = element.getAttribute(key); |
||||
consumable.consume(element, { attributes: [key] }); |
||||
} |
||||
} |
||||
return writer.createElement(modelName, attrs); |
||||
}, |
||||
converterPriority: 'high', |
||||
}); |
||||
editor.conversion.for('dataDowncast').elementToElement({ |
||||
model: { name: modelName, attributes }, |
||||
view: (element, { writer }) => { |
||||
const attrs = {}; |
||||
for (const key of attributes.slice(0, 3)) { |
||||
if (element.hasAttribute(key)) attrs[key] = element.getAttribute(key); |
||||
} |
||||
return writer.createRawElement('fn', attrs, dom => { |
||||
dom.innerHTML = element.getAttribute('body') || ''; |
||||
}); |
||||
}, |
||||
}); |
||||
editor.conversion.for('editingDowncast').elementToElement({ |
||||
model: { name: modelName, attributes }, |
||||
view: (element, { writer }) => { |
||||
const marker = writer.createContainerElement('span', { |
||||
class: 'bibcite-footnote-widget', |
||||
title: 'Double-click or select and use Reference Footnotes to edit', |
||||
}); |
||||
const value = element.getAttribute('value'); |
||||
const label = value ? '[FN ' + value + ']' : '[FN]'; |
||||
writer.insert(writer.createPositionAt(marker, 0), writer.createText(label)); |
||||
return toWidget(marker, writer, { label: 'Reference footnote' }); |
||||
}, |
||||
}); |
||||
editor.editing.mapper.on('viewToModelPosition', viewToModelPositionOutsideModelElement( |
||||
model, element => element.hasClass('bibcite-footnote-widget') |
||||
)); |
||||
view.addObserver(FootnoteDoubleClickObserver); |
||||
this.listenTo(view.document, 'dblclick', (evt, data) => { |
||||
let target = data.target; |
||||
while (target && !(target.is('element') && target.hasClass('bibcite-footnote-widget'))) { |
||||
target = target.parent; |
||||
} |
||||
if (!target || editor.isReadOnly) return; |
||||
const element = editor.editing.mapper.toModelElement(target); |
||||
if (element && element.is('element', modelName)) { |
||||
data.preventDefault(); |
||||
evt.stop(); |
||||
model.change(writer => writer.setSelection(element, 'on')); |
||||
this.open(element); |
||||
} |
||||
}); |
||||
editor.ui.componentFactory.add('footnotePicker2', locale => { |
||||
const button = new ButtonView(locale); |
||||
const footnoteIcon = ` |
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"> |
||||
<path d="M7.8 6.6c0-1.1-.9-2-2-2H4.2c-1.1 0-2 .9-2 2v2.3c0 1.1.9 2 2 2h1.1v1.7H3.7c-1 0-1.7.8-1.7 1.7v.3h4.3c1 0 1.7-.8 1.7-1.7V10c0-.7-.4-1.3-1-1.6.5-.4.8-1 .8-1.8V6.6zm10 0c0-1.1-.9-2-2-2h-1.6c-1.1 0-2 .9-2 2v2.3c0 1.1.9 2 2 2h1.1v1.7h-1.7c-1 0-1.7.8-1.7 1.7v.3h4.3c1 0 1.7-.8 1.7-1.7V10c0-.7-.4-1.3-1-1.6.5-.4.8-1 .8-1.8V6.6z"/> |
||||
</svg> |
||||
`;
|
||||
|
||||
button.set({ label: 'Reference Footnotes', icon: footnoteIcon, |
||||
tooltip: 'Insert or edit reference footnote', withText: false }); |
||||
button.on('execute', () => { |
||||
const selected = model.document.selection.getSelectedElement(); |
||||
this.open(selected && selected.is('element', modelName) ? selected : null); |
||||
}); |
||||
return button; |
||||
}); |
||||
} |
||||
|
||||
open(element) { |
||||
const editor = this.editor; |
||||
if (editor.isReadOnly) return; |
||||
const model = editor.model; |
||||
const initial = element ? { |
||||
editing: true, |
||||
reference: element.getAttribute('reference') || '', |
||||
page: element.getAttribute('page') || '', |
||||
value: element.getAttribute('value') || '', |
||||
text: element.getAttribute('body') || '', |
||||
} : {}; |
||||
openFootnoteDialog(({ reference, text, page, value }) => { |
||||
if (editor.isReadOnly) return; |
||||
const attrs = { reference, page, value, body: element && text === initial.text ? initial.text : sanitizeFootnoteHtml(text) }; |
||||
model.change(writer => { |
||||
if (element) { |
||||
if (element.root.rootName === '$graveyard' || !element.parent) return; |
||||
for (const key of attributes) { |
||||
if (attrs[key] || key === 'body') writer.setAttribute(key, attrs[key], element); |
||||
else writer.removeAttribute(key, element); |
||||
} |
||||
writer.setSelection(element, 'on'); |
||||
} else { |
||||
const newElement = writer.createElement(modelName, Object.fromEntries( |
||||
Object.entries(attrs).filter(([key, val]) => val || key === 'body') |
||||
)); |
||||
model.insertObject(newElement, null, null, { setSelection: 'on' }); |
||||
} |
||||
}); |
||||
editor.editing.view.focus(); |
||||
}, initial); |
||||
} |
||||
} |
||||
w.CKEditor5.footnotepicker2.FootnotePicker2 = FootnotePicker2; |
||||
})(); |
||||
|
||||
Loading…
Reference in new issue