@scenoco-three/unity 0.9.9 → 1.0.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/dist/input.js ADDED
@@ -0,0 +1,73 @@
1
+ /**
2
+ * SceNoCo's named axes and buttons — Unity's Input Manager list, `Horizontal` to `Cancel` — as an
3
+ * Input System actions asset: one action per name, bound to the keys, mouse buttons and gamepad
4
+ * controls core's `AXES` gives it. Made the project-wide actions, so `Input.getAxis('Horizontal')`
5
+ * ports as `InputSystem.actions["Horizontal"].ReadValue<float>()`.
6
+ */
7
+ import { createHash } from 'node:crypto';
8
+ /** A gamepad button by its index in the browser's standard layout — SceNoCo's `JoystickButtonN`. */
9
+ const PAD = ['buttonSouth', 'buttonEast', 'buttonWest', 'buttonNorth', 'leftShoulder', 'rightShoulder', 'leftTrigger', 'rightTrigger', 'select', 'start', 'leftStickPress', 'rightStickPress', 'dpad/up', 'dpad/down', 'dpad/left', 'dpad/right'];
10
+ const MOUSE = ['leftButton', 'middleButton', 'rightButton'];
11
+ const KEYS = {
12
+ ArrowUp: 'upArrow', ArrowDown: 'downArrow', ArrowLeft: 'leftArrow', ArrowRight: 'rightArrow', Enter: 'enter', Space: 'space',
13
+ Escape: 'escape', Tab: 'tab', Backspace: 'backspace', Delete: 'delete', ControlLeft: 'leftCtrl', ControlRight: 'rightCtrl',
14
+ AltLeft: 'leftAlt', AltRight: 'rightAlt', MetaLeft: 'leftMeta', MetaRight: 'rightMeta', ShiftLeft: 'leftShift', ShiftRight: 'rightShift',
15
+ };
16
+ /** A DOM key code — `KeyA`, `ArrowLeft`, `JoystickButton0` — as an Input System control path. */
17
+ export function controlPath(code) {
18
+ const pad = /^JoystickButton(\d+)$/.exec(code);
19
+ if (pad)
20
+ return PAD[Number(pad[1])] ? `<Gamepad>/${PAD[Number(pad[1])]}` : undefined;
21
+ const letter = /^Key([A-Z])$/.exec(code);
22
+ if (letter)
23
+ return `<Keyboard>/${letter[1].toLowerCase()}`;
24
+ const digit = /^Digit(\d)$/.exec(code);
25
+ if (digit)
26
+ return `<Keyboard>/${digit[1]}`;
27
+ if (/^F\d+$/.test(code))
28
+ return `<Keyboard>/${code.toLowerCase()}`;
29
+ return KEYS[code] ? `<Keyboard>/${KEYS[code]}` : undefined;
30
+ }
31
+ /** A stable id from a name, as the asset wants one per action and binding. */
32
+ const id = (name) => {
33
+ const h = createHash('sha1').update(name).digest('hex');
34
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20, 32)}`;
35
+ };
36
+ /** The `.inputactions` JSON for `axes` — core's `AXES`, as the snapshot carries it. */
37
+ export function inputActions(axes) {
38
+ const actions = [];
39
+ const bindings = [];
40
+ const bind = (action, path, extra = {}) => bindings.push({ name: '', id: id(`${action}/${path}/${bindings.length}`), path, interactions: '', processors: '', groups: '', action, isComposite: false, isPartOfComposite: false, ...extra });
41
+ for (const [name, axis] of Object.entries(axes)) {
42
+ const both = !!(axis.negative?.length && axis.positive?.length) || !!axis.stick;
43
+ actions.push({ name, type: both ? 'Value' : 'Button', id: id(name), expectedControlType: both ? 'Axis' : 'Button', processors: '', interactions: '', initialStateCheck: both });
44
+ if (both) {
45
+ // Keys pull it to -1 and +1, as the Input Manager's negative and positive buttons do.
46
+ bind(name, '1DAxis', { name: 'Keys', isComposite: true });
47
+ for (const [part, codes] of [['negative', axis.negative], ['positive', axis.positive]])
48
+ for (const code of codes ?? []) {
49
+ const path = controlPath(code);
50
+ if (path)
51
+ bind(name, path, { name: part, isPartOfComposite: true });
52
+ }
53
+ if (axis.stick)
54
+ bind(name, `<Gamepad>/leftStick/${axis.stick.axis === 0 ? 'x' : 'y'}`);
55
+ }
56
+ else {
57
+ for (const code of axis.positive ?? []) {
58
+ const path = controlPath(code);
59
+ if (path)
60
+ bind(name, path);
61
+ }
62
+ if (axis.mouse !== undefined && MOUSE[axis.mouse])
63
+ bind(name, `<Mouse>/${MOUSE[axis.mouse]}`);
64
+ }
65
+ }
66
+ // The mouse axes: this frame's movement, as Unity's Mouse X and Y are.
67
+ const mouseAxes = [['Mouse X', '<Pointer>/delta/x'], ['Mouse Y', '<Pointer>/delta/y'], ['Mouse ScrollWheel', '<Mouse>/scroll/y']];
68
+ for (const [name, path] of mouseAxes) {
69
+ actions.push({ name, type: 'Value', id: id(name), expectedControlType: 'Axis', processors: '', interactions: '', initialStateCheck: false });
70
+ bind(name, path);
71
+ }
72
+ return JSON.stringify({ name: 'SceNoCo', maps: [{ name: 'Game', id: id('Game'), actions, bindings }], controlSchemes: [] }, null, 4) + '\n';
73
+ }
package/dist/page.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * USS's named easings, by the cubic-bezier each stands for. CSS writes the curve, USS the name: a page
3
+ * that ports writes one of these curves, or one of the keywords both have.
4
+ */
5
+ export declare const USS_EASINGS: Record<string, string>;
6
+ /** The USS name of a `cubic-bezier(…)`, or undefined when USS has none. */
7
+ export declare function easingName(curve: string): string | undefined;
8
+ export interface PageOutput {
9
+ /** Files to write into the Unity project, by path under it. */
10
+ files: Map<string, string>;
11
+ /** Files to copy: from the game → to a path under the Unity project. */
12
+ copies: Map<string, string>;
13
+ /** Files to download: URL → path under the Unity project. */
14
+ downloads: Map<string, string>;
15
+ /** Each document's UXML, by the element it names. */
16
+ documents: Map<string, string>;
17
+ warnings: string[];
18
+ }
19
+ /**
20
+ * Translate the page at `root/index.html`: the elements `documents` name (a `UIDocument`'s `element`),
21
+ * its templates, and its style.
22
+ */
23
+ export declare function convertPage(root: string, documents: string[], options?: {
24
+ fonts?: boolean;
25
+ }): Promise<PageOutput>;
package/dist/page.js ADDED
@@ -0,0 +1,347 @@
1
+ /**
2
+ * The game's page as UI Toolkit's own files. A SceNoCo page is UXML and USS written in HTML — its
3
+ * `<style>` the USS, the element each `UIDocument` names the UXML — so this is a translation of
4
+ * spelling, rule by rule, not a redesign:
5
+ *
6
+ * - each `UIDocument`'s element is a `.uxml`, each `<template>` one too; a `div` is a
7
+ * `VisualElement`, or a `Label` when it holds text or may (code sets `textContent`), a `button` a
8
+ * `Button`, `id` its `name`;
9
+ * - the `<style>` is one `.uss`: what USS spells differently is respelled, what it does not have is
10
+ * left out with a word — `pointer-events` becomes each element's `picking-mode`;
11
+ * - the images the CSS names are copied in, and its web fonts downloaded as `.ttf`, which Unity makes
12
+ * Font Assets of.
13
+ */
14
+ import { existsSync, readFileSync } from 'node:fs';
15
+ import { basename, join } from 'node:path';
16
+ /**
17
+ * USS's named easings, by the cubic-bezier each stands for. CSS writes the curve, USS the name: a page
18
+ * that ports writes one of these curves, or one of the keywords both have.
19
+ */
20
+ export const USS_EASINGS = {
21
+ '0.12, 0, 0.39, 0': 'ease-in-sine',
22
+ '0.61, 1, 0.88, 1': 'ease-out-sine',
23
+ '0.37, 0, 0.63, 1': 'ease-in-out-sine',
24
+ '0.32, 0, 0.67, 0': 'ease-in-cubic',
25
+ '0.33, 1, 0.68, 1': 'ease-out-cubic',
26
+ '0.65, 0, 0.35, 1': 'ease-in-out-cubic',
27
+ '0.55, 0, 1, 0.45': 'ease-in-circ',
28
+ '0, 0.55, 0.45, 1': 'ease-out-circ',
29
+ '0.85, 0, 0.15, 1': 'ease-in-out-circ',
30
+ '0.36, 0, 0.66, -0.56': 'ease-in-back',
31
+ '0.34, 1.56, 0.64, 1': 'ease-out-back',
32
+ '0.68, -0.6, 0.32, 1.6': 'ease-in-out-back',
33
+ };
34
+ /** The USS name of a `cubic-bezier(…)`, or undefined when USS has none. */
35
+ export function easingName(curve) {
36
+ const numbers = /cubic-bezier\(([^)]*)\)/.exec(curve)?.[1]?.split(',').map((n) => String(Number(n.trim())));
37
+ return numbers ? USS_EASINGS[numbers.join(', ')] : undefined;
38
+ }
39
+ const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ', middot: '·', times: '×' };
40
+ const decode = (s) => s.replace(/&(#\d+|[a-z]+);/g, (m, e) => (e.startsWith('#') ? String.fromCharCode(Number(e.slice(1))) : (ENTITIES[e] ?? m)));
41
+ const escape = (s) => s.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
42
+ /** A page's elements: enough of HTML for the pages SceNoCo writes — no scripts, no void elements but these. */
43
+ function parse(html) {
44
+ const root = { tag: '#root', attrs: {}, children: [], text: '' };
45
+ let at = root;
46
+ const body = html.replace(/<!--[\s\S]*?-->/g, '').replace(/<(script|style)\b[\s\S]*?<\/\1>/g, '');
47
+ for (const m of body.matchAll(/<(\/?)([a-zA-Z][\w-]*)([^>]*?)(\/?)>|([^<]+)/g)) {
48
+ if (m[5] !== undefined) {
49
+ if (m[5].trim())
50
+ at.text += (at.text ? ' ' : '') + decode(m[5].trim().replace(/\s+/g, ' '));
51
+ continue;
52
+ }
53
+ const [, close, tag, rest, self] = m;
54
+ if (close) {
55
+ if (at.parent)
56
+ at = at.parent;
57
+ continue;
58
+ }
59
+ const attrs = {};
60
+ for (const a of rest.matchAll(/([\w:-]+)(?:\s*=\s*"([^"]*)")?/g))
61
+ attrs[a[1]] = decode(a[2] ?? '');
62
+ const el = { tag: tag.toLowerCase(), attrs, children: [], text: '', parent: at };
63
+ at.children.push(el);
64
+ if (!self && !['meta', 'link', 'br', 'img', 'input'].includes(el.tag))
65
+ at = el;
66
+ }
67
+ return root;
68
+ }
69
+ const all = (e) => [e, ...e.children.flatMap(all)];
70
+ /** One compound selector — `button#play.big:active` — and whether an element is it, pseudo-classes aside. */
71
+ function compoundMatches(compound, e) {
72
+ const plain = compound.replace(/::?[\w-]+(\([^)]*\))?/g, '');
73
+ if (plain === '' || plain === '*')
74
+ return true;
75
+ const tag = /^[a-zA-Z][\w-]*/.exec(plain)?.[0];
76
+ if (tag && tag.toLowerCase() !== e.tag)
77
+ return false;
78
+ const id = /#([\w-]+)/.exec(plain)?.[1];
79
+ if (id && e.attrs.id !== id)
80
+ return false;
81
+ const classes = (e.attrs.class ?? '').split(/\s+/);
82
+ return [...plain.matchAll(/\.([\w-]+)/g)].every((c) => classes.includes(c[1]));
83
+ }
84
+ /** A selector — compounds by descendant or child — and whether an element is it. `>` is read as descendant. */
85
+ function matches(selector, e) {
86
+ const parts = selector.replace(/>/g, ' ').trim().split(/\s+/);
87
+ if (!compoundMatches(parts.at(-1), e))
88
+ return false;
89
+ let ancestor = e.parent;
90
+ for (let i = parts.length - 2; i >= 0; i--) {
91
+ while (ancestor && !compoundMatches(parts[i], ancestor))
92
+ ancestor = ancestor.parent;
93
+ if (!ancestor)
94
+ return false;
95
+ ancestor = ancestor.parent;
96
+ }
97
+ return true;
98
+ }
99
+ function rules(css) {
100
+ const fontFaces = [];
101
+ const clean = css.replace(/\/\*[\s\S]*?\*\//g, '').replace(/@font-face\s*\{([^}]*)\}/g, (_, body) => (fontFaces.push(body), ''));
102
+ const out = [];
103
+ for (const m of clean.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
104
+ const declarations = m[2]
105
+ .split(';')
106
+ .filter((d) => d.includes(':'))
107
+ .map((d) => [d.slice(0, d.indexOf(':')).trim(), d.slice(d.indexOf(':') + 1).trim()]);
108
+ out.push({ selectors: m[1].split(',').map((s) => s.trim().replace(/\s+/g, ' ')), declarations });
109
+ }
110
+ return { rules: out, fontFaces };
111
+ }
112
+ /** The faces of the page's Google Fonts links: their CSS, asked for as a client that is served `.ttf`. */
113
+ async function webFonts(html, warnings) {
114
+ const faces = [];
115
+ const downloads = new Map();
116
+ for (const link of html.matchAll(/<link[^>]+href="(https:\/\/fonts\.googleapis\.com\/[^"]+)"/g)) {
117
+ const href = decode(link[1]);
118
+ let css;
119
+ try {
120
+ const response = await fetch(href, { headers: { 'User-Agent': 'scenoco-unity' } });
121
+ if (!response.ok)
122
+ throw new Error(`HTTP ${response.status}`);
123
+ css = await response.text();
124
+ }
125
+ catch (error) {
126
+ warnings.push(`the page's fonts (${href}) could not be fetched — ${error.message}. Unity's default font stands in.`);
127
+ continue;
128
+ }
129
+ for (const face of rules(css).fontFaces) {
130
+ const get = (prop) => new RegExp(`${prop}\\s*:\\s*([^;]+)`).exec(face)?.[1]?.trim() ?? '';
131
+ const family = get('font-family').replace(/['"]/g, '');
132
+ const url = /url\(([^)]+\.ttf)\)/.exec(face)?.[1];
133
+ if (!family || !url)
134
+ continue;
135
+ const weight = Number(get('font-weight')) || 400;
136
+ const italic = get('font-style') === 'italic';
137
+ const path = `Assets/UI/Fonts/${family.replace(/\s+/g, '')}-${weight}${italic ? 'Italic' : ''}.ttf`;
138
+ faces.push({ family, weight, italic, path });
139
+ downloads.set(url, path);
140
+ }
141
+ }
142
+ return { faces, downloads };
143
+ }
144
+ /**
145
+ * Translate the page at `root/index.html`: the elements `documents` name (a `UIDocument`'s `element`),
146
+ * its templates, and its style.
147
+ */
148
+ export async function convertPage(root, documents, options = {}) {
149
+ const out = { files: new Map(), copies: new Map(), downloads: new Map(), documents: new Map(), warnings: [] };
150
+ const file = join(root, 'index.html');
151
+ if (!existsSync(file) || documents.length === 0)
152
+ return out;
153
+ const html = readFileSync(file, 'utf8');
154
+ const tree = parse(html);
155
+ const byId = new Map(all(tree).filter((e) => e.attrs.id).map((e) => [e.attrs.id, e]));
156
+ for (const id of documents)
157
+ if (!byId.has(id))
158
+ out.warnings.push(`index.html has no element with id="${id}" for a UIDocument — it has no UXML.`);
159
+ const roots = documents.flatMap((id) => byId.get(id) ?? []);
160
+ // A <template> is parsed with its content as children, like any element.
161
+ const templates = all(tree).filter((e) => e.tag === 'template' && e.attrs.id);
162
+ const exported = [...roots, ...templates.flatMap((t) => t.children)];
163
+ const inside = new Set(exported.flatMap(all));
164
+ const css = [...html.matchAll(/<style>([\s\S]*?)<\/style>/g)].map((m) => m[1]).join('\n');
165
+ const parsed = rules(css);
166
+ const { faces, downloads } = options.fonts === false ? { faces: [], downloads: new Map() } : await webFonts(html, out.warnings);
167
+ for (const [url, path] of downloads)
168
+ out.downloads.set(url, path);
169
+ // Picking. Core's UIDocument takes pointer events off its element, and the page gives them back
170
+ // where a player taps: pointer-events is inherited, and the last rule that sets it on an element
171
+ // wins. A rule that gives them back counts whatever classes it names — code puts `.shown` on as the
172
+ // game runs, and USS has no picking to switch — while UI Toolkit picks nothing hidden anyway.
173
+ const loose = (sel) => sel.replace(/\.[\w-]+|::?[\w-]+(\([^)]*\))?/g, '') || '*';
174
+ const picking = new Map();
175
+ const pickable = (e) => {
176
+ if (picking.has(e))
177
+ return picking.get(e);
178
+ let value;
179
+ for (const r of parsed.rules)
180
+ for (const [p, v] of r.declarations) {
181
+ if (p !== 'pointer-events')
182
+ continue;
183
+ if (v === 'none' ? r.selectors.some((sel) => !sel.includes(':') && matches(sel, e)) : r.selectors.some((sel) => matches(loose(sel), e)))
184
+ value = v !== 'none';
185
+ }
186
+ // A document's element starts without them, and so does a template's, which code adds under one.
187
+ const top = roots.includes(e) || e.parent?.tag === 'template';
188
+ const result = value ?? (top || !e.parent || !inside.has(e.parent) ? !top : pickable(e.parent));
189
+ picking.set(e, result);
190
+ return result;
191
+ };
192
+ // --- USS -------------------------------------------------------------------------------------
193
+ const url = (raw) => {
194
+ const path = raw.replace(/^['"]|['"]$/g, '');
195
+ if (/^https?:/.test(path)) {
196
+ const local = `Assets/UI/remote/${basename(new URL(path).pathname)}`;
197
+ out.downloads.set(path, local);
198
+ return `url("project://database/${local}")`;
199
+ }
200
+ const clean = path.replace(/^\//, '');
201
+ const from = [join(root, 'public', clean), join(root, clean)].find((f) => existsSync(f));
202
+ if (!from) {
203
+ out.warnings.push(`index.html: ${path} was not found — left as it is.`);
204
+ return `url("${path}")`;
205
+ }
206
+ const to = `Assets/UI/${clean}`;
207
+ out.copies.set(from, to);
208
+ return `url("project://database/${to}")`;
209
+ };
210
+ const fontFor = (family, weight, italic) => {
211
+ const own = faces.filter((f) => f.family === family);
212
+ return own.sort((a, b) => Math.abs(a.weight - weight) + (a.italic === italic ? 0 : 1000) - (Math.abs(b.weight - weight) + (b.italic === italic ? 0 : 1000)))[0];
213
+ };
214
+ const DROPPED = new Set(['pointer-events', 'cursor', 'appearance', '-webkit-appearance', 'user-select', '-webkit-user-select', 'touch-action', 'font', 'border-style', 'overflow-wrap', 'box-sizing']);
215
+ const respell = (rule) => {
216
+ const own = new Map(rule.declarations);
217
+ const weight = own.get('font-weight');
218
+ const bold = !!weight && /bold|[6-9]00/.test(weight);
219
+ const italic = own.get('font-style') === 'italic';
220
+ const result = [];
221
+ let font;
222
+ for (const [prop, raw] of rule.declarations) {
223
+ if (DROPPED.has(prop) || /\binherit\b/.test(raw))
224
+ continue;
225
+ let value = raw.replace(/url\(([^)]+)\)/g, (_, u) => url(u));
226
+ value = value.replace(/cubic-bezier\([^)]*\)/g, (curve) => {
227
+ const name = easingName(curve);
228
+ if (name)
229
+ return name;
230
+ out.warnings.push(`index.html: ${curve} has no USS easing — ease-out stands in. Write one of the curves USS names.`);
231
+ return 'ease-out';
232
+ });
233
+ switch (prop) {
234
+ case 'font-family': {
235
+ const family = value.split(',')[0].replace(/['"]/g, '').trim();
236
+ font = fontFor(family, bold ? 700 : weight ? Number(weight) || 400 : 400, italic);
237
+ if (font)
238
+ result.push(['-unity-font-definition', `url("project://database/${font.path}")`]);
239
+ else if (!/^(system-ui|sans-serif|serif|monospace)$/.test(family))
240
+ out.warnings.push(`index.html: no font file for "${family}" — Unity's default font stands in. Add its .ttf to Assets/UI/Fonts.`);
241
+ break;
242
+ }
243
+ case 'font-weight':
244
+ case 'font-style':
245
+ break; // below, together
246
+ case 'text-align':
247
+ result.push(['-unity-text-align', { center: 'middle-center', left: 'middle-left', right: 'middle-right' }[value] ?? 'middle-left']);
248
+ break;
249
+ case 'border': {
250
+ const [width, , color] = value.split(/\s+(?![^(]*\))/);
251
+ result.push(['border-width', width]);
252
+ if (color)
253
+ result.push(['border-color', color]);
254
+ break;
255
+ }
256
+ case 'border-image': {
257
+ const m = /(url\([^)]*\))\s+(\d+)\s+fill\s*\/\s*(\d+)px/.exec(value);
258
+ if (!m) {
259
+ out.warnings.push(`index.html: border-image ${raw} is not the "url() slice fill / width" USS can nine-slice — left out.`);
260
+ break;
261
+ }
262
+ const [, image, slice, width] = m;
263
+ result.push(['background-image', image]);
264
+ for (const side of ['left', 'top', 'right', 'bottom'])
265
+ result.push([`-unity-slice-${side}`, slice]);
266
+ result.push(['-unity-slice-scale', `${Number(width) / Number(slice)}px`]);
267
+ break;
268
+ }
269
+ default:
270
+ result.push([prop, value]);
271
+ }
272
+ }
273
+ // A face of the right weight is drawn as it is; USS's bold would thicken it again.
274
+ const style = (bold && !(font && font.weight >= 600) ? 'bold' : '') + (italic && !(font && font.italic) ? 'italic' : '');
275
+ if (weight || own.has('font-style'))
276
+ result.push(['-unity-font-style', style === 'bolditalic' ? 'bold-and-italic' : style || 'normal']);
277
+ return result;
278
+ };
279
+ const uss = [
280
+ '/* Written by scenoco-unity from index.html, every export: edit the page, not this. */',
281
+ '/* UI Toolkit\'s own look, taken off as the page takes the browser\'s off its buttons. */',
282
+ '.unity-button { margin: 0; padding: 0; border-width: 0; border-radius: 0; background-color: rgba(0, 0, 0, 0); }',
283
+ '.unity-label { margin: 0; padding: 0; }',
284
+ '/* The page\'s UIDocument sizes its element to the panel; here the element fills it. */',
285
+ 'TemplateContainer { flex-grow: 1; }',
286
+ ...roots.map((r) => `#${r.attrs.id} { position: absolute; left: 0; top: 0; right: 0; bottom: 0; }`),
287
+ ];
288
+ for (const rule of parsed.rules) {
289
+ // A rule for the page around the game — html, body, the canvas, the loading screen — has no element here.
290
+ // Classes are kept whether or not the page as written has them: code puts them on as the game runs.
291
+ const ids = new Set([...inside].map((e) => e.attrs.id).filter(Boolean));
292
+ const kept = rule.selectors.filter((sel) => [...sel.matchAll(/#([\w-]+)/g)].every((m) => ids.has(m[1])) && !/(^|[\s>])(html|body|canvas|head)\b/.test(sel));
293
+ if (kept.length === 0)
294
+ continue;
295
+ const declarations = respell(rule);
296
+ if (declarations.length)
297
+ uss.push(`${kept.join(', ')} {\n${declarations.map(([p, v]) => ` ${p}: ${v};\n`).join('')}}`);
298
+ }
299
+ out.files.set('Assets/UI/Page.uss', uss.join('\n') + '\n');
300
+ out.files.set('Assets/UI/Theme.tss', '@import url("unity-theme://default");\n');
301
+ for (const face of parsed.fontFaces) {
302
+ const family = /font-family\s*:\s*['"]?([^;'"]+)/.exec(face)?.[1];
303
+ const local = /url\(([^)]+)\)/.exec(face)?.[1]?.replace(/['"]/g, '');
304
+ const ttf = local && [join(root, 'public', local.replace(/\.woff2?$/, '.ttf')), join(root, 'public', local.replace(/\.woff2?$/, '.otf'))].find((f) => existsSync(f));
305
+ if (ttf)
306
+ out.copies.set(ttf, `Assets/UI/Fonts/${basename(ttf)}`);
307
+ else
308
+ out.warnings.push(`index.html: the font "${family}" is ${local} — Unity imports .ttf and .otf, not .woff2. Put its .ttf beside it and export again.`);
309
+ }
310
+ // --- UXML ------------------------------------------------------------------------------------
311
+ const element = (e, indent) => {
312
+ const kids = e.children.filter((c) => c.tag !== 'template' && c.tag !== 'script');
313
+ // A div that holds text, or may: code sets textContent at run time, and only a Label shows text.
314
+ const tag = e.tag === 'button' ? 'ui:Button' : e.tag === 'div' && (e.text || kids.length === 0) ? 'ui:Label' : 'ui:VisualElement';
315
+ const attrs = [];
316
+ if (e.attrs.id)
317
+ attrs.push(`name="${escape(e.attrs.id)}"`);
318
+ if (e.attrs.class)
319
+ attrs.push(`class="${escape(e.attrs.class)}"`);
320
+ if (e.text)
321
+ attrs.push(`text="${escape(e.text)}"`);
322
+ if (e.attrs.style)
323
+ attrs.push(`style="${escape(e.attrs.style)}"`);
324
+ if (!pickable(e))
325
+ attrs.push('picking-mode="Ignore"');
326
+ if (!['div', 'button'].includes(e.tag))
327
+ out.warnings.push(`index.html: <${e.tag}> is not UI Toolkit's — written as a VisualElement.`);
328
+ const head = `${indent}<${tag}${attrs.length ? ' ' + attrs.join(' ') : ''}`;
329
+ if (kids.length === 0)
330
+ return [`${head} />`];
331
+ return [`${head}>`, ...kids.flatMap((k) => element(k, indent + ' ')), `${indent}</${tag}>`];
332
+ };
333
+ const uxml = (e) => ['<ui:UXML xmlns:ui="UnityEngine.UIElements">', ' <Style src="project://database/Assets/UI/Page.uss" />', ...element(e, ' '), '</ui:UXML>', ''].join('\n');
334
+ for (const r of roots) {
335
+ const path = `Assets/UI/${r.attrs.id}.uxml`;
336
+ out.files.set(path, uxml(r));
337
+ out.documents.set(r.attrs.id, path);
338
+ }
339
+ for (const t of templates) {
340
+ const content = t.children.filter((c) => c.tag !== 'script');
341
+ if (content.length !== 1)
342
+ out.warnings.push(`index.html: <template id="${t.attrs.id}"> holds ${content.length} elements — a template's UXML holds its first.`);
343
+ if (content[0])
344
+ out.files.set(`Assets/UI/${t.attrs.id}.uxml`, uxml(content[0]));
345
+ }
346
+ return out;
347
+ }
package/dist/stub.d.ts ADDED
@@ -0,0 +1,45 @@
1
+ /** One member of the class, as written. */
2
+ interface Member {
3
+ kind: 'field' | 'method' | 'get' | 'set' | 'constructor';
4
+ name: string;
5
+ isStatic: boolean;
6
+ access: 'public' | 'private' | 'protected';
7
+ /** The member's own text, from its first modifier to its end. */
8
+ text: string;
9
+ /** Its doc comment's lines, without the comment markers. */
10
+ doc: string[];
11
+ /** A method's: what comes before its body, and its body's lines. */
12
+ head?: string;
13
+ body?: string[];
14
+ params?: {
15
+ name: string;
16
+ type: string;
17
+ }[];
18
+ returns?: string;
19
+ }
20
+ export interface ClassSource {
21
+ doc: string[];
22
+ /** The class it extends, as written. */
23
+ base?: string;
24
+ members: Member[];
25
+ }
26
+ /** The class `name` declared in `code`, or undefined when it is not there. */
27
+ export declare function readClass(code: string, file: string, name: string): ClassSource | undefined;
28
+ /**
29
+ * A module's code outside the classes named — its imports left out too: the interfaces, types,
30
+ * constants and functions a behaviour's file holds beside it, which no stub carries.
31
+ */
32
+ export declare function outsideClasses(code: string, file: string, classes: string[]): string[];
33
+ /** A module no behaviour lives in, as a `.cs` holding its TypeScript for a port to write. */
34
+ export declare function moduleStub(file: string, code: string): string;
35
+ /**
36
+ * A TypeScript type as C#, where the type says it: `number` is `float`, a node is its `Transform`,
37
+ * an element of the page is a `VisualElement`. Undefined when it does not.
38
+ */
39
+ export declare function csType(ts: string, classes: Map<string, string>): string | undefined;
40
+ /**
41
+ * The C# class for a behaviour: `wired` are the fields its scenes and prefabs set — real fields, with
42
+ * the C# the exporter already chose for them — and everything else comes from its TypeScript.
43
+ */
44
+ export declare function stubClass(name: string, file: string, source: ClassSource, wired: Map<string, string>, classes: Map<string, string>, outside?: string[]): string;
45
+ export {};