diff --git a/main/recipes/forms.py b/main/recipes/forms.py index 28a004e..e4d7c0b 100644 --- a/main/recipes/forms.py +++ b/main/recipes/forms.py @@ -4,10 +4,11 @@ from django.core.files.uploadedfile import UploadedFile from PIL import Image, UnidentifiedImageError from food.models import FoodProduct -from .models import Recipe, RecipeIngredient +from .models import Recipe, RecipeIngredient, RecipeSubrecipe class RecipeForm(forms.ModelForm): + markdown_revision = forms.IntegerField(min_value=0, widget=forms.HiddenInput) tags_text = forms.CharField(required=False, label='Tags', help_text='Separate tags with commas.') remove_photo = forms.BooleanField(required=False, label='Remove current photo') @@ -32,6 +33,7 @@ class RecipeForm(forms.ModelForm): def __init__(self, *args, user, **kwargs): super().__init__(*args, **kwargs) + self.fields['markdown_revision'].initial = self.instance.markdown_revision self.fields['parent'].queryset = Recipe.objects.filter(owner=user).exclude(pk=self.instance.pk) if self.instance.pk: self.fields['tags_text'].initial = ', '.join(self.instance.tags) @@ -94,3 +96,27 @@ RecipeIngredientFormSet = inlineformset_factory( Recipe, RecipeIngredient, form=RecipeIngredientForm, formset=OwnedIngredientFormSet, extra=2, can_delete=True, ) + + +class RecipeSubrecipeForm(forms.ModelForm): + class Meta: + model = RecipeSubrecipe + fields = ('component', 'quantity', 'unit', 'note', 'display_order') + widgets = {'quantity': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}), + 'display_order': forms.NumberInput(attrs={'min': 0})} + + +class OwnedSubrecipeFormSet(BaseInlineFormSet): + def __init__(self, *args, user, **kwargs): + self.user = user + super().__init__(*args, **kwargs) + + def add_fields(self, form, index): + super().add_fields(form, index) + form.fields['component'].queryset = Recipe.objects.filter(owner=self.user).exclude(pk=self.instance.pk) + + +RecipeSubrecipeFormSet = inlineformset_factory( + Recipe, RecipeSubrecipe, form=RecipeSubrecipeForm, + formset=OwnedSubrecipeFormSet, fk_name='recipe', extra=1, can_delete=True, +) diff --git a/main/recipes/migrations/0002_recipe_markdown_revision.py b/main/recipes/migrations/0002_recipe_markdown_revision.py new file mode 100644 index 0000000..9cd1cb1 --- /dev/null +++ b/main/recipes/migrations/0002_recipe_markdown_revision.py @@ -0,0 +1,18 @@ +# Generated by Django 6.1.1 on 2026-10-11 23:40 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('recipes', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='recipe', + name='markdown_revision', + field=models.PositiveIntegerField(default=0), + ), + ] diff --git a/main/recipes/models.py b/main/recipes/models.py index 12679cd..18a799a 100644 --- a/main/recipes/models.py +++ b/main/recipes/models.py @@ -22,6 +22,7 @@ class Recipe(models.Model): description = models.TextField(blank=True) instructions_markdown = models.TextField(blank=True) notes_markdown = models.TextField(blank=True) + markdown_revision = models.PositiveIntegerField(default=0) photo = models.ImageField(upload_to='recipes/%Y/%m/', blank=True) preparation_minutes = models.PositiveIntegerField(default=0) cooking_minutes = models.PositiveIntegerField(default=0) diff --git a/main/recipes/static/recipes/editor-adapter.js b/main/recipes/static/recipes/editor-adapter.js new file mode 100644 index 0000000..9f57759 --- /dev/null +++ b/main/recipes/static/recipes/editor-adapter.js @@ -0,0 +1,51 @@ +/* Keep the rest of the recipe form independent of TOAST UI's API. */ +(() => { + window.createMarkdownEditor = (element, options = {}) => { + const editor = new toastui.Editor({ + el: element, + height: options.height || '340px', + initialEditType: 'wysiwyg', + previewStyle: window.matchMedia('(max-width: 767px)').matches ? 'tab' : 'vertical', + initialValue: options.value || '', + usageStatistics: false, + toolbarItems: [ + ['heading', 'bold', 'italic', 'strike'], + ['hr', 'quote'], + ['ul', 'ol', 'task'], + ['link', 'code', 'codeblock'], + ], + }); + const name = element.getAttribute('aria-label') || 'Markdown editor'; + const labelInputs = () => { + element.querySelectorAll('[contenteditable="true"], .CodeMirror textarea').forEach((input) => { + input.setAttribute('aria-label', name); + }); + element.querySelectorAll('.toastui-editor-mode-switch .tab-item, .toastui-editor-md-tab-container .tab-item').forEach((tab) => { + tab.removeAttribute('aria-role'); + tab.removeAttribute('aria-selected'); + tab.setAttribute('role', 'button'); + tab.setAttribute('tabindex', '0'); + tab.setAttribute('aria-pressed', String(tab.classList.contains('active'))); + if (!tab.dataset.keyboardReady) { + tab.dataset.keyboardReady = 'true'; + tab.addEventListener('keydown', (event) => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault(); + tab.click(); + } + }); + } + }); + }; + labelInputs(); + const observer = new MutationObserver(labelInputs); + observer.observe(element, {childList: true, subtree: true, attributes: true, + attributeFilter: ['class']}); + return { + getMarkdown: () => editor.getMarkdown(), + setMarkdown: (value) => editor.setMarkdown(value), + onChange: (callback) => editor.on('change', callback), + destroy: () => { observer.disconnect(); editor.destroy(); }, + }; + }; +})(); diff --git a/main/recipes/static/recipes/form.js b/main/recipes/static/recipes/form.js index 011368d..3d9e6a6 100644 --- a/main/recipes/static/recipes/form.js +++ b/main/recipes/static/recipes/form.js @@ -1,17 +1,156 @@ (() => { - const button = document.querySelector('[data-add-ingredient]'); - const container = document.querySelector('[data-ingredient-forms]'); - const template = document.querySelector('#recipe-empty-ingredient'); - const total = document.querySelector('#id_ingredients-TOTAL_FORMS'); - if (!button || !container || !template || !total) return; - button.addEventListener('click', () => { - const index = Number(total.value); - const wrapper = document.createElement('div'); - wrapper.innerHTML = template.innerHTML.replaceAll('__prefix__', String(index)); - const row = wrapper.firstElementChild; - if (!row) return; - container.appendChild(row); - total.value = String(index + 1); - row.querySelector('input[name$="-name"]')?.focus(); + const form = document.querySelector('[data-recipe-form]'); + if (!form) return; + + const addRow = (buttonSelector, containerSelector, templateSelector, totalSelector, focusSelector) => { + const button = form.querySelector(buttonSelector); + const container = form.querySelector(containerSelector); + const template = document.querySelector(templateSelector); + const total = form.querySelector(totalSelector); + if (!button || !container || !template || !total) return; + button.addEventListener('click', () => { + const wrapper = document.createElement('div'); + wrapper.innerHTML = template.innerHTML.replaceAll('__prefix__', total.value); + const row = wrapper.firstElementChild; + if (!row) return; + container.appendChild(row); + total.value = String(Number(total.value) + 1); + row.querySelector(focusSelector)?.focus(); + }); + }; + addRow('[data-add-ingredient]', '[data-ingredient-forms]', '#recipe-empty-ingredient', + '#id_ingredients-TOTAL_FORMS', 'input[name$="-name"]'); + addRow('[data-add-subrecipe]', '[data-subrecipe-forms]', '#recipe-empty-subrecipe', + '#id_subrecipes-TOTAL_FORMS', 'select[name$="-component"]'); + + const status = form.querySelector('[data-save-status]'); + const revision = form.querySelector('#id_markdown_revision'); + const editors = []; + let markdownDirty = false; + let formDirty = false; + let saving = false; + let submitting = false; + let failed = false; + let timer; + let changeNumber = 0; + + const report = (message, state) => { + if (!status) return; + status.textContent = message; + status.dataset.state = state; + }; + const sync = () => { + editors.forEach(({ field, editor }) => { field.value = editor.getMarkdown(); }); + }; + const schedule = () => { + clearTimeout(timer); + if (form.dataset.autosaveUrl && !saving && !failed) timer = setTimeout(save, 900); + }; + const save = async () => { + if (!markdownDirty || saving || !form.dataset.autosaveUrl) return; + if (!form.elements.title.value.trim()) { + report('Add a title to start autosave.', 'unsaved'); + return; + } + sync(); + const submittedChange = changeNumber; + const body = { + revision: Number(revision.value), + title: form.elements.title.value, + instructions_markdown: form.elements.instructions_markdown.value, + notes_markdown: form.elements.notes_markdown.value, + }; + if (form.dataset.draftId) body.draft_id = form.dataset.draftId; + saving = true; + report('Saving…', 'saving'); + try { + const response = await fetch(form.dataset.autosaveUrl, { + method: 'POST', + headers: {'Content-Type': 'application/json', 'X-CSRFToken': form.elements.csrfmiddlewaretoken.value}, + body: JSON.stringify(body), + credentials: 'same-origin', + }); + const result = await response.json(); + if (!response.ok) throw new Error(result.error || 'Could not save. Try again.'); + revision.value = result.revision; + if (result.edit_url) { + form.action = result.edit_url; + form.dataset.autosaveUrl = result.autosave_url; + delete form.dataset.draftId; + form.elements.draft_id?.remove(); + window.history.replaceState(null, '', result.edit_url); + const heading = document.querySelector('.recipes-form-header h1'); + if (heading) heading.textContent = 'Edit recipe'; + document.title = `Edit ${body.title} · Tasknest`; + } + markdownDirty = changeNumber !== submittedChange; + failed = false; + report(markdownDirty || formDirty ? 'Unsaved changes' : 'Saved', markdownDirty || formDirty ? 'unsaved' : 'saved'); + } catch (error) { + failed = true; + report(error.message || 'Could not save. Try again.', 'error'); + } finally { + saving = false; + if (markdownDirty && !failed) schedule(); + if (failed) submitting = false; + if (submitting && !failed) { + submitting = false; + form.requestSubmit(); + } + } + }; + + form.querySelectorAll('[data-markdown-editor]').forEach((host) => { + const field = form.elements[host.dataset.markdownEditor]; + if (!field || !window.createMarkdownEditor || !window.toastui?.Editor) return; + try { + const editor = window.createMarkdownEditor(host, {value: field.value, + height: host.dataset.markdownEditor === 'notes_markdown' ? '260px' : '360px'}); + field.hidden = true; + editors.push({field, editor}); + editor.onChange(() => { + if (editor.getMarkdown() === field.value) return; + changeNumber += 1; + markdownDirty = true; + failed = false; + report('Unsaved changes', 'unsaved'); + schedule(); + }); + } catch (error) { + host.hidden = true; + report('Editor unavailable. You can still edit Markdown in the text box.', 'error'); + } + }); + + const markOtherChange = (event) => { + if (event.target.closest('.toastui-editor-defaultUI') || event.target.matches('[hidden]')) return; + if (event.target.name === 'title') { + changeNumber += 1; + markdownDirty = true; + failed = false; + report('Unsaved changes', 'unsaved'); + schedule(); + return; + } + formDirty = true; + report('Unsaved changes', 'unsaved'); + }; + form.addEventListener('input', markOtherChange); + form.addEventListener('change', markOtherChange); + form.addEventListener('submit', (event) => { + clearTimeout(timer); + sync(); + if (saving) { + event.preventDefault(); + submitting = true; + return; + } + submitting = true; + }); + window.addEventListener('beforeunload', (event) => { + if (!submitting && (markdownDirty || formDirty || saving)) { + event.preventDefault(); + event.returnValue = ''; + } }); })(); diff --git a/main/recipes/static/recipes/recipes.css b/main/recipes/static/recipes/recipes.css index bcc2b17..64928e2 100644 --- a/main/recipes/static/recipes/recipes.css +++ b/main/recipes/static/recipes/recipes.css @@ -12,3 +12,8 @@ body[data-theme=dark] .recipes-layout{--recipe-surface:#222b25;--recipe-line:#43 @media(max-width:991px){.recipes-layout:not(.recipes-layout--form){grid-template-columns:minmax(0,1fr)}.recipes-browser,.recipes-detail,.recipes-info{grid-column:1}.recipes-list{grid-template-columns:repeat(2,minmax(0,1fr))}.recipes-hero{grid-template-columns:minmax(170px,38%) minmax(0,1fr)}.recipes-info{grid-template-columns:repeat(2,minmax(0,1fr))}.recipes-info .recipes-panel:last-child{grid-column:auto}} @media(max-width:767px){.page-content.recipes-page-content{padding-top:25px}.recipes-layout--list .recipes-detail,.recipes-layout--list .recipes-info{display:none}.recipes-layout--detail .recipes-browser{display:none}.recipes-browser__heading h1{font-size:2.4rem}.recipes-detail{padding:16px}.recipes-hero{grid-template-columns:1fr;gap:15px}.recipes-hero>img,.recipes-photo-placeholder{height:230px}.recipes-hero h2{font-size:2rem}.recipes-content-grid,.recipes-info{grid-template-columns:1fr}.recipes-list{grid-template-columns:1fr}.recipes-form-grid{grid-template-columns:1fr}.recipes-field--title,.recipes-field--description,.recipes-field--instructions_markdown,.recipes-field--notes_markdown,.recipes-field--photo,.recipes-field--remove_photo{grid-column:auto}.recipes-ingredient-form__main{grid-template-columns:minmax(0,1fr) minmax(90px,1fr)}.recipes-ingredient-form__main .recipes-field:first-child{grid-column:1/-1}.recipes-edit-card{padding:18px}.recipes-section-heading{align-items:flex-start;flex-wrap:wrap}.recipes-section-heading button{width:100%}} @media(max-width:400px){.recipes-browser__heading{display:block}.recipes-new{margin-top:12px}.recipes-filter-grid{grid-template-columns:1fr}.recipes-detail__top{flex-wrap:wrap}.recipes-ingredient-form__main{grid-template-columns:1fr 1fr}} +.recipes-markdown-source>*:first-child{margin-top:0}.recipes-markdown-source>*:last-child{margin-bottom:0}.recipes-markdown-source h1,.recipes-markdown-source h2,.recipes-markdown-source h3{line-height:1.3}.recipes-markdown-source h1{font-size:1.35rem}.recipes-markdown-source h2{font-size:1.2rem}.recipes-markdown-source h3{font-size:1.05rem}.recipes-markdown-source ul,.recipes-markdown-source ol{padding-left:1.3rem}.recipes-markdown-source li{margin:.3rem 0}.recipes-markdown-source a{color:var(--recipe-accent);text-decoration:underline}.recipes-markdown-source blockquote{margin:1rem 0;padding:.2rem 0 .2rem 1rem;border-left:3px solid var(--recipe-accent);color:var(--recipe-muted)}.recipes-markdown-source pre{max-width:100%;overflow:auto;padding:.8rem;border-radius:8px;background:var(--recipe-soft)}.recipes-markdown-source code{overflow-wrap:anywhere}.recipes-markdown-source input[type=checkbox]{margin-right:.45rem;accent-color:var(--recipe-accent)} +.recipes-field [hidden],.recipes-markdown-editor[hidden]{display:none!important}.recipes-markdown-editor{max-width:100%;min-width:0}.recipes-markdown-editor .toastui-editor-defaultUI{border-color:var(--recipe-line);border-radius:9px;overflow:hidden}.recipes-markdown-editor .toastui-editor-defaultUI-toolbar,.recipes-markdown-editor .toastui-editor-mode-switch{background:var(--recipe-soft)}.recipes-markdown-editor .toastui-editor-defaultUI button:focus-visible,.recipes-markdown-editor .toastui-editor-defaultUI .tab-item:focus-visible{outline:3px solid #77b68b;outline-offset:2px}.recipes-save-status{margin-left:auto;color:var(--recipe-muted);font-size:.8rem}.recipes-save-status[data-state=unsaved]{color:#a86a1e}.recipes-save-status[data-state=error]{color:#b6413b}.recipes-save-status[data-state=saving]{color:var(--recipe-accent)}.recipes-action-form{margin:0}.recipes-action-form button{width:100%;border:0;border-bottom:1px solid var(--recipe-line);background:none;color:inherit;text-align:left;cursor:pointer}.recipes-action-form button:hover{color:var(--recipe-accent)} +body[data-theme=dark] .recipes-markdown-editor .toastui-editor-defaultUI,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-defaultUI-toolbar,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-mode-switch,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-main{border-color:var(--recipe-line);background:var(--recipe-surface);color:var(--recipe-ink)}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-md-container,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-ww-container,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-md-preview{background:var(--recipe-surface);color:var(--recipe-ink)}body[data-theme=dark] .recipes-markdown-editor .ProseMirror,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-contents,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-md-container .CodeMirror{color:var(--recipe-ink)}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-contents *{color:inherit}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-toolbar-icons{filter:invert(.85)}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-defaultUI-toolbar button:hover{background:#405347}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-mode-switch .tab-item{color:var(--recipe-muted)}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-mode-switch .tab-item.active{background:var(--recipe-surface);color:var(--recipe-ink)} +@media(max-width:767px){.recipes-markdown-editor .toastui-editor-defaultUI-toolbar{overflow-x:auto}.recipes-markdown-editor .toastui-editor-toolbar-group{flex:none}.recipes-form-actions{flex-wrap:wrap}.recipes-save-status{width:100%;margin-left:0}} +.recipes-related-component{padding:7px 0;border-top:1px solid var(--recipe-line)}.recipes-related-component summary{color:var(--recipe-accent);font-size:.79rem;cursor:pointer}.recipes-related-component .recipes-markdown-source{margin-top:9px;padding:9px;border-radius:8px;background:var(--recipe-soft)} diff --git a/main/recipes/static/recipes/vendor/LICENSE.toast-ui-editor b/main/recipes/static/recipes/vendor/LICENSE.toast-ui-editor new file mode 100644 index 0000000..dcb10d8 --- /dev/null +++ b/main/recipes/static/recipes/vendor/LICENSE.toast-ui-editor @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 NHN Cloud Corp. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/main/recipes/static/recipes/vendor/toastui-editor-all.min.js b/main/recipes/static/recipes/vendor/toastui-editor-all.min.js new file mode 100644 index 0000000..178581e --- /dev/null +++ b/main/recipes/static/recipes/vendor/toastui-editor-all.min.js @@ -0,0 +1,24 @@ +/*! + * @toast-ui/editor + * @version 3.2.2 | Fri Feb 17 2023 + * @author NHN Cloud FE Development Lab + * @license MIT + */ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.toastui=t():(e.toastui=e.toastui||{},e.toastui.Editor=t())}(self,(function(){return function(){var e={368:function(e){ +/*! @license DOMPurify 2.3.3 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.3.3/LICENSE */ +e.exports=function(){"use strict";function e(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t1?n-1:0),o=1;o/gm),q=a(/^data-[\-\w.\u00B7-\uFFFF]/),V=a(/^aria-[\-\w]+$/),j=a(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),$=a(/^(?:\w+script|data):/i),_=a(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),U="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};function W(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t0&&void 0!==arguments[0]?arguments[0]:J(),t=function(e){return K(e)};if(t.version="2.3.3",t.removed=[],!e||!e.document||9!==e.document.nodeType)return t.isSupported=!1,t;var n=e.document,r=e.document,o=e.DocumentFragment,i=e.HTMLTemplateElement,a=e.Node,l=e.Element,c=e.NodeFilter,u=e.NamedNodeMap,d=void 0===u?e.NamedNodeMap||e.MozNamedAttrMap:u,x=e.Text,C=e.Comment,Z=e.DOMParser,X=e.trustedTypes,Q=l.prototype,Y=S(Q,"cloneNode"),ee=S(Q,"nextSibling"),te=S(Q,"childNodes"),ne=S(Q,"parentNode");if("function"==typeof i){var re=r.createElement("template");re.content&&re.content.ownerDocument&&(r=re.content.ownerDocument)}var oe=G(X,n),ie=oe&&Fe?oe.createHTML(""):"",se=r,ae=se.implementation,le=se.createNodeIterator,ce=se.createDocumentFragment,ue=se.getElementsByTagName,de=n.importNode,pe={};try{pe=M(r).documentMode?r.documentMode:{}}catch(e){}var he={};t.isSupported="function"==typeof ne&&ae&&void 0!==ae.createHTMLDocument&&9!==pe;var fe=H,me=z,ge=q,ve=V,ye=$,be=_,we=j,ke=null,xe=T({},[].concat(W(E),W(N),W(O),W(A),W(I))),Ce=null,Te=T({},[].concat(W(R),W(P),W(B),W(F))),Me=null,Se=null,Ee=!0,Ne=!0,Oe=!1,De=!1,Ae=!1,Le=!1,Ie=!1,Re=!1,Pe=!1,Be=!0,Fe=!1,He=!0,ze=!0,qe=!1,Ve={},je=null,$e=T({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),_e=null,Ue=T({},["audio","video","img","source","image","track"]),We=null,Je=T({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ge="http://www.w3.org/1998/Math/MathML",Ke="http://www.w3.org/2000/svg",Ze="http://www.w3.org/1999/xhtml",Xe=Ze,Qe=!1,Ye=void 0,et=["application/xhtml+xml","text/html"],tt="text/html",nt=void 0,rt=null,ot=r.createElement("form"),it=function(e){rt&&rt===e||(e&&"object"===(void 0===e?"undefined":U(e))||(e={}),e=M(e),ke="ALLOWED_TAGS"in e?T({},e.ALLOWED_TAGS):xe,Ce="ALLOWED_ATTR"in e?T({},e.ALLOWED_ATTR):Te,We="ADD_URI_SAFE_ATTR"in e?T(M(Je),e.ADD_URI_SAFE_ATTR):Je,_e="ADD_DATA_URI_TAGS"in e?T(M(Ue),e.ADD_DATA_URI_TAGS):Ue,je="FORBID_CONTENTS"in e?T({},e.FORBID_CONTENTS):$e,Me="FORBID_TAGS"in e?T({},e.FORBID_TAGS):{},Se="FORBID_ATTR"in e?T({},e.FORBID_ATTR):{},Ve="USE_PROFILES"in e&&e.USE_PROFILES,Ee=!1!==e.ALLOW_ARIA_ATTR,Ne=!1!==e.ALLOW_DATA_ATTR,Oe=e.ALLOW_UNKNOWN_PROTOCOLS||!1,De=e.SAFE_FOR_TEMPLATES||!1,Ae=e.WHOLE_DOCUMENT||!1,Re=e.RETURN_DOM||!1,Pe=e.RETURN_DOM_FRAGMENT||!1,Be=!1!==e.RETURN_DOM_IMPORT,Fe=e.RETURN_TRUSTED_TYPE||!1,Ie=e.FORCE_BODY||!1,He=!1!==e.SANITIZE_DOM,ze=!1!==e.KEEP_CONTENT,qe=e.IN_PLACE||!1,we=e.ALLOWED_URI_REGEXP||we,Xe=e.NAMESPACE||Ze,Ye=Ye=-1===et.indexOf(e.PARSER_MEDIA_TYPE)?tt:e.PARSER_MEDIA_TYPE,nt="application/xhtml+xml"===Ye?function(e){return e}:m,De&&(Ne=!1),Pe&&(Re=!0),Ve&&(ke=T({},[].concat(W(I))),Ce=[],!0===Ve.html&&(T(ke,E),T(Ce,R)),!0===Ve.svg&&(T(ke,N),T(Ce,P),T(Ce,F)),!0===Ve.svgFilters&&(T(ke,O),T(Ce,P),T(Ce,F)),!0===Ve.mathMl&&(T(ke,A),T(Ce,B),T(Ce,F))),e.ADD_TAGS&&(ke===xe&&(ke=M(ke)),T(ke,e.ADD_TAGS)),e.ADD_ATTR&&(Ce===Te&&(Ce=M(Ce)),T(Ce,e.ADD_ATTR)),e.ADD_URI_SAFE_ATTR&&T(We,e.ADD_URI_SAFE_ATTR),e.FORBID_CONTENTS&&(je===$e&&(je=M(je)),T(je,e.FORBID_CONTENTS)),ze&&(ke["#text"]=!0),Ae&&T(ke,["html","head","body"]),ke.table&&(T(ke,["tbody"]),delete Me.tbody),s&&s(e),rt=e)},st=T({},["mi","mo","mn","ms","mtext"]),at=T({},["foreignobject","desc","title","annotation-xml"]),lt=T({},N);T(lt,O),T(lt,D);var ct=T({},A);T(ct,L);var ut=function(e){var t=ne(e);t&&t.tagName||(t={namespaceURI:Ze,tagName:"template"});var n=m(e.tagName),r=m(t.tagName);if(e.namespaceURI===Ke)return t.namespaceURI===Ze?"svg"===n:t.namespaceURI===Ge?"svg"===n&&("annotation-xml"===r||st[r]):Boolean(lt[n]);if(e.namespaceURI===Ge)return t.namespaceURI===Ze?"math"===n:t.namespaceURI===Ke?"math"===n&&at[r]:Boolean(ct[n]);if(e.namespaceURI===Ze){if(t.namespaceURI===Ke&&!at[r])return!1;if(t.namespaceURI===Ge&&!st[r])return!1;var o=T({},["title","style","font","a","script"]);return!ct[n]&&(o[n]||!lt[n])}return!1},dt=function(e){f(t.removed,{element:e});try{e.parentNode.removeChild(e)}catch(t){try{e.outerHTML=ie}catch(t){e.remove()}}},pt=function(e,n){try{f(t.removed,{attribute:n.getAttributeNode(e),from:n})}catch(e){f(t.removed,{attribute:null,from:n})}if(n.removeAttribute(e),"is"===e&&!Ce[e])if(Re||Pe)try{dt(n)}catch(e){}else try{n.setAttribute(e,"")}catch(e){}},ht=function(e){var t=void 0,n=void 0;if(Ie)e=""+e;else{var o=g(e,/^[\r\n\t ]+/);n=o&&o[0]}"application/xhtml+xml"===Ye&&(e=''+e+"");var i=oe?oe.createHTML(e):e;if(Xe===Ze)try{t=(new Z).parseFromString(i,Ye)}catch(e){}if(!t||!t.documentElement){t=ae.createDocument(Xe,"template",null);try{t.documentElement.innerHTML=Qe?"":i}catch(e){}}var s=t.body||t.documentElement;return e&&n&&s.insertBefore(r.createTextNode(n),s.childNodes[0]||null),Xe===Ze?ue.call(t,Ae?"html":"body")[0]:Ae?t.documentElement:s},ft=function(e){return le.call(e.ownerDocument||e,e,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT,null,!1)},mt=function(e){return!(e instanceof x||e instanceof C||"string"==typeof e.nodeName&&"string"==typeof e.textContent&&"function"==typeof e.removeChild&&e.attributes instanceof d&&"function"==typeof e.removeAttribute&&"function"==typeof e.setAttribute&&"string"==typeof e.namespaceURI&&"function"==typeof e.insertBefore)},gt=function(e){return"object"===(void 0===a?"undefined":U(a))?e instanceof a:e&&"object"===(void 0===e?"undefined":U(e))&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName},vt=function(e,n,r){he[e]&&p(he[e],(function(e){e.call(t,n,r,rt)}))},yt=function(e){var n=void 0;if(vt("beforeSanitizeElements",e,null),mt(e))return dt(e),!0;if(g(e.nodeName,/[\u0080-\uFFFF]/))return dt(e),!0;var r=nt(e.nodeName);if(vt("uponSanitizeElement",e,{tagName:r,allowedTags:ke}),!gt(e.firstElementChild)&&(!gt(e.content)||!gt(e.content.firstElementChild))&&w(/<[/\w]/g,e.innerHTML)&&w(/<[/\w]/g,e.textContent))return dt(e),!0;if("select"===r&&w(/