Files

1138 lines
36 KiB
JavaScript
Raw Permalink Normal View History

/*
* NiceQuote 2.4 后台编辑器
*
* - 工具栏按钮用图标,title 走浏览器原生 tooltip,和 riven 主题自带按钮一致
* - 按钮插在图标组末尾(发表按钮 / 表情区之前),避免被挤到第三行
* - 七种引用类型各自独立:文章、页面、评论、用户、分类、标签、外部
* - 外部链接填网址即可,插入时写成 {url-https://...},站内引用仍写 {post-ID}
* - 支持一次选多条,插入时按行排列,前台会渲染成一个引用列表
* - 不往编辑器里插脏数据:没选任何内容时不会写入短码
*/
(function () {
'use strict';
var CFG = window.NiceQuoteConfig || {};
function svg(paths) {
return '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor"'
+ ' stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"'
+ ' aria-hidden="true" focusable="false">' + paths + '</svg>';
}
/**
* 七种引用类型
*
* field 是「ID 输入框」那一行的标题,把原来分开写的类型名、ID 名和短码合成了一句:
* 评论 ID(comment-ID),一眼就能对上正文里插进去的 {comment-12}。
*/
var KINDS = [
{
value: 'post',
label: '文章',
base: 'post',
field: '文章 ID(post-ID)',
placeholder: '搜索文章标题,或直接填 ID',
icon: svg('<path d="M5 4h14v16H5z"/><path d="M8.5 8.5h7M8.5 12h7M8.5 15.5h4"/>')
},
{
value: 'page',
label: '页面',
base: 'post',
field: '页面 ID(page-ID)',
placeholder: '搜索独立页面标题,或直接填 ID',
icon: svg('<path d="M7 3h7l4 4v14H7z"/><path d="M14 3v4h4"/><path d="M10 12h5M10 15.5h5"/>')
},
{
value: 'comment',
label: '评论',
base: 'comment',
field: '评论 ID(comment-ID)',
placeholder: '搜索评论内容或评论者',
icon: svg('<path d="M4 5.5h16v10H9.5L5 19v-3.5H4z"/><path d="M8.5 9.5h7M8.5 12.5h4.5"/>')
},
{
value: 'user',
label: '用户',
base: 'user',
field: '用户 ID(user-ID)',
placeholder: '搜索用户名 / 昵称',
icon: svg('<circle cx="12" cy="8.2" r="3.2"/><path d="M5.6 20c0-3.5 2.9-5.8 6.4-5.8s6.4 2.3 6.4 5.8"/>')
},
{
value: 'category',
label: '分类',
base: 'meta',
field: '分类 ID(category-ID)',
placeholder: '搜索分类名称',
icon: svg('<path d="M3.5 7.5h5.5l2 2h9.5v9H3.5z"/>')
},
{
value: 'tag',
label: '标签',
base: 'meta',
field: '标签 ID(tag-ID)',
placeholder: '搜索标签名称',
icon: svg('<path d="M4 12.6V4.5h8.1L20 12.4 12.4 20z"/><circle cx="8.6" cy="8.6" r="1.3"/>')
},
{
value: 'url',
label: '外部',
base: 'url',
url: true,
field: '外部网址(url-网址)',
placeholder: '粘贴外部文章链接',
icon: svg('<circle cx="12" cy="12" r="8"/><path d="M4 12h16"/>'
+ '<path d="M12 4c2.4 2.7 2.4 13.3 0 16"/><path d="M12 4c-2.4 2.7-2.4 13.3 0 16"/>')
}
];
var state = {
kind: 'post',
mask: null,
timer: null,
searchTimer: null,
picked: [],
active: -1,
/** 预览节点缓存:key 相同的条目复用同一个 iframe,避免每次点一下都重新请求 */
frames: {}
};
function el(tag, className, text) {
var node = document.createElement(tag);
if (className) {
node.className = className;
}
if (typeof text === 'string') {
node.textContent = text;
}
return node;
}
function kindOf(value) {
for (var i = 0; i < KINDS.length; i++) {
if (KINDS[i].value === value) {
return KINDS[i];
}
}
return KINDS[0];
}
/** 这一类引用填的是网址而不是 ID */
function isUrlKind(kind) {
return kindOf(kind).url === true;
}
function isUrl(value) {
return /^https?:\/\/[^\s"'<>{}]+$/i.test(String(value || '').trim());
}
function indexUrl() {
return CFG.index || (window.location.origin + '/index.php');
}
function withQuery(url, query) {
return url + (url.indexOf('?') === -1 ? '?' : '&') + query;
}
function buildShortcode(kind, id) {
return isUrlKind(kind) ? '{url-' + id + '}' : '{' + kind + '-' + id + '}';
}
/** 已选条目的右侧小字:站内显示 #ID,站外显示域名;标题还没查到时就不重复显示 */
function chipId(item) {
if (!isUrlKind(item.kind)) {
return item.title === '#' + item.id ? '' : '#' + item.id;
}
var host = String(item.id).replace(/^https?:\/\//i, '').split('/')[0];
return host === item.title ? '' : host;
}
/* ---------- 插入 ---------- */
/**
* 在光标处插入一段块级内容
*
* 多条引用必须各占一行、靠换行分隔,前台才会把它们认成一组列表;
* 所以这里补上前后换行,避免和上下文粘在一行。
*/
function insertBlock(text) {
var textarea = document.getElementById('text');
if (!textarea) {
window.alert('没有找到正文输入框,请手动粘贴:' + text);
return false;
}
textarea.focus();
var start = textarea.selectionStart || 0;
var end = textarea.selectionEnd || 0;
var before = textarea.value.slice(0, start);
var after = textarea.value.slice(end);
var lead = /(^|\n)\s*$/.test(before) ? '' : '\n';
var tail = /^\s*(\n|$)/.test(after) ? '' : '\n';
var payload = lead + text + tail;
if (typeof textarea.setRangeText === 'function') {
textarea.setRangeText(payload, start, end, 'end');
} else {
textarea.value = before + payload + after;
textarea.selectionStart = textarea.selectionEnd = start + payload.length;
}
textarea.dispatchEvent(new Event('input', { bubbles: true }));
textarea.dispatchEvent(new Event('change', { bubbles: true }));
return true;
}
/* ---------- 弹窗 ---------- */
function isDark() {
var admin = document.getElementById('newadmin');
if (admin && /(^|\s)dark(\s|$)/.test(admin.className)) {
return true;
}
if (document.documentElement.classList.contains('dark')
|| document.body.classList.contains('dark')) {
return true;
}
try {
return window.matchMedia('(prefers-color-scheme: dark)').matches;
} catch (e) {
return false;
}
}
function destroy() {
if (state.mask && state.mask.parentNode) {
state.mask.parentNode.removeChild(state.mask);
}
state.mask = null;
state.picked = [];
state.active = -1;
state.frames = {};
document.removeEventListener('keydown', onKeydown);
document.body.style.overflow = '';
}
function onKeydown(event) {
if (event.key === 'Escape') {
destroy();
}
}
function setKind(value) {
state.kind = value;
var modal = state.mask;
var kind = kindOf(value);
var buttons = modal.querySelectorAll('.nq-kind');
for (var i = 0; i < buttons.length; i++) {
buttons[i].classList.toggle('is-on', buttons[i].getAttribute('data-kind') === value);
}
var urlMode = kind.url === true;
var idInput = modal.querySelector('#nq-id');
var idLabel = modal.querySelector('#nq-idlabel');
var searchRow = modal.querySelector('#nq-search-row');
var searchInput = modal.querySelector('#nq-search');
idInput.classList.toggle('is-url', urlMode);
if (urlMode) {
// 站外没有本地记录可搜,直接让位给网址输入
idInput.type = 'text';
idInput.removeAttribute('inputmode');
idInput.removeAttribute('pattern');
idInput.value = '';
idInput.placeholder = 'https://example.com/post';
searchRow.hidden = true;
searchInput.value = '';
modal.querySelector('#nq-results').innerHTML = '';
} else {
idInput.type = 'text';
idInput.setAttribute('inputmode', 'numeric');
idInput.setAttribute('pattern', '[0-9]*');
idInput.placeholder = '例如 12';
searchRow.hidden = false;
searchInput.placeholder = kind.placeholder;
if (isUrl(idInput.value)) {
idInput.value = '';
}
if (searchInput.value.trim() !== '') {
search(searchInput.value);
} else {
modal.querySelector('#nq-results').innerHTML = '';
}
}
if (idLabel) {
idLabel.textContent = kind.field;
}
syncPreview();
}
/* ---------- 预览:已选几条就预览几条 ---------- */
function previewUrl(kind, id) {
if (isUrlKind(kind)) {
return withQuery(indexUrl(), 'NiceQuote=url&qurl=' + encodeURIComponent(id));
}
return withQuery(indexUrl(), 'NiceQuote=' + kindOf(kind).base + '&qid=' + id);
}
function previewKey(kind, id) {
return kind + '-' + id;
}
function hasPick(kind, id) {
for (var i = 0; i < state.picked.length; i++) {
if (state.picked[i].kind === kind && state.picked[i].id === id) {
return true;
}
}
return false;
}
/**
* 右侧要预览的条目
*
* 已选列表里的每一条都算一个;ID 框里还没点「添加」的,也顺带给一个虚线预览,
* 这样边填边看,不用先加进列表。
*/
function previewEntries() {
var entries = [];
state.picked.forEach(function (item, index) {
entries.push({
key: previewKey(item.kind, item.id),
kind: item.kind,
id: item.id,
title: item.title || (isUrlKind(item.kind) ? item.id : '#' + item.id),
no: index + 1,
index: index
});
});
var input = state.mask.querySelector('#nq-id');
if (isUrlKind(state.kind)) {
var url = input.value.trim();
if (isUrl(url) && !hasPick('url', url)) {
entries.push({
key: previewKey('url', url),
kind: 'url',
id: url,
title: '待抓取标题',
no: entries.length + 1,
index: -1
});
}
return entries;
}
var draft = parseInt(input.value, 10);
if (draft > 0 && !hasPick(state.kind, draft)) {
entries.push({
key: previewKey(state.kind, draft),
kind: state.kind,
id: draft,
title: '待添加 #' + draft,
no: entries.length + 1,
index: -1
});
}
return entries;
}
function buildPreviewItem(entry) {
var box = el('div', 'nq-preview-item' + (entry.index < 0 ? ' is-draft' : ''));
box.setAttribute('data-key', entry.key);
var cap = el('div', 'nq-preview-cap');
cap.appendChild(el('span', 'nq-preview-no', String(entry.no)));
cap.appendChild(el('span', 'nq-preview-badge', kindOf(entry.kind).label));
cap.appendChild(el('span', 'nq-preview-title', entry.title));
box.appendChild(cap);
var frameBox = el('div', 'nq-preview');
var frame = el('iframe', '');
frame.title = 'NiceQuote 预览';
frame.setAttribute('scrolling', 'no');
frame.setAttribute('loading', 'lazy');
frame.src = previewUrl(entry.kind, entry.id);
frameBox.appendChild(frame);
box.appendChild(frameBox);
// 点预览块反向选中列表条目;草稿块(index = -1)没有对应条目,点了不动
box.addEventListener('click', function () {
var index = parseInt(box.getAttribute('data-index'), 10);
if (index >= 0) {
state.active = index;
renderPicked();
syncPreview();
}
});
return box;
}
/** 把预览列表对齐到已选列表(顺序、编号、当前项高亮都跟着走) */
function syncPreview() {
if (!state.mask) {
return;
}
var list = state.mask.querySelector('#nq-preview-list');
var cap = state.mask.querySelector('#nq-preview-cap');
if (!list || !cap) {
return;
}
var entries = previewEntries();
var keep = {};
entries.forEach(function (entry) {
keep[entry.key] = true;
});
// 先摘掉不再需要的
Array.prototype.slice.call(list.children).forEach(function (node) {
if (!keep[node.getAttribute('data-key')]) {
list.removeChild(node);
}
});
cap.textContent = entries.length
? '共 ' + entries.length + ' 条,点左侧条目高亮对应预览'
: '选中条目后在这里预览';
entries.forEach(function (entry, order) {
var node = state.frames[entry.key];
if (!node) {
node = buildPreviewItem(entry);
state.frames[entry.key] = node;
}
node.classList.toggle('is-on', entry.index >= 0 && entry.index === state.active);
node.classList.toggle('is-draft', entry.index < 0);
node.setAttribute('data-index', String(entry.index));
var no = node.querySelector('.nq-preview-no');
var title = node.querySelector('.nq-preview-title');
if (no) {
no.textContent = String(entry.no);
}
if (title && title.textContent !== entry.title) {
title.textContent = entry.title;
}
if (list.children[order] !== node) {
list.insertBefore(node, list.children[order] || null);
}
});
// 当前项滚进列表可视区
var on = list.querySelector('.nq-preview-item.is-on');
if (on && list.scrollHeight > list.clientHeight) {
var top = on.offsetTop - list.offsetTop;
var bottom = top + on.offsetHeight;
if (top < list.scrollTop) {
list.scrollTop = top - 4;
} else if (bottom > list.scrollTop + list.clientHeight) {
list.scrollTop = bottom - list.clientHeight + 4;
}
}
}
function debouncePreview() {
window.clearTimeout(state.timer);
state.timer = window.setTimeout(syncPreview, 420);
}
/* ---------- 已选列表 ---------- */
function addPick(kind, id, title) {
if (isUrlKind(kind)) {
id = String(id || '').trim();
if (!isUrl(id)) {
return false;
}
} else {
id = parseInt(id, 10);
if (!id || id < 1) {
return false;
}
}
for (var i = 0; i < state.picked.length; i++) {
if (state.picked[i].kind === kind && state.picked[i].id === id) {
flashChip(i);
return false;
}
}
state.picked.push({
kind: kind,
id: id,
title: title || (isUrlKind(kind) ? id : '#' + id)
});
state.active = state.picked.length - 1;
renderPicked();
syncPreview();
return true;
}
function removePick(index) {
state.picked.splice(index, 1);
if (state.active >= state.picked.length) {
state.active = state.picked.length - 1;
}
state.mask.querySelector('#nq-id').value = '';
renderPicked();
syncPreview();
}
function flashChip(index) {
var chip = state.mask.querySelector('.nq-chip[data-index="' + index + '"]');
if (!chip) {
return;
}
chip.classList.add('nq-flash');
window.setTimeout(function () {
chip.classList.remove('nq-flash');
}, 700);
}
function renderPicked() {
if (!state.mask) {
return;
}
var box = state.mask.querySelector('#nq-picked');
var count = state.mask.querySelector('#nq-count');
var ok = state.mask.querySelector('#nq-ok');
box.innerHTML = '';
count.textContent = state.picked.length ? '已选 ' + state.picked.length + ' 条' : '还没选';
if (!state.picked.length) {
box.appendChild(el('p', 'nq-empty', '点搜索结果,或填 ID / 粘贴网址后点「添加」,可以连续添加多条'));
}
state.picked.forEach(function (item, index) {
var chip = el('div', 'nq-chip' + (index === state.active ? ' is-on' : ''));
chip.setAttribute('data-index', String(index));
chip.appendChild(el('span', 'nq-chip-badge', kindOf(item.kind).label));
chip.appendChild(el('span', 'nq-chip-title', item.title));
var extra = chipId(item);
if ('' !== extra) {
chip.appendChild(el('span', 'nq-chip-id', extra));
}
var remove = el('button', 'nq-chip-x', '×');
remove.type = 'button';
remove.setAttribute('aria-label', '移除');
remove.addEventListener('click', function (event) {
event.stopPropagation();
removePick(index);
});
chip.appendChild(remove);
chip.addEventListener('click', function () {
state.active = index;
renderPicked();
syncPreview();
});
box.appendChild(chip);
});
ok.textContent = state.picked.length ? '插入 ' + state.picked.length + ' 条引用' : '插入引用';
ok.classList.toggle('is-idle', !state.picked.length);
// 选中项滚进可视区
var current = box.querySelector('.nq-chip.is-on');
if (current && current.scrollIntoView) {
current.scrollIntoView({ block: 'nearest' });
}
}
/** 手动填 ID 添加时,顺手查一下标题,查不到就先用 #ID */
function resolveTitle(kind, id) {
var url = withQuery(
indexUrl(),
'nqSearch=' + encodeURIComponent(String(id)) + '&nqKind=' + encodeURIComponent(kind)
);
fetch(url, { credentials: 'same-origin' })
.then(function (res) { return res.json(); })
.then(function (data) {
var items = data.items || [];
for (var i = 0; i < items.length; i++) {
if (parseInt(items[i].id, 10) === id && items[i].type === kind) {
for (var j = 0; j < state.picked.length; j++) {
if (state.picked[j].kind === kind && state.picked[j].id === id) {
state.picked[j].title = items[i].title;
renderPicked();
syncPreview();
return;
}
}
return;
}
}
})
.catch(function () {});
}
/** 外部链接:抓一次标题摘要,回来就换掉「待抓取标题」 */
function resolveUrlTitle(url) {
var endpoint = withQuery(indexUrl(), 'nqUrl=' + encodeURIComponent(url));
fetch(endpoint, { credentials: 'same-origin' })
.then(function (res) { return res.json(); })
.then(function (data) {
if (!data || !data.title) {
return;
}
for (var i = 0; i < state.picked.length; i++) {
if (state.picked[i].kind === 'url' && state.picked[i].id === url) {
state.picked[i].title = data.title;
renderPicked();
syncPreview();
return;
}
}
})
.catch(function () {});
}
/* ---------- 搜索 ---------- */
function renderResults(items) {
if (!state.mask) {
return;
}
var box = state.mask.querySelector('#nq-results');
box.innerHTML = '';
if (!items.length) {
box.appendChild(el('p', 'nq-empty', '没有匹配结果,可以直接填 ID'));
return;
}
items.forEach(function (item) {
var row = el('button', 'nq-result');
row.type = 'button';
row.title = item.title;
row.appendChild(el('span', 'nq-result-title', item.title));
// 右侧竖排:日期在上、类型在下;分类 / 标签没有时间,只留类型
var meta = el('span', 'nq-result-meta');
if (item.date) {
meta.appendChild(el('span', 'nq-result-date', item.date));
}
meta.appendChild(el('span', 'nq-result-extra', item.extra || ''));
row.appendChild(meta);
row.addEventListener('click', function () {
addPick(item.type, item.id, item.title);
state.mask.querySelector('#nq-search').value = '';
state.mask.querySelector('#nq-results').innerHTML = '';
state.mask.querySelector('#nq-search').focus();
});
box.appendChild(row);
});
}
function search(keyword) {
if (!state.mask) {
return;
}
// 外部链接没有站内记录可搜
if (isUrlKind(state.kind)) {
return;
}
keyword = keyword.trim();
if (!keyword) {
state.mask.querySelector('#nq-results').innerHTML = '';
return;
}
var url = withQuery(
indexUrl(),
'nqSearch=' + encodeURIComponent(keyword) + '&nqKind=' + encodeURIComponent(state.kind)
);
fetch(url, { credentials: 'same-origin' })
.then(function (res) { return res.json(); })
.then(function (data) { renderResults(data.items || []); })
.catch(function () {
if (state.mask) {
state.mask.querySelector('#nq-results').innerHTML = '';
}
});
}
/* ---------- 构建弹窗 ---------- */
function open() {
if (state.mask) {
return;
}
state.picked = [];
state.active = -1;
var mask = el('div', 'nq-mask ' + (isDark() ? 'nq-dark' : 'nq-light'));
var modal = el('div', 'nq-modal nq-modal-wide');
modal.setAttribute('role', 'dialog');
modal.setAttribute('aria-modal', 'true');
modal.setAttribute('aria-label', '插入 NiceQuote 引用');
var head = el('div', 'nq-modal-head');
head.appendChild(el('strong', '', '插入引用'));
var count = el('span', 'nq-count', '还没选');
count.id = 'nq-count';
head.appendChild(count);
var close = el('button', 'nq-x', '×');
close.type = 'button';
close.setAttribute('aria-label', '关闭');
close.addEventListener('click', destroy);
head.appendChild(close);
var body = el('div', 'nq-modal-body nq-split');
var main = el('div', 'nq-col-main');
var side = el('div', 'nq-col-side');
// 类型:不再写「引用类型」四个字,直接摆选项
var typeRow = el('div', 'nq-row nq-row-kind');
var kinds = el('div', 'nq-kinds');
KINDS.forEach(function (item) {
var button = el('button', 'nq-kind' + (item.value === state.kind ? ' is-on' : ''));
button.type = 'button';
button.setAttribute('data-kind', item.value);
button.innerHTML = item.icon;
button.appendChild(el('span', 'nq-kind-name', item.label));
button.addEventListener('click', function () { setKind(item.value); });
kinds.appendChild(button);
});
typeRow.appendChild(kinds);
main.appendChild(typeRow);
// 搜索
var searchRow = el('div', 'nq-row');
searchRow.id = 'nq-search-row';
searchRow.appendChild(el('label', 'nq-label', '搜索'));
var searchInput = el('input', 'nq-input');
searchInput.id = 'nq-search';
searchInput.type = 'search';
searchInput.placeholder = kindOf(state.kind).placeholder;
searchInput.autocomplete = 'off';
searchInput.addEventListener('input', function () {
var value = searchInput.value;
window.clearTimeout(state.searchTimer);
state.searchTimer = window.setTimeout(function () { search(value); }, 380);
});
searchRow.appendChild(searchInput);
var results = el('div', 'nq-results');
results.id = 'nq-results';
searchRow.appendChild(results);
main.appendChild(searchRow);
// ID:标题已经把类型、ID 名和短码合成一句,下面只留输入框和「添加」
var idRow = el('div', 'nq-row');
var idLabel = el('label', 'nq-label nq-idlabel', kindOf(state.kind).field);
idLabel.id = 'nq-idlabel';
idLabel.setAttribute('for', 'nq-id');
idRow.appendChild(idLabel);
var idLine = el('div', 'nq-idline');
var idInput = el('input', 'nq-input');
idInput.id = 'nq-id';
idInput.type = 'text';
idInput.setAttribute('inputmode', 'numeric');
idInput.setAttribute('pattern', '[0-9]*');
idInput.placeholder = '例如 12';
idInput.autocomplete = 'off';
idInput.addEventListener('input', function () {
// 用 text 是为了不带右侧那对加减按钮,这里自己把非数字挡掉
if (!isUrlKind(state.kind)) {
var digits = idInput.value.replace(/[^\d]/g, '');
if (digits !== idInput.value) {
idInput.value = digits;
}
}
debouncePreview();
});
idInput.addEventListener('keydown', function (event) {
if (event.key === 'Enter') {
event.preventDefault();
addById();
}
});
idLine.appendChild(idInput);
var addButton = el('button', 'nq-btn nq-add', '添加');
addButton.type = 'button';
addButton.addEventListener('click', addById);
idLine.appendChild(addButton);
idRow.appendChild(idLine);
main.appendChild(idRow);
// 已选
var pickRow = el('div', 'nq-row nq-row-pick');
pickRow.appendChild(el('label', 'nq-label', '已选引用'));
var picked = el('div', 'nq-picked');
picked.id = 'nq-picked';
pickRow.appendChild(picked);
main.appendChild(pickRow);
// 预览:已选几条就并排/堆叠预览几条
var sideHead = el('label', 'nq-label', '预览');
var sideCap = el('span', 'nq-preview-hint', '');
sideCap.id = 'nq-preview-cap';
sideHead.appendChild(sideCap);
side.appendChild(sideHead);
var previewList = el('div', 'nq-preview-list');
previewList.id = 'nq-preview-list';
side.appendChild(previewList);
side.appendChild(el('p', 'nq-preview-empty', '选好类型、搜到内容或填上 ID / 网址,右边就会跟着显示卡片效果'));
body.appendChild(main);
body.appendChild(side);
// 底部
var foot = el('div', 'nq-modal-foot');
if (CFG.panel) {
var manage = el('a', 'nq-foot-link', '引用管理');
manage.href = CFG.panel;
manage.target = '_blank';
manage.rel = 'noopener';
foot.appendChild(manage);
}
var cancel = el('button', 'nq-btn', '取消');
cancel.type = 'button';
cancel.addEventListener('click', destroy);
var ok = el('button', 'nq-btn nq-primary is-idle', '插入引用');
ok.type = 'button';
ok.id = 'nq-ok';
ok.addEventListener('click', submit);
foot.appendChild(cancel);
foot.appendChild(ok);
modal.appendChild(head);
modal.appendChild(body);
modal.appendChild(foot);
mask.appendChild(modal);
mask.addEventListener('mousedown', function (event) {
if (event.target === mask) {
destroy();
}
});
document.body.appendChild(mask);
document.body.style.overflow = 'hidden';
document.addEventListener('keydown', onKeydown);
state.mask = mask;
renderPicked();
syncPreview();
window.setTimeout(function () {
modal.querySelector('#nq-search').focus();
}, 30);
}
function shake(node) {
if (!node) {
return;
}
node.classList.add('nq-shake');
window.setTimeout(function () { node.classList.remove('nq-shake'); }, 420);
node.focus();
}
/** 用输入框里的值添加一条 */
function addById() {
if (!state.mask) {
return;
}
var input = state.mask.querySelector('#nq-id');
if (isUrlKind(state.kind)) {
var url = input.value.trim();
if (!isUrl(url)) {
shake(input);
return;
}
if (addPick('url', url, '待抓取标题')) {
resolveUrlTitle(url);
}
input.value = '';
input.focus();
syncPreview();
return;
}
var id = parseInt(input.value, 10);
if (!id || id < 1) {
shake(input);
return;
}
addPick(state.kind, id, '#' + id);
resolveTitle(state.kind, id);
input.value = '';
input.focus();
syncPreview();
}
function submit() {
if (!state.mask) {
return;
}
if (!state.picked.length) {
var box = state.mask.querySelector('#nq-picked');
box.classList.add('nq-shake');
window.setTimeout(function () { box.classList.remove('nq-shake'); }, 420);
state.mask.querySelector('#nq-search').focus();
return;
}
var lines = state.picked.map(function (item) {
return buildShortcode(item.kind, item.id);
});
if (insertBlock(lines.join('\n'))) {
destroy();
}
}
/* ---------- 工具栏按钮 ---------- */
var BUTTON_ICON = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none"'
+ ' stroke="currentColor" stroke-width="1.7" stroke-linecap="round"'
+ ' stroke-linejoin="round" aria-hidden="true" focusable="false">'
+ '<path d="M10.6 13.4a3.9 3.9 0 0 0 5.5 0l2.3-2.3a3.9 3.9 0 0 0-5.5-5.5l-1.3 1.3"/>'
+ '<path d="M13.4 10.6a3.9 3.9 0 0 0-5.5 0l-2.3 2.3a3.9 3.9 0 0 0 5.5 5.5l1.3-1.3"/>'
+ '</svg>';
/**
* 计算插入位置:图标组最后一个按钮之后、主题追加的尾部队列之前
*
* riven 主题会把「发表」按钮和表情面板塞进 #wmd-button-row,
* 直接 append 就会跑到它们后面,被挤到第三行。
*/
function anchorNode(row) {
var nodes = row.children;
var anchor = null;
for (var i = nodes.length - 1; i >= 0; i--) {
var node = nodes[i];
if (node.id === 'nq-button') {
continue;
}
var isIcon = node.tagName === 'LI'
&& node.className.indexOf('wmd-button') !== -1
&& node.className.indexOf('wmd-spacer') === -1;
if (isIcon) {
break;
}
anchor = node;
}
return anchor;
}
function placeButton() {
var row = document.getElementById('wmd-button-row');
if (!row) {
return false;
}
var button = document.getElementById('nq-button');
if (!button) {
button = el('li', 'wmd-button');
button.id = 'nq-button';
button.title = '引用';
button.setAttribute('role', 'button');
button.setAttribute('tabindex', '0');
button.setAttribute('aria-label', '插入引用');
button.innerHTML = BUTTON_ICON;
button.addEventListener('click', open);
button.addEventListener('keydown', function (event) {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
open();
}
});
}
var anchor = anchorNode(row);
if (anchor) {
if (button.nextElementSibling !== anchor || button.parentNode !== row) {
row.insertBefore(button, anchor);
}
} else if (button.parentNode !== row || button.nextElementSibling) {
row.appendChild(button);
}
// 万一剩余空间不够被挤到下一行,自动收窄内边距再试一次
var prev = button.previousElementSibling;
if (prev && prev.offsetTop > 0 && button.offsetTop > prev.offsetTop) {
button.classList.add('nq-compact');
}
return true;
}
function fallbackButton() {
if (document.querySelector('.nq-fallback-bar')) {
return;
}
var textarea = document.getElementById('text');
if (!textarea) {
return;
}
var bar = el('div', 'nq-fallback-bar');
var button = el('button', 'nq-btn nq-primary', '插入引用');
button.type = 'button';
button.addEventListener('click', open);
bar.appendChild(button);
textarea.parentNode.insertBefore(bar, textarea);
}
function boot() {
if (placeButton()) {
// 主题/插件可能在 ready 之后再补按钮,补几次确保位置稳定
[120, 320, 700, 1200].forEach(function (delay) {
window.setTimeout(placeButton, delay);
});
return;
}
var tries = 0;
var timer = window.setInterval(function () {
tries++;
if (placeButton()) {
window.clearInterval(timer);
[320, 900].forEach(function (delay) {
window.setTimeout(placeButton, delay);
});
} else if (tries > 12) {
window.clearInterval(timer);
fallbackButton();
}
}, 100);
}
/* 预览 iframe 跟着卡片真实高度走,别把底部截掉 */
window.addEventListener('message', function (event) {
var data = event.data;
if (!data || !data.nqHeight) {
return;
}
var frames = document.querySelectorAll('.nq-preview iframe');
for (var i = 0; i < frames.length; i++) {
try {
if (frames[i].contentWindow === event.source) {
frames[i].style.height = (parseInt(data.nqHeight, 10) + 2) + 'px';
}
} catch (e) {
// 忽略跨域访问异常
}
}
});
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', boot);
} else {
boot();
}
})();