cortico-world-fun 0.1.6 → 0.2.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/src/keepsakes.js CHANGED
@@ -1,200 +1,61 @@
1
- /**
2
- * 纪念品架与场所完成度:让「去过」这件事在纪念册之外还留下点东西。
3
- *
4
- * ## 这一层解决什么问题
5
- *
6
- * 0.1.5 的纪念册是一串孤立的趟:`fun_go → fun_wander × N → fun_home`,
7
- * 每一趟结束就结束了。纪念品在 `trip.souvenirs` 里只是几个字符串,
8
- * **跨趟没有任何归集**——所以「这枚纪念币是第一次去游乐场那天买的」
9
- * 这句话说不出来,面板上也看不出「我到底攒了多少东西」。
10
- *
11
- * 而这条数据其实一直都在 `state.trips` 里躺着,只是从来没人取。
12
- *
13
- * ## 设计
14
- *
15
- * - **纯函数、不碰文件**:输入是 `state.trips`(和场所表),输出是结构化归集。
16
- * World 负责把它变成回执文字或面板 payload。
17
- * - **不算新状态**:不落盘、不加字段、不改 state 形状。纪念品架是
18
- * `trips` 的一个**视图**,随时可以从头算出来。这样老数据自动就有了,
19
- * 也不需要迁移。
20
- * - **永不抛错**:脏数据跳过那一条,绝不让纪念册打不开。
21
- *
22
- * ## 为什么不做「收藏值多少钱 / 稀有度」
23
- *
24
- * 那是给游戏做的。她真正会用到的是两句:这东西**在哪买的、哪天**,
25
- * 以及**这儿我还差什么没玩**。所以这里只归集这两类。
26
- */
27
-
28
- const norm = (v, max) => (typeof v === 'string' ? v.replace(/\s+/g, ' ').trim().slice(0, max) : '');
29
-
30
1
  import { tripDay, tripSummary } from './state.js';
2
+ const norm = (v, max) => typeof v === 'string' ? v.replace(/\s+/g, ' ').trim().slice(0, max) : '';
31
3
 
32
- /**
33
- * 把纪念册里所有趟摊平,按「东西的名字」归集。
34
- *
35
- * 同名纪念品在不同地方买算**两件不同的东西**(游乐场的棉花糖 ≠ 公园的棉花糖),
36
- * 所以 key 是 `placeId::名字`。同一处买过两次才算「买过几次」。
37
- *
38
- * @param {object[]} trips `state.trips`(最近的在前)
39
- * @returns {{ items: object[], byPlace: object[], total: number, uniquePlaces: number }}
40
- */
41
- export function collectSouvenirs(trips, timezone = 'Asia/Shanghai') {
4
+ /** 收藏可来自旧行程,或持久账本。详细回忆只关联仍保存的近期/珍藏行程。 */
5
+ export function collectSouvenirs(trips, timezone = 'Asia/Shanghai', collection = null) {
42
6
  const list = Array.isArray(trips) ? trips : [];
43
7
  const map = new Map();
44
-
45
8
  for (const t of list) {
46
9
  if (!t || typeof t !== 'object') continue;
47
- const placeId = norm(t.placeId, 40);
10
+ const placeId = norm(t.placeId, 40); if (!placeId) continue;
48
11
  const placeName = norm(t.placeName, 40) || placeId;
49
12
  const day = tripDay(t, timezone);
50
- const memory = {
51
- day,
52
- leftAt: Number(t.leftAt) || 0,
53
- company: norm(t.company, 40),
54
- note: norm(t.note, 120),
55
- summary: tripSummary({
56
- placeName,
57
- company: norm(t.company, 40),
58
- visited: (Array.isArray(t.visited) ? t.visited : []).filter((v) => norm(v?.area, 40)).map((v) => ({ area: norm(v.area, 40) })),
59
- }),
60
- };
61
- const souvenirs = Array.isArray(t.souvenirs) ? [...new Set(t.souvenirs.map((s) => norm(s, 40)).filter(Boolean))] : [];
62
- for (const raw of souvenirs) {
63
- const name = norm(raw, 40);
64
- if (!name) continue;
13
+ const memory = { day, leftAt: Number(t.leftAt) || 0, company: norm(t.company, 40), note: norm(t.note, 120), summary: tripSummary({ ...t, placeName, visited: (Array.isArray(t.visited) ? t.visited : []).filter((v) => norm(v?.area, 40)) }) };
14
+ for (const name of new Set((Array.isArray(t.souvenirs) ? t.souvenirs : []).map((s) => norm(s, 40)).filter(Boolean))) {
65
15
  const key = `${placeId}::${name}`;
66
16
  const cur = map.get(key);
67
- if (!cur) {
68
- map.set(key, {
69
- key,
70
- name,
71
- placeId,
72
- placeName,
73
- // 第一次买到它的那天:纪念册是最近的在前,所以先遇到的就是最近那次,
74
- // 要一直往前覆盖到最后遇到的那条,才是真正的「第一次」。
75
- firstDay: day,
76
- lastDay: day,
77
- times: 1,
78
- memories: [memory],
79
- });
80
- continue;
81
- }
82
- cur.times += 1;
83
- cur.memories.push(memory);
84
- if (day && (!cur.firstDay || day < cur.firstDay)) cur.firstDay = day;
85
- if (day && (!cur.lastDay || day > cur.lastDay)) cur.lastDay = day;
17
+ if (!cur) map.set(key, { key, name, placeId, placeName, firstDay: day, lastDay: day, times: 1, memories: [memory] });
18
+ else { cur.times += 1; cur.memories.push(memory); if (day && (!cur.firstDay || day < cur.firstDay)) cur.firstDay = day; if (day && (!cur.lastDay || day > cur.lastDay)) cur.lastDay = day; }
86
19
  }
87
20
  }
88
-
89
- const items = [...map.values()];
90
- // 排序:最近拿到的排前面(面板上「最新攒到」最有用),同一天按地方名。
91
- items.sort((a, b) => {
92
- if (a.lastDay !== b.lastDay) return a.lastDay < b.lastDay ? 1 : -1;
93
- return a.placeName.localeCompare(b.placeName) || a.name.localeCompare(b.name);
94
- });
95
-
96
- // 按地方分组:面板上「这一处的架子」用这个。
21
+ if (Array.isArray(collection)) {
22
+ const historical = new Map(map);
23
+ map.clear();
24
+ for (const x of collection) {
25
+ const placeId = norm(x?.placeId, 40); const name = norm(x?.name, 40); if (!placeId || !name) continue;
26
+ const key = `${placeId}::${name}`;
27
+ map.set(key, { key, placeId, placeName: norm(x.placeName, 40) || placeId, name, firstDay: norm(x.firstDay, 10), lastDay: norm(x.lastDay, 10), times: Math.max(1, Number(x.times) || 1), memories: historical.get(key)?.memories ?? (Array.isArray(x.tripIds) ? x.tripIds : []).map((id) => ({ tripId: id, archived: true })) });
28
+ }
29
+ }
30
+ const items = [...map.values()].sort((a, b) => b.lastDay.localeCompare(a.lastDay) || a.placeName.localeCompare(b.placeName) || a.name.localeCompare(b.name));
97
31
  const places = new Map();
98
32
  for (const it of items) {
99
- const cur = places.get(it.placeId) ?? {
100
- placeId: it.placeId, placeName: it.placeName, items: [], firstDay: '', lastDay: '',
101
- };
102
- cur.items.push(it);
103
- if (it.firstDay && (!cur.firstDay || it.firstDay < cur.firstDay)) cur.firstDay = it.firstDay;
104
- if (it.lastDay && (!cur.lastDay || it.lastDay > cur.lastDay)) cur.lastDay = it.lastDay;
105
- places.set(it.placeId, cur);
33
+ const group = places.get(it.placeId) ?? { placeId: it.placeId, placeName: it.placeName, items: [], firstDay: '', lastDay: '' };
34
+ group.items.push(it);
35
+ if (it.firstDay && (!group.firstDay || it.firstDay < group.firstDay)) group.firstDay = it.firstDay;
36
+ if (it.lastDay && (!group.lastDay || it.lastDay > group.lastDay)) group.lastDay = it.lastDay;
37
+ places.set(it.placeId, group);
106
38
  }
107
-
108
- return {
109
- items,
110
- byPlace: [...places.values()].sort((a, b) => b.items.length - a.items.length
111
- || a.placeName.localeCompare(b.placeName)),
112
- total: items.reduce((n, it) => n + it.times, 0),
113
- uniquePlaces: places.size,
114
- };
39
+ return { items, byPlace: [...places.values()].sort((a, b) => b.items.length - a.items.length || a.placeName.localeCompare(b.placeName)), total: items.reduce((n, x) => n + x.times, 0), uniquePlaces: places.size };
115
40
  }
116
41
 
117
- /**
118
- * 一处地方的完成度:项目 / 纪念品 / 拍照点,各逛到(买到/拍到)多少。
119
- *
120
- * `place` 是合并后的场所(预设 + 用户改动),因为自填地点也该有进度。
121
- * 传进来的 `trips` 只统计**这一处**的历史。
122
- *
123
- * 为什么三条分开算而不是一个总分:她缺的可能只是「鬼屋没去过」,
124
- * 一个 62% 的总分说不出这件事。`fun_go` 回执要的正是一句具体的
125
- * 「这儿你还差鬼屋和碰碰车」。
126
- *
127
- * @param {object} place 场所条目(含 areas / souvenirs / photoSpots)
128
- * @param {object[]} trips 全部纪念册(内部按 placeId 过滤)
129
- * @returns {{ areas: object, souvenirs: object, photos: object, percent: number, visits: number }}
130
- */
131
- export function progressFor(place, trips) {
42
+ export function progressFor(place, trips, collection = null) {
132
43
  const placeId = norm(place?.id, 40);
133
44
  const mine = (Array.isArray(trips) ? trips : []).filter((t) => t && t.placeId === placeId);
134
-
135
- const seenAreas = new Set();
136
- const bought = new Set();
137
- const shot = new Set();
45
+ const seenAreas = new Set(); const bought = new Set(); const shot = new Set();
138
46
  for (const t of mine) {
139
- for (const v of Array.isArray(t.visited) ? t.visited : []) {
140
- const a = norm(v?.area, 40);
141
- if (a) seenAreas.add(a);
142
- }
143
- for (const s of Array.isArray(t.souvenirs) ? t.souvenirs : []) {
144
- const x = norm(s, 40);
145
- if (x) bought.add(x);
146
- }
147
- for (const p of Array.isArray(t.photos) ? t.photos : []) {
148
- const x = norm(p, 60);
149
- if (x) shot.add(x);
150
- }
47
+ for (const v of Array.isArray(t.visited) ? t.visited : []) { const a = norm(v?.area, 40); if (a) seenAreas.add(a); }
48
+ for (const s of Array.isArray(t.souvenirs) ? t.souvenirs : []) { const x = norm(s, 40); if (x) bought.add(x); }
49
+ for (const p of Array.isArray(t.photos) ? t.photos : []) { const x = norm(p, 60); if (x) shot.add(x); }
151
50
  }
152
-
153
- const allAreas = (Array.isArray(place?.areas) ? place.areas : []).map((a) => norm(a, 40)).filter(Boolean);
154
- const allGoods = (Array.isArray(place?.souvenirs) ? place.souvenirs : []).map((a) => norm(a, 40)).filter(Boolean);
155
- const allShots = (Array.isArray(place?.photoSpots) ? place.photoSpots : []).map((a) => norm(a, 60)).filter(Boolean);
156
-
157
- const part = (all, seen) => {
158
- all = [...new Set(all)];
159
- const got = all.filter((x) => seen.has(x));
160
- const left = all.filter((x) => !seen.has(x));
161
- return {
162
- got, left, total: all.length, done: got.length,
163
- complete: all.length > 0 && left.length === 0,
164
- };
165
- };
166
-
167
- const areas = part(allAreas, seenAreas);
168
- const souvenirs = part(allGoods, bought);
169
- const photos = part(allShots, shot);
170
-
171
- // 一个总百分比:只用来在面板上排「哪几处快集齐了」,不作为回执主句。
172
- const denom = areas.total + souvenirs.total + photos.total;
173
- const numer = areas.done + souvenirs.done + photos.done;
174
- return {
175
- areas,
176
- souvenirs,
177
- photos,
178
- visits: mine.length,
179
- percent: denom ? Math.round((numer / denom) * 100) : 0,
180
- };
51
+ for (const x of Array.isArray(collection) ? collection : []) if (x?.placeId === placeId) bought.add(norm(x.name, 40));
52
+ const part = (all, seen) => { all = [...new Set((Array.isArray(all) ? all : []).map((x) => norm(x, 60)).filter(Boolean))]; const got = all.filter((x) => seen.has(x)); const left = all.filter((x) => !seen.has(x)); return { got, left, total: all.length, done: got.length, complete: all.length > 0 && !left.length }; };
53
+ const areas = part(place?.areas, seenAreas); const souvenirs = part(place?.souvenirs, bought); const photos = part(place?.photoSpots, shot);
54
+ const denom = areas.total + souvenirs.total + photos.total; const numer = areas.done + souvenirs.done + photos.done;
55
+ return { areas, souvenirs, photos, visits: mine.length, percent: denom ? Math.round(numer / denom * 100) : 0 };
181
56
  }
182
-
183
- /**
184
- * 把完成度写成一句能放进回执的话。**只在有内容可说时返回字符串**,
185
- * 没去过、或者全逛遍了,都返回空串(让调用方自己决定说什么)。
186
- *
187
- * 刻意写得具体:点出**还差什么**,而不是报个百分比。
188
- * 「这儿你还差鬼屋和碰碰车」比「完成度 62%」有用得多。
189
- *
190
- * @param {object} progress `progressFor()` 的结果
191
- * @param {number} max 最多点几处
192
- */
193
57
  export function progressLine(progress, max = 3) {
194
- const left = progress?.areas?.left ?? [];
195
- if (!left.length) return '';
196
- const cap = Math.max(1, Math.round(Number(max) || 3));
197
- const shown = left.slice(0, cap);
198
- const more = left.length - shown.length;
58
+ const left = progress?.areas?.left ?? []; if (!left.length) return '';
59
+ const shown = left.slice(0, Math.max(1, Math.round(Number(max) || 3))); const more = left.length - shown.length;
199
60
  return `这儿还差${shown.join('、')}${more > 0 ? ` 等 ${left.length} 处` : ''}没逛。`;
200
61
  }
package/src/names.js ADDED
@@ -0,0 +1,9 @@
1
+ /** 名称解析只负责找候选:唯一命中后始终使用清单正名落盘。 */
2
+ export function resolveName(list, input) {
3
+ const wanted = typeof input === 'string' ? input.trim() : '';
4
+ const names = [...new Set((Array.isArray(list) ? list : []).filter((x) => typeof x === 'string' && x))];
5
+ if (!wanted) return { name: null, candidates: [] };
6
+ if (names.includes(wanted)) return { name: wanted, candidates: [wanted] };
7
+ const candidates = names.filter((x) => x.includes(wanted) || wanted.includes(x));
8
+ return { name: candidates.length === 1 ? candidates[0] : null, candidates };
9
+ }
package/src/state.js CHANGED
@@ -22,6 +22,7 @@
22
22
  */
23
23
 
24
24
  import { VENUES, hoursState, pickSome } from './venues.js';
25
+ import { normalizeWishes } from './wishes.js';
25
26
 
26
27
  /** 纪念册最多留几趟。 */
27
28
  export const MAX_TRIPS = 40;
@@ -70,7 +71,61 @@ export function minutesIn(tz, nowMs) {
70
71
 
71
72
  /** 当天的新状态。 */
72
73
  export function newState(day) {
73
- return { day, session: null, trips: [] };
74
+ return { day, session: null, trips: [], collection: [], keepsakeTrips: [], tripSeq: 0, wishes: [] };
75
+ }
76
+
77
+ export function newTripId(placeId, enteredAt, leftAt) {
78
+ return `${text(placeId, 40)}-${Number(enteredAt) || 0}-${Number(leftAt) || 0}`;
79
+ }
80
+
81
+ function seedCollection(trips, timezone = 'Asia/Shanghai') {
82
+ const entries = [];
83
+ for (const trip of Array.isArray(trips) ? trips : []) {
84
+ const placeId = text(trip?.placeId, 40);
85
+ const placeName = text(trip?.placeName, 40) || placeId;
86
+ const day = tripDay(trip, timezone);
87
+ for (const name of new Set(textList(trip?.souvenirs, 12, 40))) {
88
+ entries.push({ placeId, placeName, name, day, at: Number(trip.leftAt) || 0, tripId: text(trip.id, 60) });
89
+ }
90
+ }
91
+ return mergeCollection([], entries);
92
+ }
93
+
94
+ function mergeKeptTrips(kept, recent) {
95
+ const map = new Map();
96
+ for (const raw of [...(Array.isArray(kept) ? kept : []), ...(Array.isArray(recent) ? recent.filter((t) => t?.favorite) : [])]) {
97
+ const key = stableTripId(raw);
98
+ const trip = normalizeTrip(raw, key);
99
+ if (trip) map.set(trip.id, trip);
100
+ }
101
+ return [...map.values()].sort((a, b) => b.leftAt - a.leftAt);
102
+ }
103
+
104
+ function stableTripId(raw) {
105
+ const id = text(raw?.id, 60);
106
+ return id || newTripId(raw?.placeId, raw?.enteredAt, raw?.leftAt);
107
+ }
108
+
109
+ function mergeCollection(existing, additions) {
110
+ const map = new Map();
111
+ for (const item of [...(Array.isArray(existing) ? existing : []), ...(Array.isArray(additions) ? additions : [])]) {
112
+ const placeId = text(item?.placeId, 40);
113
+ const name = text(item?.name, 40);
114
+ if (!placeId || !name) continue;
115
+ const key = `${placeId}::${name}`;
116
+ const day = text(item.day, 10);
117
+ const at = Number(item.at) || 0;
118
+ const cur = map.get(key);
119
+ if (!cur) map.set(key, { key, placeId, placeName: text(item.placeName, 40) || placeId, name, firstDay: text(item.firstDay, 10) || day, lastDay: text(item.lastDay, 10) || day, firstAt: Number(item.firstAt) || at, lastAt: Number(item.lastAt) || at, times: Math.max(1, Number(item.times) || 1), tripIds: Array.isArray(item.tripIds) ? textList(item.tripIds, 100, 60) : (item.tripId ? [text(item.tripId, 60)] : []) });
120
+ else {
121
+ cur.times += Math.max(1, Number(item.times) || 1);
122
+ if (Array.isArray(item.tripIds)) for (const tripId of item.tripIds) if (!cur.tripIds.includes(tripId)) cur.tripIds.push(text(tripId, 60));
123
+ if (day && (!cur.firstDay || day < cur.firstDay)) { cur.firstDay = day; cur.firstAt = at; }
124
+ if (day && (!cur.lastDay || day > cur.lastDay)) { cur.lastDay = day; cur.lastAt = at; }
125
+ if (item.tripId && !cur.tripIds.includes(item.tripId)) cur.tripIds.push(text(item.tripId, 60));
126
+ }
127
+ }
128
+ return [...map.values()].sort((a, b) => b.lastAt - a.lastAt || a.name.localeCompare(b.name));
74
129
  }
75
130
 
76
131
  const text = (v, max) => (typeof v === 'string' ? v.replace(/\s+/g, ' ').trim().slice(0, max) : '');
@@ -117,11 +172,24 @@ function normalizeAte(v) {
117
172
  return out;
118
173
  }
119
174
 
120
- function normalizeTrip(raw) {
175
+ function normalizeChoices(v) {
176
+ const arr = Array.isArray(v) ? v : [];
177
+ return arr.map((x) => ({ event: text(x?.event, 120), option: text(x?.option, 60), result: text(x?.result, 160), at: Number(x?.at) || 0 })).filter((x) => x.event && x.option).slice(0, 20);
178
+ }
179
+
180
+ function normalizePendingChoice(v) {
181
+ if (!v || typeof v !== 'object') return null;
182
+ const options = Array.isArray(v.options) ? v.options.map((x) => ({ id: text(x?.id, 50), label: text(x?.label, 100), result: text(x?.result, 160) })).filter((x) => x.id && x.label).slice(0, 4) : [];
183
+ const id = text(v.id, 100); const event = text(v.event, 120);
184
+ return id && event && options.length ? { id, event, area: text(v.area, 40), prompt: text(v.prompt, 160), options } : null;
185
+ }
186
+
187
+ function normalizeTrip(raw, fallbackId = '') {
121
188
  if (!raw || typeof raw !== 'object') return null;
122
189
  const placeId = text(raw.placeId, 40);
123
190
  if (!placeId) return null;
124
191
  return {
192
+ id: fallbackId || text(raw.id, 60) || newTripId(placeId, raw.enteredAt, raw.leftAt),
125
193
  placeId,
126
194
  placeName: text(raw.placeName, 40) || placeId,
127
195
  scene: text(raw.scene, 40),
@@ -141,11 +209,13 @@ function normalizeTrip(raw) {
141
209
  leftDay: DAY_RE.test(text(raw.leftDay, 10)) ? text(raw.leftDay, 10) : '',
142
210
  /** 收摊时说的那一句(和 `visited[].note` 不是一回事:那是逛某处时记的)。 */
143
211
  note: text(raw.note, 120),
212
+ favorite: raw.favorite === true,
144
213
  visited: normalizeVisited(raw.visited),
145
214
  souvenirs: textList(raw.souvenirs, 12, 40),
146
215
  photos: textList(raw.photos, 12, 60),
147
216
  ate: normalizeAte(raw.ate),
148
217
  events: textList(raw.events, 16, 120),
218
+ choices: normalizeChoices(raw.choices),
149
219
  };
150
220
  }
151
221
 
@@ -156,6 +226,7 @@ function normalizeSession(raw) {
156
226
  ...trip,
157
227
  id: text(raw.id, 40) || `${trip.placeId}-${trip.enteredAt}`,
158
228
  lastAt: Number.isFinite(Number(raw.lastAt)) ? Number(raw.lastAt) : trip.enteredAt,
229
+ pendingChoice: normalizePendingChoice(raw.pendingChoice),
159
230
  };
160
231
  }
161
232
 
@@ -183,14 +254,31 @@ function normalizeSession(raw) {
183
254
  * 纪念册(`trips`)**任何时候都不清**——跨天该清的是「今天正在逛什么」,
184
255
  * 不是「她去过哪儿」。这一条是 0.1.5 修的,别改回去。
185
256
  */
186
- export function normalizeState(raw, day, nowMs = 0, ttlMin = DEFAULT_TTL_MIN) {
257
+ export function normalizeState(raw, day, nowMs = 0, ttlMin = DEFAULT_TTL_MIN, timezone = 'Asia/Shanghai') {
187
258
  if (!raw || typeof raw !== 'object') return newState(day);
188
259
  const session = normalizeSession(raw.session);
189
260
  const keep = session && (raw.day === day || sessionAlive(session, nowMs, ttlMin));
261
+ const rawTrips = Array.isArray(raw.trips) ? raw.trips : [];
262
+ const used = new Set();
263
+ const trips = rawTrips.map((t, i) => {
264
+ const base = stableTripId(t);
265
+ const id = used.has(base) ? `${base}-legacy-${i}` : base;
266
+ used.add(base);
267
+ const normalized = normalizeTrip(t, id);
268
+ if (normalized && !t?.id) normalized.id = id;
269
+ return normalized;
270
+ }).filter(Boolean).slice(0, MAX_TRIPS);
271
+ const nextTripSeq = Number.isInteger(raw.tripSeq) && raw.tripSeq >= 0
272
+ ? raw.tripSeq
273
+ : trips.length + (Array.isArray(raw.keepsakeTrips) ? raw.keepsakeTrips.length : 0);
190
274
  return {
191
275
  day,
192
276
  session: keep ? session : null,
193
- trips: (Array.isArray(raw.trips) ? raw.trips : []).map(normalizeTrip).filter(Boolean).slice(0, MAX_TRIPS),
277
+ trips,
278
+ collection: Array.isArray(raw.collection) ? mergeCollection(raw.collection, []) : seedCollection(trips, timezone),
279
+ keepsakeTrips: mergeKeptTrips(raw.keepsakeTrips, trips),
280
+ tripSeq: nextTripSeq,
281
+ wishes: normalizeWishes(raw.wishes),
194
282
  };
195
283
  }
196
284
 
@@ -243,6 +331,7 @@ export function enterVenue(state, venue, nowMs, random = Math.random, company =
243
331
  photos: [],
244
332
  ate: [],
245
333
  events: [],
334
+ choices: [],
246
335
  };
247
336
  state.session = session;
248
337
  return { session, already: false };
@@ -267,7 +356,7 @@ export function wanderOnce(state, venue, nowMs, random = Math.random, areas = nu
267
356
  if (!pool.length) return null;
268
357
  const i = Math.floor(random() * pool.length) % pool.length;
269
358
  const area = pool[i];
270
- const evSource = Array.isArray(events) && events.length ? events : (venue.randomEvents || []);
359
+ const evSource = Array.isArray(events) ? events : (venue.randomEvents || []);
271
360
  const evPool = evSource.filter((e) => !s.events.includes(e));
272
361
  const ev = evPool.length
273
362
  ? evPool[Math.floor(random() * evPool.length) % evPool.length]
@@ -350,7 +439,10 @@ export function closeSession(state, nowMs, note = '', day = '') {
350
439
  const s = state.session;
351
440
  if (!s) return null;
352
441
  const said = text(note, 120);
442
+ state.tripSeq = (Number(state.tripSeq) || 0) + 1;
353
443
  const trip = {
444
+ id: `${newTripId(s.placeId, s.enteredAt, nowMs)}-${state.tripSeq}`,
445
+ favorite: false,
354
446
  placeId: s.placeId,
355
447
  placeName: s.placeName,
356
448
  scene: s.scene,
@@ -362,19 +454,37 @@ export function closeSession(state, nowMs, note = '', day = '') {
362
454
  // 收摊这句话以前只出现在回执里,转头就没了:纪念册重看这一趟只剩「逛了哪儿」。
363
455
  // 「今天人很多,但很开心」这种话才是她自己的记录,必须存。
364
456
  note: said,
457
+ favorite: false,
365
458
  visited: s.visited.map((v) => ({ ...v })),
366
459
  souvenirs: [...s.souvenirs],
367
460
  photos: [...s.photos],
368
461
  ate: (s.ate ?? []).map((x) => ({ ...x })),
369
462
  events: [...s.events],
463
+ choices: normalizeChoices(s.choices),
370
464
  };
371
465
  state.session = null;
372
466
  state.trips.unshift(trip);
467
+ state.collection = mergeCollection(state.collection, [...new Set(s.souvenirs)].map((name) => ({ placeId: s.placeId, placeName: s.placeName, name, day, at: nowMs, tripId: trip.id })));
468
+ const savedTrip = state.keepsakeTrips?.find((x) => x.id === trip.id);
469
+ if (savedTrip) state.keepsakeTrips = state.keepsakeTrips.map((x) => x.id === trip.id ? structuredClone(trip) : x);
373
470
  if (state.trips.length > MAX_TRIPS) state.trips.length = MAX_TRIPS;
374
471
  const stayedMin = Math.max(0, Math.round((nowMs - s.enteredAt) / 60000));
375
472
  return { trip, stayedMin, note: said };
376
473
  }
377
474
 
475
+ export function favoriteTrip(state, id, keep = true) {
476
+ const trips = [...(state.trips ?? []), ...(state.keepsakeTrips ?? [])];
477
+ const trip = trips.find((t) => t.id === id);
478
+ if (!trip) return { ok: false, error: '找不到这趟行程,请先翻纪念册取得行程 ID。' };
479
+ state.keepsakeTrips = (state.keepsakeTrips ?? []).filter((t) => t.id !== id);
480
+ trip.favorite = keep;
481
+ if (keep) state.keepsakeTrips.unshift(structuredClone(trip));
482
+ state.keepsakeTrips.sort((a, b) => b.leftAt - a.leftAt);
483
+ const recent = state.trips?.find((t) => t.id === id);
484
+ if (recent) recent.favorite = keep;
485
+ return { ok: true, trip, kept: keep };
486
+ }
487
+
378
488
  /** 这一趟挂太久了没?超过 ttlMin 就该提醒收摊(但绝不替她收)。 */
379
489
  export function isStale(session, nowMs, ttlMin) {
380
490
  if (!session) return false;
package/src/venues.js CHANGED
@@ -1125,10 +1125,9 @@ function rankPlaces(nowMin, avoid = [], places = VENUES) {
1125
1125
  const stateRank = state === 'open' ? 0 : (state === 'closingSoon' ? 1 : 2);
1126
1126
  const avoidRank = avoidSet.has(venue.id) ? 1 : 0;
1127
1127
  const crowdRank = venue.crowd === 'packed' ? 2 : (venue.crowd === 'normal' ? 1 : 0);
1128
- // 用户自己加的地方排最前:那是他特意写的,不该被「拥挤度」算法挤到
1129
- // 默认列表后面,否则看起来像没加上。开着/关着仍然在它之后生效。
1128
+ // 营业状态优先;同一状态下,自填地点优先、最近去过的降权,再比较拥挤度。
1130
1129
  const customRank = String(venue.id).startsWith('user-') ? 0 : 1;
1131
- return { venue, state, rank: [customRank, avoidRank, stateRank, crowdRank, idx] };
1130
+ return { venue, state, rank: [stateRank, customRank, avoidRank, crowdRank, idx] };
1132
1131
  });
1133
1132
  scored.sort((a, b) => {
1134
1133
  for (let i = 0; i < a.rank.length; i += 1) {
package/src/wishes.js ADDED
@@ -0,0 +1,114 @@
1
+ const TYPES = new Set(['visit', 'area', 'phase', 'souvenir']);
2
+ const STATUSES = new Set(['active', 'paused', 'completed', 'cancelled']);
3
+ const LIMIT = 100;
4
+
5
+
6
+ function text(value, max = 200) {
7
+ return typeof value === 'string' ? value.replace(/\s+/g, ' ').trim().slice(0, max) : '';
8
+ }
9
+
10
+ function timestamp(value) {
11
+ try {
12
+ const date = value instanceof Date ? value : new Date(value ?? 0);
13
+ return Number.isNaN(date.getTime()) ? new Date(0).toISOString() : date.toISOString();
14
+ } catch {
15
+ return new Date(0).toISOString();
16
+ }
17
+ }
18
+
19
+ function uniqueId(now, used = new Set()) {
20
+ const stamp = new Date(timestamp(now)).getTime();
21
+ let id;
22
+ let sequence = 0;
23
+ do {
24
+ sequence += 1;
25
+ id = `wish-${Number.isFinite(stamp) ? stamp : 0}-${sequence}`;
26
+ } while (used.has(id));
27
+ return id;
28
+ }
29
+
30
+ function cleanWish(raw, used) {
31
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
32
+ const placeId = text(raw.placeId, 80);
33
+ const placeName = text(raw.placeName, 80);
34
+ const type = text(raw.type, 20);
35
+ const target = text(raw.target, 120);
36
+ if (!placeId || !placeName || !TYPES.has(type) || (type !== 'visit' && !target)) return null;
37
+ const status = STATUSES.has(raw.status) ? raw.status : 'active';
38
+ const createdAt = timestamp(raw.createdAt);
39
+ const updatedAt = timestamp(raw.updatedAt ?? raw.createdAt);
40
+ const id = text(raw.id, 120) || uniqueId(createdAt, used);
41
+ if (used.has(id)) return null;
42
+ used.add(id);
43
+ return {
44
+ id, placeId, placeName, type, target,
45
+ reason: text(raw.reason, 120), status, createdAt, updatedAt,
46
+ completedAt: status === 'completed' ? timestamp(raw.completedAt ?? updatedAt) : '',
47
+ };
48
+ }
49
+
50
+ export function normalizeWishes(raw) {
51
+ if (!Array.isArray(raw)) return [];
52
+ const result = [];
53
+ const used = new Set();
54
+ for (const item of raw) {
55
+ const wish = cleanWish(item, used);
56
+ if (wish) result.push(wish);
57
+ if (result.length >= LIMIT) break;
58
+ }
59
+ return result;
60
+ }
61
+
62
+ export function addWish(list, input, now = 0) {
63
+ const wishes = normalizeWishes(list);
64
+ const candidate = cleanWish({ ...input, id: '', status: 'active', completedAt: '', createdAt: now, updatedAt: now }, new Set(wishes.map((w) => w.id)));
65
+ if (!candidate) return { wishes, wish: null, duplicate: false, error: '心愿信息无效' };
66
+ const duplicate = wishes.find((w) => w.placeId === candidate.placeId && w.type === candidate.type && w.target === candidate.target && ['active', 'paused'].includes(w.status));
67
+ if (duplicate) return { wishes, wish: duplicate, duplicate: true };
68
+ if (wishes.length >= LIMIT) return { wishes, wish: null, duplicate: false, error: '心愿最多保存 100 条' };
69
+ const wish = { ...candidate, id: uniqueId(now, new Set(wishes.map((w) => w.id))) };
70
+ return { wishes: [...wishes, wish], wish, duplicate: false };
71
+ }
72
+
73
+ export function changeWish(list, id, action, now = 0) {
74
+ const wishes = normalizeWishes(list);
75
+ const index = wishes.findIndex((w) => w.id === id);
76
+ if (index < 0) return { wishes, wish: null, error: '找不到这个心愿' };
77
+ const current = wishes[index];
78
+ let status = current.status;
79
+ if (action === 'pause' && status === 'active') status = 'paused';
80
+ else if (action === 'resume' && status === 'paused') status = 'active';
81
+ else if (action === 'cancel' && ['active', 'paused'].includes(status)) status = 'cancelled';
82
+ else if (!['pause', 'resume', 'cancel'].includes(action)) return { wishes, wish: current, error: '不支持的操作' };
83
+ if (status === current.status) return { wishes, wish: current };
84
+ const wish = { ...current, status, updatedAt: timestamp(now) };
85
+ const next = [...wishes];
86
+ next[index] = wish;
87
+ return { wishes: next, wish };
88
+ }
89
+
90
+ export function fulfillWishes(list, facts, now = 0) {
91
+ const wishes = normalizeWishes(list);
92
+ const placeId = text(facts?.placeId, 80);
93
+ const area = text(facts?.area, 120);
94
+ const phase = text(facts?.phase, 120);
95
+ const souvenirs = Array.isArray(facts?.souvenirs) ? facts.souvenirs.map((x) => text(x, 120)).filter(Boolean) : [];
96
+ const completed = [];
97
+ const next = wishes.map((w) => {
98
+ if (w.status !== 'active' || w.placeId !== placeId) return w;
99
+ const matched = w.type === 'visit' || (w.type === 'area' && area === w.target) || (w.type === 'phase' && phase === w.target) || (w.type === 'souvenir' && souvenirs.includes(w.target));
100
+ if (!matched) return w;
101
+ const done = { ...w, status: 'completed', updatedAt: timestamp(now), completedAt: timestamp(now) };
102
+ completed.push(done);
103
+ return done;
104
+ });
105
+ return { wishes: next, completed };
106
+ }
107
+
108
+ export function wishReason(list, venue, nowMin) {
109
+ void nowMin;
110
+ const placeId = typeof venue === 'string' ? venue : venue?.placeId ?? venue?.id;
111
+ const wish = normalizeWishes(list).find((w) => w.status === 'active' && w.placeId === placeId);
112
+ if (!wish) return '';
113
+ return wish.reason || `还想在${wish.placeName}完成「${wish.target}」这个心愿。`;
114
+ }