forked from laysense/laysite
Prepare LaySite 1.5.0 canvas and publishing improvements
This commit is contained in:
+377
-42
@@ -333,6 +333,9 @@ jQuery(function ($) {
|
||||
const canvasFields = '[data-studio-field="heading"], [data-studio-field="accent"], [data-studio-field="lead"], [data-studio-field="eyebrow"], [data-studio-part="title"], [data-studio-part="lead"], [data-studio-action], [data-studio-nav-index]';
|
||||
const bodyElements = 'a, article, blockquote, button, details, div, dl, dt, dd, figure, figcaption, footer, h1, h2, h3, h4, h5, h6, header, hr, li, nav, ol, p, pre, progress, section, summary, table, ul, td, th, caption, small';
|
||||
const mediaTargets = '[data-studio-hero-image], [data-studio-part="body"] img, [data-studio-part="body"] audio, [data-studio-part="body"] video';
|
||||
const mediaPlaceholder = '/assets/system/media-placeholder.svg';
|
||||
const textElements = 'a, button, caption, figcaption, h1, h2, h3, h4, h5, h6, label, p, pre, small, span, summary, td, th, li, dt, dd, blockquote';
|
||||
const fillElements = 'article, aside, blockquote, div, figure, header, footer, main, nav, section, p, a, button, ul, ol, li, dl, table, td, th, details, summary';
|
||||
const $handle = $studio.find('[data-media-handle]');
|
||||
const minMediaWidth = Number($handle.attr('aria-valuemin'));
|
||||
const pathGroups = '[data-studio-navigation], [data-studio-breadcrumbs]';
|
||||
@@ -377,11 +380,26 @@ jQuery(function ($) {
|
||||
});
|
||||
const $toolbar = $studio.find('[data-canvas-toolbar]');
|
||||
const $commands = $toolbar.find('[data-canvas-command]');
|
||||
const $textTools = $toolbar.find('[data-canvas-text-tools]');
|
||||
const $textCommands = $toolbar.find('[data-canvas-text-commands]');
|
||||
const $insertTools = $toolbar.find('[data-canvas-insert]');
|
||||
const $background = $toolbar.find('[data-canvas-background]');
|
||||
const $insertMedia = $commands.filter('[data-canvas-command="media"]');
|
||||
const $format = $toolbar.find('[data-canvas-format]');
|
||||
const $fontSize = $toolbar.find('[data-canvas-font-size]');
|
||||
const $fontPreset = $toolbar.find('[data-font-preset]');
|
||||
const $color = $toolbar.find('[data-canvas-color]');
|
||||
const $clearColor = $toolbar.find('[data-clear-color]');
|
||||
const $letter = $toolbar.find('[data-canvas-letter]');
|
||||
const $line = $toolbar.find('[data-canvas-line]');
|
||||
const $fill = $studio.find('[data-canvas-fill]');
|
||||
const $fillForm = $fill.find('form');
|
||||
const $fillTabs = $fill.find('[data-fill-tab]');
|
||||
const $fillError = $fill.find('[data-fill-error]');
|
||||
const fillInput = (name) => $fillForm.find('[name="' + name + '"]');
|
||||
const colorLabels = JSON.parse($fill.attr('data-color-labels'));
|
||||
let fillMode;
|
||||
let fillTarget;
|
||||
let textColorDialog = false;
|
||||
const $imageDisplay = $toolbar.find('[data-canvas-image-display]');
|
||||
const $source = $studio.find('[data-canvas-source]');
|
||||
const $sourcePart = $source.find('[data-source-part]');
|
||||
@@ -408,7 +426,7 @@ jQuery(function ($) {
|
||||
const propertyInput = (name) => $propertyForm.find('[name="' + name + '"]');
|
||||
const pageInput = (name) => $settings.find('[name="' + name + '"]');
|
||||
const settingsSnapshot = (includeHead = false) => $settings.serializeArray()
|
||||
.filter(({name}) => !['csrf', 'canvas_sections', 'canvas_order', 'provider_secret'].includes(name)
|
||||
.filter(({name}) => !['csrf', 'version', 'canvas_sections', 'canvas_order', 'provider_secret'].includes(name)
|
||||
&& (includeHead || name !== 'head_html'));
|
||||
let savedSettings = JSON.stringify(settingsSnapshot(true));
|
||||
let dialogAction;
|
||||
@@ -419,7 +437,8 @@ jQuery(function ($) {
|
||||
let textHost;
|
||||
let sections = [];
|
||||
let initialOrder;
|
||||
let saveComplete = false;
|
||||
let feedRefresh;
|
||||
const pendingFeeds = new Set();
|
||||
let syncPageFromInputs;
|
||||
let spacingTarget;
|
||||
let sourceEditor;
|
||||
@@ -428,19 +447,47 @@ jQuery(function ($) {
|
||||
const result = {};
|
||||
for (const name of node.classList) {
|
||||
const prefix = name.match(stylePattern)?.[1];
|
||||
if (prefix && (!textOnly || prefix === 'size' || prefix === 'color' || Object.hasOwn(formatOptions, prefix))) result[prefix] = name;
|
||||
if (prefix && (!textOnly || ['size', 'letter', 'line', 'color'].includes(prefix) || Object.hasOwn(formatOptions, prefix))) result[prefix] = name;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function installColor(token) {
|
||||
if (!colorSheet || canvasColors.has(token) || !/^studio-style-color-[a-f0-9]{6}$/.test(token)) return;
|
||||
colorSheet.insertRule('.' + token + '{color:#' + token.slice(-6) + '!important}', colorSheet.cssRules.length);
|
||||
function encodeImage(url) {
|
||||
return btoa(String.fromCharCode(...new TextEncoder().encode(url))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
function decodeImage(token) {
|
||||
if (!/^[A-Za-z0-9_-]{1,1334}$/.test(token)) return '';
|
||||
try {
|
||||
const bytes = Uint8Array.from(atob(token.replace(/-/g, '+').replace(/_/g, '/')), (byte) => byte.charCodeAt(0));
|
||||
const url = new TextDecoder('utf-8', {fatal: true, ignoreBOM: true}).decode(bytes);
|
||||
return bytes.length <= 1000 && safeLink(url, true) && token === encodeImage(url) ? url : '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function installStyleRule(token) {
|
||||
if (!colorSheet || canvasColors.has(token)) return;
|
||||
const color = token.match(/^studio-style-(color|fill-solid)-([0-9a-f]{6})$/);
|
||||
const gradient = token.match(/^studio-style-fill-gradient-(0|[1-9]\d{0,2})-([0-9a-f]{6})-([0-9a-f]{6})$/);
|
||||
let rule;
|
||||
if (color) rule = (color[1] === 'color' ? 'color:' : 'background:') + '#' + color[2] + '!important';
|
||||
else if (gradient && Number(gradient[1]) <= 360) {
|
||||
rule = 'background:linear-gradient(' + gradient[1] + 'deg,#' + gradient[2] + ',#' + gradient[3] + ')!important';
|
||||
} else if (token.startsWith('studio-style-fill-image-')) {
|
||||
const url = decodeImage(token.slice('studio-style-fill-image-'.length));
|
||||
if (!url) return;
|
||||
const escaped = url.replace(/["<>]/g, (character) => '\\' + character.charCodeAt(0).toString(16) + ' ');
|
||||
rule = 'background-image:url("' + escaped + '")!important;background-position:center!important;background-size:cover!important;background-repeat:no-repeat!important';
|
||||
}
|
||||
if (!rule) return;
|
||||
colorSheet.insertRule('.' + token + '{' + rule + '}', colorSheet.cssRules.length);
|
||||
canvasColors.add(token);
|
||||
}
|
||||
|
||||
function installMarkupColors(markup) {
|
||||
for (const [token] of markup.matchAll(/\bstudio-style-color-[a-f0-9]{6}(?![\w-])/g)) installColor(token);
|
||||
function installMarkupStyles(markup) {
|
||||
for (const [token] of markup.matchAll(/\bstudio-style-(?:color|fill)-[a-z0-9_-]+/gi)) installStyleRule(token);
|
||||
}
|
||||
|
||||
function putStyle(node, property, value) {
|
||||
@@ -448,7 +495,7 @@ jQuery(function ($) {
|
||||
if (current) node.classList.remove(current);
|
||||
if (value !== '') {
|
||||
const token = 'studio-style-' + property + '-' + value;
|
||||
if (property === 'color') installColor(token);
|
||||
if (property === 'color' || property === 'fill') installStyleRule(token);
|
||||
node.classList.add(token);
|
||||
}
|
||||
}
|
||||
@@ -486,7 +533,7 @@ jQuery(function ($) {
|
||||
const parent = tokens ? doc.createElement('span') : node;
|
||||
if (tokens) {
|
||||
parent.className = tokens;
|
||||
installMarkupColors(tokens);
|
||||
installMarkupStyles(tokens);
|
||||
node.append(parent);
|
||||
}
|
||||
lineBreaks(text).split('\n').forEach((line, index) => {
|
||||
@@ -557,7 +604,7 @@ jQuery(function ($) {
|
||||
function setPageStyle(node, style) {
|
||||
node.classList.remove(...Object.values(classesOf(node)));
|
||||
if (style?.classes) {
|
||||
installMarkupColors(style.classes);
|
||||
installMarkupStyles(style.classes);
|
||||
node.classList.add(...style.classes.split(' '));
|
||||
}
|
||||
}
|
||||
@@ -613,15 +660,100 @@ jQuery(function ($) {
|
||||
pageInput('canvas_sections').val(JSON.stringify(sectionChanges()));
|
||||
pageInput('canvas_order').val(canvasOrder() === initialOrder ? '' : canvasOrder());
|
||||
});
|
||||
$settings.on('studio:saved', () => { saveComplete = true; });
|
||||
function refreshDynamicSections(keys) {
|
||||
for (const key of keys) pendingFeeds.add(key);
|
||||
if (!pendingFeeds.size) return;
|
||||
feedRefresh?.abort();
|
||||
const version = pageInput('version').val();
|
||||
feedRefresh = $.ajax({url: $frame.attr('src'), dataType: 'text', cache: false}).done((html) => {
|
||||
if (version !== pageInput('version').val()) return;
|
||||
const preview = doc.createElement('template');
|
||||
preview.innerHTML = html;
|
||||
for (const entry of sections) {
|
||||
if (!pendingFeeds.has(entry.key) || JSON.stringify(entry.feed) !== entry.initialFeed) continue;
|
||||
const current = entry.fields.body.node;
|
||||
const saved = preview.content.getElementById(entry.key)?.querySelector('[data-studio-part="body"]');
|
||||
if (!saved) continue;
|
||||
const dynamicChildren = (body) => [...body.parentElement.children]
|
||||
.filter((child) => child !== body && !child.classList.contains('section-heading'));
|
||||
entry.node.querySelector('[data-studio-module-note]')?.remove();
|
||||
dynamicChildren(current).forEach((node) => node.remove());
|
||||
current.before(...dynamicChildren(saved).map((node) => doc.importNode(node, true)));
|
||||
}
|
||||
pendingFeeds.clear();
|
||||
installMarkupStyles(html);
|
||||
historyObserver?.takeRecords();
|
||||
scheduleLayers();
|
||||
});
|
||||
}
|
||||
|
||||
$settings.on('studio:saved', (_event, saved, submitter) => {
|
||||
const versions = new Map(saved.sections.map((section) => [section.key, section]));
|
||||
const dynamic = [];
|
||||
for (const entry of sections) {
|
||||
const revision = versions.get(entry.key);
|
||||
if (!revision) continue;
|
||||
if (entry.feed && (Object.hasOwn(revision, 'feed') || submitter?.name === 'status'
|
||||
|| entry.node.querySelector('[data-studio-module-note]'))) dynamic.push(entry.key);
|
||||
entry.version = revision.version;
|
||||
entry.node.dataset.studioSection = revision.version;
|
||||
if (Object.hasOwn(revision, 'body')) entry.source = revision.body;
|
||||
if (Object.hasOwn(revision, 'feed')) {
|
||||
entry.feed = revision.feed ? JSON.parse(revision.feed) : null;
|
||||
if (entry.node.classList.contains('section')) entry.node.classList.toggle('network', entry.feed?.mode === 'network');
|
||||
}
|
||||
entry.initialFeed = JSON.stringify(entry.feed);
|
||||
for (const [field, state] of Object.entries(entry.fields)) {
|
||||
state.initial = field === 'body' ? cleanBody(state.node) : plainText(state.node);
|
||||
state.initialAlignment = field === 'body' ? '' : getAlignment(state.node);
|
||||
}
|
||||
entry.initialPresentation = JSON.stringify(sectionPresentation(entry));
|
||||
delete entry.template;
|
||||
delete entry.copyOf;
|
||||
}
|
||||
for (const entry of sections) {
|
||||
entry.node.querySelector('[data-studio-module-note]')?.remove();
|
||||
}
|
||||
deletedSections = [];
|
||||
initialOrder = canvasOrder();
|
||||
pageInput('version').val(saved.version);
|
||||
pageInput('provider_secret').val('');
|
||||
pageInput('canvas_sections').val('');
|
||||
pageInput('canvas_order').val('');
|
||||
savedSettings = JSON.stringify(settingsSnapshot(true));
|
||||
|
||||
const published = saved.status === 'published';
|
||||
const status = published ? '已发布' : '草稿';
|
||||
$('[data-page-editor-title]').text('编辑 ' + saved.name);
|
||||
document.title = '编辑 ' + saved.name + ' CMS';
|
||||
$('[data-page-publication]').text(status).attr('data-published', String(published));
|
||||
const publicLink = $settings.attr('data-public-page') === '1' && published;
|
||||
$('[data-page-public]').prop('hidden', !publicLink);
|
||||
$('[data-page-preview]').prop('hidden', publicLink);
|
||||
$settings.find('[data-publish-button]').val(published ? 'draft' : 'published')
|
||||
.find('[data-publication-action]').each(function () {
|
||||
this.hidden = this.dataset.publicationAction === saved.status;
|
||||
});
|
||||
const message = submitter?.name === 'status' ? (published ? '页面已发布。' : '页面已转为草稿。') : '页面已保存。';
|
||||
const $feedback = submitter && $studio.get(0).contains(submitter) ? $studio : $settings;
|
||||
$feedback.find('[data-page-save-feedback]').text(message).prop('hidden', false);
|
||||
|
||||
// Old snapshots may reference sections deleted by this save.
|
||||
history.length = 0;
|
||||
historyIndex = 0;
|
||||
lastHistoryGroup = null;
|
||||
captureHistory();
|
||||
renderLayers();
|
||||
refreshDynamicSections(dynamic);
|
||||
});
|
||||
$settings.on('studio:busy', (_event, busy) => {
|
||||
$layout.prop('inert', busy);
|
||||
$settings.prop('inert', busy);
|
||||
});
|
||||
$(window).on('beforeunload', (event) => {
|
||||
if (!saveComplete && (sectionChanges(false).length || pageInput('provider_secret').filter(':enabled').val()
|
||||
if (sectionChanges(false).length || pageInput('provider_secret').filter(':enabled').val()
|
||||
|| initialOrder !== undefined && canvasOrder() !== initialOrder
|
||||
|| JSON.stringify(settingsSnapshot(true)) !== savedSettings)) {
|
||||
|| JSON.stringify(settingsSnapshot(true)) !== savedSettings) {
|
||||
event.preventDefault();
|
||||
event.originalEvent.returnValue = '';
|
||||
}
|
||||
@@ -681,7 +813,7 @@ jQuery(function ($) {
|
||||
activeBody = body;
|
||||
savedRange = null;
|
||||
}
|
||||
$commands.prop('disabled', !activeBody);
|
||||
syncFormatControls();
|
||||
}
|
||||
|
||||
function editBody(body, range, command, value) {
|
||||
@@ -713,15 +845,39 @@ jQuery(function ($) {
|
||||
|| parent.closest('[data-studio-part="body"], [data-studio-section], [data-studio-style-field]');
|
||||
}
|
||||
|
||||
function textTarget(node) {
|
||||
const styled = styleTarget(node);
|
||||
if (!styled || styled.matches(mediaTargets)) return null;
|
||||
if (styled.matches(canvasFields)) return styled;
|
||||
return styled.closest('[data-studio-part="body"]')
|
||||
&& (styled.matches(textElements) || [...styled.childNodes].some((child) =>
|
||||
child.nodeType === 3 && child.textContent.trim())) && styled.textContent.trim() ? styled : null;
|
||||
}
|
||||
|
||||
function formatTarget() {
|
||||
if (selectedElement && !textTarget(selectedElement)) return null;
|
||||
if (textRange?.commonAncestorContainer.isConnected && textHost?.contains(textRange.commonAncestorContainer)) {
|
||||
if (!textRange.collapsed) return textHost;
|
||||
const anchor = textRange.startContainer;
|
||||
const element = anchor.nodeType === 1 ? anchor : anchor.parentElement;
|
||||
if (!textRange.collapsed && selectedText().length) {
|
||||
return textTarget(element.closest(textElements)) || textHost;
|
||||
}
|
||||
if (!selectedElement && doc.activeElement === textHost) {
|
||||
const anchor = textRange.startContainer;
|
||||
return styleTarget(editableBodyElement(anchor.parentElement || textHost) || textHost);
|
||||
return textTarget(element.closest(textElements)) || textTarget(textHost);
|
||||
}
|
||||
}
|
||||
return styleTarget(selectedElement);
|
||||
return textTarget(selectedElement);
|
||||
}
|
||||
|
||||
function backgroundTarget(node) {
|
||||
if (!node || node.matches(mediaTargets)) return null;
|
||||
const target = styleTarget(node);
|
||||
return target?.matches(fillElements) ? target : null;
|
||||
}
|
||||
|
||||
function insertionBody() {
|
||||
if (activeBody?.isConnected) return activeBody;
|
||||
return selectedElement?.closest('[data-studio-section]')?.querySelector('[data-studio-part="body"]') || null;
|
||||
}
|
||||
|
||||
function formatState(node, property) {
|
||||
@@ -751,7 +907,15 @@ jQuery(function ($) {
|
||||
|
||||
function syncFormatControls() {
|
||||
const target = doc && formatTarget();
|
||||
const canInsertText = Boolean(target && activeBody);
|
||||
const canInsertMedia = Boolean(insertionBody());
|
||||
const canFill = Boolean(backgroundTarget(selectedElement));
|
||||
$textTools.prop('hidden', !target);
|
||||
$format.add($fontSize).add($fontPreset).prop('disabled', !target);
|
||||
$textCommands.prop('hidden', !canInsertText);
|
||||
$insertTools.prop('hidden', !canInsertMedia && !canFill);
|
||||
$background.prop('hidden', !canFill);
|
||||
$insertMedia.prop('hidden', !canInsertMedia);
|
||||
const sample = target && (selectedText()[0]?.node || target);
|
||||
const element = sample?.nodeType === 1 ? sample : sample?.parentElement;
|
||||
const computed = element ? doc.defaultView.getComputedStyle(element) : null;
|
||||
@@ -760,9 +924,14 @@ jQuery(function ($) {
|
||||
: (computed ? String(Math.round(parseFloat(computed.fontSize))) : '');
|
||||
if (!$fontSize.is(':focus')) $fontSize.val(size);
|
||||
$fontPreset.val($fontPreset.find('option').toArray().some((option) => option.value === size) ? size : '');
|
||||
$color.add($clearColor).prop('disabled', !target);
|
||||
const rgb = computed?.color.match(/^rgba?\((\d+), (\d+), (\d+)(?:, [\d.]+)?\)$/);
|
||||
if (rgb && !$color.is(':focus')) $color.val('#' + rgb.slice(1).map((channel) => Number(channel).toString(16).padStart(2, '0')).join(''));
|
||||
const letter = element && classesOf(element).letter;
|
||||
const line = element && classesOf(element).line;
|
||||
const lineHeight = computed && parseFloat(computed.lineHeight) / parseFloat(computed.fontSize);
|
||||
if (!$letter.is(':focus')) $letter.val(letter ? letter.slice('studio-style-letter-'.length)
|
||||
: computed && Number.isFinite(parseFloat(computed.letterSpacing)) ? String(Math.round(parseFloat(computed.letterSpacing))) : '');
|
||||
if (!$line.is(':focus')) $line.val(line ? Number(line.slice('studio-style-line-'.length)) / 10
|
||||
: Number.isFinite(lineHeight) ? lineHeight.toFixed(1) : '');
|
||||
$color.find('rect').attr('fill', computed && cssHex(computed.color) || 'currentColor');
|
||||
$format.each(function () {
|
||||
$(this).attr('aria-pressed', String(Boolean(sample) && formatState(sample, this.dataset.canvasFormat)));
|
||||
});
|
||||
@@ -808,15 +977,129 @@ jQuery(function ($) {
|
||||
positionSelection();
|
||||
}
|
||||
|
||||
$color.on('change', function () {
|
||||
if (/^#[0-9a-f]{6}$/i.test(this.value)) applyTextStyle('color', this.value.slice(1).toLowerCase());
|
||||
function cssHex(value) {
|
||||
if (/^#[a-f0-9]{6}$/i.test(value)) return value.toLowerCase();
|
||||
if (/^#[a-f0-9]{3}$/i.test(value)) return value.toLowerCase().replace(/[a-f0-9]/g, (digit) => digit + digit);
|
||||
const rgb = value.match(/^rgba?\((\d+), (\d+), (\d+)(?:, [\d.]+)?\)$/);
|
||||
return rgb ? '#' + rgb.slice(1).map((channel) => Number(channel).toString(16).padStart(2, '0')).join('') : '';
|
||||
}
|
||||
|
||||
function activePalette() {
|
||||
const palette = pageInput('palette_id').val();
|
||||
const custom = $settings.find('[data-palette-option]').filter((_, button) => button.dataset.paletteOption === palette)
|
||||
.find('circle').toArray();
|
||||
const colors = Object.fromEntries(custom.map((circle) => [circle.dataset.colorKey, circle.getAttribute('fill')]));
|
||||
const root = doc.querySelector('#main-content') || doc.documentElement;
|
||||
const styles = doc.defaultView.getComputedStyle(root);
|
||||
return Object.entries(colorLabels).flatMap(([key, label]) => {
|
||||
const color = colors[key] || cssHex(styles.getPropertyValue('--' + key).trim()) || (key === 'button-ink' ? '#ffffff' : '');
|
||||
return color ? [{color, label}] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function showFillTab(mode, focus = false) {
|
||||
fillMode = mode;
|
||||
$fillTabs.each(function () {
|
||||
const selected = this.dataset.fillTab === mode;
|
||||
$(this).attr('aria-selected', String(selected)).prop('tabIndex', selected ? 0 : -1);
|
||||
if (selected && focus) this.focus();
|
||||
});
|
||||
$fill.find('[data-fill-panel]').each(function () {
|
||||
this.hidden = this.dataset.fillPanel !== mode;
|
||||
$(this).find('input').prop('disabled', this.hidden);
|
||||
});
|
||||
}
|
||||
|
||||
function openFill(text) {
|
||||
fillTarget = text ? formatTarget() : backgroundTarget(selectedElement);
|
||||
if (!fillTarget?.isConnected) return;
|
||||
textColorDialog = text;
|
||||
const computed = doc.defaultView.getComputedStyle(fillTarget);
|
||||
const palette = activePalette();
|
||||
const [type, ...parts] = (classesOf(fillTarget).fill || '').slice('studio-style-fill-'.length).split('-');
|
||||
const sample = selectedText()[0]?.node.parentElement || fillTarget;
|
||||
const foreground = cssHex(doc.defaultView.getComputedStyle(sample).color);
|
||||
fillInput('solid').val(text ? foreground || '#111a2e'
|
||||
: type === 'solid' ? '#' + parts[0] : cssHex(computed.backgroundColor) || '#ffffff');
|
||||
fillInput('start').val(type === 'gradient' ? '#' + parts[1] : '#ffffff');
|
||||
fillInput('end').val(type === 'gradient' ? '#' + parts[2] : '#214ed7');
|
||||
fillInput('angle').val(type === 'gradient' ? parts[0] : '90');
|
||||
fillInput('image').val(type === 'image' ? decodeImage(parts.join('-')) : '');
|
||||
$fill.find('[data-fill-title]').text(text ? '文字颜色' : '背景填充');
|
||||
$fill.find('[data-fill-tabs]').prop('hidden', text);
|
||||
$fill.find('[data-fill-panel="solid"]').attr('aria-labelledby', text ? 'canvas-fill-title' : 'fill-tab-solid');
|
||||
$fillError.prop('hidden', true);
|
||||
$fill.find('[data-fill-swatches]').each(function () {
|
||||
const $row = $(this).empty();
|
||||
for (const {color, label} of palette) {
|
||||
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
|
||||
const circle = document.createElementNS(svg.namespaceURI, 'circle');
|
||||
$(svg).attr({viewBox: '0 0 20 20', 'aria-hidden': 'true'}).append($(circle).attr({cx: '10', cy: '10', r: '8', fill: color}));
|
||||
$row.append($('<button>', {type: 'button', 'data-swatch': color, title: label + ' ' + color, 'aria-label': label + ' ' + color}).append(svg));
|
||||
}
|
||||
});
|
||||
showFillTab(['solid', 'gradient', 'image'].includes(type) && !text ? type : 'solid');
|
||||
$fill.get(0).showModal();
|
||||
if (text) fillInput('solid').trigger('focus');
|
||||
}
|
||||
|
||||
function applyFill(value) {
|
||||
if (textColorDialog) applyTextStyle('color', value);
|
||||
else if (fillTarget?.isConnected) putStyle(fillTarget, 'fill', value);
|
||||
$fill.get(0).close();
|
||||
positionSelection();
|
||||
}
|
||||
|
||||
$fill.on('click', '[data-fill-tab]', function () { showFillTab(this.dataset.fillTab); })
|
||||
.on('keydown', '[data-fill-tab]', function (event) {
|
||||
const offset = {ArrowLeft: -1, ArrowRight: 1}[event.key];
|
||||
if (!offset && !['Home', 'End'].includes(event.key)) return;
|
||||
event.preventDefault();
|
||||
const index = event.key === 'Home' ? 0 : event.key === 'End' ? $fillTabs.length - 1
|
||||
: ($fillTabs.index(this) + offset + $fillTabs.length) % $fillTabs.length;
|
||||
showFillTab($fillTabs.get(index).dataset.fillTab, true);
|
||||
}).on('click', '[data-swatch]', function () {
|
||||
fillInput(this.parentElement.dataset.fillSwatches).val(this.dataset.swatch);
|
||||
}).on('click', '[data-fill-media]', () => {
|
||||
openPicker('image/', (file) => fillInput('image').val(file.url).trigger('focus'));
|
||||
}).on('click', '[data-fill-reset]', () => applyFill(''))
|
||||
.on('click', '[data-fill-close]', () => $fill.get(0).close());
|
||||
$fillForm.on('submit', (event) => {
|
||||
event.preventDefault();
|
||||
if (textColorDialog) {
|
||||
applyFill(fillInput('solid').val().slice(1));
|
||||
} else if (fillMode === 'solid') {
|
||||
applyFill('solid-' + fillInput('solid').val().slice(1));
|
||||
} else if (fillMode === 'gradient') {
|
||||
const angle = fillInput('angle').val() || '90';
|
||||
applyFill(['gradient', Number(angle), fillInput('start').val().slice(1), fillInput('end').val().slice(1)].join('-'));
|
||||
} else {
|
||||
const url = fillInput('image').val().trim();
|
||||
if (!safeLink(url, true) || new TextEncoder().encode(url).length > 1000) {
|
||||
$fillError.text('请选择图片,或输入有效的站内路径或 HTTPS 链接(最多 1000 字节)。').prop('hidden', false);
|
||||
return;
|
||||
}
|
||||
applyFill('image-' + encodeImage(url));
|
||||
}
|
||||
});
|
||||
$clearColor.on('click', () => applyTextStyle('color', ''));
|
||||
$color.on('click', () => openFill(true));
|
||||
$background.on('click', () => openFill(false));
|
||||
$letter.add($line).on('change', function () {
|
||||
const line = this.hasAttribute('data-canvas-line');
|
||||
if (this.validity.valid) applyTextStyle(line ? 'line' : 'letter',
|
||||
this.value === '' ? '' : String(Math.round(this.valueAsNumber * (line ? 10 : 1))));
|
||||
}).on('keydown', function (event) {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
this.blur();
|
||||
}
|
||||
});
|
||||
|
||||
$imageDisplay.on('change', function () {
|
||||
if (selectedMedia?.matches('img')) putStyle(sizingTarget(), 'display', this.value);
|
||||
positionSelection();
|
||||
});
|
||||
$toolbar.on('mousedown', '[data-canvas-format], [data-clear-color]', (event) => event.preventDefault());
|
||||
$toolbar.on('mousedown', '[data-canvas-format], [data-canvas-color], [data-canvas-background]', (event) => event.preventDefault());
|
||||
$format.on('click', function () { applyTextStyle(this.dataset.canvasFormat); });
|
||||
$fontPreset.on('change', function () {
|
||||
applyTextStyle('size', this.value);
|
||||
@@ -886,14 +1169,11 @@ jQuery(function ($) {
|
||||
$toolbar.on('mousedown', '[data-canvas-command]', (event) => event.preventDefault());
|
||||
$toolbar.on('click', '[data-canvas-command]', function () {
|
||||
const command = this.dataset.canvasCommand;
|
||||
const body = activeBody;
|
||||
const body = command === 'media' ? insertionBody() : activeBody;
|
||||
const range = savedRange?.cloneRange();
|
||||
const edit = (action, value) => editBody(body, range, action, value);
|
||||
if (command === 'media') {
|
||||
openPicker('', async (file) => {
|
||||
const markup = await mediaMarkup(file);
|
||||
if (markup) edit('insertHTML', markup);
|
||||
});
|
||||
insertMediaPlaceholder(body, range);
|
||||
} else if (command === 'link') {
|
||||
openProperties('插入链接', {label: range?.toString() || '', url: ''}, ({label, url}) => {
|
||||
queueMicrotask(() => {
|
||||
@@ -957,7 +1237,7 @@ jQuery(function ($) {
|
||||
const preview = new DOMParser().parseFromString(html, 'text/html');
|
||||
const replacement = $(preview.body).children(selector).get(0);
|
||||
if (!replacement) return;
|
||||
installMarkupColors(replacement.outerHTML);
|
||||
installMarkupStyles(replacement.outerHTML);
|
||||
$target.replaceWith(doc.importNode(replacement, true));
|
||||
rendered = choice;
|
||||
});
|
||||
@@ -998,6 +1278,13 @@ jQuery(function ($) {
|
||||
syncImage();
|
||||
$image.attr({tabindex: '0', role: 'button', 'aria-label': '编辑首屏图片'});
|
||||
heroControls.set('image', () => {
|
||||
if (!pageInput('image').val()) {
|
||||
pageInput('image').val(mediaPlaceholder);
|
||||
syncImage();
|
||||
selectElement($image.get(0));
|
||||
$image.get(0).scrollIntoView({block: 'nearest'});
|
||||
return;
|
||||
}
|
||||
openProperties('首屏图片', {url: pageInput('image').val(), alt: pageInput('alt').val()}, ({url, alt}) => {
|
||||
pageInput('image').val(url);
|
||||
pageInput('alt').val(alt);
|
||||
@@ -1066,7 +1353,11 @@ jQuery(function ($) {
|
||||
});
|
||||
pageInput('palette_id').on('change.canvas', function () {
|
||||
$doc.find('[data-page-palette]').remove();
|
||||
if (this.value) $('<link>', {rel: 'stylesheet', href: '/palette/' + this.value + '.css', 'data-page-palette': ''}).appendTo($doc.find('head'));
|
||||
if (this.value) {
|
||||
$('<link>', {rel: 'stylesheet', href: '/palette/' + this.value + '.css', 'data-page-palette': ''})
|
||||
.one('load', syncFormatControls).appendTo($doc.find('head'));
|
||||
} else syncFormatControls();
|
||||
pageInput('palette_id').trigger('change.palettePicker');
|
||||
});
|
||||
syncActions();
|
||||
|
||||
@@ -1195,7 +1486,7 @@ jQuery(function ($) {
|
||||
syncPageFromInputs = () => {
|
||||
const presentation = pagePresentation();
|
||||
$heroSource.html(presentation.heroHtml ?? '');
|
||||
installMarkupColors(presentation.heroHtml ?? '');
|
||||
installMarkupStyles(presentation.heroHtml ?? '');
|
||||
$doc.find('[data-studio-field]').each(function () {
|
||||
const field = this.dataset.studioField;
|
||||
paintText(this, pageInput(field).val(), presentation[field]?.runs);
|
||||
@@ -1220,6 +1511,10 @@ jQuery(function ($) {
|
||||
|
||||
function editResource(node) {
|
||||
const tag = node.localName;
|
||||
if (node.classList.contains('studio-media-placeholder')) {
|
||||
choosePlaceholderMedia(node);
|
||||
return;
|
||||
}
|
||||
if (node.matches('a.studio-member-slot') && $settings.find('[data-shared-auth]').length) {
|
||||
syncMemberSettings();
|
||||
$settings.find('[data-shared-auth]').prop('open', true).find('[name=provider_mode]').trigger('focus');
|
||||
@@ -1437,6 +1732,7 @@ jQuery(function ($) {
|
||||
$elementTools.find('[data-element-source]').prop('hidden', !node?.matches('[data-studio-section], [data-studio-hero]'));
|
||||
selectedMedia = node?.matches(mediaTargets) ? node : null;
|
||||
$sizing.prop('hidden', !selectedMedia);
|
||||
$imageDisplay.closest('label').prop('hidden', !selectedMedia?.matches('img'));
|
||||
$imageDisplay.prop('disabled', !selectedMedia?.matches('img')).val(classesOf(sizingTarget() || doc.documentElement).display?.slice('studio-style-display-'.length) || '');
|
||||
$layers.find('.studio-layer-row[aria-current]').removeAttr('aria-current');
|
||||
if (node) {
|
||||
@@ -1574,8 +1870,8 @@ jQuery(function ($) {
|
||||
event.preventDefault();
|
||||
const categories = moduleInput('feed_categories[]').filter(':checked').map((_, node) => node.value).get();
|
||||
const title = moduleInput('module_title').val().trim();
|
||||
if (!title || !categories.length) {
|
||||
$moduleDialog.find('[data-module-error]').text('请填写标题并至少选择一个分类。').prop('hidden', false);
|
||||
if (!title) {
|
||||
$moduleDialog.find('[data-module-error]').text('请填写模块标题。').prop('hidden', false);
|
||||
return;
|
||||
}
|
||||
const {node, fields} = editedModule;
|
||||
@@ -1733,7 +2029,7 @@ jQuery(function ($) {
|
||||
});
|
||||
selectElement(null);
|
||||
changed.forEach(([key, {node}], index) => {
|
||||
installMarkupColors(markup[index]);
|
||||
installMarkupStyles(markup[index]);
|
||||
node.replaceChildren(fragments[index]);
|
||||
if (node.dataset.studioPlaceholder) node.toggleAttribute('data-studio-empty', !plainText(node));
|
||||
if (key === 'hero') {
|
||||
@@ -2146,10 +2442,45 @@ jQuery(function ($) {
|
||||
editBody(body, insertion, 'insertHTML', template.innerHTML);
|
||||
}
|
||||
|
||||
function insertMediaPlaceholder(body, range, mime = '') {
|
||||
if (!body?.isConnected) return;
|
||||
const type = mime.split('/')[0];
|
||||
const node = doc.createElement('img');
|
||||
node.src = mediaPlaceholder;
|
||||
node.alt = {image: '图片占位', video: '视频占位', audio: '音频占位'}[type] || '媒体占位';
|
||||
node.className = 'studio-media-placeholder' + (type ? ' studio-media-placeholder-' + type : '');
|
||||
const existing = new Set(body.querySelectorAll('img.studio-media-placeholder'));
|
||||
insertInBody(node.outerHTML, body, range);
|
||||
const inserted = [...body.querySelectorAll('img.studio-media-placeholder')].find((image) => !existing.has(image));
|
||||
if (!inserted) return;
|
||||
selectBody(body);
|
||||
selectElement(inserted);
|
||||
inserted.scrollIntoView({block: 'nearest'});
|
||||
$studio.find('[data-canvas-status]').text('已插入占位图。双击占位图或选择「替换媒体」添加文件。');
|
||||
}
|
||||
|
||||
function choosePlaceholderMedia(placeholder) {
|
||||
const type = ['image', 'video', 'audio'].find((kind) => placeholder.classList.contains('studio-media-placeholder-' + kind));
|
||||
openPicker(type ? type + '/' : '', async (file) => {
|
||||
const markup = await mediaMarkup(file);
|
||||
if (!markup || !placeholder.isConnected) return;
|
||||
const template = doc.createElement('template');
|
||||
template.innerHTML = markup;
|
||||
const media = template.content.firstElementChild;
|
||||
for (const token of placeholder.classList) {
|
||||
if (!token.startsWith('studio-media-placeholder') && (!media.matches('a') || !mediaWidthClass.test(token))) {
|
||||
media.classList.add(token);
|
||||
}
|
||||
}
|
||||
placeholder.replaceWith(media);
|
||||
selectElement(media);
|
||||
});
|
||||
}
|
||||
|
||||
$presets.on('mousedown', '[data-canvas-template], [data-canvas-element]', (event) => event.preventDefault());
|
||||
$presets.on('click', '[data-canvas-element]', function () {
|
||||
const $status = $presets.find('[data-element-status]');
|
||||
const body = activeBody;
|
||||
const body = this.dataset.elementMime ? insertionBody() : activeBody;
|
||||
const range = savedRange?.cloneRange();
|
||||
if (!body) {
|
||||
$status.text('请先在画布中选中要插入的正文。');
|
||||
@@ -2162,7 +2493,8 @@ jQuery(function ($) {
|
||||
$status.text('已插入' + $(this).text() + '。');
|
||||
};
|
||||
if (this.dataset.elementMime) {
|
||||
openPicker(this.dataset.elementMime, async (file) => add(await mediaMarkup(file)));
|
||||
insertMediaPlaceholder(body, range, this.dataset.elementMime);
|
||||
$status.text('已插入' + $(this).text().trim() + '占位图。');
|
||||
} else {
|
||||
add($presets.find('template[data-element="' + this.dataset.canvasElement + '"]').get(0).innerHTML);
|
||||
}
|
||||
@@ -2205,7 +2537,10 @@ jQuery(function ($) {
|
||||
scopeTemplateIds(body, id);
|
||||
if (feed) {
|
||||
section.dataset.studioDynamic = '';
|
||||
section.dataset.studioFeed = feed;
|
||||
const config = JSON.parse(feed);
|
||||
const available = new Set(moduleInput('feed_categories[]').map((_, input) => input.value).get());
|
||||
config.categories = config.categories.filter((category) => available.has(category));
|
||||
section.dataset.studioFeed = JSON.stringify(config);
|
||||
section.tabIndex = 0;
|
||||
noteModule(section, '保存页面后将加载动态内容。');
|
||||
}
|
||||
@@ -2243,7 +2578,7 @@ jQuery(function ($) {
|
||||
})),
|
||||
deleted: [...deletedSections],
|
||||
};
|
||||
const key = JSON.stringify(state, (name, value) => name === 'entry' ? undefined : value);
|
||||
const key = JSON.stringify(state, (name, value) => ['entry', 'note'].includes(name) ? undefined : value);
|
||||
if (history[historyIndex]?.key === key) return;
|
||||
const time = performance.now();
|
||||
history.splice(historyIndex + 1);
|
||||
|
||||
Reference in New Issue
Block a user