unvendor: Move formula rendering from core to extensions

This commit is contained in:
Cohee 2024-10-17 10:08:00 +00:00
parent 08324ba801
commit b6f9c6480b
24 changed files with 17 additions and 132 deletions

View File

@ -50,7 +50,6 @@ module.exports = {
},
// These scripts are loaded in HTML; tell ESLint not to complain about them being undefined
globals: {
showdownKatex: 'readonly',
toastr: 'readonly',
SillyTavern: 'readonly',
},

View File

@ -133,7 +133,6 @@
"auto_fix_generated_markdown": false,
"send_on_enter": 0,
"console_log_prompts": false,
"render_formulas": false,
"allow_name1_display": false,
"allow_name2_display": false,
"hotswap_enabled": true,

1
public/global.d.ts vendored
View File

@ -1,5 +1,4 @@
// Global namespace modules
declare var showdownKatex;
declare var ai;
declare var SillyTavern: {

View File

@ -4390,13 +4390,6 @@
<input id="auto_fix_generated_markdown" type="checkbox" />
<small data-i18n="Auto-fix Markdown">Auto-fix Markdown</small>
</label>
<label class="checkbox_label" for="render_formulas" title="Render LaTeX and AsciiMath equation notation in chat messages. Powered by KaTeX." data-i18n="[title]Render LaTeX and AsciiMath equation notation in chat messages. Powered by KaTeX">
<input id="render_formulas" type="checkbox" />
<small data-i18n="Render Formulas">Render Formulas</small>
<a href="https://docs.sillytavern.app/usage/core-concepts/uicustomization/#formulas-rendering" class="notes-link" target="_blank">
<small class="fa-solid fa-circle-question note-link-small"></small>
</a>
</label>
<label class="checkbox_label" for="forbid_external_media" title="Disallow embedded media from other domains in chat messages." data-i18n="[title]Disallow embedded media from other domains in chat messages">
<input id="forbid_external_media" type="checkbox" />
<small data-i18n="Forbid External Media">Forbid External Media</small>
@ -6745,7 +6738,6 @@
<script src="lib/jquery.transit.min.js"></script>
<script src="lib/jquery-cookie-1.4.1.min.js"></script>
<script src="lib/jquery.ui.touch-punch.min.js"></script>
<script src="lib/showdown-katex.min.js"></script>
<script src="lib/cropper.min.js"></script>
<script src="lib/jquery-cropper.min.js"></script>
<script src="lib/toastr.min.js"></script>

View File

@ -16,8 +16,6 @@
"scripts/extensions/quick-reply/lib/**"
],
"typeAcquisition": {
"include": [
"showdown-katex"
]
"include": []
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -694,8 +694,6 @@
"Auto-save Message Edits": "حفظ التعديلات التلقائي للرسائل",
"Confirm message deletion": "تأكيد حذف الرسالة",
"Auto-fix Markdown": "إصلاح Markdown تلقائيًا",
"Render LaTeX and AsciiMath equation notation in chat messages. Powered by KaTeX": "تقديم علامة LaTeX و AsciiMath للمعادلات في رسائل الدردشة. مدعوم بواسطة KaTeX",
"Render Formulas": "تقديم الصيغ",
"Disallow embedded media from other domains in chat messages": "عدم السماح بالوسائط المضمنة من المجالات الأخرى في رسائل الدردشة.",
"Forbid External Media": "منع وسائط خارجية",
"Allow {{char}}: in bot messages": "السماح بـ {{char}}: في رسائل البوت",

View File

@ -694,8 +694,6 @@
"Auto-save Message Edits": "Nachrichtenänderungen automatisch speichern",
"Confirm message deletion": "Löschung der Nachricht bestätigen",
"Auto-fix Markdown": "Markdown automatisch reparieren",
"Render LaTeX and AsciiMath equation notation in chat messages. Powered by KaTeX": "Rendere LaTeX- und AsciiMath-Gleichungsnotation in Chat-Nachrichten. Unterstützt von KaTeX",
"Render Formulas": "Formeln rendern",
"Disallow embedded media from other domains in chat messages": "Eingebettete Medien von anderen Domänen in Chat-Nachrichten nicht zulassen.",
"Forbid External Media": "Externe Medien verbieten",
"Allow {{char}}: in bot messages": "Erlaube {{char}}: in Bot-Nachrichten",

View File

@ -694,8 +694,6 @@
"Auto-save Message Edits": "Guardar automáticamente las Ediciones de Mensajes",
"Confirm message deletion": "Confirmar eliminación de mensaje",
"Auto-fix Markdown": "Auto-corregir Markdown",
"Render LaTeX and AsciiMath equation notation in chat messages. Powered by KaTeX": "Renderizar notación de ecuaciones LaTeX y AsciiMath en mensajes de chat. Impulsado por KaTeX",
"Render Formulas": "Renderizar fórmulas",
"Disallow embedded media from other domains in chat messages": "No permitir medios incrustados de otros dominios en los mensajes de chat.",
"Forbid External Media": "Prohibir Medios Externos",
"Allow {{char}}: in bot messages": "Permitir {{char}}: en mensajes de bot",

View File

@ -694,8 +694,6 @@
"Auto-save Message Edits": "Sauvegarde automatique des modifications de message",
"Confirm message deletion": "Confirmer la suppression du message",
"Auto-fix Markdown": "Correction automatique du Markdown",
"Render LaTeX and AsciiMath equation notation in chat messages. Powered by KaTeX": "Rendre la notation d'équations LaTeX et AsciiMath dans les messages de discussion. Propulsé par KaTeX",
"Render Formulas": "Rendre les formules",
"Disallow embedded media from other domains in chat messages": "Interdire les médias intégrés provenant d'autres domaines dans les messages de discussion.",
"Forbid External Media": "Interdire les médias externes",
"Allow {{char}}: in bot messages": "Autoriser {{char}} : dans les messages du bot",

View File

@ -694,8 +694,6 @@
"Auto-save Message Edits": "Sjálfvirkur vistun skilaboðabreytinga",
"Confirm message deletion": "Staðfesta eyðingu skilaboða",
"Auto-fix Markdown": "Sjálfvirk lagfæring Markdown",
"Render LaTeX and AsciiMath equation notation in chat messages. Powered by KaTeX": "Gera LaTeX og AsciiMath jöfnutímanótur í spjall skilaboðum. Aflað af KaTeX",
"Render Formulas": "Render Formúlur",
"Disallow embedded media from other domains in chat messages": "Ekki leyfa innfellda miðla frá öðrum lénum í spjallskilaboðum.",
"Forbid External Media": "Banna ytri miðla",
"Allow {{char}}: in bot messages": "Leyfa {{char}}: í boðum botts",

View File

@ -694,8 +694,6 @@
"Auto-save Message Edits": "Salvataggio automatico delle modifiche ai messaggi",
"Confirm message deletion": "Conferma eliminazione messaggio",
"Auto-fix Markdown": "Correzione automatica di Markdown",
"Render LaTeX and AsciiMath equation notation in chat messages. Powered by KaTeX": "Rendi la notazione dell'equazione LaTeX e AsciiMath nei messaggi di chat. Alimentato da KaTeX",
"Render Formulas": "Renderizza formule",
"Disallow embedded media from other domains in chat messages": "Non consentire contenuti multimediali incorporati da altri domini nei messaggi di chat.",
"Forbid External Media": "Vietare i media esterni",
"Allow {{char}}: in bot messages": "Consenti {{char}}: nei messaggi del bot",

View File

@ -694,8 +694,6 @@
"Auto-save Message Edits": "メッセージ編集の自動保存",
"Confirm message deletion": "メッセージの削除を確認",
"Auto-fix Markdown": "Markdownの自動修正",
"Render LaTeX and AsciiMath equation notation in chat messages. Powered by KaTeX": "チャットメッセージでLaTeXおよびAsciiMathの数式表記をレンダリングします。KaTeXで動作します",
"Render Formulas": "数式のレンダリング",
"Disallow embedded media from other domains in chat messages": "チャットメッセージの他のドメインからの埋め込みメディアを禁止する",
"Forbid External Media": "外部メディアを禁止",
"Allow {{char}}: in bot messages": "ボットメッセージ内の{{char}}:を許可",

View File

@ -694,8 +694,6 @@
"Auto-save Message Edits": "메시지 편집 자동 저장",
"Confirm message deletion": "메시지 삭제 확인",
"Auto-fix Markdown": "Markdown 자동 수정",
"Render LaTeX and AsciiMath equation notation in chat messages. Powered by KaTeX": "채팅 메시지에서 LaTeX 및 AsciiMath 방정식 표기법을 렌더링합니다. KaTeX 제공",
"Render Formulas": "수식 렌더링",
"Disallow embedded media from other domains in chat messages": "채팅 메시지에 다른 도메인의 삽입된 미디어를 허용하지 않습니다.",
"Forbid External Media": "외부 미디어 금지",
"Allow {{char}}: in bot messages": "봇 메시지에서 {{char}}: 허용",

View File

@ -694,8 +694,6 @@
"Auto-save Message Edits": "Automatisch opslaan van berichtbewerkingen",
"Confirm message deletion": "Bevestig bericht verwijdering",
"Auto-fix Markdown": "Automatisch repareren van Markdown",
"Render LaTeX and AsciiMath equation notation in chat messages. Powered by KaTeX": "LaTeX en AsciiMath-vergelijking notatie renderen in chatberichten. Aangedreven door KaTeX",
"Render Formulas": "Formules renderen",
"Disallow embedded media from other domains in chat messages": "Ingesloten media van andere domeinen niet toestaan in chatberichten.",
"Forbid External Media": "Externe media verbieden",
"Allow {{char}}: in bot messages": "Toestaan {{char}}: in botberichten",

View File

@ -694,8 +694,6 @@
"Auto-save Message Edits": "Salvar automaticamente Edições de Mensagem",
"Confirm message deletion": "Confirmar exclusão de mensagem",
"Auto-fix Markdown": "Corrigir Markdown automaticamente",
"Render LaTeX and AsciiMath equation notation in chat messages. Powered by KaTeX": "Renderizar notação de equações LaTeX e AsciiMath em mensagens de chat. Alimentado por KaTeX",
"Render Formulas": "Renderizar Fórmulas",
"Disallow embedded media from other domains in chat messages": "Proibir mídia incorporada de outros domínios em mensagens de bate-papo.",
"Forbid External Media": "Proibir Mídia Externa",
"Allow {{char}}: in bot messages": "Permitir {{char}}: em mensagens de bot",

View File

@ -241,7 +241,6 @@
"Auto-save Message Edits": "Автоматически сохранять отредактированные сообщения",
"Auto-fix Markdown": "Автоисправление разметки",
"Auto-scroll Chat": "Автоматическая прокрутка чата",
"Render Formulas": "Рендер формул",
"Send on Enter": "Отправка на Enter",
"Debug Menu": "Меню отладки",
"Restore User Input": "Восстанавливать введённый текст",
@ -423,7 +422,6 @@
"Show arrow buttons on the last in-chat message to generate alternative AI responses. Both PC and mobile": "Показывать кнопки со стрелками на последнем сообщении в чате, чтобы генерировать альтернативные ответы ИИ. Как для ПК, так и для мобильных устройств.",
"Allow using swiping gestures on the last in-chat message to trigger swipe generation. Mobile only, no effect on PC": "Позволяет использовать жесты смахивания на последнем сообщении в чате, чтобы вызвать альтернативную генерацию. Только для мобильных устройств, на ПК не работает.",
"Save edits to messages without confirmation as you type": "Сохранять правки в сообщениях без подтверждения по мере ввода текста.",
"Render LaTeX and AsciiMath equation notation in chat messages. Powered by KaTeX": "Отображение нотации уравнений LaTeX и AsciiMath в сообщениях чата. При поддержке KaTeX.",
"Skip encoding and characters in message text, allowing a subset of HTML markup as well as Markdown": "Не кодировать символы < и > в тексте сообщения, что позволяет использовать подмножество HTML-разметки, а также Markdown.",
"Allow AI messages in groups to contain lines spoken by other group members": "Разрешить ИИ в группах генерировать строчки за других участников группы в своих сообщениях.",
"Requests logprobs from the API for the Token Probabilities feature": "Запросить логпробы из API для функции Token Probabilities.",

View File

@ -694,8 +694,6 @@
"Auto-save Message Edits": "Автоматичне збереження редагувань повідомлень",
"Confirm message deletion": "Підтвердити видалення повідомлення",
"Auto-fix Markdown": "Автоматичне виправлення Markdown",
"Render LaTeX and AsciiMath equation notation in chat messages. Powered by KaTeX": "Відображати формул LaTeX та AsciiMath у повідомленнях чату. Працює на основі KaTeX",
"Render Formulas": "Відображення формул",
"Disallow embedded media from other domains in chat messages": "Заборонити вбудовані мультимедійні дані з інших доменів у повідомленнях чату.",
"Forbid External Media": "Заборонити зовнішні медіа",
"Allow {{char}}: in bot messages": "Дозволити {{char}}: у повідомленнях бота",

View File

@ -694,8 +694,6 @@
"Auto-save Message Edits": "Tự động lưu Sửa Tin nhắn",
"Confirm message deletion": "Xác nhận xóa tin nhắn",
"Auto-fix Markdown": "Tự động sửa Markdown",
"Render LaTeX and AsciiMath equation notation in chat messages. Powered by KaTeX": "Kết xuất ký hiệu phương trình LaTeX và AsciiMath trong tin nhắn trò chuyện. Được cung cấp bởi KaTeX",
"Render Formulas": "Hiển thị Công thức",
"Disallow embedded media from other domains in chat messages": "Không cho phép nhúng phương tiện từ các miền khác vào tin nhắn trò chuyện.",
"Forbid External Media": "Cấm Phương tiện Ngoại tuyến",
"Allow {{char}}: in bot messages": "Cho phép {{char}}: trong các Tin nhắn Bot",

View File

@ -733,8 +733,6 @@
"Auto-save Message Edits": "自动保存消息编辑",
"Confirm message deletion": "删除消息前确认",
"Auto-fix Markdown": "自动修复 Markdown",
"Render LaTeX and AsciiMath equation notation in chat messages. Powered by KaTeX": "在聊天消息中渲染LaTeX和AsciiMath方程式符号。由KaTeX提供支持",
"Render Formulas": "渲染公式",
"Disallow embedded media from other domains in chat messages": "禁止在聊天消息中嵌入来自其他域的媒体。",
"Forbid External Media": "禁止外部媒体",
"Allow {{char}}: in bot messages": "在机器人消息中允许 {{char}}: ",

View File

@ -695,8 +695,6 @@
"Auto-save Message Edits": "自動儲存編輯的訊息",
"Confirm message deletion": "確認刪除訊息",
"Auto-fix Markdown": "自動修正 Markdown",
"Render LaTeX and AsciiMath equation notation in chat messages. Powered by KaTeX": "在聊天訊息中算繪 LaTeX 和 AsciiMath 方程式標記。由 KaTeX 提供支援。",
"Render Formulas": "算繪公式",
"Disallow embedded media from other domains in chat messages": "禁止在聊天訊息中嵌入來自其他領域的媒體。",
"Forbid External Media": "禁止使用外部媒體",
"Allow {{char}}: in bot messages": "允許機器人訊息中使用 {{char}}:",

View File

@ -508,7 +508,6 @@ console.debug('Character context menu initialized', characterContextMenu);
export let mesForShowdownParse; //intended to be used as a context to compare showdown strings against
/** @type {import('showdown').Converter} */
let converter;
reloadMarkdownProcessor();
// array for prompt token calculations
console.debug('initializing Prompt Itemization Array on Startup');
@ -758,48 +757,22 @@ async function getClientVersion() {
}
}
export function reloadMarkdownProcessor(render_formulas = false) {
if (render_formulas) {
converter = new showdown.Converter({
emoji: true,
underline: true,
tables: true,
parseImgDimensions: true,
simpleLineBreaks: true,
strikethrough: true,
disableForced4SpacesIndentedSublists: true,
extensions: [
showdownKatex(
{
delimiters: [
{ left: '$$', right: '$$', display: true, asciimath: false },
{ left: '$', right: '$', display: false, asciimath: true },
],
},
)],
});
}
else {
converter = new showdown.Converter({
emoji: true,
literalMidWordUnderscores: true,
parseImgDimensions: true,
tables: true,
underline: true,
simpleLineBreaks: true,
strikethrough: true,
disableForced4SpacesIndentedSublists: true,
extensions: [markdownUnderscoreExt()],
});
}
export function reloadMarkdownProcessor() {
converter = new showdown.Converter({
emoji: true,
literalMidWordUnderscores: true,
parseImgDimensions: true,
tables: true,
underline: true,
simpleLineBreaks: true,
strikethrough: true,
disableForced4SpacesIndentedSublists: true,
extensions: [markdownUnderscoreExt()],
});
// Inject the dinkus extension after creating the converter
// Maybe move this into power_user init?
setTimeout(() => {
if (power_user) {
converter.addExtension(markdownExclusionExt(), 'exclusion');
}
}, 1);
converter.addExtension(markdownExclusionExt(), 'exclusion');
return converter;
}
@ -958,6 +931,7 @@ async function firstLoadInit() {
initLibraryShims();
addShowdownPatch(showdown);
reloadMarkdownProcessor();
addSafariPatch();
await getClientVersion();
await readSecretState();

View File

@ -180,7 +180,6 @@ let power_user = {
console_log_prompts: false,
request_token_probabilities: false,
show_group_chat_queue: false,
render_formulas: false,
allow_name1_display: false,
allow_name2_display: false,
hotswap_enabled: true,
@ -1488,7 +1487,6 @@ async function loadPowerUserSettings(settings, data) {
$('#collapse-newlines-checkbox').prop('checked', power_user.collapse_newlines);
$('#always-force-name2-checkbox').prop('checked', power_user.always_force_name2);
$('#trim_sentences_checkbox').prop('checked', power_user.trim_sentences);
$('#render_formulas').prop('checked', power_user.render_formulas);
$('#disable_group_trimming').prop('checked', power_user.disable_group_trimming);
$('#markdown_escape_strings').val(power_user.markdown_escape_strings);
$('#fast_ui_mode').prop('checked', power_user.fast_ui_mode);
@ -1595,7 +1593,7 @@ async function loadPowerUserSettings(settings, data) {
$(`#character_sort_order option[data-order="${power_user.sort_order}"][data-field="${power_user.sort_field}"]`).prop('selected', true);
switchReducedMotion();
switchCompactInputArea();
reloadMarkdownProcessor(power_user.render_formulas);
reloadMarkdownProcessor();
await loadInstructMode(data);
await loadContextSettings();
await loadSystemPrompts(data);
@ -3067,7 +3065,7 @@ $(document).ready(() => {
$('#markdown_escape_strings').on('input', function () {
power_user.markdown_escape_strings = String($(this).val());
saveSettingsDebounced();
reloadMarkdownProcessor(power_user.render_formulas);
reloadMarkdownProcessor();
});
$('#start_reply_with').on('input', function () {
@ -3419,13 +3417,6 @@ $(document).ready(() => {
saveSettingsDebounced();
});
$('#render_formulas').on('input', function () {
power_user.render_formulas = !!$(this).prop('checked');
reloadMarkdownProcessor(power_user.render_formulas);
reloadCurrentChat();
saveSettingsDebounced();
});
$('#reload_chat').on('click', async function () {
const currentChatId = getCurrentChatId();
if (currentChatId !== undefined && currentChatId !== null) {