AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat(editor): add per-gallery fit width and fit height (#655)
Andy Jarosze1210c664b1a
diff --git a/apps/web/src/components/MobileStandaloneTiptapEditor.tsx b/apps/web/src/components/MobileStandaloneTiptapEditor.tsxindex 7f6ab7c8..29eebde2 100644--- a/apps/web/src/components/MobileStandaloneTiptapEditor.tsx+++ b/apps/web/src/components/MobileStandaloneTiptapEditor.tsx@@ -7,8 +7,9 @@ import { FileAttachment } from "@/components/editor/FileAttachment";import Image from "@tiptap/extension-image";import { mergeAttributes } from "@tiptap/core";import Placeholder from "@tiptap/extension-placeholder";-import { createExcerpt, createEdgeEverDocumentExtensions, docToMarkdown, docToText, emptyDoc, getImageReferrerPolicy, isPdfAttachment, wrapDetailsContentHtml, type MemoDetail, type MemoEditSession, type Notebook, type TagSummary, type TiptapDoc } from "@edgeever/shared";+import { ImageGallery, createExcerpt, createEdgeEverDocumentExtensions, docToMarkdown, docToText, emptyDoc, getImageReferrerPolicy, isPdfAttachment, wrapDetailsContentHtml, type MemoDetail, type MemoEditSession, type Notebook, type TagSummary, type TiptapDoc } from "@edgeever/shared";import { createEdgeEverMathematics } from "@edgeever/shared/mathematics";+import { createNativeImageGalleryView, NATIVE_IMAGE_GALLERY_CSS } from "@edgeever/shared/native-image-gallery";import { NEW_IMAGE_WIDTH_PERCENT } from "@edgeever/shared/image-display";import { insertUploadedResources } from "@/lib/resource-insertion";import { getResourceInsertionTarget } from "@/lib/resource-insertion-target";@@ -87,6 +88,8 @@ export const MobileStandaloneTiptapEditor = ({const { t, i18n } = useTranslation();const memoId = memoIdProp ?? params.get("memoId");const locale = normalizeLocale(i18n.resolvedLanguage ?? i18n.language) ?? defaultLocale;+ const localeRef = useRef(locale);+ localeRef.current = locale;const draftKey = getMobileEditorDraftKey(memoId);const [memo, setMemo] = useState<MemoDetail | null>(null);const memoRef = useRef<MemoDetail | null>(null);@@ -207,6 +210,9 @@ export const MobileStandaloneTiptapEditor = ({allowBase64: false,inline: false,}),+ gallery: ImageGallery.extend({+ addNodeView() { return createNativeImageGalleryView(() => localeRef.current); },+ }),pdf: PdfAttachment,file: FileAttachment,table: { table: { renderWrapper: true } },@@ -959,6 +965,7 @@ export const MobileStandaloneTiptapEditor = ({return (<div className="mobile-editor-shell">+ <style>{NATIVE_IMAGE_GALLERY_CSS}</style><MobileEditorHeader saveLabel={saveLabel} statusClassName={statusClassName} saveState={saveState} onLeave={() => void leavePage()} /><main className="mobile-editor-main">diff --git a/apps/web/src/components/editor/ImageGallery.tsx b/apps/web/src/components/editor/ImageGallery.tsxindex 9843f2b5..92b43a08 100644--- a/apps/web/src/components/editor/ImageGallery.tsx+++ b/apps/web/src/components/editor/ImageGallery.tsx@@ -10,7 +10,10 @@ import { useTranslation } from "react-i18next";import {ImageGallery,IMAGE_GALLERY_LAYOUTS,+ IMAGE_GALLERY_FITS,+ resolveImageGalleryFit,resolveImageGalleryLayout,+ type ImageGalleryFit,type ImageGalleryLayout,} from "@edgeever/shared";import { cn } from "@/lib/utils";@@ -18,14 +21,16 @@ import { cn } from "@/lib/utils";const ImageGalleryNodeView = ({ editor, node, selected, updateAttributes }: NodeViewProps) => {const { t } = useTranslation();const layout = resolveImageGalleryLayout(node.attrs.layout);+ const fit = resolveImageGalleryFit(node.attrs.fit);const isEditable = useEditorState({editor,selector: ({ editor: activeEditor }) => activeEditor.isEditable,});- const setLayout = useCallback((nextLayout: ImageGalleryLayout) => {- updateAttributes({ layout: nextLayout });- }, [updateAttributes]);+ const setGalleryAttributes = useCallback((attributes: { layout?: ImageGalleryLayout; fit?: ImageGalleryFit }) => {+ updateAttributes(attributes);+ editor.commands.focus(undefined, { scrollIntoView: false });+ }, [editor, updateAttributes]);return (<NodeViewWrapper@@ -33,6 +38,7 @@ const ImageGalleryNodeView = ({ editor, node, selected, updateAttributes }: Nodedata-edgeever-image-gallery="true"data-image-count={node.childCount}data-image-gallery-layout={layout}+ data-image-gallery-fit={fit}>{isEditable ? (<div@@ -41,21 +47,37 @@ const ImageGalleryNodeView = ({ editor, node, selected, updateAttributes }: Nodearia-label={t("editor.imageGallery.toolbar")}role="toolbar">- {IMAGE_GALLERY_LAYOUTS.map((item) => (- <button- key={item}- type="button"- className={cn(- "edgeever-image-gallery__button",- layout === item && "is-active",- )}- aria-pressed={layout === item}- onMouseDown={(event) => event.preventDefault()}- onClick={() => setLayout(item)}- >- {t(`editor.imageGallery.layouts.${item}`)}- </button>- ))}+ <div className="edgeever-image-gallery__group" role="group" aria-label={t("editor.imageGallery.toolbar")}>+ {IMAGE_GALLERY_LAYOUTS.map((item) => (+ <button+ key={item}+ type="button"+ className={cn(+ "edgeever-image-gallery__button",+ layout === item && "is-active",+ )}+ aria-pressed={layout === item}+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => setGalleryAttributes({ layout: item })}+ >+ {t(`editor.imageGallery.layouts.${item}`)}+ </button>+ ))}+ </div>+ <div className="edgeever-image-gallery__group" role="group" aria-label={t("editor.imageGallery.fitLabel")}>+ {IMAGE_GALLERY_FITS.map((item) => (+ <button+ key={item}+ type="button"+ className={cn("edgeever-image-gallery__button", fit === item && "is-active")}+ aria-pressed={fit === item}+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => setGalleryAttributes({ fit: item })}+ >+ {t(`editor.imageGallery.fits.${item}`)}+ </button>+ ))}+ </div></div>) : null}<NodeViewContent className="edgeever-image-gallery__content" />diff --git a/apps/web/src/styles/globals.css b/apps/web/src/styles/globals.cssindex 64cd49e4..5249090d 100644--- a/apps/web/src/styles/globals.css+++ b/apps/web/src/styles/globals.css@@ -2241,6 +2241,25 @@ html[data-edgeever-extension-theme] .edgeever-memo-divider {object-fit: cover;}+/* Height fit keeps the full source image inside a consistent gallery tile. */+.ProseMirror [data-edgeever-image-gallery][data-image-gallery-fit="height"] > img,+.ProseMirror [data-edgeever-image-gallery][data-image-gallery-fit="height"] .edgeever-image-gallery__content img {+ height: 18rem;+ min-height: 0;+ object-fit: contain;+}++.ProseMirror .edgeever-image-gallery__group {+ display: flex;+ flex-wrap: wrap;+ gap: 0.25rem;+}++.ProseMirror .edgeever-image-gallery__group + .edgeever-image-gallery__group {+ border-inline-start: 1px solid rgba(var(--brand-green-200-rgb), 0.95);+ padding-inline-start: 0.25rem;+}+.ProseMirror .edgeever-image-gallery__toolbar {position: relative;display: flex;diff --git a/apps/web/src/styles/note-html-export.css b/apps/web/src/styles/note-html-export.cssindex d116ed61..d61b946f 100644--- a/apps/web/src/styles/note-html-export.css+++ b/apps/web/src/styles/note-html-export.css@@ -263,6 +263,10 @@ body {object-fit: cover;}+.edgeever-html-content [data-edgeever-image-gallery][data-image-gallery-fit="height"] > img {+ object-fit: contain;+}+.edgeever-html-mermaid svg {margin: 0 auto;}diff --git a/apps/web/src/styles/note-print.css b/apps/web/src/styles/note-print.cssindex a8e13d72..6b9274d6 100644--- a/apps/web/src/styles/note-print.css+++ b/apps/web/src/styles/note-print.css@@ -362,6 +362,10 @@object-fit: cover;}+.edgeever-print-content [data-edgeever-image-gallery][data-image-gallery-fit="height"] > img {+ object-fit: contain;+}+.edgeever-print-mermaid svg {margin: 0 auto;}diff --git a/docs/changes/2026-10-22-gallery-image-fit.md b/docs/changes/2026-10-22-gallery-image-fit.mdnew file mode 100644index 00000000..18414f2e--- /dev/null+++ b/docs/changes/2026-10-22-gallery-image-fit.md@@ -0,0 +1,9 @@+# Gallery image fitting++Each image gallery now offers **Fit width** and **Fit height** beside its column controls. Fit width keeps the previous cropped gallery appearance. Fit height shows each entire image inside an evenly sized tile, including the top and bottom of portrait images; unused space remains beside or above the image. The choice applies to that gallery only and supports undo/redo.++The gallery stores `fit: "width" | "height"` in its rich document. Missing or unsupported values use width fitting. HTML includes `data-image-gallery-fit`, used by editor, public sharing, HTML export, and print styles. The shared Android/iOS gallery toolbar also offers the two choices. Image-card exports already show complete images and retain that behavior.++Height-fit galleries use `<!-- edgeever:image-gallery fit=height layout=… -->` and `<!-- /edgeever:image-gallery -->` around ordinary Markdown images so editing unrelated Markdown preserves both fit and column layout. Other Markdown readers can still show the images. If text is inserted inside the markers, EdgeEver preserves the edited content and splits the gallery. Default width-fit galleries retain their existing ordinary-image Markdown projection.++This adds no database migration or dependency. Revert the feature commit to roll back the implementation; older clients may ignore the fit attribute and show their previous layout, and older Markdown parsers do not preserve the comments as gallery settings. Verify Web layout, saving/reopening, Markdown edits, read-only views, export, and narrow screens. Android USB-device and iOS-device validation remain required before claiming native visual parity.diff --git a/docs/changes/2026-10-22-gallery-image-fit.zh-CN.md b/docs/changes/2026-10-22-gallery-image-fit.zh-CN.mdnew file mode 100644index 00000000..5ae5336d--- /dev/null+++ b/docs/changes/2026-10-22-gallery-image-fit.zh-CN.md@@ -0,0 +1,9 @@+# 图片画廊适应方式++每个图片画廊的列数控件旁新增了**适应宽度**和**适应高度**。适应宽度保留原有的裁剪展示效果;适应高度会在大小一致的单元格内完整显示每张图片,包括竖图的顶部和底部,剩余空间留在图片两侧或上下。设置只影响当前画廊,并支持撤销和重做。++富文档在画廊节点中保存 `fit: "width" | "height"`,缺失或不支持的值使用适应宽度。HTML 带有 `data-image-gallery-fit` 属性,供编辑器、公开分享、HTML 导出及打印样式使用。Android/iOS 共用的画廊工具栏也提供这两个选项。图片卡片导出原本就完整显示图片,本次保持该行为。++适应高度的画廊在普通 Markdown 图片外增加 `<!-- edgeever:image-gallery fit=height layout=… -->` 和 `<!-- /edgeever:image-gallery -->`,以便修改其他 Markdown 内容后仍保留适应方式和列数。其他 Markdown 阅读器仍能显示图片。如果在标记内插入文本,EdgeEver 会保留编辑后的内容并拆分画廊。默认的适应宽度画廊继续使用原有的普通图片 Markdown 投影。++本次无需数据库迁移或新增依赖。回退功能提交即可回滚实现;旧客户端可能忽略适应方式属性并显示原来的布局,旧 Markdown 解析器不会将注释保留为画廊设置。应验证 Web 布局、保存重开、Markdown 编辑、只读视图、导出及窄屏。宣称原生端视觉一致前,仍需完成 Android USB 真机及 iOS 真机验证。diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.tsindex 1b82d04a..33faa79d 100644--- a/packages/shared/src/i18n/en-US.ts+++ b/packages/shared/src/i18n/en-US.ts@@ -2326,6 +2326,8 @@ export const enUS = {previewImage: "Preview image",imageGallery: {toolbar: "Image gallery layout",+ fitLabel: "Image fit",+ fits: { width: "Fit width", height: "Fit height" },layouts: {auto: "Auto","2": "2 columns",diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.tsindex 462ef502..ef4137e2 100644--- a/packages/shared/src/i18n/ja.ts+++ b/packages/shared/src/i18n/ja.ts@@ -2315,6 +2315,8 @@ export const ja = {previewImage: "画像をプレビュー",imageGallery: {toolbar: "画像ギャラリーのレイアウト",+ fitLabel: "画像のフィット",+ fits: { width: "幅に合わせる", height: "高さに合わせる" },layouts: {auto: "自動","2": "2 列",diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.tsindex ebf66565..211f10d7 100644--- a/packages/shared/src/i18n/pl.ts+++ b/packages/shared/src/i18n/pl.ts@@ -2315,6 +2315,8 @@ export const pl = {previewImage: "Podgląd obrazu",imageGallery: {toolbar: "Układ galerii obrazów",+ fitLabel: "Dopasowanie obrazu",+ fits: { width: "Dopasuj szerokość", height: "Dopasuj wysokość" },layouts: {auto: "Automatyczny","2": "2 kolumny",diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.tsindex f1dab8ee..7270f696 100644--- a/packages/shared/src/i18n/zh-CN.ts+++ b/packages/shared/src/i18n/zh-CN.ts@@ -2326,6 +2326,8 @@ export const zhCN = {previewImage: "预览大图",imageGallery: {toolbar: "图片画廊布局",+ fitLabel: "图片适应方式",+ fits: { width: "适应宽度", height: "适应高度" },layouts: {auto: "自动","2": "2 栏",diff --git a/packages/shared/src/image-gallery-fit.test.mjs b/packages/shared/src/image-gallery-fit.test.mjsnew file mode 100644index 00000000..86f1421b--- /dev/null+++ b/packages/shared/src/image-gallery-fit.test.mjs@@ -0,0 +1,100 @@+import { describe, expect, test } from "bun:test";+import { getSchema } from "@tiptap/core";+import StarterKit from "@tiptap/starter-kit";+import Image from "@tiptap/extension-image";+import { docToMarkdown, markdownToDoc } from "./content";+import { ImageGallery, resolveImageGalleryFit } from "./image-gallery";+import { imageGalleryCopy, groupUploadedImages } from "./native-image-gallery";+import { EditorState } from "@tiptap/pm/state";+import { history, undo, redo } from "@tiptap/pm/history";+import { DOMParser, DOMSerializer } from "@tiptap/pm/model";+import { parseHTML } from "linkedom";++const schema = getSchema([StarterKit, Image, ImageGallery]);+const image = (name) => ({ type: "image", attrs: { src: `https://example.test/${name}.png`, alt: name } });+const gallery = (fit, layout = "2") => ({ type: "edgeeverImageGallery", attrs: { fit, layout }, content: [image("portrait"), image("landscape")] });+const doc = (node) => ({ type: "doc", content: [node] });++describe("gallery image fitting", () => {+ test("old and unknown fit values keep the existing width fit", () => {+ for (const value of [undefined, null, "", "width", "invalid", {}, 1]) expect(resolveImageGalleryFit(value)).toBe("width");+ expect(resolveImageGalleryFit("height")).toBe("height");+ expect(schema.nodeFromJSON(doc({ ...gallery(undefined), attrs: { layout: "2" } })).firstChild.attrs.fit).toBe("width");+ });++ test("height fit and column layout survive Markdown editing without a DOM", () => {+ expect(typeof document).toBe("undefined");+ for (const layout of ["auto", "1", "2", "3"]) {+ const markdown = docToMarkdown(doc(gallery("height", layout)));+ expect(markdown).toContain(`<!-- edgeever:image-gallery fit=height layout=${layout} -->`);+ const restored = markdownToDoc(`${markdown}\n\nAn unrelated source edit.`);+ expect(restored.content[0]).toMatchObject(gallery("height", layout));+ expect(restored.content[1].content[0].text).toBe("An unrelated source edit.");+ expect(docToMarkdown(doc(restored.content[0]))).toBe(markdown);+ }+ });++ test("default width-fit Markdown stays ordinary portable images", () => {+ const markdown = docToMarkdown(doc(gallery("width")));+ expect(markdown).not.toContain("edgeever:image-gallery");+ expect(markdownToDoc(markdown).content[0].type).toBe("edgeeverImageGallery");+ });++ test("HTML uses the saved fit for shared pages and reimport", () => {+ const { document: htmlDocument } = parseHTML("<html><body></body></html>");+ const node = schema.nodeFromJSON(doc(gallery("height", "3")));+ const fragment = DOMSerializer.fromSchema(schema).serializeFragment(node.content, { document: htmlDocument });+ htmlDocument.body.appendChild(fragment);+ const element = htmlDocument.body.firstElementChild;+ expect(element.getAttribute("data-image-gallery-fit")).toBe("height");+ expect(element.getAttribute("data-image-gallery-layout")).toBe("3");+ expect(DOMParser.fromSchema(schema).parse(htmlDocument.body).firstChild.attrs).toMatchObject({ fit: "height", layout: "3" });+ element.removeAttribute("data-image-gallery-fit");+ expect(DOMParser.fromSchema(schema).parse(htmlDocument.body).firstChild.attrs.fit).toBe("width");+ });++ test("height-fit galleries inside details survive Markdown round trips", () => {+ const nested = { type: "details", content: [+ { type: "detailsSummary", content: [{ type: "text", text: "Photos" }] },+ { type: "detailsContent", content: [gallery("height")] },+ ] };+ expect(markdownToDoc(docToMarkdown(doc(nested))).content[0]).toMatchObject(nested);+ });++ test("source edits inside a gallery preserve prose and remaining images", () => {+ const markdown = docToMarkdown(doc(gallery("height")));+ const restored = markdownToDoc(markdown.replace("![landscape]", "Inserted text.\n\n![landscape]"));+ expect(restored.content.map((node) => node.type)).toEqual(["image", "paragraph", "image"]);+ expect(restored.content[1].content[0].text).toBe("Inserted text.");+ const singleton = markdownToDoc(markdown.replace(/!\[landscape\][^\n]+/, ""));+ expect(singleton.content.map((node) => node.type)).toEqual(["image"]);+ });++ test("fit changes are undoable and survive adding images to either side", () => {+ for (const side of ["before", "after"]) {+ const original = schema.nodeFromJSON(doc(gallery("width")));+ let state = EditorState.create({ schema, doc: original, plugins: [history()] });+ const dispatch = (tr) => { state = state.apply(tr); };+ dispatch(state.tr.setNodeMarkup(0, undefined, { layout: "2", fit: "height" }));+ expect(undo(state, dispatch)).toBe(true);+ expect(state.doc.firstChild.attrs.fit).toBe("width");+ expect(redo(state, dispatch)).toBe(true);+ const extra = schema.nodeFromJSON(image("new"));+ dispatch(state.tr.insert(side === "before" ? 0 : state.doc.content.size, extra));+ const editor = { schema, state, isEditable: true, isDestroyed: false, view: { dispatch: (tr) => { editor.state = editor.state.apply(tr); } } };+ expect(groupUploadedImages(editor, [extra.attrs.src])).toBe(true);+ expect(editor.state.doc.childCount).toBe(1);+ expect(editor.state.doc.firstChild.attrs).toMatchObject({ fit: "height", layout: "2" });+ expect(editor.state.doc.firstChild.childCount).toBe(3);+ expect(schema.nodeFromJSON(editor.state.doc.toJSON()).toJSON()).toEqual(editor.state.doc.toJSON());+ }+ });++ test("native controls include localized fit choices", () => {+ for (const locale of ["en-US", "zh-CN", "ja", "pl"]) {+ expect(imageGalleryCopy(locale).width.length).toBeGreaterThan(0);+ expect(imageGalleryCopy(locale).height.length).toBeGreaterThan(0);+ }+ expect(imageGalleryCopy("en-US").height).toBe("Fit height");+ });+});diff --git a/packages/shared/src/image-gallery.ts b/packages/shared/src/image-gallery.tsindex dc4350fb..80776813 100644--- a/packages/shared/src/image-gallery.ts+++ b/packages/shared/src/image-gallery.ts@@ -4,6 +4,10 @@ import { parseImageAlignment } from "./image-alignment";export const IMAGE_GALLERY_NODE_TYPE = "edgeeverImageGallery" as const;export const IMAGE_GALLERY_LAYOUTS = ["auto", "2", "3", "1"] as const;+export const IMAGE_GALLERY_FITS = ["width", "height"] as const;+export type ImageGalleryFit = (typeof IMAGE_GALLERY_FITS)[number];+export const resolveImageGalleryFit = (value: unknown): ImageGalleryFit =>+ value === "height" ? "height" : "width";/** In-document src used while a mobile upload has not finished. */export const TRANSIENT_IMAGE_UPLOAD_PREFIX = "edgeever-image-upload://";@@ -17,8 +21,9 @@ export const resolveImageGalleryLayout = (value: unknown): ImageGalleryLayout =>: "auto";/**- * A rich-editor-only layout container. Markdown deliberately serializes its- * children as ordinary sequential images so exports stay portable.+ * Width-fit galleries retain the ordinary sequential-image Markdown projection.+ * Height-fit galleries use invisible comments to keep their presentation when+ * editing Markdown, while images remain readable in other Markdown readers.*/export const ImageGallery = Node.create({name: IMAGE_GALLERY_NODE_TYPE,@@ -29,6 +34,15 @@ export const ImageGallery = Node.create({addAttributes() {return {+ fit: {+ default: "width",+ parseHTML: (element: HTMLElement) => resolveImageGalleryFit(+ element.getAttribute("data-image-gallery-fit"),+ ),+ renderHTML: (attributes: { fit?: unknown }) => ({+ "data-image-gallery-fit": resolveImageGalleryFit(attributes.fit),+ }),+ },layout: {default: "auto",parseHTML: (element: HTMLElement) => resolveImageGalleryLayout(@@ -57,7 +71,40 @@ export const ImageGallery = Node.create({},renderMarkdown(node, helpers) {- return helpers.renderChildren(node.content ?? [], "\n\n");+ const images = helpers.renderChildren(node.content ?? [], "\n\n");+ if (resolveImageGalleryFit(node.attrs?.fit) === "width") return images;+ const layout = resolveImageGalleryLayout(node.attrs?.layout);+ return `<!-- edgeever:image-gallery fit=height layout=${layout} -->\n\n${images}\n\n<!-- /edgeever:image-gallery -->`;+ },++ parseMarkdown(token, helpers) {+ const content = helpers.parseChildren(token.tokens ?? []);+ // A source edit can split a gallery with text. Keep all edited content,+ // rather than forcing non-images into an image-only schema.+ if (content.length < 2 || content.some((child) => child.type !== "image")) return content;+ return helpers.createNode(IMAGE_GALLERY_NODE_TYPE, {+ fit: resolveImageGalleryFit(token.fit),+ layout: resolveImageGalleryLayout(token.layout),+ }, content);+ },++ markdownTokenizer: {+ name: IMAGE_GALLERY_NODE_TYPE,+ level: "block",+ start(source: string) {+ return source.indexOf("<!-- edgeever:image-gallery ");+ },+ tokenize(source: string, _tokens, lexer) {+ const match = /^<!-- edgeever:image-gallery fit=(width|height) layout=(auto|1|2|3) -->\s*\n([\s\S]*?)\n<!-- \/edgeever:image-gallery -->/.exec(source);+ if (!match) return undefined;+ return {+ type: IMAGE_GALLERY_NODE_TYPE,+ raw: match[0],+ fit: match[1],+ layout: match[2],+ tokens: lexer.blockTokens(match[3]!.trim()),+ };+ },},});diff --git a/packages/shared/src/native-image-gallery.ts b/packages/shared/src/native-image-gallery.tsindex 6b9bd11a..490c9035 100644--- a/packages/shared/src/native-image-gallery.ts+++ b/packages/shared/src/native-image-gallery.ts@@ -1,7 +1,7 @@import type { Editor, NodeViewRenderer } from "@tiptap/core";import type { Node as ProseMirrorNode } from "@tiptap/pm/model";import { NodeSelection, type EditorState } from "@tiptap/pm/state";-import { IMAGE_GALLERY_LAYOUTS, IMAGE_GALLERY_NODE_TYPE, resolveImageGalleryLayout } from "./image-gallery";+import { IMAGE_GALLERY_FITS, IMAGE_GALLERY_LAYOUTS, IMAGE_GALLERY_NODE_TYPE, resolveImageGalleryFit, resolveImageGalleryLayout } from "./image-gallery";import { mergeUploadedImagesIntoAdjacentGalleries } from "./image-gallery-editing";/** Adding images while an image/gallery is selected must not replace that content. */@@ -77,10 +77,10 @@ export const groupUploadedImages = (editor: Editor, sources: readonly string[]):};const IMAGE_GALLERY_COPY = {- "zh-CN": { label: "图片画廊布局", auto: "自动", single: "单列", columns: (count: string) => `${count} 栏` },- "en-US": { label: "Image gallery layout", auto: "Auto", single: "Single", columns: (count: string) => `${count} columns` },- ja: { label: "画像ギャラリーのレイアウト", auto: "自動", single: "1列", columns: (count: string) => `${count}列` },- pl: { label: "Układ galerii obrazów", auto: "Auto", single: "1 kolumna", columns: (count: string) => `${count} kolumny` },+ "zh-CN": { label: "图片画廊布局", auto: "自动", single: "单列", columns: (count: string) => `${count} 栏`, width: "适应宽度", height: "适应高度" },+ "en-US": { label: "Image gallery layout", auto: "Auto", single: "Single", columns: (count: string) => `${count} columns`, width: "Fit width", height: "Fit height" },+ ja: { label: "画像ギャラリーのレイアウト", auto: "自動", single: "1列", columns: (count: string) => `${count}列`, width: "幅に合わせる", height: "高さに合わせる" },+ pl: { label: "Układ galerii obrazów", auto: "Auto", single: "1 kolumna", columns: (count: string) => `${count} kolumny`, width: "Dopasuj szerokość", height: "Dopasuj wysokość" },};export const imageGalleryCopy = (locale: string) =>@@ -99,7 +99,11 @@ export const createNativeImageGalleryView = (getLocale: () => string): NodeViewRtoolbar.setAttribute("role", "toolbar");const contentDOM = document.createElement("div");contentDOM.className = "edgeever-native-gallery-content";- const buttons = IMAGE_GALLERY_LAYOUTS.map((layout) => {+ const controls = [+ ...IMAGE_GALLERY_LAYOUTS.map((value) => ({ attribute: "layout" as const, value })),+ ...IMAGE_GALLERY_FITS.map((value) => ({ attribute: "fit" as const, value })),+ ];+ const buttons = controls.map(({ attribute, value }) => {const button = document.createElement("button");button.type = "button";button.addEventListener("pointerdown", (event) => event.stopPropagation());@@ -111,25 +115,29 @@ export const createNativeImageGalleryView = (getLocale: () => string): NodeViewRif (!editor.isEditable || typeof pos !== "number") return;const target = editor.state.doc.nodeAt(pos);if (target?.type.name !== IMAGE_GALLERY_NODE_TYPE) return;- editor.view.dispatch(editor.state.tr.setNodeMarkup(pos, undefined, { ...target.attrs, layout }));+ editor.view.dispatch(editor.state.tr.setNodeMarkup(pos, undefined, { ...target.attrs, [attribute]: value }));});toolbar.appendChild(button);- return { button, layout };+ return { button, attribute, value };});dom.appendChild(toolbar);dom.appendChild(contentDOM);const sync = () => {const copy = imageGalleryCopy(getLocale());const layout = resolveImageGalleryLayout(current.attrs.layout);+ const fit = resolveImageGalleryFit(current.attrs.fit);dom.dataset.imageGalleryLayout = layout;+ dom.dataset.imageGalleryFit = fit;dom.dataset.imageCount = String(current.childCount);toolbar.hidden = !editor.isEditable;toolbar.setAttribute("aria-label", copy.label);for (const item of buttons) {- item.button.textContent = item.layout === "auto" ? copy.auto- : item.layout === "1" ? copy.single- : copy.columns(item.layout);- item.button.setAttribute("aria-pressed", String(item.layout === layout));+ item.button.textContent = item.attribute === "fit"+ ? copy[item.value as "width" | "height"]+ : item.value === "auto" ? copy.auto+ : item.value === "1" ? copy.single+ : copy.columns(item.value);+ item.button.setAttribute("aria-pressed", String(item.value === (item.attribute === "fit" ? fit : layout)));}};sync();@@ -167,5 +175,9 @@ export const NATIVE_IMAGE_GALLERY_CSS = `@media (min-width: 600px) { [data-image-gallery-layout="3"] > .edgeever-native-gallery-content { grid-template-columns: repeat(3, minmax(0, 1fr)); } }.edgeever-native-gallery-content > * { width: 100% !important; min-width: 0; height: 100%; margin: 0 !important; overflow: hidden; border-radius: 10px; background: transparent; }.edgeever-native-gallery-content > img, .edgeever-native-gallery-content > * > img { width: 100% !important; height: 100%; min-height: 112px; max-height: 220px; object-fit: cover; }+[data-edgeever-image-gallery][data-image-gallery-fit="height"] > img,+[data-edgeever-image-gallery][data-image-gallery-fit="height"] > .edgeever-image-node > img,+[data-edgeever-image-gallery][data-image-gallery-fit="height"] > .edgeever-native-gallery-content > img,+[data-edgeever-image-gallery][data-image-gallery-fit="height"] > .edgeever-native-gallery-content > * > img { height: 220px; min-height: 0; object-fit: contain; }.edgeever-native-gallery-content .edgeever-image-size-controls { display: none !important; }`;diff --git a/tests/e2e/gallery-image-fit.spec.ts b/tests/e2e/gallery-image-fit.spec.tsnew file mode 100644index 00000000..30ed87e2--- /dev/null+++ b/tests/e2e/gallery-image-fit.spec.ts@@ -0,0 +1,107 @@+import { expect, test, type Locator } from "@playwright/test";+import { readFile } from "node:fs/promises";++test.use({ locale: "en-US" });++const expectFit = async (gallery: Locator, fit: "width" | "height") => {+ await expect(gallery).toHaveAttribute("data-image-gallery-fit", fit);+ for (const img of await gallery.locator("img").all()) {+ await expect.poll(() => img.evaluate((element) => element.complete && element.naturalWidth > 0)).toBe(true);+ await expect(img).toHaveCSS("object-fit", fit === "height" ? "contain" : "cover");+ }+};++test("gallery height fit is per gallery, undoable, persistent and usable on narrow screens", async ({ page }) => {+ await page.addInitScript(() => localStorage.setItem("edgeever.locale.preference", "en-US"));+ await page.context().route("https://example.test/gallery-*.png", (route) => {+ const portrait = route.request().url().includes("portrait");+ return route.fulfill({ contentType: "image/svg+xml", headers: { "Access-Control-Allow-Origin": "http://127.0.0.1:5173", "Access-Control-Allow-Credentials": "true" }, body: `<svg xmlns="http://www.w3.org/2000/svg" width="${portrait ? 300 : 800}" height="${portrait ? 800 : 300}"><rect width="100%" height="100%" fill="#dbeafe"/><rect width="100%" height="40" fill="#047857"/><rect y="${portrait ? 760 : 260}" width="100%" height="40" fill="#c2410c"/></svg>` });+ });+ const { notebooks } = await (await page.request.get("/api/v1/notebooks")).json() as { notebooks: Array<{ id: string }> };+ const title = `Gallery fit ${Date.now()}`;+ const images = "\n\n";+ const created = await page.request.post("/api/v1/memos", { data: {+ notebookId: notebooks[0].id, title, contentMarkdown: `${images}\n\nA separate gallery below.\n\n${images}\n\nA standalone image.\n\n`,+ } });+ expect(created.status()).toBe(201);+ const { memo } = await created.json() as { memo: { id: string } };+ const readMemo = async () => (await (await page.request.get(`/api/v1/memos/${memo.id}`)).json()).memo;+ try {+ await page.goto("/");+ await page.getByRole("button", { name: "All notes", exact: true }).click();+ await page.getByPlaceholder("Search notes").fill(title);+ await page.locator(`[data-memo-id="${memo.id}"]`).locator("button").first().click();+ const galleries = page.locator(".ProseMirror [data-edgeever-image-gallery]");+ const first = galleries.nth(0);+ const second = galleries.nth(1);+ await expect(galleries).toHaveCount(2);+ await expectFit(first, "width");+ await first.getByRole("button", { name: "Fit height", exact: true }).click();+ await expectFit(first, "height");+ await expectFit(second, "width");+ await page.keyboard.press("ControlOrMeta+z");+ await expectFit(first, "width");+ await page.keyboard.press("ControlOrMeta+Shift+z");+ await expectFit(first, "height");+ await first.getByRole("button", { name: "2 columns", exact: true }).click();+ await expect(first).toHaveAttribute("data-image-gallery-layout", "2");+ await expectFit(first, "height");+ await page.keyboard.press("ControlOrMeta+s");+ await expect.poll(async () => (await readMemo()).contentJson.content[0].attrs.fit).toBe("height");++ await page.keyboard.press("ControlOrMeta+/");+ await expect(page.locator(".cm-content")).toContainText("edgeever:image-gallery fit=height layout=2");+ await page.keyboard.press("ControlOrMeta+End");+ await page.keyboard.insertText("\n\nSource edit keeps the fit setting.");+ await page.keyboard.press("ControlOrMeta+/");+ await expectFit(first, "height");+ await expectFit(second, "width");+ await page.keyboard.press("ControlOrMeta+s");+ await expect.poll(async () => (await readMemo()).contentMarkdown).toContain("Source edit keeps the fit setting.");+ const reloadedMemo = page.waitForResponse((response) => response.url().endsWith(`/api/v1/memos/${memo.id}`) && response.request().method() === "GET" && response.ok());+ await page.reload();+ await reloadedMemo;+ await expect(page.getByRole("status", { name: /^Synced/ })).toBeVisible();+ await expectFit(first, "height");+ await expect(first.getByRole("button", { name: "Fit height", exact: true })).toHaveAttribute("aria-pressed", "true");+ await page.getByRole("button", { name: /^Enable reading protection/ }).click();+ await expect(page.getByRole("button", { name: "Fit height", exact: true })).toHaveCount(0);+ await expectFit(first, "height");+ await page.getByRole("button", { name: /^Disable reading protection and edit/ }).click();++ await page.getByRole("button", { name: "More note actions", exact: true }).click();+ const downloaded = page.waitForEvent("download");+ await page.getByRole("menuitem", { name: "Export HTML", exact: true }).click();+ const html = await readFile((await (await downloaded).path())!, "utf8");+ const exported = await page.context().newPage();+ try {+ await exported.setContent(html, { waitUntil: "domcontentloaded" });+ const exportedGalleries = exported.locator("[data-edgeever-image-gallery]");+ await expectFit(exportedGalleries.nth(0), "height");+ await expectFit(exportedGalleries.nth(1), "width");+ await expect(exported.getByRole("img", { name: "Standalone", exact: true })).toHaveCSS("display", "block");+ await expect(exported.getByRole("img", { name: "Standalone", exact: true })).toHaveCSS("max-width", "100%");+ const galleryHtml = await exportedGalleries.evaluateAll((elements) => elements.map((element) => element.outerHTML).join(""));+ await exported.setContent(`<article class="edgeever-print-content">${galleryHtml}</article>`);+ await exported.addStyleTag({ content: await readFile("apps/web/src/styles/note-print.css", "utf8") });+ await expectFit(exportedGalleries.nth(0), "height");+ await expectFit(exportedGalleries.nth(1), "width");+ } finally { await exported.close(); }++ await page.setViewportSize({ width: 390, height: 844 });+ // The responsive app starts at the mobile note list when its shell changes.+ await page.getByRole("button", { name: new RegExp(`^${title} `) }).click();+ await expectFit(first, "height");+ await page.getByRole("button", { name: "Edit note", exact: true }).click();+ const button = first.getByRole("button", { name: "Fit width", exact: true });+ await button.scrollIntoViewIfNeeded();+ const bounds = await button.boundingBox();+ expect(bounds!.x).toBeGreaterThanOrEqual(0);+ expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(390);+ await button.click();+ await expectFit(first, "width");+ } finally {+ await page.request.delete(`/api/v1/memos/${memo.id}`, { timeout: 5_000 }).catch(() => {});+ await page.request.delete(`/api/v1/memos/${memo.id}?permanent=1`, { timeout: 5_000 }).catch(() => {});+ }+});