Change: add sections-editor

This commit is contained in:
eight 2018-10-09 23:38:29 +08:00
parent 30e8662946
commit 06e22d0d18
12 changed files with 851 additions and 889 deletions

View File

@ -14,7 +14,7 @@ const navigatorUtil = (() => {
} }
function initUrlChange() { function initUrlChange() {
if (!handler.urlChange) { if (handler.urlChange) {
return; return;
} }
handler.urlChange = []; handler.urlChange = [];

View File

@ -37,7 +37,7 @@ const styleManager = (() => {
}); });
function handleLivePreviewConnections() { function handleLivePreviewConnections() {
chrome.runtime.onConnect(port => { chrome.runtime.onConnect.addListener(port => {
if (port.name !== 'livePreview') { if (port.name !== 'livePreview') {
return; return;
} }

View File

@ -137,8 +137,11 @@
<template data-id="section"> <template data-id="section">
<div class="section"> <div class="section">
<!-- not using DIV to make our CSS work for #sections > div:only-of-type .remove-section -->
<p class="deleted-section">
<button class="restore-section" i18n-text="sectionRestore"></button>
</p>
<label i18n-text="sectionCode" class="code-label"></label> <label i18n-text="sectionCode" class="code-label"></label>
<br>
<div class="applies-to"> <div class="applies-to">
<label i18n-text="appliesLabel"> <label i18n-text="appliesLabel">
<a href="#" class="svg-inline-wrapper applies-to-help" tabindex="0"> <a href="#" class="svg-inline-wrapper applies-to-help" tabindex="0">
@ -159,13 +162,6 @@
</div> </div>
</template> </template>
<!-- not using DIV to make our CSS work for #sections > div:only-of-type .remove-section -->
<template data-id="deletedSection">
<p class="deleted-section">
<button class="restore-section" i18n-text="sectionRestore"></button>
</p>
</template>
<template data-id="searchReplaceDialog"> <template data-id="searchReplaceDialog">
<div id="search-replace-dialog"> <div id="search-replace-dialog">
<div data-type="main"> <div data-type="main">
@ -291,7 +287,7 @@
<h1 id="heading">&nbsp;</h1> <!-- nbsp allocates the actual height which prevents page shift --> <h1 id="heading">&nbsp;</h1> <!-- nbsp allocates the actual height which prevents page shift -->
<section id="basic-info"> <section id="basic-info">
<div id="basic-info-name"> <div id="basic-info-name">
<input id="name" class="style-contributor" spellcheck="false"> <input id="name" class="style-contributor" spellcheck="false" required>
<a id="url" target="_blank"><svg class="svg-icon"><use xlink:href="#svg-icon-external-link"/></svg></a> <a id="url" target="_blank"><svg class="svg-icon"><use xlink:href="#svg-icon-external-link"/></svg></a>
</div> </div>
<div id="basic-info-enabled"> <div id="basic-info-enabled">

View File

@ -4,7 +4,7 @@ global editors getSectionForChild showHelp
*/ */
'use strict'; 'use strict';
function beautify(event) { function beautify(scope) {
loadScript('/vendor-overwrites/beautify/beautify-css-mod.js') loadScript('/vendor-overwrites/beautify/beautify-css-mod.js')
.then(() => { .then(() => {
if (!window.css_beautify && window.exports) { if (!window.css_beautify && window.exports) {
@ -22,9 +22,6 @@ function beautify(event) {
options.indent_size = tabs ? 1 : prefs.get('editor.tabSize'); options.indent_size = tabs ? 1 : prefs.get('editor.tabSize');
options.indent_char = tabs ? '\t' : ' '; options.indent_char = tabs ? '\t' : ' ';
const section = getSectionForChild(event.target);
const scope = section ? [section.CodeMirror] : editors;
showHelp(t('styleBeautify'), showHelp(t('styleBeautify'),
$create([ $create([
$create('.beautify-options', [ $create('.beautify-options', [

View File

@ -1,8 +1,7 @@
/* /*
global CodeMirror loadScript global CodeMirror loadScript
global editors editor styleId ownTabId global editor ownTabId
global save toggleStyle setupAutocomplete makeSectionVisible getSectionForChild global save toggleStyle makeSectionVisible
global getSectionsHashes
global messageBox global messageBox
*/ */
'use strict'; 'use strict';
@ -186,8 +185,9 @@ onDOMscriptReady('/codemirror.js').then(() => {
} }
function nextPrevEditor(cm, direction) { function nextPrevEditor(cm, direction) {
const editors = style.getEditors();
cm = editors[(editors.indexOf(cm) + direction + editors.length) % editors.length]; cm = editors[(editors.indexOf(cm) + direction + editors.length) % editors.length];
makeSectionVisible(cm); editor.scrollToEditor(cm);
cm.focus(); cm.focus();
return cm; return cm;
} }
@ -400,8 +400,9 @@ onDOMscriptReady('/codemirror.js').then(() => {
function closestVisible(nearbyElement) { function closestVisible(nearbyElement) {
const cm = const cm =
nearbyElement instanceof CodeMirror ? nearbyElement : nearbyElement instanceof CodeMirror ? nearbyElement :
nearbyElement instanceof Node && (getSectionForChild(nearbyElement) || {}).CodeMirror || nearbyElement instanceof Node &&
editors.lastActive; (nearbyElement.closest('#sections > .section') || {}).CodeMirror ||
editor.getLastActivatedEditor();
if (nearbyElement instanceof Node && cm) { if (nearbyElement instanceof Node && cm) {
const {left, top} = nearbyElement.getBoundingClientRect(); const {left, top} = nearbyElement.getBoundingClientRect();
const bounds = cm.display.wrapper.getBoundingClientRect(); const bounds = cm.display.wrapper.getBoundingClientRect();
@ -466,7 +467,7 @@ onDOMscriptReady('/codemirror.js').then(() => {
} }
const cm = editors[b]; const cm = editors[b];
if (distances[b] > 0) { if (distances[b] > 0) {
makeSectionVisible(cm); editor.scrollToEditor(cm);
} }
return cm; return cm;
} }
@ -588,4 +589,40 @@ onDOMscriptReady('/codemirror.js').then(() => {
} }
return ''; return '';
} }
function setupAutocomplete(cm, enable = true) {
const onOff = enable ? 'on' : 'off';
cm[onOff]('changes', autocompleteOnTyping);
cm[onOff]('pick', autocompletePicked);
}
function autocompleteOnTyping(cm, [info], debounced) {
if (
cm.state.completionActive ||
info.origin && !info.origin.includes('input') ||
!info.text.last
) {
return;
}
if (cm.state.autocompletePicked) {
cm.state.autocompletePicked = false;
return;
}
if (!debounced) {
debounce(autocompleteOnTyping, 100, cm, [info], true);
return;
}
if (info.text.last.match(/[-a-z!]+$/i)) {
cm.state.autocompletePicked = false;
cm.options.hintOptions.completeSingle = false;
cm.execCommand('autocomplete');
setTimeout(() => {
cm.options.hintOptions.completeSingle = true;
});
}
}
function autocompletePicked(cm) {
cm.state.autocompletePicked = true;
}
}); });

View File

@ -349,6 +349,18 @@ input:invalid {
.section:only-of-type .move-section-down { .section:only-of-type .move-section-down {
display: none; display: none;
} }
/* deleted section */
.section .deleted-section {
display: none;
}
.section.removed .deleted-section {
display: block;
}
.section.removed .code-label,
.section.removed .applies-to,
.section.removed .edit-actions {
display: none;
}
.move-section-up:after { .move-section-up:after {
content: ""; content: "";
display: block; display: block;

View File

@ -11,21 +11,19 @@ global moveFocus editorWorker msg
*/ */
'use strict'; 'use strict';
let styleId = null;
// only the actually dirty items here
let dirty = {};
// array of all CodeMirror instances
const editors = [];
let saveSizeOnClose; let saveSizeOnClose;
let ownTabId; let ownTabId;
// direct & reverse mapping of @-moz-document keywords and internal property names // direct & reverse mapping of @-moz-document keywords and internal property names
const propertyToCss = {urls: 'url', urlPrefixes: 'url-prefix', domains: 'domain', regexps: 'regexp'}; const propertyToCss = {urls: 'url', urlPrefixes: 'url-prefix', domains: 'domain', regexps: 'regexp'};
const CssToProperty = {'url': 'urls', 'url-prefix': 'urlPrefixes', 'domain': 'domains', 'regexp': 'regexps'}; const CssToProperty = Object.entries(propertyToCss)
.reduce((o, v) => {
o[v[1]] = v[0];
return o;
}, {});
let editor; let editor;
document.addEventListener('visibilitychange', beforeUnload); document.addEventListener('visibilitychange', beforeUnload);
msg.onExtension(onRuntimeMessage); msg.onExtension(onRuntimeMessage);
@ -43,21 +41,17 @@ Promise.all([
$('#preview-label').classList.toggle('hidden', !styleId); $('#preview-label').classList.toggle('hidden', !styleId);
$('#beautify').onclick = beautify; $('#beautify').onclick = () => beautify(editor.getEditors());
$('#lint').addEventListener('scroll', hideLintHeaderOnScroll, {passive: true}); $('#lint').addEventListener('scroll', hideLintHeaderOnScroll, {passive: true});
window.addEventListener('resize', () => debounce(rememberWindowSize, 100)); window.addEventListener('resize', () => debounce(rememberWindowSize, 100));
exclusions.init(style); exclusions.init(style);
if (usercss) { editor = usercss ? createSourceEditor(style) : createSectionEditor(style);
editor = createSourceEditor(style);
} else {
initWithSectionStyle(style);
document.addEventListener('wheel', scrollEntirePageOnCtrlShift);
}
}); });
function preinit() { function preinit() {
// make querySelectorAll enumeration code readable // make querySelectorAll enumeration code readable
// FIXME: don't extend native
['forEach', 'some', 'indexOf', 'map'].forEach(method => { ['forEach', 'some', 'indexOf', 'map'].forEach(method => {
NodeList.prototype[method] = Array.prototype[method]; NodeList.prototype[method] = Array.prototype[method];
}); });
@ -168,11 +162,7 @@ function onRuntimeMessage(request) {
? API.getStyleFromDB(id) ? API.getStyleFromDB(id)
: Promise.resolve([request.style]) : Promise.resolve([request.style])
).then(([style]) => { ).then(([style]) => {
if (isUsercss(style)) {
editor.replaceStyle(style, request.codeIsUpdated); editor.replaceStyle(style, request.codeIsUpdated);
} else {
initWithSectionStyle(style, request.codeIsUpdated);
}
}); });
} }
break; break;
@ -192,12 +182,6 @@ function onRuntimeMessage(request) {
case 'editDeleteText': case 'editDeleteText':
document.execCommand('delete'); document.execCommand('delete');
break; break;
case 'exclusionsUpdated':
debounce(() => exclusions.update({
list: Object.keys(request.style.exclusions),
isUpdating: false
}), 100);
break;
} }
} }
@ -217,8 +201,7 @@ function beforeUnload() {
// refocus if unloading was canceled // refocus if unloading was canceled
setTimeout(() => activeElement.focus()); setTimeout(() => activeElement.focus());
} }
const isDirty = editor ? editor.isDirty() : !isCleanGlobal(); if (editor.isDirty()) {
if (isDirty) {
// neither confirm() nor custom messages work in modern browsers but just in case // neither confirm() nor custom messages work in modern browsers but just in case
return t('styleChangesNotSaved'); return t('styleChangesNotSaved');
} }
@ -274,252 +257,6 @@ function initStyleData() {
} }
} }
function initHooks() {
if (initHooks.alreadyDone) {
return;
}
initHooks.alreadyDone = true;
$$('#header .style-contributor').forEach(node => {
node.addEventListener('change', onChange);
node.addEventListener('input', onChange);
});
$('#to-mozilla').addEventListener('click', showMozillaFormat, false);
$('#to-mozilla-help').addEventListener('click', showToMozillaHelp, false);
$('#from-mozilla').addEventListener('click', fromMozillaFormat);
$('#save-button').addEventListener('click', save, false);
$('#sections-help').addEventListener('click', showSectionHelp, false);
if (!FIREFOX) {
$$([
'input:not([type])',
'input[type="text"]',
'input[type="search"]',
'input[type="number"]',
].join(','))
.forEach(e => e.addEventListener('mousedown', toggleContextMenuDelete));
}
}
function getNodeValue(node) {
// return length of exclusions; or the node value
return node.id === 'excluded-list' ? node.children.length.toString() : node.value;
}
function onChange(event) {
const node = event.target;
if ('savedValue' in node) {
const currentValue = node.type === 'checkbox' ? node.checked : getNodeValue(node);
setCleanItem(node, node.savedValue === currentValue);
} else {
// the manually added section's applies-to is dirty only when the value is non-empty
setCleanItem(node, node.localName !== 'input' || !getNodeValue(node).trim());
// only valid when actually saved
delete node.savedValue;
}
updateTitle();
}
// Set .dirty on stylesheet contributors that have changed
function setDirtyClass(node, isDirty) {
node.classList.toggle('dirty', isDirty);
}
function setCleanItem(node, isClean) {
if (!node.id) {
node.id = Date.now().toString(32).substr(-6);
}
if (isClean) {
delete dirty[node.id];
// code sections have .CodeMirror property
if (node.CodeMirror) {
node.savedValue = node.CodeMirror.changeGeneration();
} else {
node.savedValue = node.type === 'checkbox' ? node.checked : getNodeValue(node);
}
} else {
dirty[node.id] = true;
}
setDirtyClass(node, !isClean);
}
function isCleanGlobal() {
const clean = Object.keys(dirty).length === 0;
setDirtyClass(document.body, !clean);
return clean;
}
function setCleanGlobal() {
setCleanItem($('#sections'), true);
$$('#header, #sections > .section').forEach(setCleanSection);
// forget the dirty applies-to ids from a deleted section after the style was saved
dirty = {};
}
function setCleanSection(section) {
$$('.style-contributor', section).forEach(node => setCleanItem(node, true));
setCleanItem(section, true);
updateTitle();
}
function toggleStyle() {
$('#enabled').dispatchEvent(new MouseEvent('click', {bubbles: true}));
}
function save() {
if (!validate()) {
return;
}
API.editSave({
id: styleId,
name: $('#name').value.trim(),
enabled: $('#enabled').checked,
sections: getSectionsHashes(),
exclusions: exclusions.get()
})
.then(style => {
styleId = style.id;
sessionStorage.justEditedStyleId = styleId;
setCleanGlobal();
// Go from new style URL to edit style URL
if (location.href.indexOf('id=') === -1) {
history.replaceState({}, document.title, 'edit.html?id=' + style.id);
$('#heading').textContent = t('editStyleHeading');
}
updateTitle();
$('#preview-label').classList.remove('hidden');
});
}
function validate() {
const name = $('#name').value.trim();
if (!name) {
$('#name').focus();
messageBox.alert(t('styleMissingName'));
return false;
}
if ($$('.applies-to-list li:not(.applies-to-everything)')
.some(li => {
const type = $('[name=applies-type]', li).value;
const value = $('[name=applies-value]', li);
const rx = value.value.trim();
if (type === 'regexp' && rx && !tryRegExp(rx)) {
value.focus();
value.select();
return true;
}
})) {
messageBox.alert(t('styleBadRegexp'));
return false;
}
return true;
}
function updateTitle() {
const name = $('#name').savedValue;
const clean = isCleanGlobal();
const title = styleId === null ? t('addStyleTitle') : name;
document.title = (clean ? '' : '* ') + title;
window.onbeforeunload = clean ? null : beforeUnload;
$('#save-button').disabled = clean;
}
function showMozillaFormat() {
const popup = showCodeMirrorPopup(t('styleToMozillaFormatTitle'), '', {readOnly: true});
popup.codebox.setValue(toMozillaFormat());
popup.codebox.execCommand('selectAll');
}
function toMozillaFormat() {
return sectionsToMozFormat({sections: getSectionsHashes()});
}
function fromMozillaFormat() {
const popup = showCodeMirrorPopup(t('styleFromMozillaFormatPrompt'),
$create('.buttons', [
$create('button', {
name: 'import-replace',
textContent: t('importReplaceLabel'),
title: 'Ctrl-Shift-Enter:\n' + t('importReplaceTooltip'),
onclick: () => doImport({replaceOldStyle: true}),
}),
$create('button', {
name: 'import-append',
textContent: t('importAppendLabel'),
title: 'Ctrl-Enter:\n' + t('importAppendTooltip'),
onclick: doImport,
}),
]));
const contents = $('.contents', popup);
contents.insertBefore(popup.codebox.display.wrapper, contents.firstElementChild);
popup.codebox.focus();
popup.codebox.on('changes', cm => {
popup.classList.toggle('ready', !cm.isBlank());
cm.markClean();
});
// overwrite default extraKeys as those are inapplicable in popup context
popup.codebox.options.extraKeys = {
'Ctrl-Enter': doImport,
'Shift-Ctrl-Enter': () => doImport({replaceOldStyle: true}),
};
function doImport({replaceOldStyle = false}) {
lockPageUI(true);
editorWorker.parseMozFormat({code: popup.codebox.getValue().trim()})
.then(({sections, errors}) => {
// shouldn't happen but just in case
if (!sections.length && errors.length) {
return Promise.reject(errors);
}
// show the errors in case linting is disabled or stylelint misses what csslint has found
if (errors.length && prefs.get('editor.linter') !== 'csslint') {
showError(errors);
}
removeOldSections(replaceOldStyle);
return addSections(sections, div => setCleanItem(div, false));
})
.then(() => {
$('.dismiss').dispatchEvent(new Event('click'));
})
.catch(showError)
.then(() => lockPageUI(false));
}
function removeOldSections(removeAll) {
let toRemove;
if (removeAll) {
toRemove = editors.slice().reverse();
} else if (editors.last.isBlank() && $('.applies-to-everything', editors.last.getSection())) {
toRemove = [editors.last];
} else {
return;
}
toRemove.forEach(cm => removeSection({target: cm.getSection()}));
}
function lockPageUI(locked) {
document.documentElement.style.pointerEvents = locked ? 'none' : '';
if (popup.codebox) {
popup.classList.toggle('ready', locked ? false : !popup.codebox.isBlank());
popup.codebox.options.readOnly = locked;
popup.codebox.display.wrapper.style.opacity = locked ? '.5' : '';
}
}
function showError(errors) {
messageBox({
className: 'center danger',
title: t('styleFromMozillaFormatError'),
contents: $create('pre', Array.isArray(errors) ? errors.join('\n') : errors),
buttons: [t('confirmClose')],
});
}
}
function showSectionHelp(event) { function showSectionHelp(event) {
event.preventDefault(); event.preventDefault();
showHelp(t('styleSectionsTitle'), t('sectionHelp')); showHelp(t('styleSectionsTitle'), t('sectionHelp'));
@ -647,15 +384,6 @@ function setGlobalProgress(done, total) {
} }
} }
function scrollEntirePageOnCtrlShift(event) {
// make Shift-Ctrl-Wheel scroll entire page even when mouse is over a code editor
if (event.shiftKey && event.ctrlKey && !event.altKey && !event.metaKey) {
// Chrome scrolls horizontally when Shift is pressed but on some PCs this might be different
window.scrollBy(0, event.deltaX || event.deltaY);
event.preventDefault();
}
}
function hideLintHeaderOnScroll() { function hideLintHeaderOnScroll() {
// workaround part2 for the <details> not showing its toggle icon: hide <summary> on scroll // workaround part2 for the <details> not showing its toggle icon: hide <summary> on scroll
const newOpacity = this.scrollTop === 0 ? '' : '0'; const newOpacity = this.scrollTop === 0 ? '' : '0';

View File

@ -314,7 +314,7 @@ onDOMready().then(() => {
}); });
const canFocus = !state.dialog || !state.dialog.contains(document.activeElement); const canFocus = !state.dialog || !state.dialog.contains(document.activeElement);
makeTargetVisible(!canFocus && input); makeTargetVisible(!canFocus && input);
makeSectionVisible(cm); editor.scrollToEditor(cm);
if (canFocus) input.focus(); if (canFocus) input.focus();
state.cm = cm; state.cm = cm;
clearMarker(); clearMarker();
@ -778,7 +778,7 @@ onDOMready().then(() => {
cm.scrollIntoView(searchCursor.pos, SCROLL_REVEAL_MIN_PX); cm.scrollIntoView(searchCursor.pos, SCROLL_REVEAL_MIN_PX);
// scroll to the editor itself // scroll to the editor itself
makeSectionVisible(cm); editor.scrollToEditor(cm);
// focus or expose as the current search target // focus or expose as the current search target
clearMarker(); clearMarker();

View File

@ -158,7 +158,7 @@ Object.assign(linter, (() => {
} }
function gotoLintIssue(cm, anno) { function gotoLintIssue(cm, anno) {
makeSectionVisible(cm); editor.scrollToEditor(cm);
cm.focus(); cm.focus();
cm.setSelection(anno.from); cm.setSelection(anno.from);
} }

771
edit/sections-editor.js Normal file
View File

@ -0,0 +1,771 @@
/* global dirtyReporter showToMozillaHelp
showSectionHelp toggleContextMenuDelete setGlobalProgress maximizeCodeHeight
CodeMirror nextPrevEditorOnKeydown showAppliesToHelp propertyToCss
regExpTester linter cssToProperty
*/
'use strict';
function createResizeGrip(cm) {
const wrapper = cm.display.wrapper;
wrapper.classList.add('resize-grip-enabled');
const resizeGrip = template.resizeGrip.cloneNode(true);
wrapper.appendChild(resizeGrip);
let lastClickTime = 0;
resizeGrip.onmousedown = event => {
if (event.button !== 0) {
return;
}
event.preventDefault();
if (Date.now() - lastClickTime < 500) {
lastClickTime = 0;
toggleSectionHeight(cm);
return;
}
lastClickTime = Date.now();
const minHeight = cm.defaultTextHeight() +
/* .CodeMirror-lines padding */
cm.display.lineDiv.offsetParent.offsetTop +
/* borders */
wrapper.offsetHeight - wrapper.clientHeight;
wrapper.style.pointerEvents = 'none';
document.body.style.cursor = 's-resize';
document.addEventListener('mousemove', resize);
document.addEventListener('mouseup', resizeStop);
function resize(e) {
const cmPageY = wrapper.getBoundingClientRect().top + window.scrollY;
const height = Math.max(minHeight, e.pageY - cmPageY);
if (height !== wrapper.clientHeight) {
cm.setSize(null, height);
}
}
function resizeStop() {
document.removeEventListener('mouseup', resizeStop);
document.removeEventListener('mousemove', resize);
wrapper.style.pointerEvents = '';
document.body.style.cursor = '';
}
};
function toggleSectionHeight(cm) {
if (cm.state.toggleHeightSaved) {
// restore previous size
cm.setSize(null, cm.state.toggleHeightSaved);
cm.state.toggleHeightSaved = 0;
} else {
// maximize
const wrapper = cm.display.wrapper;
const allBounds = $('#sections').getBoundingClientRect();
const pageExtrasHeight = allBounds.top + window.scrollY +
parseFloat(getComputedStyle($('#sections')).paddingBottom);
const sectionExtrasHeight = cm.getSection().clientHeight - wrapper.offsetHeight;
cm.state.toggleHeightSaved = wrapper.clientHeight;
cm.setSize(null, window.innerHeight - sectionExtrasHeight - pageExtrasHeight);
const bounds = cm.getSection().getBoundingClientRect();
if (bounds.top < 0 || bounds.bottom > window.innerHeight) {
window.scrollBy(0, bounds.top);
}
}
}
}
function createSectionsEditor(style) {
let INC_ID = 0; // an increment id that is used by various object to track the order
const dirty = dirtyReporter();
dirty.onChange(() => updateTitle);
const container = $('#sections');
const sections = [];
const nameEl = $('#name');
nameEl.addEventListener('change', () => {
dirty.modify('name', style.name, nameEl.value);
style.name = nameEl.value;
});
const enabledEl = $('#enabled');
enabledEl.addEventListener('change', () => {
dirty.modify('enabled', style.enabled, enabledEl.checked);
style.enabled = enabledEl.checked;
});
$('#to-mozilla').addEventListener('click', showMozillaFormat);
$('#to-mozilla-help').addEventListener('click', showToMozillaHelp);
$('#from-mozilla').addEventListener('click', fromMozillaFormat);
$('#save-button').addEventListener('click', saveStyle);
$('#sections-help').addEventListener('click', showSectionHelp);
document.addEventListener('wheel', scrollEntirePageOnCtrlShift);
if (!FIREFOX) {
$$([
'input:not([type])',
'input[type="text"]',
'input[type="search"]',
'input[type="number"]',
].join(','))
.forEach(e => e.addEventListener('mousedown', toggleContextMenuDelete));
}
let sectionOrder = '';
initSection({
sections: style.sections.slice(),
done:() => {
// FIXME: implement this with CSS?
// https://github.com/openstyles/stylus/commit/2895ce11e271788df0e4f7314b3b981fde086574
// maximizeCodeHeight(sections[sections.length - 1], true);
dirty.clear();
}
});
const livePreview = createLivePreview();
livePreview.show(Boolean(style.id));
updateHeader();
return {
replaceStyle,
isDirty: dirty.isDirty,
getStyle: () => style,
getEditors: () =>
sections.filter(s => !s.isRemoved()).map(s => s.cm),
getLastActivatedEditor,
scrollToEditor
};
function scrollToEditor(cm) {
const section = sections.find(s => s.cm === cm);
const bounds = section.getBoundingClientRect();
if (
(bounds.bottom > window.innerHeight && bounds.top > 0) ||
(bounds.top < 0 && bounds.bottom < window.innerHeight)
) {
if (bounds.top < 0) {
window.scrollBy(0, bounds.top - 1);
} else {
window.scrollBy(0, bounds.bottom - window.innerHeight + 1);
}
}
}
function getLastActivatedEditor() {
let result;
for (const section of sections) {
if (section.isRemoved()) {
continue;
}
if (!result || section.getLastActive() > result.getLastActive) {
result = section;
}
}
return result;
}
function nextPrevEditorOnKeydown(cm, event) {
const key = event.which;
if (key < 37 || key > 40 || event.shiftKey || event.altKey || event.metaKey) {
return;
}
const {line, ch} = cm.getCursor();
switch (key) {
case 37:
// arrow Left
if (line || ch) {
return;
}
// fallthrough to arrow Up
case 38:
// arrow Up
if (line > 0 || cm === editors[0]) {
return;
}
event.preventDefault();
event.stopPropagation();
cm = CodeMirror.commands.prevEditor(cm);
cm.setCursor(cm.doc.size - 1, key === 37 ? 1e20 : ch);
break;
case 39:
// arrow Right
if (line < cm.doc.size - 1 || ch < cm.getLine(line).length - 1) {
return;
}
// fallthrough to arrow Down
case 40:
// arrow Down
if (line < cm.doc.size - 1 || cm === editors.last) {
return;
}
event.preventDefault();
event.stopPropagation();
cm = CodeMirror.commands.nextEditor(cm);
cm.setCursor(0, 0);
break;
}
const animation = (cm.getSection().firstElementChild.getAnimations() || [])[0];
if (animation) {
animation.playbackRate = -1;
animation.currentTime = 2000;
animation.play();
}
}
function scrollEntirePageOnCtrlShift(event) {
// make Shift-Ctrl-Wheel scroll entire page even when mouse is over a code editor
if (event.shiftKey && event.ctrlKey && !event.altKey && !event.metaKey) {
// Chrome scrolls horizontally when Shift is pressed but on some PCs this might be different
window.scrollBy(0, event.deltaX || event.deltaY);
event.preventDefault();
}
}
function showMozillaFormat() {
const popup = showCodeMirrorPopup(t('styleToMozillaFormatTitle'), '', {readOnly: true});
popup.codebox.setValue(sectionsToMozFormat(getModel()));
popup.codebox.execCommand('selectAll');
}
function fromMozillaFormat(text = '') {
const popup = showCodeMirrorPopup(t('styleFromMozillaFormatPrompt'),
$create('.buttons', [
$create('button', {
name: 'import-replace',
textContent: t('importReplaceLabel'),
title: 'Ctrl-Shift-Enter:\n' + t('importReplaceTooltip'),
onclick: () => doImport({replaceOldStyle: true}),
}),
$create('button', {
name: 'import-append',
textContent: t('importAppendLabel'),
title: 'Ctrl-Enter:\n' + t('importAppendTooltip'),
onclick: doImport,
}),
]));
const contents = $('.contents', popup);
contents.insertBefore(popup.codebox.display.wrapper, contents.firstElementChild);
popup.codebox.focus();
popup.codebox.on('changes', cm => {
popup.classList.toggle('ready', !cm.isBlank());
cm.markClean();
});
if (text) {
popup.codebox.setValue(text);
popup.codebox.clearHistory();
popup.codebox.markClean();
}
// overwrite default extraKeys as those are inapplicable in popup context
popup.codebox.options.extraKeys = {
'Ctrl-Enter': doImport,
'Shift-Ctrl-Enter': () => doImport({replaceOldStyle: true}),
};
function doImport({replaceOldStyle = false}) {
lockPageUI(true);
editorWorker.parseMozFormat({code: popup.codebox.getValue().trim()})
.then(({sections, errors}) => {
// shouldn't happen but just in case
if (!sections.length || errors.length) {
throw errors;
}
if (replaceOldStyle) {
return replaceSections(sections);
}
return new Promise(resolve => initSection({sections, done: resolve, focusOn: false}));
})
.then(() => {
$('.dismiss').dispatchEvent(new Event('click'));
})
.catch(showError)
.then(() => lockPageUI(false));
}
function lockPageUI(locked) {
document.documentElement.style.pointerEvents = locked ? 'none' : '';
if (popup.codebox) {
popup.classList.toggle('ready', locked ? false : !popup.codebox.isBlank());
popup.codebox.options.readOnly = locked;
popup.codebox.display.wrapper.style.opacity = locked ? '.5' : '';
}
}
function showError(errors) {
messageBox({
className: 'center danger',
title: t('styleFromMozillaFormatError'),
contents: $create('pre', Array.isArray(errors) ? errors.join('\n') : errors),
buttons: [t('confirmClose')],
});
}
}
function updateSectionOrder() {
const oldOrder = sectionOrder;
const validSections = sections.filter(s => !s.isRemoved());
sectionOrder = validSections.map(s => s.id).join(',');
dirty.modify('sectionOrder', oldOrder, sectionOrder);
container.dataset.sectionCount = validSections.length;
}
function getModel() {
return Object.assign({}, style, {
sections: sections.map(s => s.getModel())
});
}
function validate() {
if (!nameEl.reportValidity()) {
messageBox.alert(t('styleMissingName'));
return false;
}
for (const section of sections) {
for (const apply of section.appliesTo) {
if (apply.getType() !== 'regexp') {
continue;
}
if (!apply.valueEl.reportValidity()) {
messageBox.alert(t('styleBadRegexp'));
return false;
}
}
}
return true;
}
function save() {
const newStyle = getModel();
if (!validate(newStyle)) {
return;
}
API.editSave(newStyle)
.then(newStyle => {
sessionStorage.justEditedStyleId = newStyle.id;
replaceStyle(newStyle);
});
}
function updateHeader() {
nameEl.value = style.name || '';
enabledEl.checked = style.enabled !== false;
$('#url').href = style.url || '';
updateTitle();
}
function updateLivePreview() {
debounce(_updateLivePreview, 200);
}
function _updateLivePreview() {
livePreview.update(getModel());
}
function updateTitle() {
const name = style.name;
const clean = !dirty.isDirty();
const title = !style.id ? t('addStyleTitle') : name;
document.title = (clean ? '' : '* ') + title;
$('#save-button').disabled = clean;
}
function initSection({
sections: originalSections,
total = originalSections.length,
focusOn = 0,
done
}) {
if (!originalSections.length) {
setGlobalProgress();
if (focusOn !== false) {
sections[focusOn].cm.focus();
}
if (done) {
done();
}
return;
}
insertSectionAfter(originalSections.shift());
setGlobalProgress(total - originalSections.length, total);
setTimeout(initSection, 0, {
sections: originalSections,
total,
focusOn,
done
});
}
function removeSection(section) {
if (sections.every(s => s.isRemoved() || s === section)) {
throw new Error('Cannot remove last section');
}
section.remove();
if (!section.getCode()) {
const index = sections.indexOf(section);
sections.splice(index, 1);
section.el.remove();
} else {
const lines = [];
const MAX_LINES = 10;
section.cm.doc.iter(0, MAX_LINES + 1, ({text}) => lines.push(text) && false);
const title = t('sectionCode') + '\n' +
'-'.repeat(20) + '\n' +
lines.slice(0, MAX_LINES).map(s => clipString(s, 100)).join('\n') +
(lines.length > MAX_LINES ? '\n...' : '');
$('.deleted-section', section.el).title = title;
}
dirty.remove(section, section);
updateSectionOrder();
section.off(updateLivePreview);
updateLivePreview();
}
function restoreSection(section) {
section.restore();
updateSectionOrder();
section.onChange(updateLivePreview);
updateLivePreview();
}
function insertSectionAfter(init, base) {
if (!init) {
init = {code: '', urlPrefixes: ['http://example.com']};
}
const section = createSection(init);
container.appendChild(section.el);
if (base) {
const index = sections.indexOf(base);
sections.splice(index, 0, section);
} else {
sections.push(section);
}
section.render();
// maximizeCodeHeight(section.el);
updateSectionOrder();
section.onChange(updateLivePreview);
updateLivePreview();
}
function moveSectionUp(section) {
const index = sections.indexOf(section);
if (index === 0) {
return;
}
container.insertBefore(section.el, sections[index - 1].el);
sections[index] = sections[index - 1];
sections[index - 1] = section;
updateSectionOrder();
}
function moveSectionDown(section) {
const index = sections.indexOf(section);
if (index === sections.length - 1) {
return;
}
container.insertBefore(sections[index + 1].el, section.el);
sections[index] = sections[index + 1];
sections[index + 1] = section;
updateSectionOrder();
}
function createSection(originalSection) {
const sectionId = INC_ID++;
const el = template.section.cloneNode(true);
const cm = CodeMirror(wrapper => {
el.insertBefore(wrapper, $('.code-label', el).nextSibling);
}, {value: originalSection.code});
const appliesToContainer = $('.applies-to-list', el);
const appliesTo = [];
for (const [key, fnName] of Object.entries(propertyToCss)) {
if (originalSection[key]) {
originalSection[key].forEach(value =>
insertApplyAfter({type: fnName, value})
);
}
}
if (!appliesTo.length) {
const apply = createApply({all: true});
appliesTo.push(apply);
appliesToContainer.appendChild(apply.el);
dirty.addChild(apply.dirty);
}
let changeGeneration = cm.changeGeneration();
let removed = false;
registerEvents();
updateRegexpTester();
createResizeGrip(cm);
linter.enableForEditor(cm);
linter.refreshReport();
const changeListeners = new Set();
let lastActive = 0;
const section = {
id: sectionId,
el,
cm,
render,
destroy,
getCode,
getModel,
remove,
restore,
isRemoved: () => removed,
onChange,
off,
getLastActive: () => lastActive,
};
return section;
function onChange(fn) {
changeListeners.add(fn);
}
function off(fn) {
changeListeners.delete(fn);
}
function emitSectionChange() {
for (const fn of changeListeners) {
fn();
}
}
function getModel() {
const section = {
code: cm.getValue()
};
for (const apply of appliesTo) {
if (apply.all) {
continue;
}
const key = cssToProperty(apply.getType());
if (!section[key]) {
section[key] = [];
}
section[key].push(apply.getValue());
}
return section;
}
function registerEvents() {
cm.on('changes', () => {
const newGeneration = cm.changeGeneration();
dirty.modify(`section.${sectionId}.code`, changeGeneration, newGeneration);
changeGeneration = newGeneration;
emitSectionChange();
});
cm.on('paste', (cm, event) => {
const text = event.clipboardData.getData('text') || '';
if (
text.includes('@-moz-document') &&
text.replace(/\/\*[\s\S]*?(?:\*\/|$)/g, '')
.match(/@-moz-document[\s\r\n]+(url|url-prefix|domain|regexp)\(/)
) {
event.preventDefault();
fromMozillaFormat(text);
}
// FIXME: why?
// if (editors.length === 1) {
// setTimeout(() => {
// if (cm.display.sizer.clientHeight > cm.display.wrapper.clientHeight) {
// maximizeCodeHeight.stats = null;
// maximizeCodeHeight(cm.getSection(), true);
// }
// });
// }
});
if (!FIREFOX) {
cm.on('mousedown', (cm, event) => toggleContextMenuDelete.call(cm, event));
}
cm.on('focus', () => lastActive = Date.now());
cm.display.wrapper.addEventListener('keydown', event =>
nextPrevEditorOnKeydown(cm, event), true);
$('.applies-to-help', el).addEventListener('click', showAppliesToHelp);
$('.remove-section', el).addEventListener('click', () => removeSection(section));
$('.add-section', el).addEventListener('click', () => insertSectionAfter(undefined, section));
$('.clone-section', el).addEventListener('click', () => insertSectionAfter(getModel(), section));
$('.move-section-up', el).addEventListener('click', () => moveSectionUp(section));
$('.move-section-down', el).addEventListener('click', () => moveSectionDown(section));
$('.beautify-section', el).addEventListener('click', () => beautify([cm]));
$('.restore-section', el).addEventListener('click', () => restoreSection(section));
$('.test-regexp', el).addEventListener('click', () => {
regExpTester.toggle();
updateRegexpTester();
});
}
function getCode() {
return cm.getValue();
}
function remove() {
linter.disableForEditor(cm);
el.classList.add('removed');
removed = true;
appliesTo.forEach(a => a.remove());
}
function restore() {
linter.enableForEditor(cm);
el.classList.remove('removed');
removed = false;
appliesTo.forEach(a => a.restore());
render();
}
function render() {
cm.refresh();
}
function updateRegexpTester() {
const regexps = appliesTo.filter(a => a.getKey() === 'regexp')
.map(a => a.getValue());
if (regexps.length) {
el.classList.add('has-regexp');
regExpTester.update(regexps);
} else {
el.classList.remove('has-regexp');
regExpTester.toggle(false);
}
}
function insertApplyAfter(init, base) {
const apply = createApply(init);
if (base) {
const index = appliesTo.indexOf(base);
appliesTo.splice(index, 0, apply);
appliesToContainer.insertBefore(apply.el, base.el.nextSibling);
} else {
appliesTo.push(apply);
appliesToContainer.appendChild(apply.el);
}
dirty.add(apply, apply);
if (appliesTo.length && appliesTo[0].all) {
removeApply(appliesTo[0]);
}
emitSectionChange();
}
function removeApply(apply) {
const index = appliesTo.indexOf(apply);
appliesTo.splice(index, 1);
apply.remove();
apply.el.remove();
dirty.remove(apply, apply);
if (!appliesTo.length) {
insertApplyAfter({all: true});
}
emitSectionChange();
}
function createApply({type, value, all}) {
const applyId = INC_ID++;
const dirtyPrefix = `section.${sectionId}.apply.${applyId}`;
const el = all ? template.appliesToEverything.cloneNode(true) :
template.appliesTo.cloneNode(true);
const selectEl = !all && $('.applies-type', el);
if (selectEl) {
selectEl.value = type;
selectEl.addEventListener('change', () => {
const oldKey = type;
dirty.modify(`${dirtyPrefix}.type`, type, selectEl.value);
type = selectEl.value;
if (oldKey === 'regexp' || type === 'regexp') {
updateRegexpTester();
}
emitSectionChange();
validate();
});
}
const valueEl = !all && $('.applies-value', el);
if (valueEl) {
valueEl.value = value;
valueEl.addEventListener('input', () => {
dirty.modify(`${dirtyPrefix}.value`, value, valueEl.value);
value = valueEl.value;
if (type === 'regexp') {
updateRegexpTester();
}
emitSectionChange();
});
valueEl.addEventListener('change', validate);
}
const apply = {
id: applyId,
all,
remove,
restore,
el,
getType: () => type,
getValue: () => value
};
const removeButton = $('.remove-applies-to', el);
if (removeButton) {
removeButton.addEventListener('click', () => removeApply(apply));
}
$('.add-applies-to', el).addEventListener('click', () =>
insertApplyAfter({type, value: ''}, apply));
return apply;
function validate() {
if (type !== 'regexp' || tryRegExp(value)) {
valueEl.setCustomValidity('');
} else {
valueEl.setCustomValidity(t('styleBadRegexp'));
setTimeout(() => valueEl.reportValidity());
}
}
function remove() {
dirty.remove(`${dirtyPrefix}.type`, type);
dirty.remove(`${dirtyPrefix}.value`, value);
}
function restore() {
dirty.add(`${dirtyPrefix}.type`, type);
dirty.add(`${dirtyPrefix}.value`, value);
}
}
}
function replaceSections(sections) {
for (const section of sections) {
section.remove();
}
sections.length = 0;
container.textContent = '';
return new Promise(resolve => initSection({sections, done: resolve}));
}
function replaceStyle(newStyle, codeIsUpdated) {
// FIXME: avoid recreating all editors?
reinit().then(() => {
style = newStyle;
updateHeader();
dirty.clear();
// Go from new style URL to edit style URL
if (location.href.indexOf('id=') === -1 && style.id) {
history.replaceState({}, document.title, 'edit.html?id=' + style.id);
$('#heading').textContent = t('editStyleHeading');
}
livePreview.show(Boolean(style.id));
});
function reinit() {
if (codeIsUpdated !== false) {
return replaceSections(newStyle.sections.slice());
}
return Promise.resolve();
}
}
}

View File

@ -1,582 +0,0 @@
/*
global CodeMirror
global editors propertyToCss CssToProperty
global onChange initHooks setCleanGlobal
global fromMozillaFormat maximizeCodeHeight toggleContextMenuDelete
global setCleanItem updateTitle
global showAppliesToHelp beautify regExpTester setGlobalProgress setCleanSection
global clipString linter
*/
'use strict';
function initWithSectionStyle(style, codeIsUpdated) {
$('#name').value = style.name || '';
$('#enabled').checked = style.enabled !== false;
$('#url').href = style.url || '';
if (codeIsUpdated !== false) {
editors.length = 0;
$('#sections').textContent = '';
addSections(style.sections.length ? style.sections : [{code: ''}]);
initHooks();
}
setCleanGlobal();
updateTitle();
}
function addSections(sections, onAdded = () => {}) {
if (addSections.running) {
console.error('addSections cannot be re-entered: please report to the developers');
// TODO: handle this properly e.g. on update/import
return;
}
addSections.running = true;
maximizeCodeHeight.stats = null;
// make a shallow copy since we might run asynchronously
// and the original array might get modified
sections = sections.slice();
const t0 = performance.now();
const divs = [];
let index = 0;
return new Promise(function run(resolve) {
while (index < sections.length) {
const div = addSection(null, sections[index]);
maximizeCodeHeight(div, index === sections.length - 1);
onAdded(div, index);
divs.push(div);
maybeFocusFirstCM();
index++;
const elapsed = performance.now() - t0;
if (elapsed > 500) {
setGlobalProgress(index, sections.length);
}
if (elapsed > 100) {
// after 100ms the sections are added asynchronously
setTimeout(run, 0, resolve);
return;
}
}
editors.last.state.renderLintReportNow = true;
addSections.running = false;
setGlobalProgress();
resolve(divs);
});
function maybeFocusFirstCM() {
const isPageLocked = document.documentElement.style.pointerEvents;
if (divs[0] && (isPageLocked ? divs.length === sections.length : index === 0)) {
makeSectionVisible(divs[0].CodeMirror);
setTimeout(() => {
if ((document.activeElement || {}).localName !== 'input') {
divs[0].CodeMirror.focus();
}
});
}
}
}
function addSection(event, section) {
const div = template.section.cloneNode(true);
$('.applies-to-help', div).addEventListener('click', showAppliesToHelp);
$('.remove-section', div).addEventListener('click', removeSection);
$('.add-section', div).addEventListener('click', addSection);
$('.clone-section', div).addEventListener('click', cloneSection);
$('.move-section-up', div).addEventListener('click', moveSection);
$('.move-section-down', div).addEventListener('click', moveSection);
$('.beautify-section', div).addEventListener('click', beautify);
const code = (section || {}).code || '';
const appliesTo = $('.applies-to-list', div);
let appliesToAdded = false;
if (section) {
for (const i in propertyToCss) {
if (section[i]) {
section[i].forEach(url => {
addAppliesTo(appliesTo, propertyToCss[i], url);
appliesToAdded = true;
});
}
}
}
if (!appliesToAdded) {
addAppliesTo(appliesTo, event && 'url-prefix', '');
}
appliesTo.addEventListener('change', onChange);
appliesTo.addEventListener('input', onChange);
toggleTestRegExpVisibility();
appliesTo.addEventListener('change', toggleTestRegExpVisibility);
$('.test-regexp', div).onclick = () => {
regExpTester.toggle();
regExpTester.update(getRegExps());
};
function getRegExps() {
return [...appliesTo.children]
.map(item =>
!item.matches('.applies-to-everything') &&
$('.applies-type', item).value === 'regexp' &&
$('.applies-value', item).value.trim()
)
.filter(item => item);
}
function toggleTestRegExpVisibility() {
const show = getRegExps().length > 0;
div.classList.toggle('has-regexp', show);
appliesTo.oninput = appliesTo.oninput || show && (event => {
if (event.target.matches('.applies-value') &&
$('.applies-type', event.target.closest('.applies-to-item')).value === 'regexp') {
regExpTester.update(getRegExps());
}
});
}
const sections = $('#sections');
let cm;
if (event) {
let clickedSection = event && getSectionForChild(event.target, {includeDeleted: true});
clickedSection.insertAdjacentElement('afterend', div);
while (clickedSection && !clickedSection.matches('.section')) {
clickedSection = clickedSection.previousElementSibling;
}
const newIndex = getSections().indexOf(clickedSection) + 1;
cm = setupCodeMirror(div, code, newIndex);
makeSectionVisible(cm);
cm.focus();
} else {
sections.appendChild(div);
cm = setupCodeMirror(div, code);
}
linter.enableForEditor(cm);
linter.refreshReport();
div.CodeMirror = cm;
setCleanSection(div);
return div;
}
// may be invoked as a DOM listener
function addAppliesTo(list, type, value) {
let clickedItem;
if (this instanceof Node) {
clickedItem = this.closest('.applies-to-item');
list = this.closest('.applies-to-list');
// dummy <a> wrapper was clicked
if (arguments[0] instanceof Event) arguments[0].preventDefault();
}
const showingEverything = $('.applies-to-everything', list);
// blow away 'Everything' if it's there
if (showingEverything) {
list.removeChild(list.firstChild);
}
let item, toFocus;
// a section is added with known applies-to
if (type) {
item = template.appliesTo.cloneNode(true);
$('[name=applies-type]', item).value = type;
$('[name=applies-value]', item).value = value;
$('.remove-applies-to', item).addEventListener('click', removeAppliesTo);
// a "+" button was clicked
} else if (showingEverything || clickedItem) {
item = template.appliesTo.cloneNode(true);
toFocus = $('[name=applies-type]', item);
if (clickedItem) {
$('[name=applies-type]', item).value = $('[name="applies-type"]', clickedItem).value;
}
$('.remove-applies-to', item).addEventListener('click', removeAppliesTo);
// a global section is added
} else {
item = template.appliesToEverything.cloneNode(true);
}
$('.add-applies-to', item).addEventListener('click', addAppliesTo);
list.insertBefore(item, clickedItem && clickedItem.nextElementSibling);
if (toFocus) toFocus.focus();
}
function cloneSection(event) {
const section = getSectionForChild(event.target);
addSection(event, getSectionsHashes([section]).pop());
setCleanItem($('#sections'), false);
updateTitle();
}
function moveSection(event) {
const section = getSectionForChild(event.target);
const dir = event.target.closest('.move-section-up') ? -1 : 1;
const cm = section.CodeMirror;
const index = editors.indexOf(cm);
const newIndex = (index + dir + editors.length) % editors.length;
const currentNextEl = section.nextElementSibling;
const newSection = editors[newIndex].getSection();
newSection.insertAdjacentElement('afterend', section);
section.parentNode.insertBefore(newSection, currentNextEl || null);
cm.focus();
editors[index] = editors[newIndex];
editors[newIndex] = cm;
setCleanItem($('#sections'), false);
updateTitle();
}
function setupCodeMirror(sectionDiv, code, index = editors.length) {
const cm = CodeMirror(wrapper => {
$('.code-label', sectionDiv).insertAdjacentElement('afterend', wrapper);
}, {
value: code,
});
const wrapper = cm.display.wrapper;
let onChangeTimer;
cm.on('changes', (cm, changes) => {
clearTimeout(onChangeTimer);
onChangeTimer = setTimeout(indicateCodeChange, 200, cm, changes);
});
wrapper.addEventListener('keydown', event => nextPrevEditorOnKeydown(cm, event), true);
cm.on('paste', (cm, event) => {
const text = event.clipboardData.getData('text') || '';
if (
text.includes('@-moz-document') &&
text.replace(/\/\*[\s\S]*?(?:\*\/|$)/g, '')
.match(/@-moz-document[\s\r\n]+(url|url-prefix|domain|regexp)\(/)
) {
event.preventDefault();
fromMozillaFormat();
$('#help-popup').codebox.setValue(text);
$('#help-popup').codebox.clearHistory();
$('#help-popup').codebox.markClean();
}
if (editors.length === 1) {
setTimeout(() => {
if (cm.display.sizer.clientHeight > cm.display.wrapper.clientHeight) {
maximizeCodeHeight.stats = null;
maximizeCodeHeight(cm.getSection(), true);
}
});
}
});
if (!FIREFOX) {
cm.on('mousedown', (cm, event) => toggleContextMenuDelete.call(cm, event));
}
wrapper.classList.add('resize-grip-enabled');
let lastClickTime = 0;
const resizeGrip = wrapper.appendChild(template.resizeGrip.cloneNode(true));
resizeGrip.onmousedown = event => {
if (event.button !== 0) {
return;
}
event.preventDefault();
if (Date.now() - lastClickTime < 500) {
lastClickTime = 0;
toggleSectionHeight(cm);
return;
}
lastClickTime = Date.now();
const minHeight = cm.defaultTextHeight() +
/* .CodeMirror-lines padding */
cm.display.lineDiv.offsetParent.offsetTop +
/* borders */
wrapper.offsetHeight - wrapper.clientHeight;
wrapper.style.pointerEvents = 'none';
document.body.style.cursor = 's-resize';
function resize(e) {
const cmPageY = wrapper.getBoundingClientRect().top + window.scrollY;
const height = Math.max(minHeight, e.pageY - cmPageY);
if (height !== wrapper.clientHeight) {
cm.setSize(null, height);
}
}
document.addEventListener('mousemove', resize);
document.addEventListener('mouseup', function resizeStop() {
document.removeEventListener('mouseup', resizeStop);
document.removeEventListener('mousemove', resize);
wrapper.style.pointerEvents = '';
document.body.style.cursor = '';
});
};
editors.splice(index, 0, cm);
return cm;
}
function indicateCodeChange(cm) {
const section = cm.getSection();
setCleanItem(section, cm.isClean(section.savedValue));
updateTitle();
}
function setupAutocomplete(cm, enable = true) {
const onOff = enable ? 'on' : 'off';
cm[onOff]('changes', autocompleteOnTyping);
cm[onOff]('pick', autocompletePicked);
}
function autocompleteOnTyping(cm, [info], debounced) {
if (
cm.state.completionActive ||
info.origin && !info.origin.includes('input') ||
!info.text.last
) {
return;
}
if (cm.state.autocompletePicked) {
cm.state.autocompletePicked = false;
return;
}
if (!debounced) {
debounce(autocompleteOnTyping, 100, cm, [info], true);
return;
}
if (info.text.last.match(/[-a-z!]+$/i)) {
cm.state.autocompletePicked = false;
cm.options.hintOptions.completeSingle = false;
cm.execCommand('autocomplete');
setTimeout(() => {
cm.options.hintOptions.completeSingle = true;
});
}
}
function autocompletePicked(cm) {
cm.state.autocompletePicked = true;
}
function nextPrevEditorOnKeydown(cm, event) {
const key = event.which;
if (key < 37 || key > 40 || event.shiftKey || event.altKey || event.metaKey) {
return;
}
const {line, ch} = cm.getCursor();
switch (key) {
case 37:
// arrow Left
if (line || ch) {
return;
}
// fallthrough to arrow Up
case 38:
// arrow Up
if (line > 0 || cm === editors[0]) {
return;
}
event.preventDefault();
event.stopPropagation();
cm = CodeMirror.commands.prevEditor(cm);
cm.setCursor(cm.doc.size - 1, key === 37 ? 1e20 : ch);
break;
case 39:
// arrow Right
if (line < cm.doc.size - 1 || ch < cm.getLine(line).length - 1) {
return;
}
// fallthrough to arrow Down
case 40:
// arrow Down
if (line < cm.doc.size - 1 || cm === editors.last) {
return;
}
event.preventDefault();
event.stopPropagation();
cm = CodeMirror.commands.nextEditor(cm);
cm.setCursor(0, 0);
break;
}
const animation = (cm.getSection().firstElementChild.getAnimations() || [])[0];
if (animation) {
animation.playbackRate = -1;
animation.currentTime = 2000;
animation.play();
}
}
function toggleSectionHeight(cm) {
if (cm.state.toggleHeightSaved) {
// restore previous size
cm.setSize(null, cm.state.toggleHeightSaved);
cm.state.toggleHeightSaved = 0;
} else {
// maximize
const wrapper = cm.display.wrapper;
const allBounds = $('#sections').getBoundingClientRect();
const pageExtrasHeight = allBounds.top + window.scrollY +
parseFloat(getComputedStyle($('#sections')).paddingBottom);
const sectionExtrasHeight = cm.getSection().clientHeight - wrapper.offsetHeight;
cm.state.toggleHeightSaved = wrapper.clientHeight;
cm.setSize(null, window.innerHeight - sectionExtrasHeight - pageExtrasHeight);
const bounds = cm.getSection().getBoundingClientRect();
if (bounds.top < 0 || bounds.bottom > window.innerHeight) {
window.scrollBy(0, bounds.top);
}
}
}
function getSectionForChild(el, {includeDeleted} = {}) {
return el.closest(`#sections > ${includeDeleted ? '*' : '.section'}`);
}
function getSections() {
return $$('#sections > .section');
}
function getSectionsHashes(elements = getSections()) {
const sections = [];
for (const div of elements) {
const meta = {urls: [], urlPrefixes: [], domains: [], regexps: []};
for (const li of $('.applies-to-list', div).childNodes) {
if (li.className === template.appliesToEverything.className) {
break;
}
const type = $('[name=applies-type]', li).value;
const value = $('[name=applies-value]', li).value;
if (type && value) {
meta[CssToProperty[type]].push(value);
}
}
const code = div.CodeMirror.getValue();
if (/^\s*$/.test(code) && Object.keys(meta).length === 0) {
continue;
}
meta.code = code;
sections.push(meta);
}
return sections;
}
function removeAppliesTo(event) {
event.preventDefault();
const appliesTo = event.target.closest('.applies-to-item');
const appliesToList = appliesTo.closest('.applies-to-list');
removeAreaAndSetDirty(appliesTo);
if (!appliesToList.hasChildNodes()) {
addAppliesTo(appliesToList);
}
}
function removeSection(event) {
const section = getSectionForChild(event.target);
const cm = section.CodeMirror;
if (event instanceof Event && (!cm.isClean() || !cm.isBlank())) {
const stub = template.deletedSection.cloneNode(true);
const MAX_LINES = 10;
const lines = [];
cm.doc.iter(0, MAX_LINES + 1, ({text}) => lines.push(text) && false);
stub.title = t('sectionCode') + '\n' +
'-'.repeat(20) + '\n' +
lines.slice(0, MAX_LINES).map(s => clipString(s, 100)).join('\n') +
(lines.length > MAX_LINES ? '\n...' : '');
$('.restore-section', stub).onclick = () => {
let el = stub;
while (el && !el.matches('.section')) {
el = el.previousElementSibling;
}
const index = el ? editors.indexOf(el) + 1 : 0;
editors.splice(index, 0, cm);
stub.parentNode.replaceChild(section, stub);
setCleanItem(section, false);
updateTitle();
cm.focus();
linter.enableForEditor(cm);
linter.refreshReport();
};
section.insertAdjacentElement('afterend', stub);
}
setCleanItem($('#sections'), false);
removeAreaAndSetDirty(section);
editors.splice(editors.indexOf(cm), 1);
linter.disableForEditor(cm);
linter.refreshReport();
}
function removeAreaAndSetDirty(area) {
const contributors = $$('.style-contributor', area);
if (!contributors.length) {
setCleanItem(area, false);
}
contributors.some(node => {
if (node.savedValue) {
// it's a saved section, so make it dirty and stop the enumeration
setCleanItem(area, false);
return true;
} else {
// it's an empty section, so undirty the applies-to items,
// otherwise orphaned ids would keep the style dirty
setCleanItem(node, true);
}
});
updateTitle();
area.remove();
}
function makeSectionVisible(cm) {
if (editors.length === 1) {
return;
}
const section = cm.getSection();
const bounds = section.getBoundingClientRect();
if (
(bounds.bottom > window.innerHeight && bounds.top > 0) ||
(bounds.top < 0 && bounds.bottom < window.innerHeight)
) {
if (bounds.top < 0) {
window.scrollBy(0, bounds.top - 1);
} else {
window.scrollBy(0, bounds.bottom - window.innerHeight + 1);
}
}
}
function maximizeCodeHeight(sectionDiv, isLast) {
const cm = sectionDiv.CodeMirror;
const stats = maximizeCodeHeight.stats = maximizeCodeHeight.stats || {totalHeight: 0, deltas: []};
if (!stats.cmActualHeight) {
stats.cmActualHeight = getComputedHeight(cm.display.wrapper);
}
if (!stats.sectionMarginTop) {
stats.sectionMarginTop = parseFloat(getComputedStyle(sectionDiv).marginTop);
}
const sectionTop = sectionDiv.getBoundingClientRect().top - stats.sectionMarginTop;
if (!stats.firstSectionTop) {
stats.firstSectionTop = sectionTop;
}
const extrasHeight = getComputedHeight(sectionDiv) - stats.cmActualHeight;
const cmMaxHeight = window.innerHeight - extrasHeight - sectionTop - stats.sectionMarginTop;
const cmDesiredHeight = cm.display.sizer.clientHeight + 2 * cm.defaultTextHeight();
const cmGrantableHeight = Math.max(stats.cmActualHeight, Math.min(cmMaxHeight, cmDesiredHeight));
stats.deltas.push(cmGrantableHeight - stats.cmActualHeight);
stats.totalHeight += cmGrantableHeight + extrasHeight;
if (!isLast) {
return;
}
stats.totalHeight += stats.firstSectionTop;
if (stats.totalHeight <= window.innerHeight) {
editors.forEach((cm, index) => {
cm.setSize(null, stats.deltas[index] + stats.cmActualHeight);
});
return;
}
// scale heights to fill the gap between last section and bottom edge of the window
const sections = $('#sections');
const available = window.innerHeight - sections.getBoundingClientRect().bottom -
parseFloat(getComputedStyle(sections).marginBottom);
if (available <= 0) {
return;
}
const totalDelta = stats.deltas.reduce((sum, d) => sum + d, 0);
const q = available / totalDelta;
const baseHeight = stats.cmActualHeight - stats.sectionMarginTop;
stats.deltas.forEach((delta, index) => {
editors[index].setSize(null, baseHeight + Math.floor(q * delta));
});
function getComputedHeight(el) {
const compStyle = getComputedStyle(el);
return el.getBoundingClientRect().height +
parseFloat(compStyle.marginTop) + parseFloat(compStyle.marginBottom);
}
}

View File

@ -405,5 +405,8 @@ function createSourceEditor(style) {
replaceStyle, replaceStyle,
isDirty: dirty.isDirty, isDirty: dirty.isDirty,
getStyle: () => style, getStyle: () => style,
getEditors: () => [cm],
getLastActivatedEditor: () => cm,
scrollToEditor: () => {}
}; };
} }