isaachwf commited on
Commit
dbea2d0
·
verified ·
1 Parent(s): 7604e0d

Sync from GitHub via hub-sync

Browse files
README.md CHANGED
@@ -32,9 +32,11 @@ MapToPoster 是一个开源的地图海报编辑器。你可以搜索城市、
32
  - 搜索全球地点,也可以直接输入 `纬度, 经度`。
33
  - 使用交互式地图调整中心点、缩放和海报边界。
34
  - 内置多套 JSON 主题和布局,可从极简风格切换到赛博朋克、复古或自然色调。
35
- - 自定义标题、副标题、说明文字、坐标、字距、对齐方式和分隔线。
 
36
  - 控制高速、主干道、次干道、住宅道路、水域和公园图层。
37
- - 支持 `3:4`、`4:5`、`2:3`、`1:1`、`9:16`、A4 和 A3 比例。
 
38
  - 选择“开始生成”后才抓取地图数据,并在准备、渲染和导出阶段显示进度与耗时。
39
  - 导出 PNG、SVG 和 PDF;PNG 支持预览分辨率或 300 DPI 打印分辨率。
40
  - 中国行政区优先使用本地数据,其余地点通过 Nominatim 查询。
@@ -133,9 +135,11 @@ GitHub `main` 是唯一源码分支。每次推送都会先运行 Python、React
133
  - Search worldwide places or enter `latitude, longitude` manually.
134
  - Pan and zoom an interactive map to frame the poster.
135
  - Choose from a growing collection of JSON themes and layout presets.
136
- - Edit titles, subtitles, captions, coordinates, tracking, alignment, and dividers.
 
137
  - Toggle motorway, primary, secondary, residential, water, and park layers.
138
- - Use `3:4`, `4:5`, `2:3`, `1:1`, `9:16`, A4, and A3 size presets.
 
139
  - Start generation explicitly, with visible progress and elapsed time for data preparation, rendering, and export.
140
  - Export PNG, SVG, or PDF; PNG supports preview and 300 DPI print output.
141
  - Resolve Chinese administrative areas locally before falling back to Nominatim.
 
32
  - 搜索全球地点,也可以直接输入 `纬度, 经度`。
33
  - 使用交互式地图调整中心点、缩放和海报边界。
34
  - 内置多套 JSON 主题和布局,可从极简风格切换到赛博朋克、复古或自然色调。
35
+ - 搜索并选择地点后自动填充标题和行政区副标题,也可以继续手动编辑。
36
+ - 自定义标题、副标题、坐标、字距、对齐方式和分隔线。
37
  - 控制高速、主干道、次干道、住宅道路、水域和公园图层。
38
+ - 支持横向与竖向海报,包括 `3:4`、`4:3`、`4:5`、`5:4`、`2:3`、`3:2`、`9:16`、`16:9`、`1:1`、A4 和 A3。
39
+ - 根据纸张和布局扩展地图取景范围,在不裁掉原选区的前提下适配海报比例。
40
  - 选择“开始生成”后才抓取地图数据,并在准备、渲染和导出阶段显示进度与耗时。
41
  - 导出 PNG、SVG 和 PDF;PNG 支持预览分辨率或 300 DPI 打印分辨率。
42
  - 中国行政区优先使用本地数据,其余地点通过 Nominatim 查询。
 
135
  - Search worldwide places or enter `latitude, longitude` manually.
136
  - Pan and zoom an interactive map to frame the poster.
137
  - Choose from a growing collection of JSON themes and layout presets.
138
+ - Fill the title and administrative-area subtitle when a location is selected, with manual editing still available.
139
+ - Edit titles, subtitles, coordinates, tracking, alignment, and dividers.
140
  - Toggle motorway, primary, secondary, residential, water, and park layers.
141
+ - Create portrait or landscape posters with `3:4`, `4:3`, `4:5`, `5:4`, `2:3`, `3:2`, `9:16`, `16:9`, `1:1`, A4, and A3 presets.
142
+ - Expand the selected map coverage to fit the paper and layout without cropping the original area.
143
  - Start generation explicitly, with visible progress and elapsed time for data preparation, rendering, and export.
144
  - Export PNG, SVG, or PDF; PNG supports preview and 300 DPI print output.
145
  - Resolve Chinese administrative areas locally before falling back to Nominatim.
backend/schemas.py CHANGED
@@ -4,6 +4,7 @@ from __future__ import annotations
4
 
5
  from pydantic import BaseModel, Field
6
 
 
7
  from maptoposter.models import (
8
  BBox,
9
  Coordinate,
@@ -19,6 +20,7 @@ from maptoposter.models import (
19
  TypographyConfig,
20
  )
21
  from maptoposter.themes import load_style
 
22
 
23
 
24
  class LocationSchema(BaseModel):
@@ -107,7 +109,12 @@ class PosterRequest(BaseModel):
107
 
108
  def to_core(self) -> PosterConfig:
109
  location = self.location.to_core()
110
- bbox = BBox(**self.bbox.model_dump())
 
 
 
 
 
111
  style = load_style(self.style_id).with_colors(**self.colors)
112
  return PosterConfig(
113
  location=location,
@@ -117,9 +124,9 @@ class PosterRequest(BaseModel):
117
  ),
118
  style=style,
119
  typography=TypographyConfig(**self.typography.model_dump()),
120
- layout=LayoutConfig(self.layout),
121
  layers=LayerConfig(**self.layers.model_dump()),
122
- size=PosterSize(**self.size.model_dump()),
123
  )
124
 
125
 
 
4
 
5
  from pydantic import BaseModel, Field
6
 
7
+ from maptoposter.layouts import get_layout
8
  from maptoposter.models import (
9
  BBox,
10
  Coordinate,
 
20
  TypographyConfig,
21
  )
22
  from maptoposter.themes import load_style
23
+ from maptoposter.viewport import expand_bbox_to_aspect
24
 
25
 
26
  class LocationSchema(BaseModel):
 
109
 
110
  def to_core(self) -> PosterConfig:
111
  location = self.location.to_core()
112
+ raw_bbox = BBox(**self.bbox.model_dump())
113
+ size = PosterSize(**self.size.model_dump())
114
+ layout = LayoutConfig(self.layout)
115
+ map_rect = get_layout(layout.preset).map_rect
116
+ width, height = size.dimensions
117
+ bbox = expand_bbox_to_aspect(raw_bbox, (width * map_rect.width) / (height * map_rect.height))
118
  style = load_style(self.style_id).with_colors(**self.colors)
119
  return PosterConfig(
120
  location=location,
 
124
  ),
125
  style=style,
126
  typography=TypographyConfig(**self.typography.model_dump()),
127
+ layout=layout,
128
  layers=LayerConfig(**self.layers.model_dump()),
129
+ size=size,
130
  )
131
 
132
 
frontend/src/App.css CHANGED
@@ -78,11 +78,16 @@ button:disabled { cursor: not-allowed; opacity: .38; }
78
  .layout-glyph.editorial::before, .layout-glyph.editorial::after, .layout-glyph.minimal::before, .layout-glyph.minimal::after, .layout-glyph.bottom_left::before, .layout-glyph.bottom_left::after { left: 3px; right: 11px; }
79
  .layout-glyph.centered::before { bottom: 20px; }.layout-glyph.centered::after { bottom: 15px; }
80
  .toggle-list { display: grid; }.toggle-list label { height: 39px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--border-soft); font-size: 12px; text-transform: capitalize; }.toggle-list input { accent-color: var(--accent); }
 
 
 
81
  .size-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }.size-grid button { min-height: 68px; display: grid; place-items: center; align-content: center; gap: 4px; border: 1px solid var(--border); border-radius: 4px; background: #fff; font-size: 10px; }
82
- .size-shape { width: 19px; height: 25px; border: 1px solid currentColor; }.size-shape[data-ratio="1:1"] { height: 19px; }.size-shape[data-ratio="4:5"] { height: 24px; }.size-shape[data-ratio="2:3"] { height: 28px; }.size-shape[data-ratio="9:16"] { width: 16px; height: 28px; }
83
  .workspace { position: fixed; inset: var(--header) 0 0 var(--sidebar); display: grid; grid-template-rows: minmax(0, 1fr) minmax(38px, auto) 58px; background: var(--page); }
84
  .canvas-stage { min-height: 0; overflow: auto; display: grid; place-items: center; padding: 30px; }
85
- .poster-frame { position: relative; height: min(700px, calc(100vh - 190px)); max-width: 72%; background: var(--poster); border: 8px solid var(--poster); outline: 1px solid rgba(0,0,0,.65); box-shadow: var(--poster-shadow); transform-origin: center; transition: transform .16s ease, aspect-ratio .2s ease; }
 
 
86
  .poster-frame img { width: 100%; height: 100%; display: block; object-fit: contain; background: var(--poster); }
87
  .preview-loading { position: absolute; inset: 0; display: grid; place-content: center; justify-items: center; gap: 12px; padding: 24px; color: var(--text); background: rgba(246,244,239,.82); font-size: 12px; backdrop-filter: blur(2px); }
88
  .preview-status { min-height: 38px; display: flex; align-items: center; justify-content: flex-end; gap: 16px; padding: 7px 20px; color: var(--muted); font-size: 11px; background: rgba(255,255,255,.76); }.preview-status.success { color: var(--success); }.preview-status.error { color: var(--danger); }
@@ -106,7 +111,9 @@ button:disabled { cursor: not-allowed; opacity: .38; }
106
  .sidebar { display: none; }
107
  .workspace { position: static; display: contents; }
108
  .canvas-stage { height: 55vh; min-height: 420px; padding: 30px 24px 18px; overflow: hidden; order: 1; }
109
- .poster-frame { height: min(49vh, 550px); max-width: calc(100vw - 56px); border-width: 6px; }
 
 
110
  .preview-loading { font-size: 11px; }
111
  .mobile-tabs { position: sticky; z-index: 25; top: 62px; display: grid; grid-template-columns: repeat(6, minmax(54px, 1fr)); height: 68px; overflow-x: auto; border-top: 1px solid var(--border); border-bottom: 1px solid var(--border); background: #fff; order: 2; }
112
  .mobile-tabs button { position: relative; min-width: 54px; display: grid; place-content: center; justify-items: center; gap: 4px; color: var(--muted); font-size: 10px; }
 
78
  .layout-glyph.editorial::before, .layout-glyph.editorial::after, .layout-glyph.minimal::before, .layout-glyph.minimal::after, .layout-glyph.bottom_left::before, .layout-glyph.bottom_left::after { left: 3px; right: 11px; }
79
  .layout-glyph.centered::before { bottom: 20px; }.layout-glyph.centered::after { bottom: 15px; }
80
  .toggle-list { display: grid; }.toggle-list label { height: 39px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--border-soft); font-size: 12px; text-transform: capitalize; }.toggle-list input { accent-color: var(--accent); }
81
+ .orientation-toggle { display: grid; grid-template-columns: 1fr 1fr; gap: 3px; margin-bottom: 12px; padding: 3px; border-radius: 5px; background: var(--page); }
82
+ .orientation-toggle button { height: 34px; border-radius: 3px; color: var(--muted); font-size: 11px; font-weight: 600; }
83
+ .orientation-toggle button.is-selected { color: var(--text); background: #fff; box-shadow: 0 1px 4px rgba(25,32,45,.12); }
84
  .size-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }.size-grid button { min-height: 68px; display: grid; place-items: center; align-content: center; gap: 4px; border: 1px solid var(--border); border-radius: 4px; background: #fff; font-size: 10px; }
85
+ .size-shape { width: auto; height: 25px; max-width: 39px; border: 1px solid currentColor; }
86
  .workspace { position: fixed; inset: var(--header) 0 0 var(--sidebar); display: grid; grid-template-rows: minmax(0, 1fr) minmax(38px, auto) 58px; background: var(--page); }
87
  .canvas-stage { min-height: 0; overflow: auto; display: grid; place-items: center; padding: 30px; }
88
+ .poster-frame { position: relative; background: var(--poster); border: 8px solid var(--poster); outline: 1px solid rgba(0,0,0,.65); box-shadow: var(--poster-shadow); transform-origin: center; transition: transform .16s ease, aspect-ratio .2s ease; }
89
+ .poster-frame.is-tall { height: min(700px, calc(100vh - 190px)); max-width: 72%; }
90
+ .poster-frame.is-wide { width: min(78%, calc(100vh - 190px)); max-height: calc(100vh - 190px); }
91
  .poster-frame img { width: 100%; height: 100%; display: block; object-fit: contain; background: var(--poster); }
92
  .preview-loading { position: absolute; inset: 0; display: grid; place-content: center; justify-items: center; gap: 12px; padding: 24px; color: var(--text); background: rgba(246,244,239,.82); font-size: 12px; backdrop-filter: blur(2px); }
93
  .preview-status { min-height: 38px; display: flex; align-items: center; justify-content: flex-end; gap: 16px; padding: 7px 20px; color: var(--muted); font-size: 11px; background: rgba(255,255,255,.76); }.preview-status.success { color: var(--success); }.preview-status.error { color: var(--danger); }
 
111
  .sidebar { display: none; }
112
  .workspace { position: static; display: contents; }
113
  .canvas-stage { height: 55vh; min-height: 420px; padding: 30px 24px 18px; overflow: hidden; order: 1; }
114
+ .poster-frame { border-width: 6px; }
115
+ .poster-frame.is-tall { width: auto; height: min(49vh, 550px); max-width: calc(100vw - 56px); }
116
+ .poster-frame.is-wide { width: calc(100vw - 56px); height: auto; max-height: 49vh; }
117
  .preview-loading { font-size: 11px; }
118
  .mobile-tabs { position: sticky; z-index: 25; top: 62px; display: grid; grid-template-columns: repeat(6, minmax(54px, 1fr)); height: 68px; overflow-x: auto; border-top: 1px solid var(--border); border-bottom: 1px solid var(--border); background: #fff; order: 2; }
119
  .mobile-tabs button { position: relative; min-width: 54px; display: grid; place-content: center; justify-items: center; gap: 4px; color: var(--muted); font-size: 10px; }
frontend/src/App.test.tsx CHANGED
@@ -1,6 +1,6 @@
1
- import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
2
- import { beforeEach, describe, expect, it, vi } from 'vitest'
3
- import { prepareMap, renderPreview } from './api'
4
  import App from './App'
5
 
6
  vi.mock('./components/MapViewport', () => ({
@@ -19,6 +19,7 @@ vi.mock('./api', () => ({
19
 
20
  describe('editor shell', () => {
21
  beforeEach(() => vi.clearAllMocks())
 
22
 
23
  it('loads styles and exposes product controls', async () => {
24
  render(<App />)
@@ -41,6 +42,41 @@ describe('editor shell', () => {
41
  expect(screen.getAllByText('Paris, France').length).toBeGreaterThan(0)
42
  })
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  it('changes zoom and fit state', () => {
45
  render(<App />)
46
  expect(screen.getAllByText('82%').length).toBeGreaterThan(0)
 
1
+ import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
3
+ import { prepareMap, renderPreview, searchPlaces } from './api'
4
  import App from './App'
5
 
6
  vi.mock('./components/MapViewport', () => ({
 
19
 
20
  describe('editor shell', () => {
21
  beforeEach(() => vi.clearAllMocks())
22
+ afterEach(cleanup)
23
 
24
  it('loads styles and exposes product controls', async () => {
25
  render(<App />)
 
42
  expect(screen.getAllByText('Paris, France').length).toBeGreaterThan(0)
43
  })
44
 
45
+ it('fills poster text from a selected Chinese location and omits caption', async () => {
46
+ vi.mocked(searchPlaces).mockResolvedValueOnce([{
47
+ display_name: '深圳市, 广东省, 中国', latitude: 22.5431, longitude: 114.0579,
48
+ country: '中国', region: '广东省', country_code: 'cn', provider: 'china-local',
49
+ }])
50
+ render(<App />)
51
+ await waitFor(() => expect(screen.getAllByText('Japanese Ink').length).toBeGreaterThan(0))
52
+
53
+ const search = screen.getAllByRole('textbox', { name: 'Search a place' })[0]
54
+ fireEvent.change(search, { target: { value: '深圳' } })
55
+ fireEvent.submit(search.closest('form')!)
56
+ await waitFor(() => expect(screen.getAllByText('深圳市, 广东省, 中国').length).toBeGreaterThan(0))
57
+ fireEvent.click(screen.getAllByText('深圳市, 广东省, 中国')[0])
58
+
59
+ expect(screen.getAllByRole('textbox', { name: 'Title' }).map((input) => (input as HTMLInputElement).value)).toEqual(['深圳市'])
60
+ expect(screen.getAllByRole('textbox', { name: 'Subtitle' }).map((input) => (input as HTMLInputElement).value)).toEqual(['广东省'])
61
+ expect(screen.queryByRole('textbox', { name: 'Caption' })).not.toBeInTheDocument()
62
+ })
63
+
64
+ it('offers landscape ratios and sends the selected size for generation', async () => {
65
+ render(<App />)
66
+ await waitFor(() => expect(screen.getAllByText('Japanese Ink').length).toBeGreaterThan(0))
67
+ fireEvent.click(screen.getAllByRole('button', { name: 'Size' })[0])
68
+ fireEvent.click(screen.getAllByRole('button', { name: 'Landscape' })[0])
69
+ fireEvent.click(screen.getAllByRole('button', { name: 'landscape 16:9' })[0])
70
+
71
+ expect(document.querySelector('.poster-frame')).toHaveStyle({ aspectRatio: String(16 / 9) })
72
+ fireEvent.click(screen.getAllByRole('button', { name: /Generate preview/i })[0])
73
+ await waitFor(() => expect(prepareMap).toHaveBeenCalled())
74
+ expect(prepareMap).toHaveBeenCalledWith(
75
+ expect.objectContaining({ layout: 'classic', size: { preset: '16:9' } }),
76
+ expect.any(AbortSignal),
77
+ )
78
+ })
79
+
80
  it('changes zoom and fit state', () => {
81
  render(<App />)
82
  expect(screen.getAllByText('82%').length).toBeGreaterThan(0)
frontend/src/App.tsx CHANGED
@@ -15,7 +15,7 @@ const DEFAULT_LOCATION: LocationResult = {
15
  }
16
  const DEFAULT_BBOX: BBox = { west: 116.292, south: 39.955, east: 116.405, north: 40.047 }
17
  const DEFAULT_TYPE: Typography = {
18
- title: 'BEIJING FORESTRY UNIVERSITY', subtitle: 'BEIJING', caption: '2023 — 2027', coordinates: '',
19
  font_family: 'auto', title_size: 46, subtitle_size: 17, caption_size: 13, coordinate_size: 11,
20
  letter_spacing: 0.08, line_height: 1.15, alignment: 'center', show_coordinates: true, show_divider: true,
21
  }
@@ -24,7 +24,27 @@ const DEFAULT_LAYERS: LayerState = {
24
  }
25
  const PANEL_IDS = ['location', 'style', 'layout', 'type', 'layers', 'size'] as const
26
  type PanelId = typeof PANEL_IDS[number]
27
- const SIZE_OPTIONS = ['3:4', '4:5', '2:3', '1:1', '9:16', 'A4', 'A3']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  const LAYOUT_OPTIONS = ['classic', 'editorial', 'minimal', 'bottom_left', 'centered']
29
  const panelMeta = {
30
  location: ['Location', MapPin], style: ['Style', Palette], layout: ['Layout', LayoutTemplate],
@@ -103,7 +123,8 @@ export default function App() {
103
  const [typography, setTypography] = useState(DEFAULT_TYPE)
104
  const [layout, setLayout] = useState('classic')
105
  const [layers, setLayers] = useState(DEFAULT_LAYERS)
106
- const [size, setSize] = useState('3:4')
 
107
  const [mapDataId, setMapDataId] = useState('')
108
  const [preparedSignature, setPreparedSignature] = useState('')
109
  const [renderedSignature, setRenderedSignature] = useState('')
@@ -139,11 +160,14 @@ export default function App() {
139
  colors: customColors, typography, layout, layers, size: { preset: size },
140
  }), [bbox, customColors, layers, layout, location, mapZoom, size, styleId, typography])
141
  const posterSignature = useMemo(() => JSON.stringify(poster), [poster])
142
- const dataSignature = useMemo(() => JSON.stringify({ location, bbox, network: poster.network_type }), [bbox, location, poster.network_type])
143
  const prepareRequest = useMemo(() => ({
144
  location, bbox, distance_m: 10_000, zoom: mapZoom, network_type: 'all' as const,
145
- style_id: 'japanese_ink', colors: {}, typography: DEFAULT_TYPE, layout: 'classic', layers: DEFAULT_LAYERS, size: { preset: '3:4' },
146
- }), [bbox, location, mapZoom])
 
 
 
147
  const isGenerating = previewPhase === 'preparing' || previewPhase === 'rendering'
148
  const previewStale = renderedSignature !== posterSignature
149
 
@@ -195,7 +219,14 @@ export default function App() {
195
 
196
  const chooseLocation = (result: LocationResult) => {
197
  setLocation(result); setBBox(extentFor(result)); setMapZoom(null); setSearchResults([]); setSearchQuery('')
198
- setTypography((current) => ({ ...current, subtitle: result.region || result.country || current.subtitle }))
 
 
 
 
 
 
 
199
  }
200
 
201
  const updateColor = (key: string, value: string) => setCustomColors((current) => ({ ...current, [key]: value }))
@@ -305,14 +336,20 @@ export default function App() {
305
  type: <div className="form-stack">
306
  <label className="field"><span>Title</span><input value={typography.title} onChange={(event) => setTypography({ ...typography, title: event.target.value })} /></label>
307
  <label className="field"><span>Subtitle</span><input value={typography.subtitle} onChange={(event) => setTypography({ ...typography, subtitle: event.target.value })} /></label>
308
- <label className="field"><span>Caption</span><input value={typography.caption} onChange={(event) => setTypography({ ...typography, caption: event.target.value })} /></label>
309
  <div className="two-fields"><label className="field"><span>Title size</span><input type="number" min="12" max="120" value={typography.title_size} onChange={(event) => setTypography({ ...typography, title_size: Number(event.target.value) })} /></label><label className="field"><span>Alignment</span><select value={typography.alignment} onChange={(event) => setTypography({ ...typography, alignment: event.target.value as Typography['alignment'] })}><option>left</option><option>center</option><option>right</option></select></label></div>
310
  <label className="range-field"><span>Letter spacing <output>{Math.round(typography.letter_spacing * 100)}%</output></span><input type="range" min="0" max="0.3" step="0.01" value={typography.letter_spacing} onChange={(event) => setTypography({ ...typography, letter_spacing: Number(event.target.value) })} /></label>
311
  <label className="check-field"><input type="checkbox" checked={typography.show_coordinates} onChange={(event) => setTypography({ ...typography, show_coordinates: event.target.checked })} />Show coordinates</label>
312
  <label className="check-field"><input type="checkbox" checked={typography.show_divider} onChange={(event) => setTypography({ ...typography, show_divider: event.target.checked })} />Show divider</label>
313
  </div>,
314
  layers: <div className="toggle-list">{Object.entries(layers).map(([key, value]) => <label key={key}><span>{key.replace('_', ' ')}</span><input type="checkbox" checked={value} onChange={(event) => setLayers({ ...layers, [key]: event.target.checked })} /></label>)}</div>,
315
- size: <><div className="size-grid">{SIZE_OPTIONS.map((value) => <button key={value} className={size === value ? 'is-selected' : ''} onClick={() => setSize(value)}><span className="size-shape" data-ratio={value} />{value}</button>)}</div><p className="field-help">Preview is optimized for speed. Export uses the selected print ratio and DPI.</p></>,
 
 
 
 
 
 
 
316
  }
317
 
318
  return <div className="app-shell">
@@ -335,7 +372,7 @@ export default function App() {
335
 
336
  <main className="workspace">
337
  <div className="canvas-stage">
338
- <div className="poster-frame" style={{ transform: `scale(${canvasZoom / 100})`, aspectRatio: size === '1:1' ? '1 / 1' : size === '4:5' ? '4 / 5' : size === '2:3' ? '2 / 3' : size === '9:16' ? '9 / 16' : size === 'A4' || size === 'A3' ? '210 / 297' : '3 / 4' }}>
339
  <img src={previewUrl} alt={`Poster preview for ${location.display_name}`} />
340
  {isGenerating && <div className="preview-loading"><LoaderCircle className="spin" /><ProgressFeedback value={generationProgress} label={statusText} elapsed={generationElapsed} /></div>}
341
  </div>
 
15
  }
16
  const DEFAULT_BBOX: BBox = { west: 116.292, south: 39.955, east: 116.405, north: 40.047 }
17
  const DEFAULT_TYPE: Typography = {
18
+ title: 'BEIJING FORESTRY UNIVERSITY', subtitle: 'BEIJING', caption: '', coordinates: '',
19
  font_family: 'auto', title_size: 46, subtitle_size: 17, caption_size: 13, coordinate_size: 11,
20
  letter_spacing: 0.08, line_height: 1.15, alignment: 'center', show_coordinates: true, show_divider: true,
21
  }
 
24
  }
25
  const PANEL_IDS = ['location', 'style', 'layout', 'type', 'layers', 'size'] as const
26
  type PanelId = typeof PANEL_IDS[number]
27
+ type Orientation = 'portrait' | 'landscape'
28
+ const SIZE_OPTIONS = [
29
+ { id: '3:4', label: '3:4', aspect: 3 / 4, orientation: 'portrait' },
30
+ { id: '4:5', label: '4:5', aspect: 4 / 5, orientation: 'portrait' },
31
+ { id: '2:3', label: '2:3', aspect: 2 / 3, orientation: 'portrait' },
32
+ { id: '9:16', label: '9:16', aspect: 9 / 16, orientation: 'portrait' },
33
+ { id: 'A4', label: 'A4', aspect: 210 / 297, orientation: 'portrait' },
34
+ { id: 'A3', label: 'A3', aspect: 297 / 420, orientation: 'portrait' },
35
+ { id: '4:3', label: '4:3', aspect: 4 / 3, orientation: 'landscape' },
36
+ { id: '5:4', label: '5:4', aspect: 5 / 4, orientation: 'landscape' },
37
+ { id: '3:2', label: '3:2', aspect: 3 / 2, orientation: 'landscape' },
38
+ { id: '16:9', label: '16:9', aspect: 16 / 9, orientation: 'landscape' },
39
+ { id: 'A4-landscape', label: 'A4', aspect: 297 / 210, orientation: 'landscape' },
40
+ { id: 'A3-landscape', label: 'A3', aspect: 420 / 297, orientation: 'landscape' },
41
+ { id: '1:1', label: '1:1', aspect: 1, orientation: 'square' },
42
+ ] as const
43
+ type PosterSizeId = typeof SIZE_OPTIONS[number]['id']
44
+ const ORIENTATION_PAIR: Partial<Record<PosterSizeId, PosterSizeId>> = {
45
+ '3:4': '4:3', '4:3': '3:4', '4:5': '5:4', '5:4': '4:5', '2:3': '3:2', '3:2': '2:3',
46
+ '9:16': '16:9', '16:9': '9:16', A4: 'A4-landscape', 'A4-landscape': 'A4', A3: 'A3-landscape', 'A3-landscape': 'A3',
47
+ }
48
  const LAYOUT_OPTIONS = ['classic', 'editorial', 'minimal', 'bottom_left', 'centered']
49
  const panelMeta = {
50
  location: ['Location', MapPin], style: ['Style', Palette], layout: ['Layout', LayoutTemplate],
 
123
  const [typography, setTypography] = useState(DEFAULT_TYPE)
124
  const [layout, setLayout] = useState('classic')
125
  const [layers, setLayers] = useState(DEFAULT_LAYERS)
126
+ const [orientation, setOrientation] = useState<Orientation>('portrait')
127
+ const [size, setSize] = useState<PosterSizeId>('3:4')
128
  const [mapDataId, setMapDataId] = useState('')
129
  const [preparedSignature, setPreparedSignature] = useState('')
130
  const [renderedSignature, setRenderedSignature] = useState('')
 
160
  colors: customColors, typography, layout, layers, size: { preset: size },
161
  }), [bbox, customColors, layers, layout, location, mapZoom, size, styleId, typography])
162
  const posterSignature = useMemo(() => JSON.stringify(poster), [poster])
163
+ const dataSignature = useMemo(() => JSON.stringify({ location, bbox, network: poster.network_type, layout, size }), [bbox, layout, location, poster.network_type, size])
164
  const prepareRequest = useMemo(() => ({
165
  location, bbox, distance_m: 10_000, zoom: mapZoom, network_type: 'all' as const,
166
+ style_id: 'japanese_ink', colors: {}, typography: DEFAULT_TYPE, layout, layers: DEFAULT_LAYERS, size: { preset: size },
167
+ }), [bbox, layout, location, mapZoom, size])
168
+ const sizeOption = SIZE_OPTIONS.find((option) => option.id === size) ?? SIZE_OPTIONS[0]
169
+ const posterAspect = sizeOption.aspect
170
+ const visibleSizeOptions = SIZE_OPTIONS.filter((option) => option.orientation === orientation || option.orientation === 'square')
171
  const isGenerating = previewPhase === 'preparing' || previewPhase === 'rendering'
172
  const previewStale = renderedSignature !== posterSignature
173
 
 
219
 
220
  const chooseLocation = (result: LocationResult) => {
221
  setLocation(result); setBBox(extentFor(result)); setMapZoom(null); setSearchResults([]); setSearchQuery('')
222
+ const title = result.display_name.split(',')[0]?.trim() || result.display_name
223
+ setTypography((current) => ({ ...current, title, subtitle: result.region || result.country, caption: '' }))
224
+ }
225
+
226
+ const changeOrientation = (next: Orientation) => {
227
+ if (next === orientation) return
228
+ setOrientation(next)
229
+ setSize((current) => current === '1:1' ? current : ORIENTATION_PAIR[current] ?? (next === 'portrait' ? '3:4' : '4:3'))
230
  }
231
 
232
  const updateColor = (key: string, value: string) => setCustomColors((current) => ({ ...current, [key]: value }))
 
336
  type: <div className="form-stack">
337
  <label className="field"><span>Title</span><input value={typography.title} onChange={(event) => setTypography({ ...typography, title: event.target.value })} /></label>
338
  <label className="field"><span>Subtitle</span><input value={typography.subtitle} onChange={(event) => setTypography({ ...typography, subtitle: event.target.value })} /></label>
 
339
  <div className="two-fields"><label className="field"><span>Title size</span><input type="number" min="12" max="120" value={typography.title_size} onChange={(event) => setTypography({ ...typography, title_size: Number(event.target.value) })} /></label><label className="field"><span>Alignment</span><select value={typography.alignment} onChange={(event) => setTypography({ ...typography, alignment: event.target.value as Typography['alignment'] })}><option>left</option><option>center</option><option>right</option></select></label></div>
340
  <label className="range-field"><span>Letter spacing <output>{Math.round(typography.letter_spacing * 100)}%</output></span><input type="range" min="0" max="0.3" step="0.01" value={typography.letter_spacing} onChange={(event) => setTypography({ ...typography, letter_spacing: Number(event.target.value) })} /></label>
341
  <label className="check-field"><input type="checkbox" checked={typography.show_coordinates} onChange={(event) => setTypography({ ...typography, show_coordinates: event.target.checked })} />Show coordinates</label>
342
  <label className="check-field"><input type="checkbox" checked={typography.show_divider} onChange={(event) => setTypography({ ...typography, show_divider: event.target.checked })} />Show divider</label>
343
  </div>,
344
  layers: <div className="toggle-list">{Object.entries(layers).map(([key, value]) => <label key={key}><span>{key.replace('_', ' ')}</span><input type="checkbox" checked={value} onChange={(event) => setLayers({ ...layers, [key]: event.target.checked })} /></label>)}</div>,
345
+ size: <>
346
+ <div className="orientation-toggle" role="group" aria-label="Poster orientation">
347
+ <button type="button" className={orientation === 'portrait' ? 'is-selected' : ''} aria-pressed={orientation === 'portrait'} onClick={() => changeOrientation('portrait')}>Portrait</button>
348
+ <button type="button" className={orientation === 'landscape' ? 'is-selected' : ''} aria-pressed={orientation === 'landscape'} onClick={() => changeOrientation('landscape')}>Landscape</button>
349
+ </div>
350
+ <div className="size-grid">{visibleSizeOptions.map((option) => <button key={option.id} aria-label={`${orientation} ${option.label}`} className={size === option.id ? 'is-selected' : ''} onClick={() => setSize(option.id)}><span className="size-shape" style={{ aspectRatio: String(option.aspect) }} />{option.label}</button>)}</div>
351
+ <p className="field-help">The selected map area is expanded to fit the poster without cropping. Export uses this ratio and DPI.</p>
352
+ </>,
353
  }
354
 
355
  return <div className="app-shell">
 
372
 
373
  <main className="workspace">
374
  <div className="canvas-stage">
375
+ <div className={`poster-frame ${posterAspect >= 1 ? 'is-wide' : 'is-tall'}`} style={{ transform: `scale(${canvasZoom / 100})`, aspectRatio: String(posterAspect) }}>
376
  <img src={previewUrl} alt={`Poster preview for ${location.display_name}`} />
377
  {isGenerating && <div className="preview-loading"><LoaderCircle className="spin" /><ProgressFeedback value={generationProgress} label={statusText} elapsed={generationElapsed} /></div>}
378
  </div>
src/maptoposter/models.py CHANGED
@@ -20,10 +20,16 @@ class SizePreset(StrEnum):
20
  THREE_FOUR = "3:4"
21
  FOUR_FIVE = "4:5"
22
  TWO_THREE = "2:3"
 
 
 
23
  SQUARE = "1:1"
24
  NINE_SIXTEEN = "9:16"
 
25
  A4 = "A4"
26
  A3 = "A3"
 
 
27
  CUSTOM = "custom"
28
 
29
 
@@ -161,10 +167,16 @@ SIZE_PRESETS: dict[SizePreset, tuple[float, float]] = {
161
  SizePreset.THREE_FOUR: (12.0, 16.0),
162
  SizePreset.FOUR_FIVE: (12.0, 15.0),
163
  SizePreset.TWO_THREE: (12.0, 18.0),
 
 
 
164
  SizePreset.SQUARE: (12.0, 12.0),
165
  SizePreset.NINE_SIXTEEN: (9.0, 16.0),
 
166
  SizePreset.A4: (8.2677, 11.6929),
167
  SizePreset.A3: (11.6929, 16.5354),
 
 
168
  }
169
 
170
 
 
20
  THREE_FOUR = "3:4"
21
  FOUR_FIVE = "4:5"
22
  TWO_THREE = "2:3"
23
+ FOUR_THREE = "4:3"
24
+ FIVE_FOUR = "5:4"
25
+ THREE_TWO = "3:2"
26
  SQUARE = "1:1"
27
  NINE_SIXTEEN = "9:16"
28
+ SIXTEEN_NINE = "16:9"
29
  A4 = "A4"
30
  A3 = "A3"
31
+ A4_LANDSCAPE = "A4-landscape"
32
+ A3_LANDSCAPE = "A3-landscape"
33
  CUSTOM = "custom"
34
 
35
 
 
167
  SizePreset.THREE_FOUR: (12.0, 16.0),
168
  SizePreset.FOUR_FIVE: (12.0, 15.0),
169
  SizePreset.TWO_THREE: (12.0, 18.0),
170
+ SizePreset.FOUR_THREE: (16.0, 12.0),
171
+ SizePreset.FIVE_FOUR: (15.0, 12.0),
172
+ SizePreset.THREE_TWO: (18.0, 12.0),
173
  SizePreset.SQUARE: (12.0, 12.0),
174
  SizePreset.NINE_SIXTEEN: (9.0, 16.0),
175
+ SizePreset.SIXTEEN_NINE: (16.0, 9.0),
176
  SizePreset.A4: (8.2677, 11.6929),
177
  SizePreset.A3: (11.6929, 16.5354),
178
+ SizePreset.A4_LANDSCAPE: (11.6929, 8.2677),
179
+ SizePreset.A3_LANDSCAPE: (16.5354, 11.6929),
180
  }
181
 
182
 
src/maptoposter/viewport.py CHANGED
@@ -40,3 +40,32 @@ def create_bbox_tuple(
40
  ) -> tuple[float, float, float, float]:
41
  """Backward-compatible bbox helper."""
42
  return create_viewport(Coordinate(*point), distance_m, width, height).bbox.as_tuple()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  ) -> tuple[float, float, float, float]:
41
  """Backward-compatible bbox helper."""
42
  return create_viewport(Coordinate(*point), distance_m, width, height).bbox.as_tuple()
43
+
44
+
45
+ def expand_bbox_to_aspect(bbox: BBox, target_aspect: float) -> BBox:
46
+ """Expand a bbox to an aspect ratio without cropping its original coverage."""
47
+ if target_aspect <= 0:
48
+ raise ValueError("Target aspect ratio must be greater than zero.")
49
+
50
+ center_lon = (bbox.west + bbox.east) / 2
51
+ center_lat = (bbox.south + bbox.north) / 2
52
+ _, _, width_m = GEOD.inv(bbox.west, center_lat, bbox.east, center_lat)
53
+ _, _, height_m = GEOD.inv(center_lon, bbox.south, center_lon, bbox.north)
54
+ if width_m <= 0 or height_m <= 0:
55
+ raise ValueError("Bounding box dimensions must be greater than zero.")
56
+
57
+ current_aspect = width_m / height_m
58
+ if abs(current_aspect - target_aspect) < 0.005:
59
+ return bbox
60
+ if current_aspect > target_aspect:
61
+ extra_m = (width_m / target_aspect - height_m) / 2
62
+ _, south, _ = GEOD.fwd(center_lon, bbox.south, 180, extra_m)
63
+ _, north, _ = GEOD.fwd(center_lon, bbox.north, 0, extra_m)
64
+ return BBox(bbox.west, south, bbox.east, north)
65
+
66
+ extra_m = (height_m * target_aspect - width_m) / 2
67
+ west, _, _ = GEOD.fwd(bbox.west, center_lat, 270, extra_m)
68
+ east, _, _ = GEOD.fwd(bbox.east, center_lat, 90, extra_m)
69
+ if west >= east:
70
+ raise ValueError("Aspect fitting would cross the antimeridian.")
71
+ return BBox(west, bbox.south, east, bbox.north)
tests/test_api.py CHANGED
@@ -26,7 +26,14 @@ def test_catalog_endpoints() -> None:
26
  assert client.get("/api/v1/health").json()["status"] == "ok"
27
  assert len(client.get("/api/v1/styles").json()) >= 5
28
  assert len(client.get("/api/v1/layouts").json()) == 5
29
- assert {item["id"] for item in client.get("/api/v1/sizes").json()} >= {"3:4", "1:1", "A4"}
 
 
 
 
 
 
 
30
 
31
 
32
  def test_prepare_preview_and_export_contract(monkeypatch, tmp_path) -> None:
 
26
  assert client.get("/api/v1/health").json()["status"] == "ok"
27
  assert len(client.get("/api/v1/styles").json()) >= 5
28
  assert len(client.get("/api/v1/layouts").json()) == 5
29
+ assert {item["id"] for item in client.get("/api/v1/sizes").json()} >= {
30
+ "3:4",
31
+ "4:3",
32
+ "16:9",
33
+ "1:1",
34
+ "A4",
35
+ "A4-landscape",
36
+ }
37
 
38
 
39
  def test_prepare_preview_and_export_contract(monkeypatch, tmp_path) -> None:
tests/test_map_data_and_renderer.py CHANGED
@@ -101,7 +101,14 @@ def test_renderer_design_matrix(map_data, poster_config) -> None:
101
  assert renderer.render_preview(map_data, config, PreviewConfig(dpi=48, max_dimension_px=220)).startswith(
102
  b"\x89PNG"
103
  )
104
- for preset in (SizePreset.THREE_FOUR, SizePreset.FOUR_FIVE, SizePreset.SQUARE, SizePreset.A4):
 
 
 
 
 
 
 
105
  config = poster_config.__class__(
106
  location=poster_config.location,
107
  map=poster_config.map,
 
101
  assert renderer.render_preview(map_data, config, PreviewConfig(dpi=48, max_dimension_px=220)).startswith(
102
  b"\x89PNG"
103
  )
104
+ for preset in (
105
+ SizePreset.THREE_FOUR,
106
+ SizePreset.FOUR_FIVE,
107
+ SizePreset.FOUR_THREE,
108
+ SizePreset.SIXTEEN_NINE,
109
+ SizePreset.SQUARE,
110
+ SizePreset.A4,
111
+ ):
112
  config = poster_config.__class__(
113
  location=poster_config.location,
114
  map=poster_config.map,
tests/test_models_and_design.py CHANGED
@@ -3,10 +3,10 @@ from __future__ import annotations
3
  import pytest
4
 
5
  from maptoposter.layouts import LAYOUTS, get_layout
6
- from maptoposter.models import Coordinate, LayoutPreset, PosterSize, SizePreset, TypographyConfig
7
  from maptoposter.themes import list_themes, load_style
8
  from maptoposter.typography import apply_letter_spacing, fitted_font_size, format_coordinates, safe_slug
9
- from maptoposter.viewport import create_viewport
10
 
11
 
12
  def test_coordinate_and_viewport_validation() -> None:
@@ -21,6 +21,9 @@ def test_coordinate_and_viewport_validation() -> None:
21
 
22
  def test_sizes_and_layouts_are_distinct() -> None:
23
  assert PosterSize(SizePreset.THREE_FOUR).dimensions == (12.0, 16.0)
 
 
 
24
  assert PosterSize(SizePreset.SQUARE).dimensions == (12.0, 12.0)
25
  with pytest.raises(ValueError, match="requires"):
26
  PosterSize(SizePreset.CUSTOM)
@@ -28,6 +31,19 @@ def test_sizes_and_layouts_are_distinct() -> None:
28
  assert len({get_layout(item).map_rect for item in LayoutPreset}) >= 3
29
 
30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  def test_theme_loading_and_custom_colors() -> None:
32
  names = list_themes()
33
  assert len(names) >= 5
 
3
  import pytest
4
 
5
  from maptoposter.layouts import LAYOUTS, get_layout
6
+ from maptoposter.models import BBox, Coordinate, LayoutPreset, PosterSize, SizePreset, TypographyConfig
7
  from maptoposter.themes import list_themes, load_style
8
  from maptoposter.typography import apply_letter_spacing, fitted_font_size, format_coordinates, safe_slug
9
+ from maptoposter.viewport import GEOD, create_viewport, expand_bbox_to_aspect
10
 
11
 
12
  def test_coordinate_and_viewport_validation() -> None:
 
21
 
22
  def test_sizes_and_layouts_are_distinct() -> None:
23
  assert PosterSize(SizePreset.THREE_FOUR).dimensions == (12.0, 16.0)
24
+ assert PosterSize(SizePreset.FOUR_THREE).dimensions == (16.0, 12.0)
25
+ assert PosterSize(SizePreset.SIXTEEN_NINE).dimensions == (16.0, 9.0)
26
+ assert PosterSize(SizePreset.A4_LANDSCAPE).dimensions[0] > PosterSize(SizePreset.A4_LANDSCAPE).dimensions[1]
27
  assert PosterSize(SizePreset.SQUARE).dimensions == (12.0, 12.0)
28
  with pytest.raises(ValueError, match="requires"):
29
  PosterSize(SizePreset.CUSTOM)
 
31
  assert len({get_layout(item).map_rect for item in LayoutPreset}) >= 3
32
 
33
 
34
+ def test_bbox_aspect_fitting_preserves_the_selected_area() -> None:
35
+ original = BBox(113.9, 22.4, 114.2, 22.6)
36
+ fitted = expand_bbox_to_aspect(original, 3 / 4)
37
+
38
+ assert fitted.west <= original.west and fitted.east >= original.east
39
+ assert fitted.south <= original.south and fitted.north >= original.north
40
+ center_lon = (fitted.west + fitted.east) / 2
41
+ center_lat = (fitted.south + fitted.north) / 2
42
+ _, _, width_m = GEOD.inv(fitted.west, center_lat, fitted.east, center_lat)
43
+ _, _, height_m = GEOD.inv(center_lon, fitted.south, center_lon, fitted.north)
44
+ assert width_m / height_m == pytest.approx(3 / 4, abs=0.01)
45
+
46
+
47
  def test_theme_loading_and_custom_colors() -> None:
48
  names = list_themes()
49
  assert len(names) >= 5