Recipes phase 2
This commit is contained in:
@@ -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(); },
|
||||
};
|
||||
};
|
||||
})();
|
||||
@@ -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 = '';
|
||||
}
|
||||
});
|
||||
})();
|
||||
|
||||
@@ -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)}
|
||||
|
||||
@@ -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.
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user