@1agh/maude 2.0.1 → 2.0.2

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.
@@ -0,0 +1,175 @@
1
+ // client/v2/assets/ds-library.js — the Assets tab's "Design system" source (2.0.2): a design system's own library,
2
+ // folder by folder, a page at a time.
3
+ //
4
+ // v1 let a person browse the design system's picked photo gallery from the left panel; v2's tab listed only the
5
+ // project's uploads. The tab's source switch (`sourcesOf`) now offers each design system too, and this file reads
6
+ // `GET /_api/ds/assets` (routes/ds-assets.ts) for one: the folders of the current one, its pictures by name, the next
7
+ // page when the person scrolls to the end, and a search below the folder.
8
+ //
9
+ // A row's `path` is the LITERAL reference a placement writes (`/<designRel>/system/<ds>/assets/…`,
10
+ // editing/ds-asset-ref.ts): the same string is the tile's picture URL, what a drag carries and what ↵ asks `image.place`
11
+ // for — one string, so what the tile shows is what the canvas gets. Pure parts first; the hook at the end.
12
+
13
+ import { useCallback, useEffect, useRef, useState } from 'react';
14
+ import { dsAssetSrc } from '../../../editing/ds-asset-ref.ts';
15
+
16
+ export const PROJECT_SOURCE = 'project';
17
+ const DS_PREFIX = 'ds:';
18
+ export const DS_PAGE = 200;
19
+
20
+ /** The tab's sources: this project's assets, then each design system the session sees. */
21
+ export function sourcesOf(designSystems) {
22
+ const list = Array.isArray(designSystems) ? designSystems : [];
23
+ const seen = new Set();
24
+ const out = [{ id: PROJECT_SOURCE, label: 'This project' }];
25
+ for (const d of list) {
26
+ const name = typeof d?.name === 'string' ? d.name : '';
27
+ if (!name || seen.has(name)) continue;
28
+ seen.add(name);
29
+ out.push({ id: `${DS_PREFIX}${name}`, label: name, ds: name });
30
+ }
31
+ return out;
32
+ }
33
+
34
+ /** The design system a source id names, or null (this project). */
35
+ export const dsOfSource = (id) =>
36
+ typeof id === 'string' && id.startsWith(DS_PREFIX) ? id.slice(DS_PREFIX.length) || null : null;
37
+
38
+ /** The request for one page. */
39
+ export function dsLibraryUrl({ ds, dir = '', q = '', cursor = null, limit = DS_PAGE }) {
40
+ const p = new URLSearchParams({ ds });
41
+ if (dir) p.set('dir', dir);
42
+ if (q.trim()) p.set('q', q.trim());
43
+ if (cursor) p.set('cursor', cursor);
44
+ p.set('limit', String(limit));
45
+ return `/_api/ds/assets?${p.toString()}`;
46
+ }
47
+
48
+ /** A page's files → tile rows (the AssetTile shape), each with its literal reference as `path`. */
49
+ export function rowsFromDsPage(page, designRel) {
50
+ const files = Array.isArray(page?.files) ? page.files : [];
51
+ const out = [];
52
+ for (const f of files) {
53
+ if (!f || typeof f.path !== 'string') continue;
54
+ const literal = dsAssetSrc(f.path, designRel);
55
+ out.push({
56
+ // a picture that cannot be a reference (a name with a quote, a sound) still shows — by its plain URL
57
+ path: literal ?? `/${String(designRel).replace(/^\/+|\/+$/g, '')}/${f.path}`,
58
+ rel: f.path,
59
+ name: f.name || f.path.split('/').pop(),
60
+ kind: f.kind || 'image',
61
+ size: Number(f.size) || 0,
62
+ mtimeMs: Number(f.mtimeMs) || 0,
63
+ placeable: !!f.placeable && literal !== null,
64
+ usedIn: null,
65
+ });
66
+ }
67
+ return out;
68
+ }
69
+
70
+ /** The folders of a page, by name, relative to the library (what the breadcrumb and `dir=` take). */
71
+ export function dirsFromDsPage(page) {
72
+ const root = typeof page?.root === 'string' ? page.root : '';
73
+ return (Array.isArray(page?.dirs) ? page.dirs : [])
74
+ .filter((d) => d && typeof d.path === 'string' && d.path.startsWith(`${root}/`))
75
+ .map((d) => ({
76
+ dir: d.path.slice(root.length + 1),
77
+ name: d.name || d.path.split('/').pop(),
78
+ count: Number(d.count) || 0,
79
+ }));
80
+ }
81
+
82
+ /** "Alligators › photos-cut › 2024": each step and the dir it opens. */
83
+ export function crumbsOf(ds, dir) {
84
+ const out = [{ label: ds, dir: '' }];
85
+ const parts = String(dir || '')
86
+ .split('/')
87
+ .filter(Boolean);
88
+ parts.forEach((p, i) => out.push({ label: p, dir: parts.slice(0, i + 1).join('/') }));
89
+ return out;
90
+ }
91
+
92
+ /** "1 file" · "3007 files". */
93
+ export const filesWords = (n) => `${n} ${n === 1 ? 'file' : 'files'}`;
94
+
95
+ /** The state after one answer: a first page replaces, a next page appends (never twice the same row). */
96
+ export function mergeDsPage(state, page, designRel, { append = false } = {}) {
97
+ const rows = rowsFromDsPage(page, designRel);
98
+ if (!append)
99
+ return {
100
+ dirs: dirsFromDsPage(page),
101
+ rows,
102
+ total: Number(page?.total) || rows.length,
103
+ next: page?.next ?? null,
104
+ };
105
+ const have = new Set(state.rows.map((r) => r.path));
106
+ return {
107
+ ...state,
108
+ rows: [...state.rows, ...rows.filter((r) => !have.has(r.path))],
109
+ total: Number(page?.total) || state.total,
110
+ next: page?.next ?? null,
111
+ };
112
+ }
113
+
114
+ const EMPTY = Object.freeze({ dirs: [], rows: [], total: 0, next: null });
115
+
116
+ /**
117
+ * One design system's library at `dir`, searched by `q`.
118
+ * @returns {{ state: {dirs, rows, total, next} | null, error: string, loading: boolean, loadMore: () => Promise<void> }}
119
+ * `state` is null until the first answer.
120
+ */
121
+ export function useDsLibrary({ ds, dir, q, designRel, fetchImpl }) {
122
+ const [state, setState] = useState(null);
123
+ const [error, setError] = useState('');
124
+ const [loading, setLoading] = useState(false);
125
+ const fetchRef = useRef(fetchImpl || ((...a) => fetch(...a)));
126
+ fetchRef.current = fetchImpl || fetchRef.current;
127
+ const gen = useRef(0);
128
+ const stateRef = useRef(state);
129
+ stateRef.current = state;
130
+
131
+ const read = useCallback(
132
+ async (cursor) => {
133
+ const my = gen.current;
134
+ setLoading(true);
135
+ try {
136
+ const r = await fetchRef.current(dsLibraryUrl({ ds, dir, q, cursor }), {
137
+ cache: 'no-store',
138
+ });
139
+ const j = await r.json().catch(() => null);
140
+ if (my !== gen.current) return;
141
+ if (!r.ok || !j?.ok) {
142
+ setError(
143
+ r.status === 404
144
+ ? 'Nothing here. It may have moved; go back to the top.'
145
+ : 'The library could not be read. Try again.'
146
+ );
147
+ if (!cursor) setState(EMPTY);
148
+ return;
149
+ }
150
+ setError('');
151
+ setState((s) => mergeDsPage(s ?? EMPTY, j, designRel, { append: !!cursor }));
152
+ } catch {
153
+ if (my === gen.current) setError('The studio could not be reached. Try again.');
154
+ } finally {
155
+ if (my === gen.current) setLoading(false);
156
+ }
157
+ },
158
+ [ds, dir, q, designRel]
159
+ );
160
+
161
+ useEffect(() => {
162
+ gen.current += 1;
163
+ setState(null);
164
+ setError('');
165
+ if (ds) void read(null);
166
+ }, [ds, read]);
167
+
168
+ const loadMore = useCallback(async () => {
169
+ const s = stateRef.current;
170
+ if (!s?.next || loading) return;
171
+ await read(s.next);
172
+ }, [read, loading]);
173
+
174
+ return { state, error, loading, loadMore };
175
+ }
@@ -55,6 +55,8 @@ import { AssetTileMenu, tileMenuItems } from '../assets/tile-menu.jsx';
55
55
  import { ConfirmTrash, NotCountedNote, TidyFoot, tidyModel } from '../assets/tidy.jsx';
56
56
  import { moveAssetsToTrash, undoAssetTrash } from '../assets/trash-assets.js';
57
57
  import { useAssets } from '../assets/use-assets.js';
58
+ import { dsOfSource, PROJECT_SOURCE, sourcesOf } from '../assets/ds-library.js';
59
+ import { DsLibraryView } from '../assets/ds-library-view.jsx';
58
60
  import { AskButton, copy, Empty } from '../empty/index.js';
59
61
  import { getPaletteEnv } from '../search/search-env.js';
60
62
  import { menuRunner } from '../shell/menu-runner.js';
@@ -160,9 +162,16 @@ export function AssetsPanel({
160
162
  isOffline = undefined,
161
163
  // S8.21 — "Used in" in the details opens the canvas (`<designRel>/<canvas>`) and selects the artboard
162
164
  onOpenCanvas = undefined,
165
+ // 2.0.2 — the project's design systems (config `designSystems`): each is a source the tab can show instead
166
+ designSystems = [],
163
167
  fetchImpl = undefined,
164
168
  }) {
165
169
  const { assets, history, reload } = useAssets({ fetchImpl });
170
+ // 2.0.2 — which library the tab shows: this project's assets, or one design system's own (ds-library-view.jsx)
171
+ const sources = useMemo(() => sourcesOf(designSystems), [designSystems]);
172
+ const [source, setSource] = useState(PROJECT_SOURCE);
173
+ const sourceDs = sources.some((x) => x.id === source) ? dsOfSource(source) : null;
174
+ const dsApi = useRef(null);
166
175
  const generated = useGenerated({ fetchImpl });
167
176
  const reloadGenerated = generated.reload;
168
177
  // a run's record is a file of its own: re-read when the rows move, so a take that just landed is in its run
@@ -566,6 +575,7 @@ export function AssetsPanel({
566
575
  // The registry reaches the tab through the bus: the same functions the tile menu runs.
567
576
  const live = useRef({});
568
577
  live.current = {
578
+ sourceDs,
569
579
  describe,
570
580
  picked,
571
581
  browse,
@@ -582,7 +592,8 @@ export function AssetsPanel({
582
592
  bindAssetsPanel({
583
593
  place: () => {
584
594
  const l = live.current;
585
- if (l.browse) {
595
+ if (l.sourceDs) void dsApi.current?.place();
596
+ else if (l.browse) {
586
597
  const list = l.browsePicked();
587
598
  if (list.length) void l.placeMany(list);
588
599
  } else if (l.picked) void l.place(l.picked);
@@ -623,6 +634,7 @@ export function AssetsPanel({
623
634
  },
624
635
  tileSelected: () => {
625
636
  const l = live.current;
637
+ if (l.sourceDs) return !!dsApi.current?.tileSelected();
626
638
  const has = l.browse ? l.browse.selected.size > 0 : !!l.picked;
627
639
  return has && !!rootRef.current?.contains(document.activeElement);
628
640
  },
@@ -791,6 +803,52 @@ export function AssetsPanel({
791
803
  void upload(() => Promise.all(files.map((f) => uploadNamed(f, noteProgress))));
792
804
  };
793
805
 
806
+ // 2.0.2 — "Library": this project, or a design system's own (only when the project has one)
807
+ const sourceSwitch =
808
+ sources.length > 1 ? (
809
+ <div className="lp-source-row">
810
+ <label className="lp-source">
811
+ <span className="lp-source-l">Library</span>
812
+ <select
813
+ data-testid="assets-source"
814
+ aria-label="Library"
815
+ value={sourceDs ? source : PROJECT_SOURCE}
816
+ onChange={(e) => {
817
+ setSource(e.target.value);
818
+ setPicked(null);
819
+ setBrowse(null);
820
+ setDetails(null);
821
+ setMenu(null);
822
+ }}
823
+ >
824
+ {sources.map((x) => (
825
+ <option key={x.id} value={x.id}>
826
+ {x.ds ? `${x.label} · design system` : x.label}
827
+ </option>
828
+ ))}
829
+ </select>
830
+ </label>
831
+ </div>
832
+ ) : null;
833
+ if (sourceDs)
834
+ return (
835
+ <div className="lp-assets" data-testid="assets-panel" data-source="ds">
836
+ {sourceSwitch}
837
+ <DsLibraryView
838
+ key={sourceDs}
839
+ ds={sourceDs}
840
+ designRel={designRel}
841
+ readOnly={readOnly}
842
+ placeTarget={placeTarget}
843
+ placeLabel={placeLabel}
844
+ onRecord={onRecord}
845
+ toast={toast}
846
+ apiRef={dsApi}
847
+ fetchImpl={fetchImpl}
848
+ />
849
+ </div>
850
+ );
851
+
794
852
  return (
795
853
  // biome-ignore lint/a11y/noStaticElementInteractions: a file drop target is a pointer door; the Upload button is the keyboard path
796
854
  <div
@@ -809,6 +867,7 @@ export function AssetsPanel({
809
867
  }}
810
868
  onDrop={onDrop}
811
869
  >
870
+ {detailed ? null : sourceSwitch}
812
871
  {detailed ? null : (
813
872
  <div className="lp-head-row">
814
873
  <label className="lp-find">