@blocklet/pages-kit-inner-components 0.6.18 → 0.6.20

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.
@@ -1,569 +0,0 @@
1
- import { jsx as W } from "react/jsx-runtime";
2
- import { joinURL as b, withQuery as K } from "ufo";
3
- import { createAxios as V } from "@blocklet/js-sdk";
4
- import z from "lodash/isEmpty";
5
- import * as Q from "yaml";
6
- import { useLocaleContext as X } from "@arcblock/ux/lib/Locale/context";
7
- import { nextId as O } from "@blocklet/pages-kit/utils/common";
8
- import { getPageTemplateModel as q } from "@blocklet/pages-kit/utils/page-model";
9
- import "@mui/material";
10
- import Y, { getYjsDoc as Z } from "@syncedstore/core";
11
- import { useSyncedStore as H } from "@syncedstore/react";
12
- import { useLocalStorageState as ee } from "ahooks";
13
- import { produce as v } from "immer";
14
- import T from "lodash/cloneDeep";
15
- import J from "lodash/debounce";
16
- import { createContext as te, useState as L, useRef as oe, useMemo as I, useCallback as M, useEffect as x, useContext as ne } from "react";
17
- import { useParams as re, useNavigate as se } from "react-router-dom";
18
- import { IndexeddbPersistence as ce } from "y-indexeddb";
19
- import { WebsocketProvider as ae } from "y-websocket";
20
- import { UndoManager as ie } from "yjs";
21
- import "@blocklet/pages-kit/types";
22
- function de() {
23
- const { pathname: o } = window.location, l = o.match(/\/admin\/(maker|previewer)\/([^/]+)/)?.[2], p = window.__PROJECT_ID__;
24
- if (!l && !p)
25
- throw new Error("Unable to get projectId from pathname");
26
- return l || p;
27
- }
28
- function Ue(o) {
29
- return `${o}:pages:version`;
30
- }
31
- function Fe(o, r) {
32
- return r === "yaml" ? z(o) ? "" : Q.stringify(o, { indent: 2 }) : r === "json" ? JSON.parse(JSON.stringify(o || {})) : r === "array" ? JSON.parse(JSON.stringify(o || [])) : o;
33
- }
34
- const k = window.blocklet?.prefix || "/", G = V({
35
- timeout: 200 * 1e3
36
- }), le = window.location.protocol === "https:" ? "wss" : "ws", We = (o) => b(`${le}://${window.location.hostname}`, k, `api/${o}/ws/pages`), ue = "z8ia1mAXo8ZE7ytGF36L5uBf9kD2kenhqFGp9";
37
- blocklet?.componentMountPoints.find((o) => o.did === ue)?.mountPoint || b(k, "/image-bin");
38
- function Ke(o) {
39
- return o && !/^(https?:\/\/|\/)/.test(o) ? window.location.origin + b(k, "uploads", o) : o;
40
- }
41
- const pe = window.innerWidth <= 750;
42
- function Ve(o, r, l) {
43
- if (!o || /\.gif/.test(o)) return o;
44
- const p = (pe ? r / 1.5 : r) * (l === "quality" ? 1.5 : 1);
45
- return me(o, { imageFilter: "resize", w: p, f: "webp" });
46
- }
47
- function me(o, r) {
48
- return !o || !r ? o : K(o, r);
49
- }
50
- async function fe(o) {
51
- return G.get(`/api/projects/${o}`).then((r) => r.data);
52
- }
53
- async function ge(o) {
54
- return G.post(`/api/projects/${o.id}/update`, o).then((r) => r.data);
55
- }
56
- const Se = 500, B = te(null);
57
- function ze({
58
- url: o,
59
- name: r,
60
- children: l,
61
- waitingSynced: p
62
- }) {
63
- const [w, h] = L(!1), { locale: m } = X(), P = U(), E = `${P}:MakerLocalState`, e = `${P}:${r}`, [t, s] = ee(E, {
64
- defaultValue: {},
65
- listenStorageChange: !0
66
- }), n = oe(t);
67
- n.current = t;
68
- const i = I(
69
- () => Y({
70
- dataSourceIds: [],
71
- dataSources: {},
72
- pages: {},
73
- pageIds: [],
74
- routes: {},
75
- routeIds: [],
76
- components: {},
77
- supportedLocales: [],
78
- config: {},
79
- resources: {}
80
- }),
81
- []
82
- ), c = I(() => Z(i), [i]);
83
- I(() => new ce(e, c), [e, c]);
84
- const a = I(
85
- () => new ae(o, e, c, {
86
- params: {},
87
- resyncInterval: 5 * 60 * 1e3
88
- }),
89
- [o, e, c]
90
- ), d = M(() => {
91
- a && (a.disconnect(), a.connect());
92
- }, [a]), f = I(
93
- () => new ie(
94
- [
95
- c.getArray("pageIds"),
96
- c.getMap("pages"),
97
- c.getArray("supportedLocales"),
98
- c.getMap("config"),
99
- c.getMap("dataSources"),
100
- c.getArray("dataSourceIds"),
101
- c.getArray("routeIds"),
102
- c.getMap("routes")
103
- ],
104
- { doc: c }
105
- ),
106
- [c]
107
- ), [C, j] = L(null), [N, A] = L(!1), [R, _] = L(void 0), $ = M(async () => {
108
- if (P) {
109
- A(!0);
110
- try {
111
- const u = await fe(P);
112
- j(u);
113
- } catch (u) {
114
- console.error("Failed to fetch project:", u);
115
- } finally {
116
- A(!1);
117
- }
118
- }
119
- }, [P]), D = M(
120
- async (u, g) => {
121
- if (_(void 0), !!P) {
122
- g?.optimisticUpdate && C && j((S) => ({
123
- ...S,
124
- ...u
125
- }));
126
- try {
127
- const S = await ge({
128
- ...u
129
- });
130
- j(S);
131
- } catch (S) {
132
- console.error("Failed to update project:", S), g?.optimisticUpdate && j(C), _(S?.response?.data);
133
- }
134
- }
135
- },
136
- [P, C]
137
- );
138
- x(() => {
139
- P && $();
140
- }, [P, $]);
141
- const F = I(
142
- () => ({
143
- doc: c,
144
- state: i,
145
- localState: {
146
- ...t,
147
- // always use the locale from the context
148
- currentLocale: m
149
- },
150
- setLocalState: (u) => s(typeof u == "function" ? (g) => u(g ?? {}) : u),
151
- undoManager: f,
152
- projectState: {
153
- project: C,
154
- isLoadingProject: N,
155
- error: R
156
- },
157
- updateProject: D,
158
- forceSync: d
159
- }),
160
- // eslint-disable-next-line react-hooks/exhaustive-deps
161
- [
162
- c,
163
- i,
164
- JSON.stringify(t),
165
- // resolve the problem of react warning
166
- s,
167
- f,
168
- C,
169
- N,
170
- D,
171
- R,
172
- m,
173
- d
174
- ]
175
- );
176
- return x(() => {
177
- f.on("stack-item-added", ({ stackItem: u }) => {
178
- const { currentPageId: g, currentLocale: S, pages: y } = n.current;
179
- u.meta.set("localState", { currentPageId: g, currentLocale: S, pages: y });
180
- }), f.on("stack-item-popped", ({ stackItem: u }) => {
181
- const g = u.meta.get("localState");
182
- g && s((S) => ({ ...S, ...g }));
183
- });
184
- }, [f, s]), x(() => {
185
- a.awareness.setLocalState(t);
186
- }, [a, t]), x(() => {
187
- a.once("synced", () => h(!0));
188
- const u = () => {
189
- s((y) => ({
190
- ...y,
191
- networkStatus: void 0
192
- }));
193
- }, g = () => {
194
- s((y) => ({
195
- ...y,
196
- networkStatus: "offline"
197
- }));
198
- }, S = J(({ status: y }) => {
199
- y === "connected" ? u() : y === "disconnected" && g();
200
- }, Se);
201
- return a.on("status", S), window.addEventListener("online", u), window.addEventListener("offline", g), () => {
202
- a.off("status", S), window.removeEventListener("online", u), window.removeEventListener("offline", g);
203
- };
204
- }, [a, s]), p && !w ? null : /* @__PURE__ */ W(B.Provider, { value: F, children: l });
205
- }
206
- const Pe = () => {
207
- const o = ne(B);
208
- if (!o)
209
- throw new Error("Context is null");
210
- const r = H(o.state), { setLocalState: l, localState: p } = o, w = se(), h = U(), m = I(
211
- () => ({
212
- get currentPage() {
213
- const {
214
- localState: { currentPageId: e }
215
- } = o;
216
- return e ? r.pages[e] : void 0;
217
- },
218
- get currentSection() {
219
- const {
220
- localState: { currentPageId: e, ...t }
221
- } = o;
222
- if (!e)
223
- return;
224
- const s = t.pages?.[e]?.currentSectionId;
225
- if (s)
226
- return r.pages[e]?.sections[s] ?? this.currentPageModel?.getComponentById(s)?.model;
227
- },
228
- get currentSectionProperties() {
229
- const {
230
- localState: { currentPageId: e, ...t }
231
- } = o;
232
- if (!e)
233
- return;
234
- const s = t.pages?.[e]?.currentSectionId;
235
- if (!s)
236
- return;
237
- const n = r.pages[e]?.dataSource?.[s];
238
- if (!n)
239
- return;
240
- const { currentLocale: i } = this.currentLocaleMap;
241
- return i ? n[i] : void 0;
242
- },
243
- get currentSectionPropertiesWithFallback() {
244
- const {
245
- localState: { currentPageId: e, ...t }
246
- } = o;
247
- if (!e)
248
- return;
249
- const s = t.pages?.[e]?.currentSectionId;
250
- if (!s)
251
- return;
252
- const n = r.pages[e]?.dataSource?.[s];
253
- if (!n)
254
- return;
255
- const { currentLocale: i, defaultLocale: c, fallbackLocale: a } = this.currentLocaleMap;
256
- if (i && n[i])
257
- return n[i];
258
- if (c && n[c])
259
- return n[c];
260
- if (a && n[a])
261
- return n[a];
262
- },
263
- get currentLocaleMap() {
264
- const {
265
- localState: { currentLocale: e },
266
- state: {
267
- supportedLocales: t,
268
- config: { defaultLocale: s }
269
- }
270
- } = o;
271
- return {
272
- currentLocale: e,
273
- defaultLocale: s,
274
- fallbackLocale: t?.[0]?.locale ?? "en"
275
- };
276
- },
277
- get currentRoute() {
278
- const {
279
- localState: { currentRouteId: e }
280
- } = o;
281
- return e ? r.routes?.[e] : void 0;
282
- },
283
- get currentPageModel() {
284
- const e = this.currentPage ?? null;
285
- if (e)
286
- return q(e, !1);
287
- }
288
- }),
289
- [JSON.stringify(p), r]
290
- ), P = I(
291
- () => ({
292
- setCurrentSectionId: (e, t) => {
293
- e === p.currentPageId && t === p.pages?.[e]?.currentSectionId || (w(b("/admin/maker", h ?? "", "pages", e)), l(
294
- (s) => v(s, (n) => {
295
- n.currentPageId = e, n.currentComponentId = void 0, t !== void 0 && (n.pages ??= {}, n.pages[e] ??= {}, n.pages[e].currentSectionId = t ?? void 0), t ? window.sessionStorage.setItem("iframe_show_id", `"${t}"`) : window.sessionStorage.removeItem("iframe_show_id");
296
- })
297
- ));
298
- },
299
- setCurrentComponentId: (e) => {
300
- e !== p.currentComponentId && (w(b("/admin/maker", h ?? "", "components", e)), l(
301
- (t) => v(t, (s) => {
302
- s.currentComponentId = e;
303
- })
304
- ));
305
- },
306
- setCurrentRouteId: ({ routeId: e, dynamicParams: t }) => {
307
- l(
308
- (s) => v(s, (n) => {
309
- n.currentRouteId = e, n.currentDynamicParams = t;
310
- })
311
- );
312
- },
313
- // 本地缓存组件调试参数,避免用户切换组件后,需要重新输入
314
- setCustomComponentPreviewerProperties: (() => {
315
- const e = {};
316
- let t = "";
317
- const s = J(() => {
318
- l(
319
- (n) => v(n, (i) => {
320
- i.customComponentPreviewerProperties ??= {}, i.customComponentPreviewerProperties[t] = {
321
- ...i.customComponentPreviewerProperties[t],
322
- ...T(e[t])
323
- }, delete e[t];
324
- })
325
- );
326
- }, 5);
327
- return (n, i) => {
328
- const c = e[n] ?? {};
329
- Object.assign(c, i), e[n] = c, t = n, s();
330
- };
331
- })(),
332
- setRouteGenerateProcess: (e) => {
333
- l(
334
- (t) => v(t, (s) => {
335
- e ? s.routeGenerateProcess = {
336
- ...s.routeGenerateProcess,
337
- ...e
338
- } : s.routeGenerateProcess = {};
339
- })
340
- );
341
- },
342
- resetRouteGenerateProcess: () => {
343
- l(
344
- (e) => v(e, (t) => {
345
- t.routeGenerateProcess = {
346
- progress: "complete"
347
- };
348
- })
349
- );
350
- }
351
- }),
352
- [l, w, h, m]
353
- ), E = I(
354
- () => ({
355
- addPage: (e, t) => {
356
- const s = e?.id ?? O(), n = {
357
- ...e,
358
- id: s,
359
- createdAt: e?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
360
- updatedAt: e?.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
361
- publishedAt: (/* @__PURE__ */ new Date(0)).toISOString(),
362
- slug: e?.slug ?? `/${s}`,
363
- sections: e?.sections ?? {},
364
- sectionIds: e?.sectionIds ?? [],
365
- isPublic: e?.isPublic ?? !0,
366
- templateConfig: e?.templateConfig ?? {
367
- isTemplate: e?.templateConfig?.isTemplate ?? !0,
368
- displayTemplateId: e?.templateConfig?.displayTemplateId ?? void 0,
369
- dataSourceIds: e?.templateConfig?.dataSourceIds ?? void 0,
370
- dataSourceParameters: e?.templateConfig?.dataSourceParameters ?? {},
371
- enabledGenerate: e?.templateConfig?.enabledGenerate ?? !1,
372
- agentId: e?.templateConfig?.agentId ?? void 0
373
- }
374
- };
375
- return o.doc.transact(() => {
376
- r.pages[n.id] = n, r.pageIds.splice(t ?? r.pageIds.length, 0, n.id);
377
- }), n;
378
- },
379
- addRoute: (e, t) => {
380
- const s = e?.id ?? O(), n = {
381
- ...e,
382
- id: s,
383
- createdAt: e?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
384
- updatedAt: e?.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
385
- publishedAt: (/* @__PURE__ */ new Date(0)).toISOString(),
386
- path: e?.path ?? `/${s}`,
387
- handler: e?.handler ?? "Pages Kit",
388
- isPublic: e?.isPublic ?? !0,
389
- params: e?.params ?? [],
390
- enabledGenerate: e?.enabledGenerate ?? !1,
391
- displayTemplateId: e?.displayTemplateId ?? void 0,
392
- dataSource: e?.dataSource ?? {}
393
- };
394
- return o.doc.transact(() => {
395
- r.routes ??= {}, r.routeIds ??= [], r.routes[n.id] = n, r.routeIds.splice(t ?? r.routeIds.length, 0, n.id);
396
- }), n;
397
- },
398
- deleteRoute: (e) => {
399
- if (!e)
400
- return;
401
- const t = r.routeIds?.indexOf(e);
402
- t !== void 0 && t !== -1 && o.doc.transact(() => {
403
- r.routeIds?.splice(t, 1), delete r.routes?.[e];
404
- });
405
- },
406
- deletePage: (e) => {
407
- const t = r.pageIds.indexOf(e);
408
- t !== -1 && o.doc.transact(() => {
409
- r.pageIds.splice(t, 1), delete r.pages[e];
410
- });
411
- },
412
- movePage: (e, t) => {
413
- const { pageIds: s } = r, n = s.indexOf(e);
414
- n >= 0 && s.splice(t, 0, ...s.splice(n, 1));
415
- },
416
- addSection: (e, t, s, n) => {
417
- const i = r.pages[e];
418
- if (!i)
419
- throw new Error(`Page ${e} is not exists`);
420
- const c = {
421
- ...t,
422
- id: t.id ?? O(),
423
- isTemplateSection: t.isTemplateSection ?? !0,
424
- llmConfig: t.llmConfig ?? {}
425
- }, a = T(c.locales);
426
- return delete c.locales, o.doc.transact(() => {
427
- if (n && n.component === "layout-block") {
428
- const d = m.currentPageModel?.getComponentById(n.id);
429
- d && (d.model.sections ??= {}, d.model.sections[c.id] = c, d.model.sectionIds ??= [], d.model.sectionIds.push(c.id));
430
- } else
431
- i.sections[c.id] = c, i.sectionIds.splice(s ?? i.sectionIds.length, 0, c.id);
432
- a && (i.dataSource ??= {}, i.dataSource[c.id] = a);
433
- }), c;
434
- },
435
- deleteSection: (e, t) => {
436
- const s = r.pages[e];
437
- if (!s)
438
- throw new Error(`Page ${e} is not exists`);
439
- o.doc.transact(() => {
440
- const n = [], i = m.currentPageModel?.getComponentById(t), c = i?.parent;
441
- if (i && (n.push(i.model.id, ...i.all().map((a) => a.model.id)), c?.model.component === "layout-block")) {
442
- const a = c.model.sectionIds?.indexOf(t);
443
- a !== void 0 && a !== -1 && (c.model.sectionIds?.splice(a, 1), delete c.model.sections?.[t]), c.model.config?.gridSettings && Object.keys(c.model.config.gridSettings).forEach((d) => {
444
- try {
445
- delete c.model.config.gridSettings[d]?.[t];
446
- } catch {
447
- }
448
- }), c.model.config?.backgroundSectionId === t && (c.model.config.backgroundSectionId = void 0);
449
- }
450
- n.forEach((a) => {
451
- const d = s.sectionIds.indexOf(a);
452
- d !== -1 && s.sectionIds.splice(d, 1), s.sections[a] && delete s.sections[a], s.dataSource?.[a] && delete s.dataSource?.[a];
453
- });
454
- });
455
- },
456
- lockSection: (e, t) => {
457
- if (!r.pages[e])
458
- throw new Error(`Page ${e} is not exists`);
459
- const n = m.currentPageModel?.getComponentById(t)?.model;
460
- n && (n.locked = !n.locked);
461
- },
462
- toggleSectionVisibility: (e, t, s) => {
463
- if (!r.pages[e])
464
- throw new Error(`Page ${e} is not exists`);
465
- const i = m.currentPageModel?.getComponentById(t)?.model;
466
- i && (i.visibility = s);
467
- },
468
- moveSection: (e, t, s, n) => {
469
- if (!r.pages[e])
470
- throw new Error(`Page ${e} is not exists`);
471
- if (n && n !== t) {
472
- const c = m.currentPageModel?.getComponentById(t), a = m.currentPageModel?.getComponentById(n), d = c?.parent, f = a?.parent;
473
- f && d && f?.model?.id === d?.model?.id ? o.doc.transact(() => {
474
- d.model.sectionIds.splice(c.getIndex(), 1), d.model.sectionIds.splice(a.getIndex(), 0, t);
475
- }) : f && d && f?.model?.id !== d?.model?.id && t !== n && !c?.model?.sectionIds?.includes(n) && o.doc.transact(() => {
476
- f.model.sections[t] = JSON.parse(JSON.stringify(c.model)), f.model.sectionIds.splice(a.getIndex(), 0, t), d.model.sectionIds.splice(c.getIndex(), 1), delete d.model.sections[t];
477
- });
478
- }
479
- },
480
- copySection: (e, t) => {
481
- if (!r.pages[e])
482
- throw new Error(`Page ${e} is not exists`);
483
- const n = m.currentPageModel?.getComponentById(t);
484
- if (!n?.model)
485
- throw new Error(`Section ${t} is not exists`);
486
- const i = JSON.parse(JSON.stringify(n.model)), c = he(i), a = c.id, d = n?.parent;
487
- return d && (d.model.sections[a] = c, d.model.sectionIds.push(a), P.setCurrentSectionId(e, a), m.currentPage?.dataSource?.[t] && (m.currentPage.dataSource[a] = JSON.parse(
488
- JSON.stringify(m.currentPage.dataSource[t])
489
- ))), c;
490
- },
491
- addDataSource: (e) => {
492
- const t = e.id ?? O(), s = {
493
- ...e ?? {},
494
- id: t,
495
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
496
- };
497
- return o.doc.transact(() => {
498
- r.dataSourceIds ??= [], r.dataSources ??= {}, r.dataSourceIds.push(t), r.dataSources[t] = s;
499
- }), r.dataSources[t];
500
- },
501
- deleteDataSource: (e) => {
502
- const t = r.dataSourceIds.indexOf(e);
503
- t !== -1 && o.doc.transact(() => {
504
- r.dataSourceIds.splice(t, 1), delete r.dataSources[e];
505
- });
506
- }
507
- }),
508
- [r, o.doc, m]
509
- );
510
- return {
511
- ...o,
512
- state: r,
513
- actions: E,
514
- localActions: P,
515
- ...m
516
- };
517
- }, U = () => {
518
- const { projectId: o } = re();
519
- return o ?? de() ?? "";
520
- }, Qe = () => window.__PROJECT_SLUG__ ?? "";
521
- function we(o) {
522
- const { resources: r } = o;
523
- if (!r.components)
524
- return {};
525
- const l = {};
526
- return window?.blocklet?.componentMountPoints?.forEach((p) => {
527
- l[p.did] = p;
528
- }), Object.fromEntries(
529
- Object.entries(r.components).map(([p, { blockletId: w, component: h }]) => [
530
- p,
531
- { data: h, blockletId: w, blockletTitle: l[w]?.title || w }
532
- ])
533
- );
534
- }
535
- function Ie(o) {
536
- const { components: r } = o;
537
- return r || {};
538
- }
539
- function ye(o) {
540
- return {
541
- ...we(o),
542
- ...Ie(o)
543
- };
544
- }
545
- const Xe = () => ye(Pe().state);
546
- function he(o) {
547
- const r = JSON.parse(JSON.stringify(o)), l = O();
548
- return {
549
- ...r,
550
- id: l
551
- };
552
- }
553
- export {
554
- ze as S,
555
- Pe as a,
556
- Ue as b,
557
- ye as c,
558
- Qe as d,
559
- Ve as e,
560
- Ke as f,
561
- We as g,
562
- Xe as h,
563
- G as i,
564
- Ie as j,
565
- we as k,
566
- de as l,
567
- Fe as t,
568
- U as u
569
- };