cortico-world-fun 0.1.5 → 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/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,11 +71,68 @@ 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) : '');
77
132
 
133
+ /** 本地日期形状:`YYYY-MM-DD`。存在 trip 上,读回来时校验形状而不是重新换算。 */
134
+ const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
135
+
78
136
  function textList(v, maxItems, maxLen) {
79
137
  const arr = Array.isArray(v) ? v : [];
80
138
  return arr.map((x) => text(x, maxLen)).filter(Boolean).slice(0, maxItems);
@@ -114,22 +172,50 @@ function normalizeAte(v) {
114
172
  return out;
115
173
  }
116
174
 
117
- 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 = '') {
118
188
  if (!raw || typeof raw !== 'object') return null;
119
189
  const placeId = text(raw.placeId, 40);
120
190
  if (!placeId) return null;
121
191
  return {
192
+ id: fallbackId || text(raw.id, 60) || newTripId(placeId, raw.enteredAt, raw.leftAt),
122
193
  placeId,
123
194
  placeName: text(raw.placeName, 40) || placeId,
124
195
  scene: text(raw.scene, 40),
125
196
  outfit: text(raw.outfit, 40),
197
+ // 跟谁一起去的:只进回执不留档的话,「上一次是和阿岚去的」这种话永远说不出来。
198
+ company: text(raw.company, 40),
126
199
  enteredAt: Number.isFinite(Number(raw.enteredAt)) ? Number(raw.enteredAt) : 0,
127
200
  leftAt: Number.isFinite(Number(raw.leftAt)) ? Number(raw.leftAt) : 0,
201
+ /**
202
+ * 收摊那天的**本地**日期(YYYY-MM-DD)。
203
+ *
204
+ * 为什么单存一个:`leftAt` 是毫秒,换算成「哪天」需要时区。老代码用
205
+ * `toISOString().slice(0,10)` 取 UTC 日期,于是上海时间早上 8 点前收的摊
206
+ * 会被算成前一天——「同一天早上去过两次」会被说成「上一次是昨天」。
207
+ * 收摊时由 World 按它自己的时区算好存下来,读的人就不用再猜了。
208
+ */
209
+ leftDay: DAY_RE.test(text(raw.leftDay, 10)) ? text(raw.leftDay, 10) : '',
210
+ /** 收摊时说的那一句(和 `visited[].note` 不是一回事:那是逛某处时记的)。 */
211
+ note: text(raw.note, 120),
212
+ favorite: raw.favorite === true,
128
213
  visited: normalizeVisited(raw.visited),
129
214
  souvenirs: textList(raw.souvenirs, 12, 40),
130
215
  photos: textList(raw.photos, 12, 60),
131
216
  ate: normalizeAte(raw.ate),
132
217
  events: textList(raw.events, 16, 120),
218
+ choices: normalizeChoices(raw.choices),
133
219
  };
134
220
  }
135
221
 
@@ -140,40 +226,93 @@ function normalizeSession(raw) {
140
226
  ...trip,
141
227
  id: text(raw.id, 40) || `${trip.placeId}-${trip.enteredAt}`,
142
228
  lastAt: Number.isFinite(Number(raw.lastAt)) ? Number(raw.lastAt) : trip.enteredAt,
229
+ pendingChoice: normalizePendingChoice(raw.pendingChoice),
143
230
  };
144
231
  }
145
232
 
146
233
  /**
147
234
  * 把磁盘上的旧状态补齐成当前形状(不信任文件内容)。
148
- * `day` 和今天不一致 = 跨天了:只清 session,纪念册(trips)留着。
149
- */
150
- /**
151
- * 把磁盘上的旧状态补齐成当前形状(不信任文件内容)。
152
235
  *
153
- * `day` 和今天不一致 = 跨天了:**只清掉没逛完的那一趟(session)**,
154
- * 纪念册(trips)必须留着。
236
+ * ## 跨天为什么不再无脑清 session
237
+ *
238
+ * 0.1.5 及以前:`raw.day !== day` 就直接 `session = null`。这看起来合理
239
+ * (「昨天没逛完就是不逛完了」),实际会踩一条真会发生的路:
155
240
  *
156
- * 这一条是做「去过的痕迹」时修的:旧版一直整份重来,于是 `trips` 活不过一天——
157
- * 「去过的痕迹」做出来才发现纪念册每天清零,记了等于没记。
158
- * 跨天该清的是「今天正在逛什么」,不是「她去过哪儿」。
241
+ * 夜市 17:30–01:00、KTV 18:00–02:00。23:50 进夜市逛着,过了午夜再
242
+ * `fun_wander`,回执就是「你还没进门呢」——她正在逛的那一趟凭空消失,
243
+ * 而那个地方本来就没打烊。
244
+ *
245
+ * 现在的判据是两条取或:
246
+ *
247
+ * 1. **还是同一天** → 留着。同一天里挂久了不算「没逛完」,`fun_wander`
248
+ * 会提一句「挂得有点久了」,但绝不替她把这一趟收掉(这是 0.1.4 的行为,
249
+ * 不能因为修跨午夜就一起改坏)。
250
+ * 2. **跨了天,但上一次动在 TTL 之内** → 留着。这就是夜市/KTV 那条路。
251
+ *
252
+ * 跨了天、又挂过 TTL 的才丢(「逛到一半去睡觉,第二天回来发现不算了」)。
253
+ *
254
+ * 纪念册(`trips`)**任何时候都不清**——跨天该清的是「今天正在逛什么」,
255
+ * 不是「她去过哪儿」。这一条是 0.1.5 修的,别改回去。
159
256
  */
160
- export function normalizeState(raw, day) {
257
+ export function normalizeState(raw, day, nowMs = 0, ttlMin = DEFAULT_TTL_MIN, timezone = 'Asia/Shanghai') {
161
258
  if (!raw || typeof raw !== 'object') return newState(day);
162
- const sameDay = raw.day === day;
259
+ const session = normalizeSession(raw.session);
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);
163
274
  return {
164
275
  day,
165
- // 跨天一律丢 session:昨天没逛完的那一趟就是不逛完了,不该接着逛。
166
- session: sameDay ? normalizeSession(raw.session) : null,
167
- trips: (Array.isArray(raw.trips) ? raw.trips : []).map(normalizeTrip).filter(Boolean).slice(0, MAX_TRIPS),
276
+ session: keep ? session : null,
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),
168
282
  };
169
283
  }
170
284
 
285
+ /** 和 config.js 的 `funSessionTTLMin` 默认值保持一致(纯函数不 import 配置,防循环依赖)。 */
286
+ export const DEFAULT_TTL_MIN = 90;
287
+
288
+ /**
289
+ * 这一趟挂太久没有(跨天时用来判「还认不认昨天那一趟」)。
290
+ *
291
+ * 只看「上次动过之后过了多久」,不看日历。**不传 now 时返回 true**
292
+ * (没有时间可判时宁可留着——丢错了她会「你还没进门呢」,留错了顶多提醒一句收摊)。
293
+ */
294
+ export function sessionAlive(session, nowMs, ttlMin = DEFAULT_TTL_MIN) {
295
+ if (!session) return false;
296
+ const now = Number(nowMs);
297
+ const last = Number(session.lastAt ?? session.enteredAt);
298
+ if (!Number.isFinite(now) || now <= 0) return true;
299
+ if (!Number.isFinite(last) || last <= 0) return true;
300
+ // 时钟往回调过(last 在未来):当作还活着,别因为对钟就把人踢出去。
301
+ if (last > now) return true;
302
+ const ttl = Math.max(1, Math.round(Number(ttlMin) || DEFAULT_TTL_MIN));
303
+ return now - last <= ttl * 60000;
304
+ }
305
+
171
306
  /**
172
307
  * 进门:把一处场所变成一趟 session。
173
308
  * 已经在逛就**不覆盖**——先让她 `fun_home` 收摊,或者她自己说换地方。
309
+ *
310
+ * `company` 是「跟谁一起去的」,进 session 也进纪念册:只写进当次回执的话,
311
+ * 「上一次是和阿岚去的」这种话以后永远说不出来。
312
+ *
174
313
  * 返回 { session, already } —— already 为 true 表示原来就有一趟没结束。
175
314
  */
176
- export function enterVenue(state, venue, nowMs, random = Math.random) {
315
+ export function enterVenue(state, venue, nowMs, random = Math.random, company = '') {
177
316
  if (state.session) return { session: state.session, already: true };
178
317
  const session = {
179
318
  id: `${venue.id}-${nowMs}`,
@@ -184,6 +323,7 @@ export function enterVenue(state, venue, nowMs, random = Math.random) {
184
323
  // imggen 会提示「库里没找到」,那一项白填还显得她填错了。
185
324
  scene: typeof venue.scene === 'string' ? venue.scene.trim() : '',
186
325
  outfit: venue.recommendedOutfit || '',
326
+ company: text(company, 40),
187
327
  enteredAt: nowMs,
188
328
  lastAt: nowMs,
189
329
  visited: [],
@@ -191,6 +331,7 @@ export function enterVenue(state, venue, nowMs, random = Math.random) {
191
331
  photos: [],
192
332
  ate: [],
193
333
  events: [],
334
+ choices: [],
194
335
  };
195
336
  state.session = session;
196
337
  return { session, already: false };
@@ -215,7 +356,7 @@ export function wanderOnce(state, venue, nowMs, random = Math.random, areas = nu
215
356
  if (!pool.length) return null;
216
357
  const i = Math.floor(random() * pool.length) % pool.length;
217
358
  const area = pool[i];
218
- const evSource = Array.isArray(events) && events.length ? events : (venue.randomEvents || []);
359
+ const evSource = Array.isArray(events) ? events : (venue.randomEvents || []);
219
360
  const evPool = evSource.filter((e) => !s.events.includes(e));
220
361
  const ev = evPool.length
221
362
  ? evPool[Math.floor(random() * evPool.length) % evPool.length]
@@ -288,28 +429,60 @@ export function buySouvenir(state, item, nowMs) {
288
429
  *
289
430
  * `note` 是她收摊时说的一句话(可空)。**回执正文由 World 拼**,
290
431
  * 这里只给结构化摘要,便于单测断言。
432
+ *
433
+ * `day` 必须由调用方按**本地时区**算好传进来(`dayIn(tz, nowMs)`),
434
+ * 存进 `trip.leftDay`。以前不传,于是所有读纪念册的地方都用 UTC 反算日期,
435
+ * 上海时间早上 8 点前收的摊会被算成前一天。不传就留空,读的一方回退到
436
+ * 按插件当前时区读取 leftAt(不迁移、不改写旧记录)。
291
437
  */
292
- export function closeSession(state, nowMs, note = '') {
438
+ export function closeSession(state, nowMs, note = '', day = '') {
293
439
  const s = state.session;
294
440
  if (!s) return null;
441
+ const said = text(note, 120);
442
+ state.tripSeq = (Number(state.tripSeq) || 0) + 1;
295
443
  const trip = {
444
+ id: `${newTripId(s.placeId, s.enteredAt, nowMs)}-${state.tripSeq}`,
445
+ favorite: false,
296
446
  placeId: s.placeId,
297
447
  placeName: s.placeName,
298
448
  scene: s.scene,
299
449
  outfit: s.outfit,
450
+ company: text(s.company, 40),
300
451
  enteredAt: s.enteredAt,
301
452
  leftAt: nowMs,
453
+ leftDay: DAY_RE.test(text(day, 10)) ? text(day, 10) : '',
454
+ // 收摊这句话以前只出现在回执里,转头就没了:纪念册重看这一趟只剩「逛了哪儿」。
455
+ // 「今天人很多,但很开心」这种话才是她自己的记录,必须存。
456
+ note: said,
457
+ favorite: false,
302
458
  visited: s.visited.map((v) => ({ ...v })),
303
459
  souvenirs: [...s.souvenirs],
304
460
  photos: [...s.photos],
305
461
  ate: (s.ate ?? []).map((x) => ({ ...x })),
306
462
  events: [...s.events],
463
+ choices: normalizeChoices(s.choices),
307
464
  };
308
465
  state.session = null;
309
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);
310
470
  if (state.trips.length > MAX_TRIPS) state.trips.length = MAX_TRIPS;
311
471
  const stayedMin = Math.max(0, Math.round((nowMs - s.enteredAt) / 60000));
312
- return { trip, stayedMin, note: text(note, 120) };
472
+ return { trip, stayedMin, note: said };
473
+ }
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 };
313
486
  }
314
487
 
315
488
  /** 这一趟挂太久了没?超过 ttlMin 就该提醒收摊(但绝不替她收)。 */
@@ -329,6 +502,7 @@ export function visitedText(session) {
329
502
  export function tripSummary(trip) {
330
503
  if (!trip) return '';
331
504
  const parts = [trip.placeName];
505
+ if (trip.company) parts.push(`跟${trip.company}一起`);
332
506
  if (trip.visited?.length) parts.push(`逛了${trip.visited.map((v) => v.area).join('、')}`);
333
507
  if (trip.souvenirs?.length) parts.push(`买了${trip.souvenirs.join('、')}`);
334
508
  if (trip.photos?.length) parts.push(`在${trip.photos.join('、')}拍了照`);
@@ -337,6 +511,24 @@ export function tripSummary(trip) {
337
511
  return parts.join(',');
338
512
  }
339
513
 
514
+ /**
515
+ * 这一趟算哪一天(本地日期)。
516
+ *
517
+ * 优先用收摊时存下的 `leftDay`;旧记录按当前插件时区解释时间戳。
518
+ * 只在读取时换算,不迁移、不改写旧记录;无法还原旧记录当时未保存的时区。
519
+ */
520
+ export function tripDay(trip, timezone = 'Asia/Shanghai') {
521
+ const stored = text(trip?.leftDay, 10);
522
+ if (DAY_RE.test(stored)) return stored;
523
+ try {
524
+ if (!trip?.leftAt) return '';
525
+ const day = dayIn(timezone, trip.leftAt);
526
+ return DAY_RE.test(day) ? day : '';
527
+ } catch {
528
+ return '';
529
+ }
530
+ }
531
+
340
532
  /** 最近去过的地方 id(跨天也算),给 fun_places 排序用。正在逛的排最前。 */
341
533
  export function recentPlaceIds(state, limit = 3) {
342
534
  const ids = [];