Add multiple gradient stops and image fill modes

This commit is contained in:
2026-11-28 02:19:28 +08:00
parent a0df3e60de
commit 0d99a3475b
10 changed files with 337 additions and 39 deletions
+26
View File
@@ -537,3 +537,29 @@
.dashboard-page-actions > form > button { min-height: 2.25rem; padding: .28rem .55rem; }
.destructive-action:hover { color: #9c252a; border-color: #e6b6b9; background: #feebeb; }
[data-page-save-feedback] { margin: .35rem 0 0; }
.studio-gradient-preview {
min-height: 5rem; margin-block: .75rem .65rem; border: 1px solid var(--line);
border-radius: .45rem; background-color: var(--paper);
}
.studio-gradient-editor { margin: .55rem .8rem 1rem; }
.studio-gradient-editor .grp-wrapper { border-radius: .35rem; }
.studio-gradient-editor .grp-preview {
position: absolute; inset: 0; border-radius: inherit; outline: 1px solid var(--line); cursor: crosshair;
}
.studio-gradient-editor .grp-handler { height: 100%; width: 0; user-select: none; z-index: 1; }
.studio-gradient-editor .grp-handler-selected { z-index: 2; }
.studio-gradient-editor :is(.grp-handler-close-c, .grp-handler-cp-c) { display: none; }
.studio-gradient-editor .grp-handler-drag {
display: grid; place-items: center; position: absolute; inset: 50% auto auto 0; transform: translate(-50%, -50%);
width: 1.5rem; height: 1.5rem; border: 2px solid white; border-radius: 50%;
box-shadow: 0 0 0 1px #26344e99; cursor: ew-resize; touch-action: none;
}
.studio-gradient-editor .grp-handler-selected .grp-handler-drag { box-shadow: 0 0 0 2px var(--ink); }
.studio-gradient-editor .grp-handler-drag:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
.studio-gradient-controls { display: flex; flex-wrap: wrap; gap: .5rem .7rem; align-items: end; }
.studio-gradient-controls button { min-height: 2.35rem; padding: .3rem .6rem; }
.studio-gradient-controls input[type=number] { inline-size: 5.75rem; }
.canvas-fill [data-gradient-angle] input[type=range] { min-height: 2.1rem; padding: 0; accent-color: var(--accent); }
.canvas-fill [data-gradient-angle] output { font-variant-numeric: tabular-nums; }
.studio-background-image-options { margin-top: .75rem; }
+170
View File
@@ -0,0 +1,170 @@
'use strict';
window.LaySiteFill = (function ($) {
const hex = '[a-f0-9]{6}';
const anglePattern = /^(0|[1-9]\d{0,2})$/;
const maxStops = 12;
const sizes = {cover: 'cover', contain: 'contain', stretch: '100% 100%', original: 'auto', tile: 'auto'};
const positions = {
c: 'center', tl: 'left top', tc: 'center top', tr: 'right top',
ml: 'left center', mr: 'right center', bl: 'left bottom', bc: 'center bottom', br: 'right bottom'
};
function read(value, decodeImage) {
const solid = value.match(new RegExp('^solid-(' + hex + ')$'));
if (solid) return {kind: 'solid', color: '#' + solid[1]};
const legacy = value.match(new RegExp('^gradient-(\\d{1,3})-(' + hex + ')-(' + hex + ')$'));
if (legacy && anglePattern.test(legacy[1]) && Number(legacy[1]) <= 360) {
return {kind: 'gradient', type: 'linear', angle: Number(legacy[1]), stops: [[0, '#' + legacy[2]], [100, '#' + legacy[3]]]};
}
if (value.startsWith('gradient-')) {
const [, type, ...parts] = value.split('-', 16);
if (!['linear', 'radial'].includes(type)) return null;
const angle = type === 'linear' ? parts.shift() : '90';
if (!anglePattern.test(angle) || Number(angle) > 360 || parts.length < 2 || parts.length > maxStops) return null;
const stops = [];
for (const part of parts) {
const stop = part.match(/^(0|[1-9]\d?|100)_([a-f0-9]{6})$/);
if (!stop || Number(stop[1]) < (stops.at(-1)?.[0] || 0)) return null;
stops.push([Number(stop[1]), '#' + stop[2]]);
}
return {kind: 'gradient', type, angle: Number(angle), stops};
}
if (!value.startsWith('image-')) return null;
const option = value.match(/^image-v2-([a-z]+)-([a-z]+)-([A-Za-z0-9_-]{1,1334})$/);
const [, size, position, payload] = option || ['', 'cover', 'c', value.slice('image-'.length)];
if (!Object.hasOwn(sizes, size) || !Object.hasOwn(positions, position)) return null;
const url = decodeImage(payload);
return url ? {kind: 'image', size, position, url} : null;
}
function declarations(fill) {
if (!fill) return '';
if (fill.kind === 'solid') return 'background:' + fill.color + '!important';
if (fill.kind === 'gradient') {
const direction = fill.type === 'linear' ? fill.angle + 'deg' : 'circle at center';
const stops = fill.stops.map(([position, color]) => color + ' ' + position + '%');
return 'background:' + fill.type + '-gradient(' + [direction, ...stops].join(',') + ')!important';
}
const url = fill.url.replace(/["<>]/g, (character) => '\\' + character.charCodeAt(0).toString(16) + ' ');
return 'background-image:url("' + url + '")!important;background-position:' + positions[fill.position]
+ '!important;background-size:' + sizes[fill.size] + '!important;background-repeat:'
+ (fill.size === 'tile' ? 'repeat' : 'no-repeat') + '!important';
}
function gradientEditor($dialog, colorHex) {
if (typeof window.Grapick !== 'function') return null;
const $track = $dialog.find('[data-gradient-track]');
const $preview = $dialog.find('[data-gradient-preview]');
const $type = $dialog.find('[name=gradient_type]');
const $angleRow = $dialog.find('[data-gradient-angle]');
const $angle = $angleRow.find('input');
const $color = $dialog.find('[name=stop_color]');
const $position = $dialog.find('[name=stop_position]');
const $add = $dialog.find('[data-gradient-add]');
const $remove = $dialog.find('[data-gradient-remove]');
const picker = new window.Grapick({
el: $track.get(0), height: '1.45rem', colorEl: '<span></span>', onValuePos: Math.round,
});
const thumb = (stop) => stop.getEl().querySelector('[data-toggle=handler-drag]');
function sync() {
const selected = picker.getSelected();
const stops = picker.getHandlers();
const radial = $type.val() === 'radial';
$angleRow.prop('hidden', radial).find('output').text($angle.val() + '°');
$preview.get(0).style.backgroundImage = picker.getValue(radial ? 'radial' : 'linear', radial ? 'center' : $angle.val() + 'deg');
if (selected) {
$color.val(colorHex(selected.getColor()));
if (!$position.is(':focus')) $position.val(selected.getPosition());
}
$add.prop('disabled', stops.length >= maxStops);
$remove.prop('disabled', !selected || stops.length <= 2);
for (const stop of stops) {
const color = colorHex(stop.getColor());
const handle = thumb(stop);
handle.style.backgroundColor = color;
$(handle).attr({'aria-label': '色标 ' + color, 'aria-valuenow': stop.getPosition(), 'aria-valuetext': stop.getPosition() + '%'});
}
}
function enableStop(stop) {
const handle = thumb(stop);
$(handle).attr({tabindex: 0, role: 'slider', 'aria-valuemin': 0, 'aria-valuemax': 100})
.on('focus', () => { if (!stop.isSelected()) stop.select(); })
.on('keydown', (event) => {
const offset = {ArrowLeft: -1, ArrowDown: -1, ArrowRight: 1, ArrowUp: 1}[event.key];
if (!offset && !['Home', 'End'].includes(event.key)) return;
event.preventDefault();
const next = event.key === 'Home' ? 0 : event.key === 'End' ? 100
: stop.getPosition() + offset * (event.shiftKey ? 10 : 1);
stop.setPosition(Math.max(0, Math.min(100, next)));
});
}
// Grapick owns pointer dragging and interpolation when a track position is clicked.
picker.on('handler:add', enableStop);
picker.on('handler:select', sync);
picker.on('change', sync);
$track.get(0).addEventListener('click', (event) => {
if (event.target.matches('.grp-preview') && picker.getHandlers().length >= maxStops) event.stopPropagation();
}, true);
$type.add($angle).on('input change', sync);
$color.on('input', function () { picker.getSelected()?.setColor(this.value); });
$position.on('input', function () {
if (this.value !== '' && this.validity.valid) picker.getSelected()?.setPosition(this.valueAsNumber);
}).on('blur', sync);
$add.on('click', () => {
const stops = picker.getHandlers();
if (stops.length >= maxStops) return;
const points = [0, ...stops.map((stop) => stop.getPosition()), 100];
let gap = 1;
for (let i = 2; i < points.length; i++) {
if (points[i] - points[i - 1] > points[gap] - points[gap - 1]) gap = i;
}
const before = stops[Math.max(0, gap - 2)];
const after = stops[Math.min(stops.length - 1, gap - 1)];
const channels = colorHex(before.getColor()).slice(1).match(/../g).map((value, index) => {
const other = colorHex(after.getColor()).slice(1 + 2 * index, 3 + 2 * index);
return Math.round((parseInt(value, 16) + parseInt(other, 16)) / 2).toString(16).padStart(2, '0');
});
const stop = picker.addHandler(Math.round((points[gap] + points[gap - 1]) / 2), '#' + channels.join(''));
thumb(stop).focus();
});
$remove.on('click', () => {
const stops = picker.getHandlers();
const selected = picker.getSelected();
if (!selected || stops.length <= 2) return;
const index = stops.indexOf(selected);
selected.remove();
thumb(stops[Math.min(index, stops.length - 1)]).focus();
});
function setup(initial, accent) {
const fill = initial?.kind === 'gradient' ? initial
: {type: 'linear', angle: 90, stops: [[0, '#ffffff'], [100, accent || '#214ed7']]};
$type.val(fill.type);
$angle.val(fill.angle);
picker.clear({silent: true});
for (const [position, color] of fill.stops) enableStop(picker.addHandler(position, color, false, {silent: true}));
picker.getHandler(0).select();
picker.updatePreview();
}
function value() {
const parts = ['gradient', $type.val()];
if ($type.val() === 'linear') parts.push($angle.val());
for (const stop of picker.getHandlers()) {
parts.push(stop.getPosition() + '_' + colorHex(stop.getColor()).slice(1));
}
return parts.join('-');
}
return {setup, value};
}
return {read, declarations, gradientEditor};
})(jQuery);
+26 -25
View File
@@ -396,6 +396,8 @@ jQuery(function ($) {
const $fillTabs = $fill.find('[data-fill-tab]');
const $fillError = $fill.find('[data-fill-error]');
const fillInput = (name) => $fillForm.find('[name="' + name + '"]');
const fillControls = window.LaySiteFill;
let gradientEditor;
const colorLabels = JSON.parse($fill.attr('data-color-labels'));
let fillMode;
let fillTarget;
@@ -469,18 +471,10 @@ jQuery(function ($) {
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';
}
const color = token.match(/^studio-style-color-([0-9a-f]{6})$/);
const fillPrefix = 'studio-style-fill-';
const rule = color ? 'color:#' + color[1] + '!important'
: token.startsWith(fillPrefix) && fillControls?.declarations(fillControls.read(token.slice(fillPrefix.length), decodeImage));
if (!rule) return;
colorSheet.insertRule('.' + token + '{' + rule + '}', colorSheet.cssRules.length);
canvasColors.add(token);
@@ -1007,12 +1001,13 @@ jQuery(function ($) {
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}] : [];
return color ? [{color, label, key}] : [];
});
}
function showFillTab(mode, focus = false) {
fillMode = mode;
$fillError.prop('hidden', true);
$fillTabs.each(function () {
const selected = this.dataset.fillTab === mode;
$(this).attr('aria-selected', String(selected)).prop('tabIndex', selected ? 0 : -1);
@@ -1020,7 +1015,7 @@ jQuery(function ($) {
});
$fill.find('[data-fill-panel]').each(function () {
this.hidden = this.dataset.fillPanel !== mode;
$(this).find('input').prop('disabled', this.hidden);
$(this).find('input, select').prop('disabled', this.hidden);
});
}
@@ -1030,15 +1025,18 @@ jQuery(function ($) {
textColorDialog = text;
const computed = doc.defaultView.getComputedStyle(fillTarget);
const palette = activePalette();
const [type, ...parts] = (classesOf(fillTarget).fill || '').slice('studio-style-fill-'.length).split('-');
const fill = fillControls?.read((classesOf(fillTarget).fill || '').slice('studio-style-fill-'.length), decodeImage);
if (!text) {
gradientEditor ??= fillControls?.gradientEditor($fill, cssHex);
gradientEditor?.setup(fill, palette.find(({key}) => key === 'accent')?.color);
}
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?.kind === 'solid' ? fill.color : cssHex(computed.backgroundColor) || '#ffffff');
fillInput('image').val(fill?.url || '');
fillInput('image_size').val(fill?.size || 'cover');
fillInput('image_position').val(fill?.position || 'c');
$fill.find('[data-fill-title]').text(text ? '文字颜色' : backgroundLabel(fillTarget));
$fill.find('[data-fill-tabs]').prop('hidden', text);
$fill.find('[data-fill-panel="solid"]').attr('aria-labelledby', text ? 'canvas-fill-title' : 'fill-tab-solid');
@@ -1052,7 +1050,7 @@ jQuery(function ($) {
$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');
showFillTab(!text && fill ? fill.kind : 'solid');
$fill.get(0).showModal();
if (text) fillInput('solid').trigger('focus');
}
@@ -1073,7 +1071,7 @@ jQuery(function ($) {
: ($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);
fillInput(this.parentElement.dataset.fillSwatches).val(this.dataset.swatch).trigger('input');
}).on('click', '[data-fill-media]', () => {
openPicker('image/', (file) => fillInput('image').val(file.url).trigger('focus'));
}).on('click', '[data-fill-reset]', () => applyFill(''))
@@ -1085,15 +1083,18 @@ jQuery(function ($) {
} 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('-'));
if (!gradientEditor) {
$fillError.text('渐变编辑器暂时无法加载,请刷新页面后重试。').prop('hidden', false);
return;
}
applyFill(gradientEditor.value());
} 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));
applyFill(['image-v2', fillInput('image_size').val(), fillInput('image_position').val(), encodeImage(url)].join('-'));
}
});
$color.on('click', () => openFill(true));
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) Artur Arseniev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
File diff suppressed because one or more lines are too long