Build a full-width CMS canvas and restore featured home products
This commit is contained in:
+233
-37
@@ -108,6 +108,77 @@ jQuery(function ($) {
|
||||
filter();
|
||||
});
|
||||
|
||||
function bodyEdits(original, edited) {
|
||||
// Work in Unicode code points, then encode offsets in UTF-8 for PHP.
|
||||
const before = Array.from(original);
|
||||
const after = Array.from(edited);
|
||||
const encoder = new TextEncoder();
|
||||
const anchorSize = 32;
|
||||
let start = 0;
|
||||
let beforeEnd = before.length;
|
||||
let afterEnd = after.length;
|
||||
while (start < beforeEnd && start < afterEnd && before[start] === after[start]) start++;
|
||||
while (beforeEnd > start && afterEnd > start && before[beforeEnd - 1] === after[afterEnd - 1]) {
|
||||
beforeEnd--;
|
||||
afterEnd--;
|
||||
}
|
||||
if (beforeEnd === start && afterEnd === start) return [];
|
||||
|
||||
const anchors = new Map();
|
||||
for (let index = start; index + anchorSize <= beforeEnd; index += anchorSize) {
|
||||
const key = before.slice(index, index + anchorSize).join('');
|
||||
if (!anchors.has(key)) anchors.set(key, []);
|
||||
anchors.get(key).push(index);
|
||||
}
|
||||
|
||||
const edits = [];
|
||||
let oldIndex = start;
|
||||
let newIndex = start;
|
||||
let byteOffset = encoder.encode(before.slice(0, start).join('')).length;
|
||||
function copy() {
|
||||
const first = oldIndex;
|
||||
while (oldIndex < beforeEnd && newIndex < afterEnd && before[oldIndex] === after[newIndex]) {
|
||||
oldIndex++;
|
||||
newIndex++;
|
||||
}
|
||||
byteOffset += encoder.encode(before.slice(first, oldIndex).join('')).length;
|
||||
}
|
||||
|
||||
function replace(oldEnd, newEnd) {
|
||||
if (oldEnd === oldIndex && newEnd === newIndex) return;
|
||||
const removed = encoder.encode(before.slice(oldIndex, oldEnd).join('')).length;
|
||||
edits.push([byteOffset, removed, after.slice(newIndex, newEnd).join('')]);
|
||||
byteOffset += removed;
|
||||
oldIndex = oldEnd;
|
||||
newIndex = newEnd;
|
||||
}
|
||||
|
||||
for (let scan = start; scan + anchorSize <= afterEnd && edits.length < 511; scan++) {
|
||||
const matches = anchors.get(after.slice(scan, scan + anchorSize).join(''));
|
||||
if (!matches) continue;
|
||||
let low = 0;
|
||||
let high = matches.length;
|
||||
while (low < high) {
|
||||
const middle = Math.floor((low + high) / 2);
|
||||
if (matches[middle] < oldIndex) low = middle + 1;
|
||||
else high = middle;
|
||||
}
|
||||
if (low === matches.length) continue;
|
||||
let nextOld = matches[low];
|
||||
let nextNew = scan;
|
||||
while (nextOld > oldIndex && nextNew > newIndex && before[nextOld - 1] === after[nextNew - 1]) {
|
||||
nextOld--;
|
||||
nextNew--;
|
||||
}
|
||||
replace(nextOld, nextNew);
|
||||
copy();
|
||||
scan = newIndex - 1;
|
||||
}
|
||||
replace(beforeEnd, afterEnd);
|
||||
|
||||
return edits;
|
||||
}
|
||||
|
||||
$('[data-preview-studio]').each(function () {
|
||||
const $studio = $(this);
|
||||
const $frame = $studio.find('iframe');
|
||||
@@ -116,7 +187,7 @@ jQuery(function ($) {
|
||||
const width = $window.width();
|
||||
const height = $window.height();
|
||||
if (!width || !height) return;
|
||||
const viewport = $studio.hasClass('studio-phone') ? 390 : 1280;
|
||||
const viewport = $studio.hasClass('studio-phone') ? 390 : Math.max(1280, width);
|
||||
const scale = Math.min(1, width / viewport);
|
||||
$window.addClass('has-scaled-preview');
|
||||
$frame.css({
|
||||
@@ -132,7 +203,17 @@ jQuery(function ($) {
|
||||
$(window).on('resize', fitPreview);
|
||||
}
|
||||
fitPreview();
|
||||
const $settings = $studio.closest('.studio-layout').find('.studio-inspector');
|
||||
const $layout = $studio.closest('.studio-layout');
|
||||
const $settings = $layout.find('.studio-inspector');
|
||||
const $sizing = $studio.find('[data-media-sizing]');
|
||||
const $width = $sizing.find('[data-media-width]');
|
||||
const availableWidths = Array.from($width.get(0).options, ({value}) => value).filter((value) => value !== '0');
|
||||
const sizeClasses = availableWidths.map((value) => 'studio-media-' + value);
|
||||
const $presets = $layout.find('[data-canvas-presets]');
|
||||
const $templateStatus = $presets.find('[data-template-status]');
|
||||
const $pending = $presets.find('[data-template-pending]');
|
||||
const heroControls = new Map();
|
||||
let selectedMedia;
|
||||
$studio.on('click', '[data-preview-size]', function () {
|
||||
const $button = $(this);
|
||||
$studio.toggleClass('studio-phone', $button.data('preview-size') === 'phone');
|
||||
@@ -157,12 +238,14 @@ jQuery(function ($) {
|
||||
let sections = [];
|
||||
let saveComplete = false;
|
||||
|
||||
function sectionChanges() {
|
||||
return sections.flatMap(({key, version, fields}) => {
|
||||
function sectionChanges(withEdits = true) {
|
||||
return sections.flatMap(({key, version, fields, source}) => {
|
||||
const changes = {};
|
||||
for (const [field, {node, initial}] of Object.entries(fields)) {
|
||||
const value = field === 'body' ? node.innerHTML : node.textContent;
|
||||
if (value !== initial) changes[field] = value;
|
||||
if (version === null || value !== initial) {
|
||||
changes[field] = withEdits && field === 'body' && version !== null ? bodyEdits(source, value) : value;
|
||||
}
|
||||
}
|
||||
return Object.keys(changes).length ? [{key, version, fields: changes}] : [];
|
||||
});
|
||||
@@ -171,11 +254,11 @@ jQuery(function ($) {
|
||||
$settings.on('studio:sync', () => pageInput('canvas_sections').val(JSON.stringify(sectionChanges())));
|
||||
$settings.on('studio:saved', () => { saveComplete = true; });
|
||||
$settings.on('studio:busy', (_event, busy) => {
|
||||
$studio.prop('inert', busy);
|
||||
$layout.prop('inert', busy);
|
||||
$settings.prop('inert', busy);
|
||||
});
|
||||
$(window).on('beforeunload', (event) => {
|
||||
if (!saveComplete && (sectionChanges().length || JSON.stringify(settingsSnapshot()) !== savedSettings)) {
|
||||
if (!saveComplete && (sectionChanges(false).length || JSON.stringify(settingsSnapshot()) !== savedSettings)) {
|
||||
event.preventDefault();
|
||||
event.originalEvent.returnValue = '';
|
||||
}
|
||||
@@ -184,7 +267,7 @@ jQuery(function ($) {
|
||||
function openProperties(heading, values, apply, mime = null, allowEmptyUrl = false) {
|
||||
$properties.find('[data-property-heading]').text(heading);
|
||||
$propertyError.prop('hidden', true);
|
||||
for (const key of ['label', 'url', 'alt', 'poster']) {
|
||||
for (const key of ['label', 'url', 'alt', 'poster', 'quicklinks']) {
|
||||
const visible = Object.hasOwn(values, key);
|
||||
$propertyForm.find('[data-property-row="' + key + '"]').prop('hidden', !visible);
|
||||
propertyInput(key).val(visible ? values[key] : '');
|
||||
@@ -205,7 +288,7 @@ jQuery(function ($) {
|
||||
event.preventDefault();
|
||||
const {values, apply, mime, allowEmptyUrl} = dialogAction;
|
||||
const result = Object.fromEntries(Object.keys(values).map((field) => [field, propertyInput(field).val().trim()]));
|
||||
if ((!result.url && !allowEmptyUrl) || (result.url && !safeLink(result.url, mime !== null))
|
||||
if ((Object.hasOwn(result, 'url') && ((!result.url && !allowEmptyUrl) || (result.url && !safeLink(result.url, mime !== null))))
|
||||
|| (result.poster && !safeLink(result.poster, true))) {
|
||||
$propertyError.prop('hidden', false).text('请输入有效的站内地址或链接。媒体也可使用 HTTPS 地址。');
|
||||
return;
|
||||
@@ -292,6 +375,7 @@ jQuery(function ($) {
|
||||
function syncImage() {
|
||||
const path = pageInput('image').val().trim();
|
||||
const valid = safeLink(path, true);
|
||||
setMediaWidth($visual.get(0), pageInput('image_scale').val());
|
||||
$visual.prop('hidden', !valid).parent().toggleClass('hero-text-only', !valid);
|
||||
if (valid) $image.attr('src', path);
|
||||
else $image.removeAttr('src');
|
||||
@@ -299,7 +383,8 @@ jQuery(function ($) {
|
||||
}
|
||||
$settings.find('[name="image"], [name="alt"]').on('input.canvas', syncImage);
|
||||
syncImage();
|
||||
$image.attr({tabindex: '0', role: 'button', 'aria-label': '编辑首屏图片'}).on('click', () => {
|
||||
$image.attr({tabindex: '0', role: 'button', 'aria-label': '编辑首屏图片'});
|
||||
heroControls.set('image', () => {
|
||||
openProperties('首屏图片', {url: pageInput('image').val(), alt: pageInput('alt').val()}, ({url, alt}) => {
|
||||
pageInput('image').val(url);
|
||||
pageInput('alt').val(alt);
|
||||
@@ -314,12 +399,10 @@ jQuery(function ($) {
|
||||
const $url = pageInput('url' + index);
|
||||
function sync() {
|
||||
const url = $url.val().trim();
|
||||
const target = url === '/#product' && $doc.find('.hero-home').length ? '/services' : url;
|
||||
$button.text($label.val()).attr('href', safeLink(target) ? target : '#').prop('hidden', !$label.val() && !url);
|
||||
$button.text($label.val()).attr('href', safeLink(url) ? url : '#').prop('hidden', !$label.val() && !url);
|
||||
}
|
||||
$label.add($url).on('input.canvas', sync);
|
||||
$button.on('click', (event) => {
|
||||
event.preventDefault();
|
||||
const editButton = () => {
|
||||
openProperties('首屏按钮', {label: $label.val(), url: $url.val()}, ({label, url}) => {
|
||||
if (Boolean(label) !== Boolean(url)) {
|
||||
$propertyError.prop('hidden', false).text('请同时填写按钮文案和链接,或将两项都留空。');
|
||||
@@ -329,6 +412,11 @@ jQuery(function ($) {
|
||||
$url.val(url);
|
||||
sync();
|
||||
}, null, true);
|
||||
};
|
||||
heroControls.set(index, editButton);
|
||||
$button.on('click', (event) => {
|
||||
event.preventDefault();
|
||||
editButton();
|
||||
});
|
||||
sync();
|
||||
});
|
||||
@@ -366,6 +454,12 @@ jQuery(function ($) {
|
||||
$navigation.prop('hidden', !$navContent.children().length);
|
||||
}
|
||||
$navInput.on('input.canvas', syncNavigation);
|
||||
heroControls.set('navigation', () => {
|
||||
openProperties('本页目录', {quicklinks: $navInput.val()}, ({quicklinks}) => {
|
||||
$navInput.val(quicklinks);
|
||||
syncNavigation();
|
||||
});
|
||||
});
|
||||
syncNavigation();
|
||||
}
|
||||
|
||||
@@ -403,6 +497,109 @@ jQuery(function ($) {
|
||||
}, (tag === 'img' ? 'image' : tag) + '/');
|
||||
}
|
||||
|
||||
function registerSection(section, version = Number(section.dataset.studioSection)) {
|
||||
const fields = {};
|
||||
for (const node of section.querySelectorAll('[data-studio-part]')) {
|
||||
const part = node.dataset.studioPart;
|
||||
const body = part === 'body';
|
||||
const label = {title: '区块标题', lead: '添加区块简介', body: '区块正文'}[part];
|
||||
if (body) {
|
||||
node.contentEditable = 'true';
|
||||
node.setAttribute('aria-label', label);
|
||||
node.dataset.studioPlaceholder = label;
|
||||
} else {
|
||||
configureText(node, label, part === 'lead');
|
||||
}
|
||||
fields[part] = {node, initial: body ? node.innerHTML : node.textContent};
|
||||
}
|
||||
const source = new TextDecoder('utf-8', {ignoreBOM: true}).decode(Uint8Array.from(
|
||||
atob(section.dataset.studioSource || ''), (byte) => byte.charCodeAt(0)
|
||||
));
|
||||
sections.push({key: section.id, version, fields, source});
|
||||
}
|
||||
|
||||
function setMediaWidth(node, width) {
|
||||
node.classList.remove(...sizeClasses);
|
||||
if (availableWidths.includes(width)) node.classList.add('studio-media-' + width);
|
||||
}
|
||||
|
||||
function selectMedia(node) {
|
||||
selectedMedia?.removeAttribute('data-studio-selected');
|
||||
selectedMedia = node;
|
||||
if (!node) {
|
||||
$sizing.prop('hidden', true);
|
||||
return;
|
||||
}
|
||||
node.setAttribute('data-studio-selected', '');
|
||||
const width = node.hasAttribute('data-studio-hero-image') ? pageInput('image_scale').val()
|
||||
: availableWidths.find((value) => node.classList.contains('studio-media-' + value)) || '0';
|
||||
$width.val(width);
|
||||
$sizing.prop('hidden', false);
|
||||
}
|
||||
|
||||
function replaceMedia() {
|
||||
if (!selectedMedia?.isConnected) return;
|
||||
if (selectedMedia.hasAttribute('data-studio-hero-image')) heroControls.get('image')();
|
||||
else editResource(selectedMedia);
|
||||
}
|
||||
|
||||
$width.on('change', function () {
|
||||
if (!selectedMedia?.isConnected) return;
|
||||
const hero = selectedMedia.hasAttribute('data-studio-hero-image');
|
||||
if (hero) pageInput('image_scale').val(this.value);
|
||||
setMediaWidth(hero ? selectedMedia.parentElement : selectedMedia, this.value);
|
||||
});
|
||||
$sizing.on('click', '[data-replace-media]', replaceMedia);
|
||||
$layout.on('click', '[data-hero-control]', function () {
|
||||
heroControls.get(this.dataset.heroControl)?.();
|
||||
});
|
||||
$presets.on('mousedown', '[data-canvas-template]', (event) => event.preventDefault());
|
||||
$presets.on('click', '[data-canvas-template]', function () {
|
||||
const markup = $presets.find('template[data-preset="' + this.dataset.canvasTemplate + '"]').get(0).innerHTML;
|
||||
if ($presets.find('[data-template-inline]').prop('checked')) {
|
||||
if (!activeBody) {
|
||||
$templateStatus.text('先在画布中选择要插入的区块正文。');
|
||||
return;
|
||||
}
|
||||
// Insert at the saved caret without replacing any selected text.
|
||||
const insertion = savedRange?.cloneRange();
|
||||
insertion?.collapse(false);
|
||||
editBody(activeBody, insertion, 'insertHTML', markup);
|
||||
$templateStatus.text('已插入当前正文。');
|
||||
return;
|
||||
}
|
||||
if (sections.filter(({version}) => version === null).length >= 50) {
|
||||
$templateStatus.text('请先保存,再添加更多区块。');
|
||||
return;
|
||||
}
|
||||
const end = doc.querySelector('[data-studio-section-end]');
|
||||
const section = end.content.firstElementChild.cloneNode(true);
|
||||
const id = 'block-' + Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, '0')).join('');
|
||||
section.id = id;
|
||||
const title = section.querySelector('[data-studio-part="title"]');
|
||||
title.id = 'heading-' + id;
|
||||
title.textContent = this.textContent.trim();
|
||||
section.setAttribute('aria-labelledby', title.id);
|
||||
section.querySelector('[data-studio-part="body"]').innerHTML = markup;
|
||||
end.before(section);
|
||||
registerSection(section, null);
|
||||
section.scrollIntoView({block: 'start'});
|
||||
section.querySelector('[data-studio-part="body"]').focus({preventScroll: true});
|
||||
const $cancel = $('<button>', {type: 'button', text: '取消新增:' + title.textContent});
|
||||
const $item = $('<li>').append($cancel).appendTo($pending);
|
||||
$pending.prop('hidden', false);
|
||||
$cancel.on('click', () => {
|
||||
if (section.contains(activeBody)) selectBody(null);
|
||||
if (section.contains(selectedMedia)) selectMedia(null);
|
||||
section.remove();
|
||||
sections = sections.filter(({key}) => key !== id);
|
||||
$item.remove();
|
||||
$pending.prop('hidden', !$pending.children().length);
|
||||
$templateStatus.text('已取消新增区块。');
|
||||
});
|
||||
$templateStatus.text('已添加 ' + title.textContent + ' 区块。');
|
||||
});
|
||||
|
||||
function attachCanvas() {
|
||||
doc = $frame.get(0).contentDocument;
|
||||
if (!doc?.querySelector('[data-studio-field]') || doc.documentElement.hasAttribute('data-studio-editing')) return;
|
||||
@@ -411,40 +608,38 @@ jQuery(function ($) {
|
||||
$settings.find(':input').off('.canvas');
|
||||
bindPage($doc);
|
||||
selectBody(null);
|
||||
sections = $doc.find('[data-studio-section]').map(function () {
|
||||
const fields = {};
|
||||
$(this).find('[data-studio-part]').each(function () {
|
||||
const part = this.dataset.studioPart;
|
||||
const body = part === 'body';
|
||||
const label = {title: '区块标题', lead: '添加区块简介', body: '区块正文'}[part];
|
||||
if (body) {
|
||||
this.contentEditable = 'true';
|
||||
this.setAttribute('aria-label', label);
|
||||
this.dataset.studioPlaceholder = label;
|
||||
} else {
|
||||
configureText(this, label, part === 'lead');
|
||||
}
|
||||
fields[part] = {node: this, initial: body ? this.innerHTML : this.textContent};
|
||||
});
|
||||
return {key: this.id, version: Number(this.dataset.studioSection), fields};
|
||||
}).get();
|
||||
selectMedia(null);
|
||||
$pending.empty().prop('hidden', true);
|
||||
sections = [];
|
||||
$doc.find('[data-studio-section]').each((_, section) => registerSection(section));
|
||||
|
||||
$doc.on('focusin.canvas', '[contenteditable]', function () {
|
||||
selectBody(this.dataset.studioPart === 'body' ? this : null);
|
||||
});
|
||||
$doc.on('selectionchange.canvas', rememberSelection);
|
||||
$doc.on('click.canvas', (event) => {
|
||||
if (!event.target.closest?.('[data-studio-selected]')) selectMedia(null);
|
||||
});
|
||||
$doc.on('click.canvas auxclick.canvas', 'a', (event) => event.preventDefault());
|
||||
$doc.on('click.canvas', '[data-studio-part="body"] a, [data-studio-part="body"] img, [data-studio-part="body"] audio, [data-studio-part="body"] video', function (event) {
|
||||
const mediaTargets = '[data-studio-hero-image], [data-studio-part="body"] :is(img, audio, video)';
|
||||
$doc.on('click.canvas dblclick.canvas', mediaTargets, function (event) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const node = this;
|
||||
selectBody(node.closest('[data-studio-part="body"]'));
|
||||
editResource(node);
|
||||
selectBody(this.closest('[data-studio-part="body"]'));
|
||||
selectMedia(this);
|
||||
if (event.type === 'dblclick') replaceMedia();
|
||||
});
|
||||
$doc.on('click.canvas', '[data-studio-part="body"] a', function (event) {
|
||||
event.preventDefault();
|
||||
if ($(this).find('img, audio, video').length && event.target.closest('img, audio, video')) return;
|
||||
selectBody(this.closest('[data-studio-part="body"]'));
|
||||
editResource(this);
|
||||
});
|
||||
$doc.on('keydown.canvas', '[data-studio-hero-image]', function (event) {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault();
|
||||
$(this).trigger('click');
|
||||
selectMedia(this);
|
||||
$width.trigger('focus');
|
||||
}
|
||||
});
|
||||
$doc.on('beforeinput.canvas', '[contenteditable="plaintext-only"]', (event) => {
|
||||
@@ -459,7 +654,8 @@ jQuery(function ($) {
|
||||
}
|
||||
});
|
||||
$toolbar.prop('hidden', false);
|
||||
$studio.closest('.studio-layout').find('[data-canvas-jump]').prop('hidden', false);
|
||||
$layout.find('[data-canvas-jump]').prop('hidden', false);
|
||||
$layout.find('[data-canvas-template], [data-hero-control]').prop('disabled', false);
|
||||
}
|
||||
|
||||
$frame.on('load', attachCanvas);
|
||||
|
||||
Reference in New Issue
Block a user