From 0d99a3475bc4a18744d7fcd3bc31553503fcba9e Mon Sep 17 00:00:00 2001 From: ChatGPT Date: Sat, 28 Nov 2026 02:19:28 +0800 Subject: [PATCH] Add multiple gradient stops and image fill modes --- README.md | 4 +- app/Content/CanvasStyle.php | 61 ++++++- app/Content/Licenses.php | 2 + app/view/admin-layout.php | 4 + app/view/studio-fill.php | 35 ++-- public/assets/admin.css | 26 +++ public/assets/studio-fill.js | 170 ++++++++++++++++++++ public/assets/studio.js | 51 +++--- public/assets/vendor/grapick/LICENSE | 21 +++ public/assets/vendor/grapick/grapick.min.js | 2 + 10 files changed, 337 insertions(+), 39 deletions(-) create mode 100644 public/assets/studio-fill.js create mode 100644 public/assets/vendor/grapick/LICENSE create mode 100644 public/assets/vendor/grapick/grapick.min.js diff --git a/README.md b/README.md index e048274..675c427 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,9 @@ php start.php start - 媒体库和媒体选择器只列出用户上传文件。编辑器图标、示例资产、字体、模板缩略图和产品标识随程序发布。 - 发布后的站点具备独立标题、描述、canonical、Open Graph、站点地图和 robots.txt。可在「站点设置」配置站点名称和静态资源 CDN。 -选中文字后可调整字号、字距、行距、字形和颜色。选中支持背景的容器或组件后,可以选择纯色、线性渐变或背景图。文字颜色和背景色选择器均提供当前配色方案的色样。样式以经过校验的 CSS 类保存,内容中的内联 `style` 属性会被清理。网页和画布按需加载样式。 +选中文字后可调整字号、字距、行距、字形和颜色。选中支持背景的容器或组件后,可以选择纯色、渐变或背景图。渐变支持线性与中心扩散,可在色条上添加、拖动和删除色标。在线性模式下通过滑块调整角度。背景图可选覆盖、完整显示、拉伸、原始尺寸或平铺,并可调整图片位置。文字颜色和背景色选择器均提供当前配色方案的色样。样式以经过校验的 CSS 类保存,内容中的内联 `style` 属性会被清理。网页和画布按需加载样式。 + +渐变色标使用 Grapick 0.1.13,按 MIT 许可随后台提供。[Grapick 源码包](https://registry.npmjs.org/grapick/-/grapick-0.1.13.tgz) 在「网站页面」可删除页面。删除首页后,访问 `/` 会显示站点的 404 页面。要重建首页,新建网址标识为 `home` 的普通页面并发布即可。在「文章分类」删除分类会保留文章,并从动态组件的展示范围移除该分类。 diff --git a/app/Content/CanvasStyle.php b/app/Content/CanvasStyle.php index 5da266d..f65ac9e 100644 --- a/app/Content/CanvasStyle.php +++ b/app/Content/CanvasStyle.php @@ -27,6 +27,13 @@ final class CanvasStyle 'strike-on' => 'text-decoration-line:line-through', 'strike-off' => 'text-decoration-line:none', ]; private const PREFIX = 'studio-style-'; + private const IMAGE_SIZES = [ + 'cover' => 'cover', 'contain' => 'contain', 'stretch' => '100% 100%', 'original' => 'auto', 'tile' => 'auto', + ]; + private const IMAGE_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', + ]; public static function encode(array $presentation): string { @@ -175,18 +182,64 @@ final class CanvasStyle if (preg_match('/^gradient-(0|[1-9]\d{0,2})-([a-f0-9]{6})-([a-f0-9]{6})$/D', $token, $parts) && (int) $parts[1] <= 360) { return "background:linear-gradient({$parts[1]}deg,#{$parts[2]},#{$parts[3]})!important"; } - if (!preg_match('/^image-([A-Za-z0-9_-]{1,1334})$/D', $token, $parts)) { + if (str_starts_with($token, 'gradient-')) { + return self::gradient(substr($token, strlen('gradient-'))); + } + $size = 'cover'; + $position = 'c'; + if (preg_match('/^image-v2-([a-z]+)-([a-z]+)-([A-Za-z0-9_-]{1,1334})$/D', $token, $parts)) { + [, $size, $position, $encoded] = $parts; + } elseif (preg_match('/^image-([A-Za-z0-9_-]{1,1334})$/D', $token, $parts)) { + $encoded = $parts[1]; + } else { return null; } - $url = base64_decode(strtr($parts[1], '-_', '+/'), true); + if (!isset(self::IMAGE_SIZES[$size], self::IMAGE_POSITIONS[$position])) { + return null; + } + $url = base64_decode(strtr($encoded, '-_', '+/'), true); if ($url === false || strlen($url) > 1000 || !mb_check_encoding($url, 'UTF-8') || !Html::url($url, true) - || rtrim(strtr(base64_encode($url), '+/', '-_'), '=') !== $parts[1]) { + || rtrim(strtr(base64_encode($url), '+/', '-_'), '=') !== $encoded) { return null; } // Quote the URL for CSS and keep the result safe inside a raw-text HTML style element. $escaped = str_replace(['"', '<', '>'], ['\\22 ', '\\3c ', '\\3e '], $url); - return 'background-image:url("' . $escaped . '")!important;background-position:center!important;background-size:cover!important;background-repeat:no-repeat!important'; + $repeat = $size === 'tile' ? 'repeat' : 'no-repeat'; + + return 'background-image:url("' . $escaped . '")!important;background-position:' . self::IMAGE_POSITIONS[$position] + . '!important;background-size:' . self::IMAGE_SIZES[$size] . '!important;background-repeat:' . $repeat . '!important'; + } + + private static function gradient(string $token): ?string + { + $parts = explode('-', $token, 15); + $type = array_shift($parts); + if ($type === 'linear') { + $angle = array_shift($parts); + if ($angle === null || !preg_match('/^(0|[1-9]\d{0,2})$/D', $angle) || (int) $angle > 360) { + return null; + } + $direction = $angle . 'deg'; + } elseif ($type === 'radial') { + $direction = 'circle at center'; + } else { + return null; + } + if (count($parts) < 2 || count($parts) > 12) { + return null; + } + $last = 0; + $stops = []; + foreach ($parts as $stop) { + if (!preg_match('/^(0|[1-9]\d?|100)_([a-f0-9]{6})$/D', $stop, $color) || (int) $color[1] < $last) { + return null; + } + $last = (int) $color[1]; + $stops[] = "#{$color[2]} {$last}%"; + } + + return "background:{$type}-gradient($direction," . implode(',', $stops) . ')!important'; } public static function dynamicRules(string $markup): string diff --git a/app/Content/Licenses.php b/app/Content/Licenses.php index 189ebcb..1ef0a94 100644 --- a/app/Content/Licenses.php +++ b/app/Content/Licenses.php @@ -36,6 +36,8 @@ final class Licenses 'url' => 'https://github.com/codemirror/codemirror5', 'file' => $root . '/public/assets/vendor/codemirror/LICENSE'], 'js-beautify' => ['name' => 'JS Beautifier', 'version' => '1.15.4', 'license' => 'MIT', 'url' => 'https://github.com/beautifier/js-beautify', 'file' => $root . '/public/assets/vendor/js-beautify/LICENSE'], + 'grapick' => ['name' => 'Grapick', 'version' => '0.1.13', 'license' => 'MIT', + 'url' => 'https://github.com/artf/grapick', 'file' => $root . '/public/assets/vendor/grapick/LICENSE'], 'geist' => ['name' => 'Geist', 'license' => 'OFL-1.1', 'url' => 'https://github.com/vercel/geist-font', 'file' => $root . '/public/assets/geist-OFL.txt'], 'dompurify' => ['name' => 'DOMPurify', 'version' => self::declaredVersion($editor, '~@license DOMPurify\h+' . $version . '~'), 'license' => 'Apache-2.0 / MPL-2.0', diff --git a/app/view/admin-layout.php b/app/view/admin-layout.php index 76ae5cf..8117bb4 100644 --- a/app/view/admin-layout.php +++ b/app/view/admin-layout.php @@ -23,6 +23,10 @@ $active = match (true) { + + + + diff --git a/app/view/studio-fill.php b/app/view/studio-fill.php index e070ef6..33edba3 100644 --- a/app/view/studio-fill.php +++ b/app/view/studio-fill.php @@ -19,20 +19,37 @@ $e = View::escape(...);
diff --git a/public/assets/admin.css b/public/assets/admin.css index 09f32bc..a6d15fb 100644 --- a/public/assets/admin.css +++ b/public/assets/admin.css @@ -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; } diff --git a/public/assets/studio-fill.js b/public/assets/studio-fill.js new file mode 100644 index 0000000..fb02a9a --- /dev/null +++ b/public/assets/studio-fill.js @@ -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: '', 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); diff --git a/public/assets/studio.js b/public/assets/studio.js index 2557078..cff0930 100644 --- a/public/assets/studio.js +++ b/public/assets/studio.js @@ -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($('