dsh-design-studio 1.0.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/drift.js ADDED
@@ -0,0 +1,222 @@
1
+ /**
2
+ * 共用部件各屏写得不一样(#30 第 1 步):同一个 class 的样式,在好几屏自己的 <style> 里各写了一份、写得还不一样。
3
+ *
4
+ * 屏一多、上下文一压缩,模型照抄部件时最容易走样(字号、边距、颜色差一点),单看哪屏都说得过去,放一起就乱。
5
+ * 这里不开浏览器,只读文件:把每屏 <style> 里「.类名」开头的规则按选择器归到一起,比声明,写法不止一种的报出来。
6
+ * 只是提醒(不算体检的问题数):改法是挪进共用的 app.css,各屏删掉自己那份。
7
+ *
8
+ * 只比各屏自己的 <style>:共用的 app.css / tokens.css 本来就只有一份。<link> 进来的样式不看。
9
+ */
10
+ import fs from 'node:fs'
11
+ import path from 'node:path'
12
+
13
+ const MAX_FILES = 600 // 屏再多也只读这么多(几百屏的原型也够)
14
+ const MAX_BYTES = 512 * 1024 // 一屏超过这么大不读
15
+ const MAX_ITEMS = 8
16
+ const PLACE = /^(top|left|right|bottom|inset(-[a-z-]+)?|z-index|position|order|grid-(area|column|row)(-[a-z]+)?|transform|translate|rotate|scale|align-self|justify-self|place-self)$/
17
+
18
+ /** 同一个值的不同记法写成一样(#FFF / #ffffff、0px / 0、.5 / 0.5、单双引号),不然报成「写得不一样」 */
19
+ export function sameValue(v) {
20
+ return String(v)
21
+ .replace(/#([0-9a-f]{3,8})\b/gi, (m, h) => '#' + (h.length === 3 || h.length === 4 ? [...h].map((c) => c + c).join('') : h).toLowerCase())
22
+ .replace(/(^|[\s,(/])0(?:px|em|rem|vh|vw|pt)(?=$|[\s,)/])/g, '$10')
23
+ .replace(/(^|[\s,(/+*-])\.(\d)/g, '$10.$2')
24
+ .replace(/'/g, '"')
25
+ }
26
+
27
+ /** 选择器列表按最外层的逗号分开(:is(.a, .b)、[title="a,b"] 里的逗号不算) */
28
+ export function splitTop(head) {
29
+ const out = []
30
+ let depth = 0
31
+ let quote = ''
32
+ let at = 0
33
+ for (let i = 0; i < head.length; i++) {
34
+ const c = head[i]
35
+ if (quote) { if (c === '\\') i++; else if (c === quote) quote = ''; continue }
36
+ if (c === '"' || c === "'") quote = c
37
+ else if (c === '(' || c === '[') depth++
38
+ else if ((c === ')' || c === ']') && depth > 0) depth--
39
+ else if (c === ',' && !depth) { out.push(head.slice(at, i)); at = i + 1 }
40
+ }
41
+ out.push(head.slice(at))
42
+ return out
43
+ }
44
+
45
+ /** 一段 CSS → [{ sel, decls }](@media 里的规则带上条件当选择器的一部分;@keyframes、@font-face 跳过) */
46
+ export function cssRules(css) {
47
+ const out = []
48
+ const src = String(css || '').replace(/\/\*[\s\S]*?\*\//g, '')
49
+ const walk = (text, prefix, depth) => {
50
+ let i = 0
51
+ while (i < text.length) {
52
+ const open = text.indexOf('{', i)
53
+ if (open < 0) break
54
+ const head = text.slice(i, open).trim()
55
+ // 找配对的 }
56
+ let d = 1
57
+ let j = open + 1
58
+ while (j < text.length && d) { const c = text[j]; if (c === '{') d++; else if (c === '}') d--; j++ }
59
+ const body = text.slice(open + 1, j - 1)
60
+ i = j
61
+ if (!head) continue
62
+ if (head.startsWith('@')) {
63
+ if (depth < 2 && /^@(media|supports|container|layer)\b/i.test(head)) walk(body, prefix + head.replace(/\s+/g, ' ') + ' ', depth + 1)
64
+ continue
65
+ }
66
+ if (body.includes('{')) continue // 嵌套写法(CSS nesting):不认,跳过
67
+ const decls = body.split(';').map((x) => x.trim()).filter(Boolean).map((x) => {
68
+ const k = x.indexOf(':')
69
+ return k > 0 ? [x.slice(0, k).trim().toLowerCase(), sameValue(x.slice(k + 1).trim().replace(/\s+/g, ' ').replace(/\s*,\s*/g, ',').replace(/\s*!\s*important$/i, ' !important'))] : null
70
+ }).filter(Boolean)
71
+ if (!decls.length) continue
72
+ for (const sel of splitTop(head).map((x) => x.trim().replace(/\s+/g, ' ')).filter(Boolean)) out.push({ sel: prefix + sel, decls })
73
+ }
74
+ }
75
+ walk(src, '', 0)
76
+ return out
77
+ }
78
+
79
+ /** 这个选择器像不像「部件」:以 .类名 开头(可以带后代 / 伪类),不碰状态、不是整页的 */
80
+ export function partSel(sel) {
81
+ const s = sel.replace(/^@[^ ]+ [^.]*?(?=\.)/, '') // @media (…) .card → .card
82
+ if (!/^\.[A-Za-z_][\w-]*/.test(s)) return false
83
+ if (/\[data-state|\[data-theme|\[data-mode/.test(sel)) return false // 状态、深浅色各屏本来就不一样
84
+ return true
85
+ }
86
+
87
+ /** 一屏 HTML 里每个 class 用在哪几种标签上(整页只扫一遍;class 按整词认,.card 不算 card-title) */
88
+ function tagTable(html) {
89
+ const out = new Map()
90
+ const re = /<([a-zA-Z][\w-]*)\b[^>]*?\sclass\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/g
91
+ let m
92
+ while ((m = re.exec(html))) {
93
+ const tag = m[1].toLowerCase()
94
+ for (const c of (m[2] ?? m[3] ?? m[4] ?? '').split(/\s+/)) {
95
+ if (!c) continue
96
+ if (!out.has(c)) out.set(c, new Set())
97
+ out.get(c).add(tag)
98
+ }
99
+ }
100
+ return out
101
+ }
102
+
103
+ /** 一屏 HTML 里自己写的样式(<style media="(max-width: 600px)"> 的包成 @media,和别的断点分开比) */
104
+ export function inlineCss(html) {
105
+ // 注释掉的旧 <style> 不算(浏览器里它不生效)
106
+ // <template> 里的(没放进页面就不生效)也不算
107
+ return [...String(html || '').replace(/<!--[\s\S]*?(?:-->|$)/g, '').replace(/<template\b[\s\S]*?<\/template\s*>/gi, '').matchAll(/<style\b([^>]*)>([\s\S]*?)<\/style>/gi)].map((m) => {
108
+ const media = /\bmedia\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(m[1])
109
+ const q = media ? String(media[1] ?? media[2] ?? media[3] ?? '').trim() : ''
110
+ return q && !/^(all|screen)$/i.test(q) ? `@media ${q.replace(/[{}]/g, '')} {${m[2]}}` : m[2]
111
+ }).join('\n')
112
+ }
113
+
114
+ /**
115
+ * 比各屏:pages = [{ key, html }] → [{ sel, screens 写了它的屏数, variants 几种写法, props: [{ prop, values: [{ v, keys }] }] }]
116
+ * 同一屏里同一个选择器写了几次:按出现顺序合起来(后面的盖前面的),和浏览器一样
117
+ */
118
+ /** 几个方向并排(home-a / home-b,或 login / login-b):本来就故意不一样,这几屏不比(和画布认方向一个规则) */
119
+ export function takeKeys(keys) {
120
+ const VAR = /^(.+)-([a-z])\.html?$/i
121
+ const stem = (k) => { const v = VAR.exec(k); return (v ? v[1] : k.replace(/\.html?$/i, '')).toLowerCase() }
122
+ const by = new Map()
123
+ for (const k of keys) { const s = stem(k); if (!by.has(s)) by.set(s, []); by.get(s).push(k) }
124
+ const out = new Set()
125
+ for (const list of by.values()) if (list.length > 1 && list.some((k) => VAR.test(k))) for (const k of list) out.add(k)
126
+ return out
127
+ }
128
+
129
+ export function compareParts(pages, { max = MAX_ITEMS } = {}) {
130
+ const takes = takeKeys(pages.map((p) => p.key))
131
+ pages = pages.filter((p) => !takes.has(p.key))
132
+ const bySel = new Map() // sel → Map(key → Map(prop → value))
133
+ const htmlOf = new Map(pages.map((p) => [p.key, String(p.html || '')]))
134
+ for (const { key, html } of pages) {
135
+ const mine = new Map()
136
+ for (const r of cssRules(inlineCss(html))) {
137
+ if (!partSel(r.sel)) continue
138
+ if (!mine.has(r.sel)) mine.set(r.sel, new Map())
139
+ const m = mine.get(r.sel)
140
+ // 后写的盖前面的;前面那条带 !important、后面的没带:前面的赢(和浏览器一样)
141
+ for (const [k, v] of r.decls) if (!(/ !important$/.test(m.get(k) || '') && !/ !important$/.test(v))) m.set(k, v)
142
+ }
143
+ for (const [sel, m] of mine) {
144
+ if (!bySel.has(sel)) bySel.set(sel, new Map())
145
+ bySel.get(sel).set(key, m)
146
+ }
147
+ }
148
+ const out = []
149
+ // 标签表用到才建(屏多、样式多的设计,只有真写得不一样的部件才要看标签)
150
+ const tables = new Map()
151
+ const tagsOf = (key, cls) => {
152
+ if (!tables.has(key)) tables.set(key, tagTable(htmlOf.get(key)))
153
+ return tables.get(key).get(cls) || new Set()
154
+ }
155
+ for (const [sel, per] of bySel) {
156
+ if (per.size < 2) continue
157
+ // 哪几项不一样:只比两屏以上都写了、值又不一样的(一屏多写一项 = 这页自己加的,不算走样);
158
+ // 位置类的(top / left / z-index / grid-area…)各页本来就摆得不一样,不比
159
+ const props = new Set([...per.values()].flatMap((m) => [...m.keys()]))
160
+ const diff = []
161
+ let shared = 0
162
+ for (const p of props) {
163
+ if (PLACE.test(p)) continue
164
+ const vals = new Map()
165
+ let n = 0
166
+ for (const [key, m] of per) { if (!m.has(p)) continue; n++; const v = m.get(p); if (!vals.has(v)) vals.set(v, []); vals.get(v).push(key) }
167
+ if (n < 2) continue
168
+ shared++
169
+ if (vals.size > 1) diff.push({ prop: p, values: [...vals].map(([v, keys]) => ({ v, keys })).sort((x, y) => y.keys.length - x.keys.length) })
170
+ }
171
+ if (!diff.length) continue
172
+ // 只写了一两项的(.issue{padding-bottom:10px} 对 12px)差一项就是走样;共同写了好几项、一大半都不一样的才当撞名字
173
+ if (shared >= 3 && diff.length * 2 > shared) continue
174
+ // 不是同一个部件、只是撞了名字(首页的 .title 是大标题、详情页的 .title 是小节标题):
175
+ // 标签对不上(一屏是 h1、一屏是 h2)不算;声明一大半都不一样也不算——走了样的部件只差几项
176
+ const cls = /^(?:@[^ ]+ [^.]*?)?\.([A-Za-z_][\w-]*)/.exec(sel)
177
+ if (cls) {
178
+ const tags = [...per.keys()].map((k) => tagsOf(k, cls[1]))
179
+ const known = tags.filter((x) => x.size)
180
+ const seen = new Map() // 标签 → 几屏用它
181
+ for (const x of known) for (const tg of x) seen.set(tg, (seen.get(tg) || 0) + 1)
182
+ if (known.length >= 2 && ![...seen.values()].some((n) => n >= 2)) continue
183
+ }
184
+ const variants = new Set([...per.values()].filter((m) => diff.some((d) => m.has(d.prop))).map((m) => JSON.stringify(diff.map((d) => (m.has(d.prop) ? m.get(d.prop) : null))))).size
185
+ if (variants < 2) continue
186
+ out.push({ sel, screens: per.size, variants, props: diff.slice(0, 4), more: Math.max(0, diff.length - 4), keys: [...per.keys()] })
187
+ }
188
+ // 写的屏越多、写法越多的越要紧
189
+ out.sort((a, b) => b.screens - a.screens || b.variants - a.variants || (a.sel < b.sel ? -1 : 1))
190
+ return { items: out.slice(0, max), more: Math.max(0, out.length - max) }
191
+ }
192
+
193
+ /** 读一套设计的各屏(keys 是相对 root 的文件名)再比 */
194
+ export function partDrift(root, keys) {
195
+ const pages = []
196
+ for (const key of (keys || []).slice(0, MAX_FILES)) {
197
+ const f = path.join(root, key)
198
+ try {
199
+ const st = fs.statSync(f)
200
+ if (!st.isFile() || st.size > MAX_BYTES) continue
201
+ pages.push({ key, html: fs.readFileSync(f, 'utf8') })
202
+ } catch { /* 读不了的跳过 */ }
203
+ }
204
+ return compareParts(pages)
205
+ }
206
+
207
+ const short = (keys, n = 3) => keys.slice(0, n).map((k) => k.replace(/\.html?$/i, '')).join('、') + (keys.length > n ? ` 等 ${keys.length} 屏` : '')
208
+
209
+ /** 给模型的字(体检结果后面接着) */
210
+ export function formatDrift(r, total) {
211
+ if (!r || !r.items.length) return ''
212
+ const lines = [`\n共用部件各屏写得不一样(不算进问题数,是提醒):同一个 class 在几屏自己的 <style> 里各写了一份、还不一样,放一起看会乱。`]
213
+ for (const it of r.items) {
214
+ const ps = it.props.map((p) => `${p.prop}:${p.values.map((x) => `${x.v || '没写'}(${short(x.keys)})`).join(' / ')}`)
215
+ lines.push(`- ${it.sel}:${it.screens} 屏里有 ${it.variants} 种写法。${ps.join(';')}${it.more ? `;还有 ${it.more} 项不同` : ''}`)
216
+ }
217
+ if (r.more) lines.push(`- 还有 ${r.more} 个部件也这样`)
218
+ lines.push(total > 6
219
+ ? '改法:定一种写法挪进共用的 app.css,各屏删掉自己那份。屏多,先告诉用户哪几个部件不一致、问要不要统一,他说改再改,别一口气把所有屏都改了。'
220
+ : '改法:定一种写法(多数屏用的那种)挪进共用的 app.css,各屏删掉自己那份。')
221
+ return lines.join('\n')
222
+ }
package/lib/handoff.js CHANGED
@@ -21,6 +21,26 @@ import { annotationsMd } from './annotations.js'
21
21
  import { tokensOf } from './system.js'
22
22
  import { FRAMES_DIR } from './frames.js'
23
23
  import { FRAME_MAIN, SLOT_BOX } from './slot.js'
24
+ import { statesOfHtml } from './states.js'
25
+
26
+ /**
27
+ * 交接文档里的「页面状态」:写了几个状态的屏,列出状态、各状态用到的样式条数、哪些按钮会切到哪个状态
28
+ * @param htmlByKey 屏 → HTML;css 共用样式表的内容(数 [data-state] 规则用)
29
+ */
30
+ export function statesMd(htmlByKey, css = '') {
31
+ const out = []
32
+ for (const [key, html] of htmlByKey) {
33
+ const st = statesOfHtml(html)
34
+ if (!st.length) continue
35
+ const all = String(html) + '\n' + css
36
+ const uses = (n) => (all.match(new RegExp(`\\[data-state\\s*=\\s*["']?${n}["']?\\s*\\]`, 'g')) || []).length
37
+ const names = st.map((x, i) => `\`${x.name}\`${x.label !== x.name ? `(${x.label})` : ''}${i === 0 ? '·默认' : ''}${uses(x.name) ? `,样式 ${uses(x.name)} 处` : ''}`)
38
+ const go = new Set()
39
+ for (const m of String(html).matchAll(/(?:href|data-href|data-to)\s*=\s*["']([^"'#]*?)\?state=([A-Za-z0-9_-]{1,32})/gi)) go.add(`${m[1] ? m[1].replace(/^\.?\//, '') : key} → ${m[2]}`)
40
+ out.push(`- ${key} 有 ${st.length} 个状态:${names.join(';')}。是同一个页面的几种样子:做成一个组件 + 状态(如 \`status: ${st.map((x) => `'${x.name}'`).join(' | ')}\`),按 \`[data-state="…"]\` 那几条样式显示 / 隐藏,别拆成几个页面${go.size ? `;会切状态的链接:${[...go].slice(0, 8).join('、')}` : ''}。`)
41
+ }
42
+ return out
43
+ }
24
44
 
25
45
  export const HANDOFF_DIR = 'handoff'
26
46
  /** 版本名里哪些是用户在右侧栏亲手改的(见 core.js:改字、调样式、调节滑块) */
@@ -601,6 +621,10 @@ export function handoffMd({ root, rows, kind, size, framework, dest, project, sy
601
621
  if (bits.length) inter.push(`- ${key}:${bits.join(';')}`)
602
622
  }
603
623
  lines.push(...(inter.length ? inter : ['- 设计稿里没有脚本和表单,纯展示。']))
624
+ // 一页多状态(#30):同一个页面的几种样子写在一个文件里,转代码时是一个组件带状态,不是几个页面
625
+ const stLines = statesMd(htmlByKey, [...sheets, 'tokens.css'].map((n) => { try { return fs.readFileSync(path.join(root, n), 'utf8') } catch { return '' } }).join('\n'))
626
+ if (stLines.length) lines.push(...stLines)
627
+ if ([...htmlByKey.values()].some((h) => /\sdata-back\b/i.test(slotHtml(h)))) lines.push('- 写了 `data-back` 的返回按钮:做成「返回上一页」(router.back() / navigation.goBack()),没有上一页时才去它写的 href。')
604
628
  if (hover) lines.push(`- 悬停 / 聚焦 / 按下的样式 ${hover} 处:照搬,别丢。`)
605
629
  if ([...htmlByKey.values()].some((h) => /prefers-color-scheme\s*:\s*dark|data-theme=["']?dark/.test(h)) || /\[data-theme=["']?dark/.test(Object.keys(tok).length ? fs.readFileSync(path.join(root, 'tokens.css'), 'utf8') : '')) lines.push('- 有深色样式:项目里也要能切(跟系统,或 `<html data-theme="dark">`)。')
606
630
  const tw = readTweaks(root)
package/lib/htmlpack.js CHANGED
@@ -14,6 +14,7 @@
14
14
  import crypto from 'node:crypto'
15
15
  import { bundle, strictMeta } from './bundle.js'
16
16
  import { defang } from './serve.js'
17
+ import { statesOfHtml } from './states.js'
17
18
 
18
19
  /** 每屏的 <base>:一个不存在的地址(.invalid 不会被解析),屏里的相对链接都落在它下面,小脚本据此认出「站内跳转」 */
19
20
  export const PACK_ORIGIN = 'https://ddp-pack.invalid'
@@ -94,7 +95,7 @@ function storeShim(D) {
94
95
  * 每屏最前面(页面脚本跑之前就装好):点了跳到别的屏 → 告诉播放器换屏;页内锚点自己滚;站外链接开新标签页。
95
96
  * 和 picker.js 里「试用 / 远程看」的拦法一样(LINK_SEL、LINK_JS 同一份);再加上调节滑块的值、不画滚动条
96
97
  */
97
- function navScript(C) {
98
+ function navScript(C, ST) {
98
99
  const SEL = C.sel
99
100
  const JS = new RegExp(C.js)
100
101
  const post = (m) => { try { parent.postMessage({ ddpPack: 1, ...m }, '*') } catch { /* 没有外层 */ } }
@@ -106,6 +107,21 @@ function navScript(C) {
106
107
  const de = document.documentElement
107
108
  for (const [k, v] of Object.entries((C.tweak && C.tweak.vars) || {})) { try { de.style.setProperty(k, String(v), 'important') } catch { /* 不认的值 */ } }
108
109
  for (const [k, v] of Object.entries((C.tweak && C.tweak.attrs) || {})) { try { if (v == null || v === false) de.removeAttribute(k); else de.setAttribute(k, String(v)) } catch { /* 不认的名字 */ } }
110
+ // 一页多状态(#30):播放器放这一屏时给的状态(order.html?state=paid)写在 <html data-state> 上
111
+ const STATE_RE = /^[A-Za-z0-9_-]{1,32}$/
112
+ /** 这页 <meta name="dsh-states"> 里写了哪几个状态(不到两个当没写) */
113
+ const declared = () => {
114
+ const m = document.querySelector('meta[name=dsh-states]')
115
+ const out = []
116
+ for (const part of String((m && m.getAttribute('content')) || '').split(/[,,;;\n]+/)) {
117
+ const x = /^\s*([A-Za-z0-9_-]{1,32})/.exec(part)
118
+ if (x && !out.includes(x[1])) out.push(x[1])
119
+ }
120
+ return out.length >= 2 ? out : []
121
+ }
122
+ // 播放器只在这屏写了这个状态时才给(老页面自己拿 ?state= 当参数的给 '',完全不碰 data-state)
123
+ if (typeof ST === 'string' && STATE_RE.test(ST)) de.setAttribute('data-state', ST)
124
+ const stateOf = (u) => { const v = u.searchParams.get('state') || ''; return STATE_RE.test(v) ? v : '' }
109
125
 
110
126
  /** 这个地址是不是跳到演示包里的别的屏:{ path, hash };同一页(只有锚点)给 { same, hash };站外给 { out } */
111
127
  const where = (raw) => {
@@ -114,23 +130,35 @@ function navScript(C) {
114
130
  let u
115
131
  try { u = new URL(raw, document.baseURI) } catch { return null }
116
132
  if (u.origin !== C.origin) return /^https?:$/.test(u.protocol) ? { out: u.href } : null
117
- // href="#"(「全部」)的 u.hash 是空串:记成 '#',和「同一页、没锚点」(导航栏里指着本页)分开
118
- if (u.pathname === here().pathname) return { same: true, hash: u.hash || (/#$/.test(u.href) ? '#' : '') }
133
+ let state = stateOf(u)
119
134
  let p = u.pathname
120
135
  try { p = decodeURIComponent(p) } catch { /* 原样 */ }
121
- return { path: p, hash: u.hash }
136
+ // href="#"(「全部」)的 u.hash 是空串:记成 '#',和「同一页、没锚点」(导航栏里指着本页)分开。同一页换个状态(?state=paid)算跳
137
+ // 在别的状态里(地址带了状态进来的)点指着本页、不带状态也不带锚点的链接(href="order.html")= 回默认状态,也算跳
138
+ // 同一页换个这页没写的状态(老页面自己拿 ?state= 当参数):和以前一样当本页链接
139
+ const cur = de.getAttribute('data-state') || ''
140
+ const raw0 = state
141
+ if (u.pathname === here().pathname && state && !declared().includes(state)) state = ''
142
+ // 回默认状态只认什么参数都不带的(?page=2 是页面自己的参数);已经在默认状态(播放器给的 ST 是空的)就不用回
143
+ if (u.pathname === here().pathname && (state ? state === cur : raw0 || u.search || u.hash || /#$/.test(u.href) || !(typeof ST === 'string' && ST && ST === cur && declared().includes(ST) && ST !== declared()[0]))) return { same: true, hash: u.hash || (/#$/.test(u.href) ? '#' : '') }
144
+ return { path: p, hash: u.hash, state }
122
145
  }
123
146
  const rawOf = (el) => {
124
147
  let raw = el.getAttribute('href') || el.getAttribute('data-href') || el.getAttribute('data-to') || ''
125
148
  if (!raw && el.hasAttribute('onclick')) { const m = JS.exec(el.getAttribute('onclick') || ''); if (m) raw = m[1] }
126
149
  return raw
127
150
  }
128
- // 页内锚点:照常改这一页的 #(页面里按 # 换内容的写法照样能用);<base> 指着别处,不能让链接自己跳
151
+ // 页内锚点:照常改这一页的 #(页面里按 # 换内容的写法照样能用);<base> 指着别处,不能让链接自己跳。
152
+ // 换掉当前这条浏览器历史、不多记(#30):演示包的历史只记换屏、换状态,「返回」一下就回上一屏(不然第一下只是清掉锚点)
153
+ const setHash = (hash) => {
154
+ try { location.replace(location.href.replace(/#.*$/, '') + (hash || '#')); return } catch { /* 换不了:照常改 # */ }
155
+ location.hash = hash
156
+ }
129
157
  const jumpTo = (hash) => {
130
158
  hash = String(hash || '')
131
- if (hash && hash !== '#' && location.hash !== hash) { location.hash = hash; return }
159
+ if (hash && hash !== '#' && location.hash !== hash) { setHash(hash); return }
132
160
  // 点过「待配送」#tab2 再点「全部」href="#":清掉旧的 #(按 hashchange 换内容的页面回到默认),浏览器自己滚回顶上
133
- if (hash === '#' && location.hash) { location.hash = ''; return }
161
+ if (hash === '#' && location.hash) { setHash(''); return }
134
162
  let id = hash.replace(/^#/, '')
135
163
  try { id = decodeURIComponent(id) } catch { /* 原样 */ }
136
164
  const t = id ? document.getElementById(id) || document.getElementsByName(id)[0] : null
@@ -146,10 +174,21 @@ function navScript(C) {
146
174
  return true
147
175
  }
148
176
  if (w.same) { jumpTo(w.hash); return true }
149
- post({ type: 'nav', path: w.path, hash: w.hash })
177
+ post({ type: 'nav', path: w.path, hash: w.hash, state: w.state || '' })
150
178
  return true
151
179
  }
152
180
 
181
+ // 返回(data-back):按看的人走过的路退一步,没得退(直接打开的这屏)才去它写的地方。点的那一下就拦(不等页面自己跳)
182
+ addEventListener('click', (e) => {
183
+ if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return
184
+ const el = e.target && e.target.closest ? e.target.closest('[data-back]') : null
185
+ if (!el) return
186
+ const w = where(rawOf(el))
187
+ e.preventDefault()
188
+ e.stopImmediatePropagation() // 同在 window 上的跳屏监听(别人做的屏、旧浏览器那条路)别再换一次
189
+ post({ type: 'nav', back: true, path: w && w.path ? w.path : '', hash: (w && w.hash) || '', state: (w && w.state) || '' })
190
+ }, true)
191
+
153
192
  // 跳到别的屏、站外。自己做的屏(收得到 navigate):<a href> 让浏览器照常跳,下面的 navigate 按最终地址接住——
154
193
  // 页面自己的点击处理先跑完(「去结算」先存购物车、点的时候才改 href),拦了默认行为就不跳,和真浏览器一样;
155
194
  // 地址只写在 onclick 里的(onclick="if (!同意) {…; return} location.href='x'"),页面真跳了 navigate 也接住;
@@ -304,21 +343,25 @@ function player() {
304
343
  return assets.get(i)
305
344
  }
306
345
  const store = { l: {}, s: {} }
307
- const htmlOf = (i) => {
346
+ const htmlOf = (i, state = '') => {
308
347
  if (!cache.has(i)) {
309
348
  cache.set(i, JSON.parse($('ddp-s-' + i).textContent).replace(assetRe, (m, n) => asset(Number(n))))
310
349
  if (cache.size > 8) cache.delete(cache.keys().next().value) // 屏多、图大:只留最近放过的几屏
311
350
  }
312
- // 存储的初始内容:每次放进去都是当时的(上一屏刚存的这一屏读得到)
313
- return cache.get(i).replace(C.storeMark, () => JSON.stringify(store).replace(/</g, '\\u003c'))
351
+ // 存储的初始内容:每次放进去都是当时的(上一屏刚存的这一屏读得到);状态(#30)也是放的时候才定
352
+ const out = cache.get(i).replace(C.storeMark, () => JSON.stringify(store).replace(/</g, '\\u003c'))
353
+ const ok = /^[A-Za-z0-9_-]{1,32}$/.test(state) && (C.screens[i].states || []).includes(state) // 这屏写了的状态才设
354
+ return C.stateMark ? out.split(C.stateMark).join(JSON.stringify(ok ? state : '')) : out
314
355
  }
315
356
  let shell = !!C.shellDefault
316
357
  // 看的人开关过外壳就记着(每份演示自己记:别的演示点过不影响这份导出时定的默认)
317
358
  const SHELL_KEY = 'ddp-pack-shell-' + C.token // 每份演示自己记(直接双击打开的本地文件共用一份 localStorage)
318
359
  try { const v = localStorage.getItem(SHELL_KEY); if (C.framed && (v === '1' || v === '0')) shell = v === '1' } catch { /* 存不了 */ }
319
360
  let cur = -1
361
+ let curState = ''
320
362
  let seq = 0
321
363
  let pendingHash = ''
364
+ const trail = [] // 看的人在演示里走过的路(地址的 # 部分):返回(data-back)按它退一步
322
365
  const stage = $('stage')
323
366
  const bar = $('bar')
324
367
  const sel = $('sel')
@@ -436,7 +479,7 @@ function player() {
436
479
  }
437
480
 
438
481
  /** 放一屏:新 iframe 在后面载好了再换上来(不白一下) */
439
- function show(i, hash = '') {
482
+ function show(i, hash = '', state = '') {
440
483
  const me = ++seq
441
484
  const s = C.screens[i]
442
485
  const fr = document.createElement('iframe')
@@ -457,20 +500,37 @@ function player() {
457
500
  }
458
501
  fr.addEventListener('load', swap)
459
502
  setTimeout(swap, 2500) // 页面里有载不完的东西:别一直等
460
- fr.srcdoc = htmlOf(i)
503
+ fr.srcdoc = htmlOf(i, state)
461
504
  vp.appendChild(fr)
462
505
  }
463
506
 
464
- const indexOfHash = () => {
507
+ /** 地址的 # 部分 → 第几屏、哪个状态(#order.html?state=paid) */
508
+ const posOfHash = () => {
465
509
  let h = ''
466
510
  try { h = decodeURIComponent(location.hash.replace(/^#/, '')) } catch { h = '' }
467
- const k = h ? C.screens.findIndex((s) => s.key === h) : -1
468
- return k >= 0 ? k : 0
511
+ const m = /^(.*)\?state=([A-Za-z0-9_-]{1,32})$/.exec(h)
512
+ const k = h ? C.screens.findIndex((s) => s.key === (m ? m[1] : h)) : -1
513
+ return k >= 0 ? { i: k, state: m ? normState(k, m[2]) : '' } : { i: 0, state: '' }
469
514
  }
515
+ // 默认状态写不写都是同一屏(order.html 和 order.html?state=default):统一成不写,返回的路才对得上
516
+ const normState = (i, state) => (state && !(C.screens[i].states && C.screens[i].states[0] === state) ? state : '')
517
+ const hashOf = (i, state) => '#' + encodeURIComponent(C.screens[i].key) + (normState(i, state) ? '?state=' + state : '')
518
+ // 走到第几步,记在这一条浏览器历史记录上:页面里的「返回」(data-back)有得退就是浏览器后退一步,
519
+ // 和浏览器自己的后退、前进是同一份路(后退再前进也对得上)。记不了的(沙盒不给改历史)照老办法按 trail 退
520
+ const depthOf = () => { try { const s = history.state; return s && typeof s.ddpPos === 'number' ? s.ddpPos : -1 } catch { return -1 } }
521
+ const tag = (n) => { try { history.replaceState({ ...(history.state && typeof history.state === 'object' ? history.state : {}), ddpPos: n }, ''); return depthOf() === n } catch { return false } }
522
+ let depth = Math.max(0, depthOf())
523
+ const tagged = tag(depth)
470
524
  function render() {
471
- const i = indexOfHash()
472
- if (i === cur && dev) return
525
+ const { i, state } = posOfHash()
526
+ if (tagged) {
527
+ const n = depthOf()
528
+ if (n >= 0) depth = n // 浏览器后退 / 前进回到记过的那一步
529
+ else { depth += 1; tag(depth) } // 新走的一步
530
+ } else if (trail.length && trail[trail.length - 1] === hashOf(i, state)) trail.pop() // 浏览器后退回到了上一步
531
+ if (i === cur && state === curState && dev) return
473
532
  cur = i
533
+ curState = state
474
534
  sel.value = String(i)
475
535
  count.textContent = T.of.replace('{i}', String(i + 1)).replace('{n}', String(N))
476
536
  $('prev').disabled = i === 0
@@ -481,27 +541,34 @@ function player() {
481
541
  decorate()
482
542
  const hash = pendingHash
483
543
  pendingHash = ''
484
- show(i, hash)
544
+ show(i, hash, state)
485
545
  }
486
546
  /** 外框重搭(开关外壳、横竖屏换了):当前这屏重放 */
487
- const rebuild = () => { build(); decorate(); show(cur) }
488
- const go = (i, hash = '') => {
547
+ const rebuild = () => { build(); decorate(); show(cur, '', curState) }
548
+ const go = (i, hash = '', state = '') => {
489
549
  if (i < 0 || i >= N) return
490
- if (i === cur) { if (hash) { const fr = vp && [...vp.querySelectorAll('iframe:not(.nx)')].pop(); if (fr) fr.contentWindow.postMessage({ ddpPack: 1, type: 'jump', hash }, '*') } return }
550
+ state = normState(i, state)
551
+ if (i === cur && state === curState) { if (hash) { const fr = vp && [...vp.querySelectorAll('iframe:not(.nx)')].pop(); if (fr) fr.contentWindow.postMessage({ ddpPack: 1, type: 'jump', hash }, '*') } return }
552
+ if (cur >= 0) { trail.push(hashOf(cur, curState)); if (trail.length > 30) trail.shift() }
491
553
  pendingHash = hash
492
- location.hash = '#' + encodeURIComponent(C.screens[i].key)
554
+ location.hash = hashOf(i, state)
493
555
  }
494
556
  const keyOf = (p) => { let k = String(p || '').replace(/^\/+/, ''); if (!k || k.endsWith('/')) k += 'index.html'; return k }
495
557
 
496
558
  addEventListener('message', (e) => {
497
559
  const d = e.data
498
560
  if (!d || d.ddpPack !== 1 || !vp || ![...vp.querySelectorAll('iframe')].some((f) => f.contentWindow === e.source)) return
499
- if (d.type === 'nav') {
561
+ if (d.type === 'nav' && d.back === true && (tagged ? depth > 0 : trail.length)) {
562
+ if (tagged) history.back()
563
+ else location.hash = trail.pop()
564
+ } else if (d.type === 'nav' && d.back === true && !d.path) {
565
+ // 没得退、也没写去哪:不动
566
+ } else if (d.type === 'nav') {
500
567
  const k = keyOf(d.path)
501
568
  let i = C.screens.findIndex((s) => s.key === k)
502
569
  if (i < 0) i = C.screens.findIndex((s) => s.key === k + '.html')
503
570
  if (i < 0) say(T.notIn.replace('{p}', k))
504
- else go(i, typeof d.hash === 'string' ? d.hash : '')
571
+ else go(i, typeof d.hash === 'string' ? d.hash : '', typeof d.state === 'string' && /^[A-Za-z0-9_-]{1,32}$/.test(d.state) ? d.state : '')
505
572
  } else if (d.type === 'store' && (d.area === 'l' || d.area === 's')) {
506
573
  const m = store[d.area]
507
574
  if (d.op === 'set') m[String(d.k)] = String(d.v)
@@ -626,7 +693,8 @@ export function buildPack({ screens, read, strictOf = () => false, kind, w, h, o
626
693
  const navCfg = { origin: PACK_ORIGIN, sel: LINK_SEL, js: LINK_JS.source, pages: !!FIXED[kind], tweak: tweak && typeof tweak === 'object' ? { vars: tweak.vars || {}, attrs: tweak.attrs || {} } : null }
627
694
  const script = (src, strict) => `<script${strict ? ` nonce="${nonce}"` : ''}>${src.replace(/<\/(script)/gi, '<\\/$1').replace(/<!--/g, '<\\!--')}</script>`
628
695
  const shimSrc = `(${storeShim})(${storeMark});`
629
- const navSrc = (strict) => `(${navScript})(${JSON.stringify({ ...navCfg, strict })});`
696
+ const stateMark = `/*ddpT${token}*/''` // 放一屏时换成这屏的状态(#30)
697
+ const navSrc = (strict) => `(${navScript})(${JSON.stringify({ ...navCfg, strict })}, ${stateMark});`
630
698
  const mode = dark ? 'dark' : scheme === 'dark' ? 'media' : 'light'
631
699
  const schemeSrc = `(${schemeScript})(${JSON.stringify(mode)});`
632
700
 
@@ -659,7 +727,8 @@ export function buildPack({ screens, read, strictOf = () => false, kind, w, h, o
659
727
  total += out.length
660
728
  if (total > PACK_MAX) { const e = new Error('tooBig'); e.code = 'tooBig'; throw e }
661
729
  parts.push(`<script type="application/json" id="ddp-s-${list.length}">${jsonTag(out)}</script>`)
662
- list.push({ key: s.key, label: String(s.label || s.key).slice(0, 80), top: !!s.top, ...(strict ? { strict: true } : null) })
730
+ const states = statesOfHtml(text).map((x) => x.name) // 这屏写了哪几个状态(#30):放这屏时只设写了的
731
+ list.push({ key: s.key, label: String(s.label || s.key).slice(0, 80), top: !!s.top, ...(strict ? { strict: true } : null), ...(states.length ? { states } : null) })
663
732
  }
664
733
  if (!list.length) { const e = new Error('noScreens'); e.code = 'noScreens'; throw e }
665
734
 
@@ -670,7 +739,7 @@ export function buildPack({ screens, read, strictOf = () => false, kind, w, h, o
670
739
  framed: !!FRAMED[kind], fixed: !!FIXED[kind],
671
740
  // 网页默认不套浏览器框(铺满窗口),右侧栏开着「按画幅显示」的照它套着;手机、平板、桌面软件默认套着
672
741
  shellDefault: !!FRAMED[kind] && (kind !== 'web' || !!fit),
673
- screens: list, token, storeMark, strings: S,
742
+ screens: list, token, storeMark, stateMark, strings: S,
674
743
  }
675
744
  const docTitle = cfg.title || list[0].label
676
745
  const html = '<!doctype html>\n'