mock: 仮決定に沿ってモックを実装する(PHY Editor・IDX・ELC・MAP・Generator)
provisional/decisions.md の仮決定(T-1〜T-28)に従い、mock/ に Vue 3 + Vite + TypeScript のモックを置いた。 T-3 の1〜3(回転したクラスター内のドラッグと保存の往復、IDX・MAPとの連携、ELCと出力の対応表)まで。疑似デバイスとの往復(T-24)は未着手。 - KLE JSONの入出力は、KLE本家の serial.js の deserialize の結果を期待値とする fixture(tests/fixtures/kle-oracle.json)で照合した。本家のコードは取り込んでいない(T-7) - 基本キーコードの表は QMK の data/constants/keycodes/keycodes_0.0.1_basic.hjson(1e340cd)から抽出した - 実装は Codex(Luna)、レビューは Codex(Sol)。検証: Vitest 53件、Playwright 20件、vue-tsc、vite build - TypeScript は vue-tsc が 7 系に未対応のため 6 系に固定した - 操作性の改善(ELCの提供者の表示、一括配線とGeneratorのピン設定の引き継ぎ、キー内の文字のはみ出し)は別途行う Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AATqjRyp6rrnwTNdYw8XBT
This commit is contained in:
@@ -0,0 +1,129 @@
|
||||
import type { ProjectFile } from "./project";
|
||||
import type { Node, Variant, VariantGroupNode } from "./phy";
|
||||
|
||||
export type CascadeReference = { layer: "idx" | "elc" | "map" | "ledChains"; location: string; id: string };
|
||||
type DeleteTarget =
|
||||
{ kind: "node"; node: Node } | { kind: "variant"; variant: Variant; group: VariantGroupNode };
|
||||
|
||||
function descendants(node: Node | Variant): string[] {
|
||||
const ids = [node.id];
|
||||
if (node.type === "cluster") node.children.forEach((child) => ids.push(...descendants(child)));
|
||||
if (node.type === "variantGroup") for (const variant of node.children) ids.push(...descendants(variant));
|
||||
if (node.type === "variant") node.children.forEach((child) => ids.push(...descendants(child)));
|
||||
return ids;
|
||||
}
|
||||
|
||||
/** Lists all saved references to a PHY node, Variant, and its descendants. T-15. */
|
||||
export function listDeleteReferences(p: ProjectFile, nodeId: string): CascadeReference[] {
|
||||
const target = findTarget(p.phy.root, nodeId);
|
||||
if (!target) throw new Error(`Unknown node: ${nodeId}`);
|
||||
const ids = new Set(descendants(target.kind === "node" ? target.node : target.variant));
|
||||
const out: CascadeReference[] = [];
|
||||
p.idx.order.forEach((id) => {
|
||||
if (ids.has(id)) out.push({ layer: "idx", location: "/idx/order", id });
|
||||
});
|
||||
p.elc.keys.forEach((w, i) => {
|
||||
if (ids.has(w.key)) out.push({ layer: "elc", location: `/elc/keys/${i}`, id: w.key });
|
||||
});
|
||||
p.elc.ledChains?.forEach((chain) =>
|
||||
chain.order.forEach((id) => {
|
||||
if (ids.has(id)) out.push({ layer: "ledChains", location: `/elc/ledChains/${chain.id}`, id });
|
||||
}),
|
||||
);
|
||||
p.map.layers.forEach((layer) =>
|
||||
layer.keymap.forEach((assignment) => {
|
||||
if (ids.has(assignment.keyId))
|
||||
out.push({ layer: "map", location: `/map/layers/${layer.name}`, id: assignment.keyId });
|
||||
}),
|
||||
);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Removes a PHY node or Variant and its references in one immutable project result. T-15. */
|
||||
export function deleteNodeCascade(p: ProjectFile, nodeId: string): ProjectFile {
|
||||
const o = structuredClone(p);
|
||||
const target = findTarget(o.phy.root, nodeId);
|
||||
if (!target) throw new Error(`Unknown node: ${nodeId}`);
|
||||
const deletedIds = new Set(descendants(target.kind === "node" ? target.node : target.variant));
|
||||
removeTarget(o.phy.root, target);
|
||||
|
||||
o.idx.order = o.idx.order.filter((id) => !deletedIds.has(id));
|
||||
o.elc.keys = o.elc.keys.filter((w) => !deletedIds.has(w.key));
|
||||
if (o.elc.ledChains)
|
||||
o.elc.ledChains = o.elc.ledChains.map((chain) => ({
|
||||
...chain,
|
||||
order: chain.order.filter((id) => !deletedIds.has(id)),
|
||||
}));
|
||||
o.map.layers = o.map.layers.map((layer) => ({
|
||||
...layer,
|
||||
keymap: layer.keymap.filter((assignment) => !deletedIds.has(assignment.keyId)),
|
||||
}));
|
||||
|
||||
if (target.kind === "variant") {
|
||||
if (target.group.default === nodeId) target.group.default = target.group.children[0]!.id;
|
||||
if (o.output.variantSelection[target.group.id] === nodeId)
|
||||
o.output.variantSelection[target.group.id] = target.group.default;
|
||||
}
|
||||
pruneVariantSelection(o);
|
||||
return o;
|
||||
}
|
||||
|
||||
function findTarget(nodes: Node[], id: string): DeleteTarget | undefined {
|
||||
for (const node of nodes) {
|
||||
if (node.id === id) return { kind: "node", node };
|
||||
if (node.type === "cluster") {
|
||||
const found = findTarget(node.children, id);
|
||||
if (found) return found;
|
||||
}
|
||||
if (node.type === "variantGroup")
|
||||
for (const variant of node.children) {
|
||||
if (variant.id === id) return { kind: "variant", variant, group: node };
|
||||
const found = findTarget(variant.children, id);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function removeTarget(nodes: Node[], target: DeleteTarget): void {
|
||||
const id = target.kind === "node" ? target.node.id : target.variant.id;
|
||||
if (target.kind === "variant") {
|
||||
const { group, variant } = target;
|
||||
if (group.children.length <= 2)
|
||||
throw new Error("Cannot delete a variant leaving fewer than two variants");
|
||||
group.children.splice(group.children.indexOf(variant), 1);
|
||||
if (group.default === id) group.default = group.children[0]!.id;
|
||||
return;
|
||||
}
|
||||
const index = nodes.findIndex((node) => node.id === id);
|
||||
if (index >= 0) {
|
||||
nodes.splice(index, 1);
|
||||
return;
|
||||
}
|
||||
for (const node of nodes) {
|
||||
if (node.type === "cluster") removeTarget(node.children, target);
|
||||
if (node.type === "variantGroup")
|
||||
for (const variant of node.children) removeTarget(variant.children, target);
|
||||
}
|
||||
}
|
||||
|
||||
function pruneVariantSelection(project: ProjectFile): void {
|
||||
const valid = new Map<string, { ids: Set<string>; defaultId: string }>();
|
||||
const walk = (nodes: Node[]) =>
|
||||
nodes.forEach((node) => {
|
||||
if (node.type === "cluster") walk(node.children);
|
||||
if (node.type === "variantGroup") {
|
||||
valid.set(node.id, {
|
||||
ids: new Set(node.children.map((variant) => variant.id)),
|
||||
defaultId: node.default,
|
||||
});
|
||||
node.children.forEach((variant) => walk(variant.children));
|
||||
}
|
||||
});
|
||||
walk(project.phy.root);
|
||||
for (const [groupId, variantId] of Object.entries(project.output.variantSelection)) {
|
||||
const group = valid.get(groupId);
|
||||
if (!group) delete project.output.variantSelection[groupId];
|
||||
else if (!group.ids.has(variantId)) project.output.variantSelection[groupId] = group.defaultId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import type { PhyReference } from "./idx";
|
||||
export type PinRef = string;
|
||||
export type McuProvider = { id: string; kind: "mcu"; part: string; [key: string]: unknown };
|
||||
export type AnalogMuxProvider = {
|
||||
id: string;
|
||||
kind: "analog-mux";
|
||||
channels: number;
|
||||
select: PinRef[];
|
||||
common: PinRef;
|
||||
enable?: PinRef;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
export type ContactWiring = {
|
||||
key: string;
|
||||
detect: "contact";
|
||||
terminals: { a: PinRef; b: PinRef };
|
||||
diode?: "a-to-b" | "b-to-a";
|
||||
[key: string]: unknown;
|
||||
};
|
||||
export type AnalogWiring = {
|
||||
key: string;
|
||||
detect: "analog";
|
||||
terminals: { out: PinRef; vcc: PinRef; gnd: PinRef };
|
||||
[key: string]: unknown;
|
||||
};
|
||||
export type KeyWiring = ContactWiring | AnalogWiring;
|
||||
export type LedChain = { id: string; data: PinRef; order: string[]; [key: string]: unknown };
|
||||
export type ElcFile = {
|
||||
version: string;
|
||||
phyReference: PhyReference;
|
||||
providers: (McuProvider | AnalogMuxProvider)[];
|
||||
keys: KeyWiring[];
|
||||
ledChains?: LedChain[];
|
||||
[key: string]: unknown;
|
||||
};
|
||||
/** Returns RP2040 GPIO pin suggestions, or no fixed list for unknown parts. T-26. */
|
||||
export function mcuPinCandidates(provider: McuProvider): string[] {
|
||||
return provider.part.toUpperCase() === "RP2040" ? Array.from({ length: 30 }, (_, i) => `GP${i}`) : [];
|
||||
}
|
||||
/** Creates an empty ELC file. */
|
||||
export function createElc(ref: PhyReference): ElcFile {
|
||||
return { version: "0.1.0", phyReference: structuredClone(ref), providers: [], keys: [], ledChains: [] };
|
||||
}
|
||||
/** Adds or replaces provider settings, rejecting IDs that conflict with PinRef syntax. T-26. */
|
||||
export function setProvider(elc: ElcFile, p: McuProvider | AnalogMuxProvider): ElcFile {
|
||||
if (!p.id || p.id.includes(".")) throw new Error("Provider ID must be nonempty and cannot contain '.'");
|
||||
const o = structuredClone(elc);
|
||||
const i = o.providers.findIndex((x) => x.id === p.id);
|
||||
if (i < 0) o.providers.push(structuredClone(p));
|
||||
else {
|
||||
const old = o.providers[i]!;
|
||||
const known = new Set(["id", "kind", "part", "channels", "select", "common", "enable"]);
|
||||
const extensions = Object.fromEntries(Object.entries(old).filter(([key]) => !known.has(key)));
|
||||
o.providers[i] = { ...extensions, ...(old.kind === p.kind ? old : {}), ...p } as
|
||||
McuProvider | AnalogMuxProvider;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
/** Removes a provider and its dependent references. */
|
||||
export function removeProvider(elc: ElcFile, id: string): ElcFile {
|
||||
const o = structuredClone(elc),
|
||||
removed = new Set([id]);
|
||||
let changed = true;
|
||||
while (changed) {
|
||||
changed = false;
|
||||
for (const p of o.providers)
|
||||
if (p.kind === "analog-mux" && !removed.has(p.id)) {
|
||||
const refs = [...p.select, p.common, ...(p.enable ? [p.enable] : [])];
|
||||
if (refs.some((ref) => [...removed].some((owner) => ref.startsWith(owner + ".")))) {
|
||||
removed.add(p.id);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
const pin = (s: string) => [...removed].some((owner) => s.startsWith(owner + "."));
|
||||
o.providers = o.providers.filter((p) => !removed.has(p.id));
|
||||
o.keys = o.keys.filter((k) => !Object.values(k.terminals).some((v) => pin(v)));
|
||||
if (o.ledChains) o.ledChains = o.ledChains.filter((c) => !pin(c.data));
|
||||
return o;
|
||||
}
|
||||
/** Adds or edits terminal and diode configuration for a key. */
|
||||
export function setKeyWiring(elc: ElcFile, w: KeyWiring): ElcFile {
|
||||
const o = structuredClone(elc);
|
||||
const i = o.keys.findIndex((x) => x.key === w.key);
|
||||
if (i < 0) o.keys.push(structuredClone(w));
|
||||
else {
|
||||
const old = o.keys[i]!;
|
||||
const known = new Set(["key", "detect", "terminals", "diode"]);
|
||||
const extensions = Object.fromEntries(Object.entries(old).filter(([key]) => !known.has(key)));
|
||||
const knownTerminals = old.detect === "contact" ? new Set(["a", "b"]) : new Set(["out", "vcc", "gnd"]);
|
||||
const terminalExtensions = Object.fromEntries(
|
||||
Object.entries(old.terminals).filter(([key]) => !knownTerminals.has(key)),
|
||||
);
|
||||
const updated = {
|
||||
...extensions,
|
||||
...(old.detect === w.detect ? old : {}),
|
||||
...w,
|
||||
terminals: { ...terminalExtensions, ...(old.detect === w.detect ? old.terminals : {}), ...w.terminals },
|
||||
} as KeyWiring;
|
||||
if (w.detect === "contact" && w.diode === undefined) delete (updated as ContactWiring).diode;
|
||||
o.keys[i] = updated;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
/** Removes wiring for a key. */
|
||||
export function removeKeyWiring(elc: ElcFile, keyId: string): ElcFile {
|
||||
const o = structuredClone(elc);
|
||||
o.keys = o.keys.filter((x) => x.key !== keyId);
|
||||
return o;
|
||||
}
|
||||
/** Returns keys without any ELC entry. */
|
||||
export function unwiredKeys(keyIds: string[], elc: ElcFile): string[] {
|
||||
const wired = new Set(elc.keys.map((k) => k.key));
|
||||
return keyIds.filter((k) => !wired.has(k));
|
||||
}
|
||||
/** Creates an LED chain with an independent ordered node list. T-11. */
|
||||
export function createLedChain(elc: ElcFile, id: string, data: PinRef): ElcFile {
|
||||
const o = structuredClone(elc);
|
||||
o.ledChains ??= [];
|
||||
if (o.ledChains.some((c) => c.id === id)) throw new Error("Duplicate LED chain ID");
|
||||
o.ledChains.push({ id, data, order: [] });
|
||||
return o;
|
||||
}
|
||||
/** Replaces LED order while preserving the chain's other fields. */
|
||||
export function setLedOrder(elc: ElcFile, id: string, order: string[]): ElcFile {
|
||||
const o = structuredClone(elc);
|
||||
const c = o.ledChains?.find((x) => x.id === id);
|
||||
if (!c) throw new Error("Unknown LED chain");
|
||||
c.order = [...order];
|
||||
return o;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { setKeyWiring, type ContactWiring, type ElcFile } from "./elc";
|
||||
|
||||
/** Assigns a row-major matrix to the supplied keys. The input order is preserved. */
|
||||
export function wireMatrixKeys(
|
||||
elc: ElcFile,
|
||||
keyIds: string[],
|
||||
rowPins: string[],
|
||||
colPins: string[],
|
||||
diode?: "a-to-b" | "b-to-a",
|
||||
): ElcFile {
|
||||
if (!rowPins.length || !colPins.length) throw new Error("rowPins and colPins are required");
|
||||
if (keyIds.length > rowPins.length * colPins.length)
|
||||
throw new Error("Matrix does not have enough row/column positions");
|
||||
let next = elc;
|
||||
keyIds.forEach((key, i) => {
|
||||
const wiring: ContactWiring = {
|
||||
key,
|
||||
detect: "contact",
|
||||
terminals: { a: rowPins[Math.floor(i / colPins.length)]!, b: colPins[i % colPins.length]! },
|
||||
...(diode ? { diode } : {}),
|
||||
};
|
||||
// Keep unknown extension fields on an existing ELC entry, just like normal edits.
|
||||
next = setKeyWiring(next, wiring);
|
||||
});
|
||||
return next;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import type { ProjectFile } from "./project";
|
||||
import { flattenKeys } from "./geometry";
|
||||
import { validateProject, type ValidationIssue } from "./validate";
|
||||
export type MockTarget = {
|
||||
format: "mock-target";
|
||||
version: "0.1.0";
|
||||
layout: Array<{ keyId: string; x: number; y: number; rotation: number; w: number; h: number }>;
|
||||
idx: string[];
|
||||
matrix: { rowPins: string[]; colPins: string[]; rows: number[]; cols: number[] };
|
||||
keymaps: Array<{ name: string; keycodes: string[] }>;
|
||||
mapping: Array<{ number: number; keyId: string; row: number; col: number; label: string }>;
|
||||
};
|
||||
export type GeneratorResult = { target?: MockTarget; errors: ValidationIssue[] };
|
||||
/** Generates preview output after validation, without modifying the project. T-2/T-19. */
|
||||
export function generateMockTarget(p: ProjectFile): GeneratorResult {
|
||||
const errors = validateProject(p).filter(
|
||||
(x) => x.severity === "blocksOutput" || x.severity === "blocksSave",
|
||||
);
|
||||
if (!p.output.matrix)
|
||||
errors.push({
|
||||
severity: "blocksOutput",
|
||||
code: "matrix-settings-missing",
|
||||
message: "Matrix rowPins and colPins must be configured",
|
||||
});
|
||||
if (p.output.matrix?.kind && p.output.matrix.kind !== "matrix")
|
||||
errors.push({
|
||||
severity: "blocksOutput",
|
||||
code: "unsupported-scan-mode",
|
||||
message: `${p.output.matrix.kind} scan mode is not supported`,
|
||||
});
|
||||
if (errors.length) return { errors };
|
||||
const selected = flattenKeys(p.phy, p.output.variantSelection),
|
||||
active = new Set(selected.map((x) => x.key.id)),
|
||||
order = p.idx.order.filter((id) => active.has(id)),
|
||||
matrix = p.output.matrix!;
|
||||
const rowIndex = new Map(matrix.rowPins.map((x, i) => [x, i])),
|
||||
colIndex = new Map(matrix.colPins.map((x, i) => [x, i]));
|
||||
const wiring = new Map(p.elc.keys.map((x) => [x.key, x]));
|
||||
const row: number[] = [],
|
||||
col: number[] = [];
|
||||
for (const id of order) {
|
||||
const w = wiring.get(id);
|
||||
if (!w || w.detect !== "contact")
|
||||
return {
|
||||
errors: [
|
||||
{
|
||||
severity: "blocksOutput",
|
||||
code: "unsupported-detection",
|
||||
message: "Only contact matrix wiring is supported",
|
||||
ids: [id],
|
||||
},
|
||||
],
|
||||
};
|
||||
const a = w.terminals.a,
|
||||
b = w.terminals.b;
|
||||
let r: number | undefined, c: number | undefined;
|
||||
if (rowIndex.has(a) && colIndex.has(b)) {
|
||||
r = rowIndex.get(a);
|
||||
c = colIndex.get(b);
|
||||
} else if (rowIndex.has(b) && colIndex.has(a)) {
|
||||
r = rowIndex.get(b);
|
||||
c = colIndex.get(a);
|
||||
}
|
||||
if (r === undefined || c === undefined)
|
||||
return {
|
||||
errors: [
|
||||
{
|
||||
severity: "blocksOutput",
|
||||
code: "unsupported-matrix-wiring",
|
||||
message: "Wiring is not a supported row/column matrix",
|
||||
ids: [id],
|
||||
},
|
||||
],
|
||||
};
|
||||
row.push(r);
|
||||
col.push(c);
|
||||
}
|
||||
const poses = new Map(selected.map((x) => [x.key.id, x]));
|
||||
const keymaps = p.map.layers.map((l) => ({
|
||||
name: l.name,
|
||||
keycodes: order.map((id) => l.keymap.find((a) => a.keyId === id)!.keycode),
|
||||
}));
|
||||
const target: MockTarget = {
|
||||
format: "mock-target",
|
||||
version: "0.1.0",
|
||||
layout: order.map((id) => {
|
||||
const x = poses.get(id)!;
|
||||
return { keyId: id, x: x.x, y: x.y, rotation: x.rotation, w: x.key.size.w, h: x.key.size.h };
|
||||
}),
|
||||
idx: order,
|
||||
matrix: { rowPins: [...matrix.rowPins], colPins: [...matrix.colPins], rows: row, cols: col },
|
||||
keymaps,
|
||||
mapping: order.map((id, i) => ({
|
||||
number: i,
|
||||
keyId: id,
|
||||
row: row[i]!,
|
||||
col: col[i]!,
|
||||
label: poses.get(id)!.key.labels?.find(Boolean) ?? "",
|
||||
})),
|
||||
};
|
||||
return { target, errors: [] };
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { FlatKey, Node, PhyFile, Transform } from "./phy";
|
||||
|
||||
/** Translate·Rotate のアフィン行列を返す。 */
|
||||
export function matrix(t: Transform): Affine {
|
||||
const a = (t.rotation * Math.PI) / 180,
|
||||
c = Math.cos(a),
|
||||
s = Math.sin(a);
|
||||
return { a: c, b: s, c: -s, d: c, e: t.x, f: t.y };
|
||||
}
|
||||
export type Affine = { a: number; b: number; c: number; d: number; e: number; f: number };
|
||||
/** 左から右の順でなく、通常の行列積 left·right を返す。 */
|
||||
export function compose(left: Affine, right: Affine): Affine {
|
||||
return {
|
||||
a: left.a * right.a + left.c * right.b,
|
||||
b: left.b * right.a + left.d * right.b,
|
||||
c: left.a * right.c + left.c * right.d,
|
||||
d: left.b * right.c + left.d * right.d,
|
||||
e: left.a * right.e + left.c * right.f + left.e,
|
||||
f: left.b * right.e + left.d * right.f + left.f,
|
||||
};
|
||||
}
|
||||
/** 剛体変換の逆行列を返す。 */
|
||||
export function inverse(m: Affine): Affine {
|
||||
return { a: m.a, b: m.c, c: m.b, d: m.d, e: -(m.a * m.e + m.b * m.f), f: -(m.c * m.e + m.d * m.f) };
|
||||
}
|
||||
/** 点に行列を適用する。 */
|
||||
export function apply(m: Affine, p: { x: number; y: number }): { x: number; y: number } {
|
||||
return { x: m.a * p.x + m.c * p.y + m.e, y: m.b * p.x + m.d * p.y + m.f };
|
||||
}
|
||||
/** PHY ノードのワールド行列を計算する。 */
|
||||
export function worldTransform(file: PhyFile, id: string): Affine {
|
||||
const walk = (nodes: Node[], parent: Affine): Affine | undefined => {
|
||||
for (const n of nodes) {
|
||||
const own = compose(parent, matrix(n.transform));
|
||||
if (n.id === id) return own;
|
||||
if (n.type === "cluster") {
|
||||
const r = walk(n.children, own);
|
||||
if (r) return r;
|
||||
}
|
||||
if (n.type === "variantGroup")
|
||||
for (const v of n.children) {
|
||||
const r = walk(v.children, own);
|
||||
if (r) return r;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
const found = walk(file.root, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
|
||||
if (!found) throw new Error(`Unknown node: ${id}`);
|
||||
return found;
|
||||
}
|
||||
/** 選択したVariantに従いキーを平坦化する。省略時は各Groupのdefaultを使う。 */
|
||||
export function flattenKeys(file: PhyFile, selection: Record<string, string> = {}): FlatKey[] {
|
||||
const out: FlatKey[] = [];
|
||||
const visit = (nodes: Node[], parent: Affine, parentRotation: number, path: string[]) => {
|
||||
for (const n of nodes) {
|
||||
const wm = compose(parent, matrix(n.transform)),
|
||||
p = [...path, n.id],
|
||||
absoluteRotation = parentRotation + n.transform.rotation;
|
||||
if (n.type === "key") out.push({ key: n, x: wm.e, y: wm.f, rotation: absoluteRotation, path: p });
|
||||
else if (n.type === "cluster") visit(n.children, wm, absoluteRotation, p);
|
||||
else if (n.type === "variantGroup") {
|
||||
const v = n.children.find((x) => x.id === (selection[n.id] ?? n.default));
|
||||
if (!v) throw new Error(`Unknown variant for ${n.id}`);
|
||||
visit(v.children, wm, absoluteRotation, [...p, v.id]);
|
||||
}
|
||||
}
|
||||
};
|
||||
visit(file.root, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }, 0, []);
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { ProjectFile } from "./project";
|
||||
/** Snapshot history for whole-project undo/redo. T-17. */
|
||||
export class ProjectHistory {
|
||||
private items: ProjectFile[];
|
||||
private cursor = 0;
|
||||
private pending = false;
|
||||
constructor(
|
||||
initial: ProjectFile,
|
||||
private readonly limit = 100,
|
||||
) {
|
||||
this.items = [structuredClone(initial)];
|
||||
}
|
||||
/** Adds one undoable snapshot unless a grouped edit is active. */
|
||||
push(value: ProjectFile): void {
|
||||
if (this.pending) {
|
||||
this.replaceTop(value);
|
||||
return;
|
||||
}
|
||||
this.add(value);
|
||||
}
|
||||
/** Starts grouping subsequent pushes into a single operation. T-17. */
|
||||
begin(): void {
|
||||
if (this.pending) throw new Error("History group already active");
|
||||
this.items = this.items.slice(0, this.cursor + 1);
|
||||
this.items.push(structuredClone(this.items[this.cursor]!));
|
||||
this.cursor = this.items.length - 1;
|
||||
if (this.items.length > this.limit) {
|
||||
this.items.shift();
|
||||
this.cursor--;
|
||||
}
|
||||
this.pending = true;
|
||||
}
|
||||
/** Commits the final grouped snapshot as one undo step. T-17. */
|
||||
commit(value?: ProjectFile): void {
|
||||
if (!this.pending) throw new Error("No history group active");
|
||||
if (value) this.items[this.cursor] = structuredClone(value);
|
||||
if (JSON.stringify(this.items[this.cursor]) === JSON.stringify(this.items[this.cursor - 1])) {
|
||||
this.items.pop();
|
||||
this.cursor--;
|
||||
}
|
||||
this.pending = false;
|
||||
}
|
||||
/** Replaces the current snapshot during a grouped drag. T-17. */
|
||||
replaceTop(value: ProjectFile): void {
|
||||
this.items[this.cursor] = structuredClone(value);
|
||||
}
|
||||
/** Moves to the previous snapshot. */
|
||||
undo(): ProjectFile {
|
||||
if (!this.canUndo) throw new Error("Nothing to undo");
|
||||
return structuredClone(this.items[--this.cursor]!);
|
||||
}
|
||||
/** Moves to the next snapshot. */
|
||||
redo(): ProjectFile {
|
||||
if (!this.canRedo) throw new Error("Nothing to redo");
|
||||
return structuredClone(this.items[++this.cursor]!);
|
||||
}
|
||||
get canUndo(): boolean {
|
||||
return this.cursor > 0;
|
||||
}
|
||||
get canRedo(): boolean {
|
||||
return this.cursor < this.items.length - 1;
|
||||
}
|
||||
/** Returns a copy of the current snapshot. */
|
||||
current(): ProjectFile {
|
||||
return structuredClone(this.items[this.cursor]!);
|
||||
}
|
||||
private add(value: ProjectFile) {
|
||||
this.items = this.items.slice(0, this.cursor + 1);
|
||||
this.items.push(structuredClone(value));
|
||||
this.cursor = this.items.length - 1;
|
||||
if (this.items.length > this.limit) {
|
||||
this.items.shift();
|
||||
this.cursor--;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/** T-11: UUID先頭12文字を種別接頭辞に付ける。生成器を注入できる。 */
|
||||
export function createId(prefix: string, uuid: () => string = () => globalThis.crypto.randomUUID()): string {
|
||||
return `${prefix}${uuid().replaceAll("-", "").slice(0, 12)}`;
|
||||
}
|
||||
/** T-11: ノード種別ごとのIDを生成する。 */
|
||||
export function createNodeId(
|
||||
kind: "key" | "cluster" | "component" | "variantGroup" | "variant",
|
||||
uuid?: () => string,
|
||||
): string {
|
||||
return createId(
|
||||
{ key: "key-", cluster: "cl-", component: "cmp-", variantGroup: "vg-", variant: "v-" }[kind],
|
||||
uuid,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { PhyFile, Node, KeyNode } from "./phy";
|
||||
export type PhyReference = { source: string; checksum: string; [key: string]: unknown };
|
||||
export type IdxFile = {
|
||||
version: string;
|
||||
phyReference: PhyReference;
|
||||
order: string[];
|
||||
[key: string]: unknown;
|
||||
};
|
||||
/** Collects keys in document order, including ghost keys and excluding decals. T-18. */
|
||||
export function eligibleKeyIds(phy: PhyFile): string[] {
|
||||
const ids: string[] = [];
|
||||
const visit = (nodes: Node[]) =>
|
||||
nodes.forEach((n) => {
|
||||
if (n.type === "key") {
|
||||
if (!n.decal) ids.push(n.id);
|
||||
} else if (n.type === "cluster") visit(n.children);
|
||||
else if (n.type === "variantGroup") n.children.forEach((v) => visit(v.children));
|
||||
});
|
||||
visit(phy.root);
|
||||
return ids;
|
||||
}
|
||||
/** Makes initial index order from KLE occurrence order. T-18. */
|
||||
export function createIdx(phy: PhyFile, keyOrder: string[], phyReference: PhyReference): IdxFile {
|
||||
const valid = new Set(eligibleKeyIds(phy));
|
||||
return {
|
||||
version: "0.1.0",
|
||||
phyReference: structuredClone(phyReference),
|
||||
order: keyOrder.filter((id) => valid.has(id)),
|
||||
};
|
||||
}
|
||||
/** Lists eligible PHY keys omitted from the saved order. T-18. */
|
||||
export function unregisteredKeys(phy: PhyFile, idx: IdxFile): string[] {
|
||||
const registered = new Set(idx.order);
|
||||
return eligibleKeyIds(phy).filter((id) => !registered.has(id));
|
||||
}
|
||||
/** Registers new keys at the end without rebuilding existing order. T-18. */
|
||||
export function appendKeys(idx: IdxFile, ids: string[]): IdxFile {
|
||||
const out = structuredClone(idx);
|
||||
for (const id of ids) if (!out.order.includes(id)) out.order.push(id);
|
||||
return out;
|
||||
}
|
||||
/** Removes one key from index order. */
|
||||
export function excludeKey(idx: IdxFile, keyId: string): IdxFile {
|
||||
const o = structuredClone(idx);
|
||||
o.order = o.order.filter((x) => x !== keyId);
|
||||
return o;
|
||||
}
|
||||
/** Reorders the saved key list. */
|
||||
export function reorderKeys(idx: IdxFile, order: string[]): IdxFile {
|
||||
if (
|
||||
order.length !== idx.order.length ||
|
||||
new Set(order).size !== order.length ||
|
||||
order.some((x) => !idx.order.includes(x))
|
||||
)
|
||||
throw new Error("Order must contain every registered key exactly once");
|
||||
return { ...structuredClone(idx), order: [...order] };
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { qmkBasicKeycodes } from "./qmkBasicKeycodes";
|
||||
|
||||
/** Small US keyboard display map for common QMK basic keys. T-23. */
|
||||
export const keycodeLabels: Record<string, string> = {
|
||||
KC_A: "A",
|
||||
KC_B: "B",
|
||||
KC_C: "C",
|
||||
KC_D: "D",
|
||||
KC_E: "E",
|
||||
KC_F: "F",
|
||||
KC_G: "G",
|
||||
KC_H: "H",
|
||||
KC_I: "I",
|
||||
KC_J: "J",
|
||||
KC_K: "K",
|
||||
KC_L: "L",
|
||||
KC_M: "M",
|
||||
KC_N: "N",
|
||||
KC_O: "O",
|
||||
KC_P: "P",
|
||||
KC_Q: "Q",
|
||||
KC_R: "R",
|
||||
KC_S: "S",
|
||||
KC_T: "T",
|
||||
KC_U: "U",
|
||||
KC_V: "V",
|
||||
KC_W: "W",
|
||||
KC_X: "X",
|
||||
KC_Y: "Y",
|
||||
KC_Z: "Z",
|
||||
KC_1: "1",
|
||||
KC_2: "2",
|
||||
KC_3: "3",
|
||||
KC_4: "4",
|
||||
KC_5: "5",
|
||||
KC_6: "6",
|
||||
KC_7: "7",
|
||||
KC_8: "8",
|
||||
KC_9: "9",
|
||||
KC_0: "0",
|
||||
KC_SPC: "Space",
|
||||
KC_ENTER: "Enter",
|
||||
KC_ESC: "Escape",
|
||||
KC_TAB: "Tab",
|
||||
KC_MINUS: "-",
|
||||
KC_EQUAL: "=",
|
||||
KC_LBRC: "[",
|
||||
KC_RBRC: "]",
|
||||
KC_BSLS: "\\",
|
||||
KC_SCLN: ";",
|
||||
KC_QUOT: "'",
|
||||
KC_GRV: "`",
|
||||
KC_COMM: ",",
|
||||
KC_DOT: ".",
|
||||
KC_SLSH: "/",
|
||||
};
|
||||
|
||||
const qmkCodeByName = new Map(
|
||||
qmkBasicKeycodes.flatMap((entry) =>
|
||||
[entry.key, ...entry.aliases].map((name) => [name, entry.key] as const),
|
||||
),
|
||||
);
|
||||
|
||||
/** Looks up the existing US display label, resolving a QMK alias to its formal name. */
|
||||
export function getKeycodeLabel(code: string): string | undefined {
|
||||
const formalName = qmkCodeByName.get(code);
|
||||
if (!formalName) return keycodeLabels[code];
|
||||
return (
|
||||
keycodeLabels[code] ??
|
||||
keycodeLabels[formalName] ??
|
||||
qmkBasicKeycodes
|
||||
.find((entry) => entry.key === formalName)
|
||||
?.aliases.map((alias) => keycodeLabels[alias])
|
||||
.find((label): label is string => label !== undefined)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import type { PhyReference } from "./idx";
|
||||
import { qmkBasicKeycodes } from "./qmkBasicKeycodes";
|
||||
export type KeyAssignment = { keyId: string; keycode: string; [key: string]: unknown };
|
||||
export type MapLayer = { name: string; keymap: KeyAssignment[]; [key: string]: unknown };
|
||||
export type MapFile = {
|
||||
version: string;
|
||||
phyReference: PhyReference;
|
||||
layers: MapLayer[];
|
||||
[key: string]: unknown;
|
||||
};
|
||||
export type ParsedKeycode = {
|
||||
kind: "basic" | "modifier" | "none" | "transparent" | "layer" | "modified" | "unknown";
|
||||
code: string;
|
||||
layer?: string;
|
||||
inner?: ParsedKeycode;
|
||||
};
|
||||
const codesFor = (groups: QmkKeyGroup[]) =>
|
||||
new Set(
|
||||
qmkBasicKeycodes
|
||||
.filter((keycode) => groups.includes(keycode.group))
|
||||
.flatMap(({ key, aliases }) => [key, ...aliases]),
|
||||
);
|
||||
type QmkKeyGroup = (typeof qmkBasicKeycodes)[number]["group"];
|
||||
const codesForKey = (key: string) => {
|
||||
const entry = qmkBasicKeycodes.find((keycode) => keycode.key === key);
|
||||
return new Set(entry ? [entry.key, ...entry.aliases] : []);
|
||||
};
|
||||
const basic = codesFor(["basic"]);
|
||||
const modifiers = codesFor(["modifiers"]);
|
||||
const noneCodes = codesForKey("KC_NO");
|
||||
const transparentCodes = codesForKey("KC_TRANSPARENT");
|
||||
/** Parses supported QMK keycode syntax without evaluation. T-22. */
|
||||
export function parseKeycode(s: string): ParsedKeycode {
|
||||
const m = s.match(/^(MO|TG|TO|TT|DF|OSL)\(([^()]+)\)$/);
|
||||
if (m) return { kind: "layer", code: m[1]!, layer: m[2]! };
|
||||
const lt = s.match(/^LT\(([^(),]+),\s*([A-Za-z0-9_]+)\)$/);
|
||||
if (lt) return { kind: "layer", code: "LT", layer: lt[1]!, inner: parseKeycode(lt[2]!) };
|
||||
const mod = s.match(/^(LCTL|LSFT|LALT|LGUI|RCTL|RSFT|RALT|RGUI)\(([A-Za-z0-9_]+)\)$/);
|
||||
if (mod) return { kind: "modified", code: mod[1]!, inner: parseKeycode(mod[2]!) };
|
||||
if (noneCodes.has(s)) return { kind: "none", code: s };
|
||||
if (transparentCodes.has(s)) return { kind: "transparent", code: s };
|
||||
if (basic.has(s)) return { kind: "basic", code: s };
|
||||
if (modifiers.has(s)) return { kind: "modifier", code: s };
|
||||
return { kind: "unknown", code: s };
|
||||
}
|
||||
|
||||
function simpleEditableKeycode(parsed: ParsedKeycode): boolean {
|
||||
return (
|
||||
parsed.kind === "basic" ||
|
||||
parsed.kind === "modifier" ||
|
||||
parsed.kind === "none" ||
|
||||
parsed.kind === "transparent"
|
||||
);
|
||||
}
|
||||
|
||||
/** Returns whether a keycode uses syntax editable under T-22. */
|
||||
export function isEditableKeycode(keycode: string): boolean {
|
||||
const parsed = parseKeycode(keycode);
|
||||
if (parsed.kind === "unknown") return false;
|
||||
if (parsed.kind === "modified") return !!parsed.inner && simpleEditableKeycode(parsed.inner);
|
||||
if (parsed.kind === "layer")
|
||||
return parsed.code !== "LT" || (!!parsed.inner && simpleEditableKeycode(parsed.inner));
|
||||
return true;
|
||||
}
|
||||
/** Creates a MAP with one empty Base layer. T-22. */
|
||||
export function createMap(ref: PhyReference): MapFile {
|
||||
return { version: "0.1.0", phyReference: structuredClone(ref), layers: [{ name: "Base", keymap: [] }] };
|
||||
}
|
||||
/** Adds a uniquely named layer. T-22. */
|
||||
export function addLayer(map: MapFile, name: string): MapFile {
|
||||
if (map.layers.some((l) => l.name === name)) throw new Error("Layer name already exists");
|
||||
const o = structuredClone(map);
|
||||
o.layers.push({ name, keymap: [] });
|
||||
return o;
|
||||
}
|
||||
/** Renames a layer and rewrites encoded layer references. T-22. */
|
||||
export function renameLayer(map: MapFile, oldName: string, newName: string): MapFile {
|
||||
if (map.layers.some((l) => l.name === newName)) throw new Error("Layer name already exists");
|
||||
const o = structuredClone(map);
|
||||
const l = o.layers.find((x) => x.name === oldName);
|
||||
if (!l) throw new Error("Unknown layer");
|
||||
l.name = newName;
|
||||
for (const x of o.layers)
|
||||
for (const a of x.keymap) a.keycode = rewriteLayerRef(a.keycode, oldName, newName);
|
||||
return o;
|
||||
}
|
||||
function rewriteLayerRef(s: string, oldName: string, newName: string): string {
|
||||
const p = parseKeycode(s);
|
||||
if (p.kind === "layer" && p.layer === oldName) {
|
||||
if (p.code === "LT") return `LT(${newName}, ${p.inner?.code ?? ""})`;
|
||||
return `${p.code}(${newName})`;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
/** Moves a layer to a new array position. */
|
||||
export function reorderLayer(map: MapFile, name: string, index: number): MapFile {
|
||||
const o = structuredClone(map),
|
||||
i = o.layers.findIndex((x) => x.name === name);
|
||||
if (i < 0) throw new Error("Unknown layer");
|
||||
const [l] = o.layers.splice(i, 1);
|
||||
o.layers.splice(Math.max(0, Math.min(index, o.layers.length)), 0, l!);
|
||||
return o;
|
||||
}
|
||||
/** Deletes an unreferenced layer; references block deletion. T-22. */
|
||||
export function deleteLayer(map: MapFile, name: string): MapFile {
|
||||
if (map.layers.length < 2) throw new Error("At least one layer is required");
|
||||
if (
|
||||
map.layers.some((l) =>
|
||||
l.keymap.some((a) => {
|
||||
const p = parseKeycode(a.keycode);
|
||||
return p.kind === "layer" && p.layer === name;
|
||||
}),
|
||||
)
|
||||
)
|
||||
throw new Error("Layer is referenced");
|
||||
const o = structuredClone(map);
|
||||
o.layers = o.layers.filter((l) => l.name !== name);
|
||||
return o;
|
||||
}
|
||||
/** Assigns a keycode to a key, replacing an existing assignment. T-22. */
|
||||
export function assignKey(map: MapFile, layerName: string, keyId: string, keycode: string): MapFile {
|
||||
if (!isEditableKeycode(keycode)) throw new Error(`Unsupported editable keycode: ${keycode}`);
|
||||
const parsed = parseKeycode(keycode);
|
||||
if (parsed.kind === "layer" && !map.layers.some((layer) => layer.name === parsed.layer))
|
||||
throw new Error(`Unknown MAP layer reference: ${parsed.layer}`);
|
||||
const o = structuredClone(map),
|
||||
l = o.layers.find((x) => x.name === layerName);
|
||||
if (!l) throw new Error("Unknown layer");
|
||||
const i = l.keymap.findIndex((a) => a.keyId === keyId),
|
||||
old = i < 0 ? undefined : l.keymap[i],
|
||||
a = { ...old, keyId, keycode };
|
||||
if (i < 0) l.keymap.push(a);
|
||||
else l.keymap[i] = a;
|
||||
return o;
|
||||
}
|
||||
/** Removes a key assignment. */
|
||||
export function unassignKey(map: MapFile, layerName: string, keyId: string): MapFile {
|
||||
const o = structuredClone(map),
|
||||
l = o.layers.find((x) => x.name === layerName);
|
||||
if (!l) throw new Error("Unknown layer");
|
||||
l.keymap = l.keymap.filter((a) => a.keyId !== keyId);
|
||||
return o;
|
||||
}
|
||||
/** Lists keys not assigned in a layer. T-22. */
|
||||
export function unassignedKeys(map: MapFile, layerName: string, keyIds: string[]): string[] {
|
||||
const l = map.layers.find((x) => x.name === layerName);
|
||||
const assigned = new Set(l?.keymap.map((x) => x.keyId));
|
||||
return keyIds.filter((x) => !assigned?.has(x));
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/** PHY JSON Schema §1 の型。D-1: Schema の必須 type/name/compatibility を採用。 */
|
||||
export type Point = { x: number; y: number };
|
||||
export type Transform = { x: number; y: number; rotation: number };
|
||||
export type Size = { w: number; h: number; x2?: number; y2?: number; w2?: number; h2?: number };
|
||||
export type Profile = {
|
||||
id: string;
|
||||
name: string;
|
||||
unitSize: Point;
|
||||
visualOffset?: { top: number; right: number; bottom: number; left: number; radius: number };
|
||||
};
|
||||
export type KleCompatibility = Record<string, unknown>;
|
||||
export type KeyNode = {
|
||||
type: "key";
|
||||
id: string;
|
||||
profile: string;
|
||||
transform: Transform;
|
||||
size: Size;
|
||||
switchOffset?: Point;
|
||||
partGroup?: string;
|
||||
orientation?: 0 | 90 | 180 | 270;
|
||||
perKeyLED?: boolean;
|
||||
decal?: boolean;
|
||||
ghost?: boolean;
|
||||
labels?: string[];
|
||||
kleCompatibility?: KleCompatibility;
|
||||
};
|
||||
export type ComponentNode = { type: "component"; id: string; transform: Transform; partGroup?: string };
|
||||
export type ClusterNode = {
|
||||
type: "cluster";
|
||||
id: string;
|
||||
name?: string;
|
||||
transform: Transform;
|
||||
children: Node[];
|
||||
};
|
||||
export type Variant = { type: "variant"; id: string; name: string; children: Node[] };
|
||||
export type VariantGroupNode = {
|
||||
type: "variantGroup";
|
||||
id: string;
|
||||
name: string;
|
||||
transform: Transform;
|
||||
default: string;
|
||||
children: Variant[];
|
||||
};
|
||||
export type Node = KeyNode | ComponentNode | ClusterNode | VariantGroupNode;
|
||||
export type PhyFile = {
|
||||
version: string;
|
||||
metadata: { name?: string; author?: string; description?: string; created?: string; modified?: string };
|
||||
profiles: Profile[];
|
||||
root: Node[];
|
||||
kleCompatibility?: KleCompatibility;
|
||||
};
|
||||
|
||||
export type FlatKey = { key: KeyNode; x: number; y: number; rotation: number; path: string[] };
|
||||
@@ -0,0 +1,426 @@
|
||||
import type { ClusterNode, KeyNode, Node, PhyFile, Transform, Variant, VariantGroupNode } from "./phy";
|
||||
import { apply, compose, inverse, matrix } from "./geometry";
|
||||
import { createNodeId } from "./ids";
|
||||
|
||||
const ident = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };
|
||||
type Container = { nodes: Node[]; parentWorld: typeof ident; parentRotation: number };
|
||||
function containers(f: PhyFile): Map<string, Container> {
|
||||
const m = new Map<string, Container>();
|
||||
const rec = (ns: Node[], w: typeof ident, angle: number) => {
|
||||
for (const n of ns) {
|
||||
m.set(n.id, { nodes: ns, parentWorld: w, parentRotation: angle });
|
||||
const nw = compose(w, matrix(n.transform));
|
||||
const nextAngle = angle + n.transform.rotation;
|
||||
if (n.type === "cluster") rec(n.children, nw, nextAngle);
|
||||
if (n.type === "variantGroup")
|
||||
for (const v of n.children) {
|
||||
m.set(v.id, { nodes: v.children, parentWorld: nw, parentRotation: nextAngle });
|
||||
rec(v.children, nw, nextAngle);
|
||||
}
|
||||
}
|
||||
};
|
||||
rec(f.root, ident, 0);
|
||||
return m;
|
||||
}
|
||||
function find(f: PhyFile, id: string): Node {
|
||||
const c = containers(f).get(id);
|
||||
const n = c?.nodes.find((x) => x.id === id);
|
||||
if (!n) throw new Error(`Unknown node: ${id}`);
|
||||
return n;
|
||||
}
|
||||
function world(f: PhyFile, id: string): typeof ident {
|
||||
const c = containers(f).get(id);
|
||||
const n = c?.nodes.find((x) => x.id === id);
|
||||
if (!n) throw new Error(`Unknown node: ${id}`);
|
||||
return compose(c!.parentWorld, matrix(n.transform));
|
||||
}
|
||||
function worldRotation(f: PhyFile, id: string): number {
|
||||
const c = containers(f).get(id);
|
||||
const n = c?.nodes.find((x) => x.id === id);
|
||||
if (!n || !c) throw new Error(`Unknown node: ${id}`);
|
||||
return c.parentRotation + n.transform.rotation;
|
||||
}
|
||||
function mutable(f: PhyFile): PhyFile {
|
||||
return structuredClone(f);
|
||||
}
|
||||
function nodeId(kind: Parameters<typeof createNodeId>[0], gen?: () => string) {
|
||||
return createNodeId(kind, gen);
|
||||
}
|
||||
/** 新しいPHYを返す。T-11。 */
|
||||
export function addKey(
|
||||
f: PhyFile,
|
||||
at: Transform,
|
||||
size: { w: number; h: number },
|
||||
profile = f.profiles[0]!.id,
|
||||
gen?: () => string,
|
||||
): PhyFile {
|
||||
const o = mutable(f);
|
||||
o.root.push({ type: "key", id: nodeId("key", gen), profile, transform: { ...at }, size: { ...size } });
|
||||
return o;
|
||||
}
|
||||
/** 新しいPHYを返す。T-11。 */
|
||||
export function addComponent(f: PhyFile, at: Transform, partGroup?: string, gen?: () => string): PhyFile {
|
||||
const o = mutable(f);
|
||||
o.root.push({
|
||||
type: "component",
|
||||
id: nodeId("component", gen),
|
||||
transform: { ...at },
|
||||
...(partGroup === undefined ? {} : { partGroup }),
|
||||
});
|
||||
return o;
|
||||
}
|
||||
/** ローカル座標の差分でノードを移動する。 */
|
||||
export function moveNode(f: PhyFile, id: string, dx: number, dy: number): PhyFile {
|
||||
const o = mutable(f),
|
||||
n = find(o, id);
|
||||
n.transform.x += dx;
|
||||
n.transform.y += dy;
|
||||
return o;
|
||||
}
|
||||
/** ノードを回転する。 */
|
||||
export function rotateNode(f: PhyFile, id: string, delta: number): PhyFile {
|
||||
const o = mutable(f),
|
||||
n = find(o, id);
|
||||
n.transform.rotation += delta;
|
||||
return o;
|
||||
}
|
||||
/** キーのサイズを変更する。 */
|
||||
export function resizeKey(f: PhyFile, id: string, size: KeyNode["size"]): PhyFile {
|
||||
const o = mutable(f),
|
||||
n = find(o, id);
|
||||
if (n.type !== "key") throw new Error(`${id} is not a key`);
|
||||
n.size = { ...size };
|
||||
return o;
|
||||
}
|
||||
/** 同じ親のノードを新クラスターにまとめ、絶対変換を保つ。T-11。 */
|
||||
export function clusterNodes(f: PhyFile, ids: string[], name = "Cluster", gen?: () => string): PhyFile {
|
||||
if (ids.length < 1) throw new Error("Select at least one node");
|
||||
const o = mutable(f),
|
||||
cs = containers(o),
|
||||
first = cs.get(ids[0]!);
|
||||
if (!first || ids.some((id) => cs.get(id)?.nodes !== first.nodes))
|
||||
throw new Error("Selected nodes must be siblings");
|
||||
const selected = ids.map((id) => first.nodes.find((n) => n.id === id)!);
|
||||
if (selected.some((n) => !n)) throw new Error("Unknown selection");
|
||||
const angles = selected.map((n) => world(o, n.id));
|
||||
const selectedAngles = selected.map((n) => first.parentRotation + n.transform.rotation);
|
||||
const angle = selectedAngles[0]!;
|
||||
const same = selectedAngles.every((candidate) => Math.abs(candidate - angle) < 1e-9);
|
||||
const basis = matrix({ x: 0, y: 0, rotation: same ? angle : 0 }),
|
||||
basisInverse = inverse(basis);
|
||||
const shapePoints = selected.flatMap((n, i) => boundsPoints(n, angles[i]!));
|
||||
if (shapePoints.length === 0) angles.forEach((m) => shapePoints.push({ x: m.e, y: m.f }));
|
||||
const localOrigins = shapePoints.map((p) => apply(basisInverse, p));
|
||||
const min = { x: Math.min(...localOrigins.map((p) => p.x)), y: Math.min(...localOrigins.map((p) => p.y)) };
|
||||
const origin = apply(basis, min);
|
||||
const wt = matrix({ x: origin.x, y: origin.y, rotation: same ? angle : 0 });
|
||||
const local = compose(inverse(first.parentWorld), wt);
|
||||
const id = nodeId("cluster", gen),
|
||||
cluster: ClusterNode = {
|
||||
type: "cluster",
|
||||
id,
|
||||
name,
|
||||
transform: { x: local.e, y: local.f, rotation: (same ? angle : 0) - first.parentRotation },
|
||||
children: [],
|
||||
};
|
||||
const inv = inverse(wt);
|
||||
cluster.children = selected.map((n) => {
|
||||
const w = world(o, n.id),
|
||||
rel = compose(inv, w);
|
||||
return {
|
||||
...n,
|
||||
transform: { x: rel.e, y: rel.f, rotation: selectedAngles[selected.indexOf(n)]! - (same ? angle : 0) },
|
||||
} as Node;
|
||||
});
|
||||
const indices = selected.map((n) => first.nodes.indexOf(n)).sort((a, b) => a - b);
|
||||
const insert = indices[0]!;
|
||||
first.nodes.splice(0, first.nodes.length, ...first.nodes.filter((n) => !ids.includes(n.id)));
|
||||
first.nodes.splice(insert, 0, cluster);
|
||||
return o;
|
||||
}
|
||||
/** clusterの子を同じ親へ戻し、絶対変換を保つ。 */
|
||||
export function uncluster(f: PhyFile, id: string): PhyFile {
|
||||
const o = mutable(f),
|
||||
cs = containers(o),
|
||||
c = cs.get(id),
|
||||
cluster = c?.nodes.find((n) => n.id === id);
|
||||
if (!cluster || cluster.type !== "cluster") throw new Error(`${id} is not a cluster`);
|
||||
const clusterWorldRotation = c!.parentRotation + cluster.transform.rotation;
|
||||
const cw = compose(c!.parentWorld, matrix(cluster.transform)),
|
||||
converted = cluster.children.map((n) => {
|
||||
const w = compose(cw, matrix(n.transform)),
|
||||
rel = compose(inverse(c!.parentWorld), w);
|
||||
return {
|
||||
...n,
|
||||
transform: {
|
||||
x: rel.e,
|
||||
y: rel.f,
|
||||
rotation: clusterWorldRotation + n.transform.rotation - c!.parentRotation,
|
||||
},
|
||||
} as Node;
|
||||
});
|
||||
const index = c!.nodes.indexOf(cluster);
|
||||
c!.nodes.splice(index, 1, ...converted);
|
||||
return o;
|
||||
}
|
||||
/** ノードを任意の親/rootへ移し、絶対変換を保つ。T-27。 */
|
||||
export function reparent(f: PhyFile, id: string, newParentId: string | null, index?: number): PhyFile {
|
||||
const o = mutable(f),
|
||||
cs = containers(o),
|
||||
src = cs.get(id),
|
||||
n = src?.nodes.find((x) => x.id === id);
|
||||
if (!n) throw new Error(`Unknown node: ${id}`);
|
||||
const oldW = world(o, id),
|
||||
oldRotation = worldRotation(o, id);
|
||||
let target: Node[] = o.root,
|
||||
parentW = ident,
|
||||
parentRotation = 0;
|
||||
if (newParentId) {
|
||||
const p = find(o, newParentId);
|
||||
if (p.type !== "cluster")
|
||||
throw new Error("Target parent must be a cluster; use reparentToVariant for variant children");
|
||||
if (containsNode(n, newParentId)) throw new Error("Cannot reparent a node into its descendant");
|
||||
target = p.children;
|
||||
parentW = world(o, p.id);
|
||||
parentRotation = worldRotation(o, p.id);
|
||||
}
|
||||
const oldIndex = src!.nodes.indexOf(n),
|
||||
sameParent = target === src!.nodes;
|
||||
src!.nodes.splice(oldIndex, 1);
|
||||
const rel = compose(inverse(parentW), oldW);
|
||||
n.transform = { x: rel.e, y: rel.f, rotation: oldRotation - parentRotation };
|
||||
let at = index ?? target.length;
|
||||
if (sameParent && index !== undefined && oldIndex < index) at--;
|
||||
target.splice(Math.max(0, Math.min(at, target.length)), 0, n);
|
||||
return o;
|
||||
}
|
||||
/** variant内へ移動するreparent。T-27。 */
|
||||
export function reparentToVariant(f: PhyFile, id: string, variantId: string, index?: number): PhyFile {
|
||||
const o = mutable(f),
|
||||
cs = containers(o),
|
||||
src = cs.get(id),
|
||||
n = src?.nodes.find((x) => x.id === id);
|
||||
const v = findVariant(o, variantId);
|
||||
if (!n || !src) throw new Error(`Unknown node: ${id}`);
|
||||
if (containsNode(n, variantId)) throw new Error("Cannot reparent a node into its descendant");
|
||||
const old = world(o, id),
|
||||
oldRotation = worldRotation(o, id),
|
||||
parent = srcVariantWorld(o, variantId),
|
||||
rel = compose(inverse(parent), old);
|
||||
const parentRotation = srcVariantRotation(o, variantId);
|
||||
src.nodes.splice(src.nodes.indexOf(n), 1);
|
||||
n.transform = { x: rel.e, y: rel.f, rotation: oldRotation - parentRotation };
|
||||
v.children.splice(index ?? v.children.length, 0, n);
|
||||
return o;
|
||||
}
|
||||
function containsNode(n: Node, id: string): boolean {
|
||||
if (n.id === id) return true;
|
||||
if (n.type === "cluster") return n.children.some((c) => containsNode(c, id));
|
||||
if (n.type === "variantGroup")
|
||||
return n.children.some((v) => v.id === id || v.children.some((c) => containsNode(c, id)));
|
||||
return false;
|
||||
}
|
||||
function boundsPoints(n: Node, worldMatrix: ReturnType<typeof matrix>): { x: number; y: number }[] {
|
||||
if (n.type === "key") {
|
||||
const points = [
|
||||
{ x: 0, y: 0 },
|
||||
{ x: n.size.w, y: 0 },
|
||||
{ x: n.size.w, y: n.size.h },
|
||||
{ x: 0, y: n.size.h },
|
||||
];
|
||||
if (
|
||||
n.size.w2 !== undefined ||
|
||||
n.size.h2 !== undefined ||
|
||||
n.size.x2 !== undefined ||
|
||||
n.size.y2 !== undefined
|
||||
) {
|
||||
const x = n.size.x2 ?? 0;
|
||||
const y = n.size.y2 ?? 0;
|
||||
const w = n.size.w2 ?? n.size.w;
|
||||
const h = n.size.h2 ?? n.size.h;
|
||||
points.push({ x, y }, { x: x + w, y }, { x: x + w, y: y + h }, { x, y: y + h });
|
||||
}
|
||||
return points.map((point) => apply(worldMatrix, point));
|
||||
}
|
||||
if (n.type === "component") return [{ x: worldMatrix.e, y: worldMatrix.f }];
|
||||
if (n.type === "cluster")
|
||||
return n.children.flatMap((child) => boundsPoints(child, compose(worldMatrix, matrix(child.transform))));
|
||||
const selected = n.children.find((variant) => variant.id === n.default);
|
||||
return selected
|
||||
? selected.children.flatMap((child) => boundsPoints(child, compose(worldMatrix, matrix(child.transform))))
|
||||
: [{ x: worldMatrix.e, y: worldMatrix.f }];
|
||||
}
|
||||
function findVariant(f: PhyFile, id: string): Variant {
|
||||
for (const n of f.root) {
|
||||
const r = walk(n, id);
|
||||
if (r) return r;
|
||||
}
|
||||
throw new Error(`Unknown variant: ${id}`);
|
||||
}
|
||||
function walk(n: Node, id: string): Variant | undefined {
|
||||
if (n.type === "variantGroup") {
|
||||
for (const v of n.children) {
|
||||
if (v.id === id) return v;
|
||||
for (const c of v.children) {
|
||||
const r = walk(c, id);
|
||||
if (r) return r;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (n.type === "cluster")
|
||||
for (const c of n.children) {
|
||||
const r = walk(c, id);
|
||||
if (r) return r;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
function srcVariantWorld(f: PhyFile, id: string): typeof ident {
|
||||
const rec = (ns: Node[], w: typeof ident): typeof ident | undefined => {
|
||||
for (const n of ns) {
|
||||
const nw = compose(w, matrix(n.transform));
|
||||
if (n.type === "variantGroup")
|
||||
for (const v of n.children) {
|
||||
if (v.id === id) return nw;
|
||||
const r = rec(v.children, nw);
|
||||
if (r) return r;
|
||||
}
|
||||
if (n.type === "cluster") {
|
||||
const r = rec(n.children, nw);
|
||||
if (r) return r;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
const x = rec(f.root, ident);
|
||||
if (!x) throw new Error(`Unknown variant ${id}`);
|
||||
return x;
|
||||
}
|
||||
function srcVariantRotation(f: PhyFile, id: string): number {
|
||||
const rec = (nodes: Node[], parentRotation: number): number | undefined => {
|
||||
for (const n of nodes) {
|
||||
const angle = parentRotation + n.transform.rotation;
|
||||
if (n.type === "variantGroup")
|
||||
for (const v of n.children) {
|
||||
if (v.id === id) return angle;
|
||||
const found = rec(v.children, angle);
|
||||
if (found !== undefined) return found;
|
||||
}
|
||||
if (n.type === "cluster") {
|
||||
const found = rec(n.children, angle);
|
||||
if (found !== undefined) return found;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
const found = rec(f.root, 0);
|
||||
if (found === undefined) throw new Error(`Unknown variant ${id}`);
|
||||
return found;
|
||||
}
|
||||
/** クラスターの座標枠を変え、配下の絶対位置を保つ。PHY-P-13仮決定。 */
|
||||
export function reframe(f: PhyFile, id: string, frame: Transform): PhyFile {
|
||||
const o = mutable(f),
|
||||
n = find(o, id);
|
||||
if (n.type !== "cluster") throw new Error(`${id} is not a cluster`);
|
||||
const c = containers(o).get(id)!,
|
||||
oldRotation = c.parentRotation + n.transform.rotation,
|
||||
old = compose(c.parentWorld, matrix(n.transform)),
|
||||
next = compose(c.parentWorld, matrix(frame)),
|
||||
correction = compose(inverse(next), old);
|
||||
n.children = n.children.map((ch) => {
|
||||
const t = compose(correction, matrix(ch.transform));
|
||||
return {
|
||||
...ch,
|
||||
transform: {
|
||||
x: t.e,
|
||||
y: t.f,
|
||||
rotation: oldRotation + ch.transform.rotation - (c.parentRotation + frame.rotation),
|
||||
},
|
||||
} as Node;
|
||||
});
|
||||
n.transform = { ...frame };
|
||||
return o;
|
||||
}
|
||||
/** VariantGroupを作成する。T-11。 */
|
||||
export function createVariantGroup(
|
||||
f: PhyFile,
|
||||
name: string,
|
||||
at: Transform,
|
||||
variants: [{ name: string; children?: Node[] }, { name: string; children?: Node[] }],
|
||||
gen?: () => string,
|
||||
): PhyFile {
|
||||
const o = mutable(f),
|
||||
children = variants.map((x) => ({
|
||||
type: "variant" as const,
|
||||
id: nodeId("variant", gen),
|
||||
name: x.name,
|
||||
children: structuredClone(x.children ?? []),
|
||||
}));
|
||||
o.root.push({
|
||||
type: "variantGroup",
|
||||
id: nodeId("variantGroup", gen),
|
||||
name,
|
||||
transform: { ...at },
|
||||
default: children[0]!.id,
|
||||
children,
|
||||
});
|
||||
return o;
|
||||
}
|
||||
/** Variantを追加する。T-11。 */
|
||||
export function addVariant(f: PhyFile, groupId: string, name: string, gen?: () => string): PhyFile {
|
||||
const o = mutable(f),
|
||||
g = find(o, groupId);
|
||||
if (g.type !== "variantGroup") throw new Error("Not a variant group");
|
||||
g.children.push({ type: "variant", id: nodeId("variant", gen), name, children: [] });
|
||||
return o;
|
||||
}
|
||||
/** Variantを削除する。子が1つになる場合は拒否し、default削除時は先頭へ移す。T-15。 */
|
||||
export function deleteVariant(f: PhyFile, groupId: string, variantId: string): PhyFile {
|
||||
const o = mutable(f),
|
||||
g = find(o, groupId);
|
||||
if (g.type !== "variantGroup") throw new Error("Not a variant group");
|
||||
if (g.children.length <= 2) throw new Error("Cannot leave a VariantGroup with fewer than two variants");
|
||||
const i = g.children.findIndex((v) => v.id === variantId);
|
||||
if (i < 0) throw new Error("Unknown variant");
|
||||
g.children.splice(i, 1);
|
||||
if (g.default === variantId) g.default = g.children[0]!.id;
|
||||
return o;
|
||||
}
|
||||
/** default Variantを変更する。 */
|
||||
export function setDefaultVariant(f: PhyFile, groupId: string, variantId: string): PhyFile {
|
||||
const o = mutable(f),
|
||||
g = find(o, groupId);
|
||||
if (g.type !== "variantGroup" || !g.children.some((v) => v.id === variantId))
|
||||
throw new Error("Invalid group or variant");
|
||||
g.default = variantId;
|
||||
return o;
|
||||
}
|
||||
/** ノードを削除する。 */
|
||||
export function deleteNode(f: PhyFile, id: string): PhyFile {
|
||||
const o = mutable(f),
|
||||
c = containers(o).get(id);
|
||||
if (!c) throw new Error(`Unknown node: ${id}`);
|
||||
const i = c.nodes.findIndex((n) => n.id === id);
|
||||
c.nodes.splice(i, 1);
|
||||
return o;
|
||||
}
|
||||
/** ノードと配下を複製し、すべてのIDを新しくする。T-11。 */
|
||||
export function duplicateNode(f: PhyFile, id: string, gen?: () => string): PhyFile {
|
||||
const o = mutable(f),
|
||||
n = find(o, id),
|
||||
copy = structuredClone(n);
|
||||
const renew = (x: Node) => {
|
||||
x.id = nodeId(x.type, gen);
|
||||
if (x.type === "cluster") x.children.forEach(renew);
|
||||
if (x.type === "variantGroup")
|
||||
for (const v of x.children) {
|
||||
v.id = nodeId("variant", gen);
|
||||
v.children.forEach(renew);
|
||||
}
|
||||
};
|
||||
renew(copy);
|
||||
copy.transform.x += 0.25;
|
||||
copy.transform.y += 0.25;
|
||||
const c = containers(o).get(id)!;
|
||||
c.nodes.splice(c.nodes.indexOf(n) + 1, 0, copy);
|
||||
return o;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { PhyFile } from "./phy";
|
||||
import type { PhyReference } from "./idx";
|
||||
import { sha256Jcs } from "../io/json";
|
||||
/** Computes the project-local PHY reference checksum. T-12. */
|
||||
export async function makePhyReference(phy: PhyFile, source = "project:phy"): Promise<PhyReference> {
|
||||
return { source, checksum: await sha256Jcs(phy) };
|
||||
}
|
||||
/** Checks whether a stored checksum matches PHY. T-12. */
|
||||
export async function phyReferenceMatches(phy: PhyFile, ref: PhyReference): Promise<boolean> {
|
||||
return ref.checksum === (await sha256Jcs(phy));
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { PhyFile, Node } from "./phy";
|
||||
import { createId } from "./ids";
|
||||
import { importKle } from "../io/kleImport";
|
||||
import { sha256Jcs } from "../io/json";
|
||||
import { createIdx, type IdxFile } from "./idx";
|
||||
import { createElc, type ElcFile } from "./elc";
|
||||
import { createMap, type MapFile } from "./map";
|
||||
export type MatrixOutputSettings = {
|
||||
rowPins: string[];
|
||||
colPins: string[];
|
||||
kind?: "matrix" | "charlieplexing" | "direct";
|
||||
[key: string]: unknown;
|
||||
};
|
||||
export type ProjectFile = {
|
||||
format: "beyond-kle-mock-project";
|
||||
version: string;
|
||||
projectId: string;
|
||||
phy: PhyFile;
|
||||
elc: ElcFile;
|
||||
idx: IdxFile;
|
||||
map: MapFile;
|
||||
output: { variantSelection: Record<string, string>; matrix?: MatrixOutputSettings; [key: string]: unknown };
|
||||
ui?: unknown;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
/** Creates default variant selections from PHY. T-10/T-20. */
|
||||
export function defaultVariantSelection(phy: PhyFile): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
const walk = (nodes: Node[]) =>
|
||||
nodes.forEach((n) => {
|
||||
if (n.type === "cluster") walk(n.children);
|
||||
if (n.type === "variantGroup") {
|
||||
out[n.id] = n.default;
|
||||
const v = n.children.find((x) => x.id === n.default);
|
||||
if (v) walk(v.children);
|
||||
}
|
||||
});
|
||||
walk(phy.root);
|
||||
return out;
|
||||
}
|
||||
/** Creates an empty project with default reference values. T-10/T-13. */
|
||||
export async function createProject(phy: PhyFile, gen?: () => string): Promise<ProjectFile> {
|
||||
const ref = { source: "project:phy", checksum: await sha256Jcs(phy) };
|
||||
return {
|
||||
format: "beyond-kle-mock-project",
|
||||
version: "0.1.0",
|
||||
projectId: createId("project-", gen),
|
||||
phy: structuredClone(phy),
|
||||
elc: createElc(ref),
|
||||
idx: createIdx(phy, [], ref),
|
||||
map: createMap(ref),
|
||||
output: { variantSelection: defaultVariantSelection(phy) },
|
||||
};
|
||||
}
|
||||
/** Imports KLE as a new project and initializes IDX from occurrence order. T-18. */
|
||||
export async function createProjectFromKle(
|
||||
input: unknown,
|
||||
options: { idGenerator?: () => string; name?: string; projectIdGenerator?: () => string } = {},
|
||||
): Promise<ProjectFile> {
|
||||
const { phy, keyOrder } = importKle(input, options);
|
||||
const p = await createProject(phy, options.projectIdGenerator);
|
||||
p.idx = createIdx(phy, keyOrder, p.idx.phyReference);
|
||||
return p;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,354 @@
|
||||
import type { ProjectFile } from "./project";
|
||||
import { flattenKeys } from "./geometry";
|
||||
import type { Node } from "./phy";
|
||||
import { eligibleKeyIds, unregisteredKeys } from "./idx";
|
||||
import { parseKeycode } from "./map";
|
||||
import { validateSchema } from "../io/validateSchema";
|
||||
export type ValidationIssue = {
|
||||
severity: "blocksSave" | "blocksOutput" | "warning";
|
||||
code: string;
|
||||
message: string;
|
||||
path?: string;
|
||||
ids?: string[];
|
||||
};
|
||||
/** Performs semantic validation of a complete mock project. T-13/T-16/T-21/T-25. */
|
||||
export function validateProject(p: ProjectFile): ValidationIssue[] {
|
||||
const out: ValidationIssue[] = [];
|
||||
for (const layer of ["phy", "idx", "elc", "map"] as const)
|
||||
for (const e of validateSchema(layer, p[layer]))
|
||||
out.push({ severity: "blocksSave", code: "schema", message: e.message, path: `${layer}${e.path}` });
|
||||
if (p.format !== "beyond-kle-mock-project")
|
||||
out.push({
|
||||
severity: "blocksSave",
|
||||
code: "project-format",
|
||||
message: "Unsupported ProjectFile format",
|
||||
path: "/format",
|
||||
});
|
||||
if (p.version !== "0.1.0")
|
||||
out.push({
|
||||
severity: "blocksSave",
|
||||
code: "version",
|
||||
message: "Unsupported ProjectFile version",
|
||||
path: "/version",
|
||||
});
|
||||
for (const layer of ["phy", "idx", "elc", "map"] as const)
|
||||
if (p[layer].version !== "0.1.0")
|
||||
out.push({
|
||||
severity: "blocksSave",
|
||||
code: "version",
|
||||
message: `Unsupported ${layer} version`,
|
||||
path: `/${layer}/version`,
|
||||
});
|
||||
const ids = new Map<string, string[]>();
|
||||
const add = (id: string, path: string) => ids.set(id, [...(ids.get(id) ?? []), path]);
|
||||
const walk = (ns: Node[], path: string) =>
|
||||
ns.forEach((n, i) => {
|
||||
const q = `${path}/${i}`;
|
||||
add(n.id, q);
|
||||
if (n.type === "cluster") walk(n.children, q + "/children");
|
||||
if (n.type === "variantGroup") {
|
||||
if (!n.children.some((v) => v.id === n.default))
|
||||
out.push({
|
||||
severity: "blocksSave",
|
||||
code: "missing-default-variant",
|
||||
message: "VariantGroup default does not reference a child",
|
||||
path: q + "/default",
|
||||
ids: [n.id, n.default],
|
||||
});
|
||||
for (const v of n.children) {
|
||||
add(v.id, q + "/children");
|
||||
walk(v.children, q + `/children/${v.id}/children`);
|
||||
}
|
||||
}
|
||||
});
|
||||
walk(p.phy.root, "/phy/root");
|
||||
for (const [id, paths] of ids)
|
||||
if (paths.length > 1)
|
||||
out.push({
|
||||
severity: "blocksSave",
|
||||
code: "duplicate-id",
|
||||
message: "Duplicate PHY node ID",
|
||||
ids: [id],
|
||||
path: paths[1],
|
||||
});
|
||||
const nodes = new Set(ids.keys()),
|
||||
keys = new Set(eligibleKeyIds(p.phy));
|
||||
const ref = (id: string, path: string, valid: Set<string> = nodes) => {
|
||||
if (!valid.has(id))
|
||||
out.push({
|
||||
severity: "blocksSave",
|
||||
code: "missing-reference",
|
||||
message: `Unknown reference: ${id}`,
|
||||
path,
|
||||
ids: [id],
|
||||
});
|
||||
};
|
||||
p.idx.order.forEach((id, i) => ref(id, `/idx/order/${i}`, keys));
|
||||
p.elc.keys.forEach((k, i) => ref(k.key, `/elc/keys/${i}/key`, keys));
|
||||
p.elc.ledChains?.forEach((c, i) => c.order.forEach((id, j) => ref(id, `/elc/ledChains/${i}/order/${j}`)));
|
||||
p.map.layers.forEach((l, i) =>
|
||||
l.keymap.forEach((a, j) => {
|
||||
ref(a.keyId, `/map/layers/${i}/keymap/${j}/keyId`, keys);
|
||||
const keycode = parseKeycode(a.keycode);
|
||||
if (keycode.kind === "layer" && !p.map.layers.some((candidate) => candidate.name === keycode.layer))
|
||||
out.push({
|
||||
severity: "blocksSave",
|
||||
code: "missing-map-layer-reference",
|
||||
message: `Unknown MAP layer reference: ${keycode.layer}`,
|
||||
path: `/map/layers/${i}/keymap/${j}/keycode`,
|
||||
ids: [l.name, keycode.layer ?? ""],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const providerIds = new Map<string, number>();
|
||||
p.elc.providers.forEach((provider, index) => {
|
||||
const first = providerIds.get(provider.id);
|
||||
if (first !== undefined)
|
||||
out.push({
|
||||
severity: "blocksSave",
|
||||
code: "duplicate-provider-id",
|
||||
message: "Provider IDs must be unique",
|
||||
path: `/elc/providers/${index}/id`,
|
||||
ids: [provider.id],
|
||||
});
|
||||
else providerIds.set(provider.id, index);
|
||||
if (!provider.id || provider.id.includes("."))
|
||||
out.push({
|
||||
severity: "blocksSave",
|
||||
code: "invalid-provider-id",
|
||||
message: "Provider IDs must be nonempty and cannot contain '.'",
|
||||
path: `/elc/providers/${index}/id`,
|
||||
ids: [provider.id],
|
||||
});
|
||||
});
|
||||
const chainIds = new Set<string>();
|
||||
p.elc.ledChains?.forEach((chain, index) => {
|
||||
if (chainIds.has(chain.id))
|
||||
out.push({
|
||||
severity: "blocksSave",
|
||||
code: "duplicate-led-chain-id",
|
||||
message: "LED chain IDs must be unique",
|
||||
path: `/elc/ledChains/${index}/id`,
|
||||
ids: [chain.id],
|
||||
});
|
||||
chainIds.add(chain.id);
|
||||
});
|
||||
const wiredKeys = new Set<string>();
|
||||
p.elc.keys.forEach((wiring, index) => {
|
||||
if (wiredKeys.has(wiring.key))
|
||||
out.push({
|
||||
severity: "blocksSave",
|
||||
code: "duplicate-key-wiring",
|
||||
message: "A key may have only one ELC wiring entry",
|
||||
path: `/elc/keys/${index}/key`,
|
||||
ids: [wiring.key],
|
||||
});
|
||||
wiredKeys.add(wiring.key);
|
||||
});
|
||||
|
||||
const validatePinRef = (pin: string, path: string) => {
|
||||
if (pin === "VCC" || pin === "GND") return;
|
||||
const parts = pin.split(".");
|
||||
const providerId = parts[0];
|
||||
const pinName = parts[1];
|
||||
if (parts.length !== 2 || !providerId || !pinName) {
|
||||
out.push({
|
||||
severity: "blocksSave",
|
||||
code: "invalid-pin-reference",
|
||||
message: `Malformed PinRef: ${pin}`,
|
||||
path,
|
||||
ids: [pin],
|
||||
});
|
||||
return;
|
||||
}
|
||||
const provider = p.elc.providers.find((candidate) => candidate.id === providerId);
|
||||
if (!provider) {
|
||||
out.push({
|
||||
severity: "blocksSave",
|
||||
code: "missing-pin-provider",
|
||||
message: `Unknown PinRef provider: ${providerId}`,
|
||||
path,
|
||||
ids: [providerId, pin],
|
||||
});
|
||||
return;
|
||||
}
|
||||
let valid = true;
|
||||
if (provider.kind === "analog-mux")
|
||||
valid = /^(0|[1-9]\d*)$/.test(pinName) && Number(pinName) < provider.channels;
|
||||
else if (provider.part.toUpperCase() === "RP2040") valid = /^GP(?:[0-9]|[12][0-9])$/.test(pinName);
|
||||
if (!valid)
|
||||
out.push({
|
||||
severity: "blocksSave",
|
||||
code: "unknown-provider-pin",
|
||||
message: `Unknown pin ${pinName} on provider ${providerId}`,
|
||||
path,
|
||||
ids: [providerId, pinName],
|
||||
});
|
||||
};
|
||||
p.elc.providers.forEach((provider, index) => {
|
||||
if (provider.kind === "analog-mux") {
|
||||
provider.select.forEach((pin, i) => validatePinRef(pin, `/elc/providers/${index}/select/${i}`));
|
||||
validatePinRef(provider.common, `/elc/providers/${index}/common`);
|
||||
if (provider.enable !== undefined) validatePinRef(provider.enable, `/elc/providers/${index}/enable`);
|
||||
}
|
||||
});
|
||||
p.elc.keys.forEach((wiring, index) =>
|
||||
Object.entries(wiring.terminals).forEach(([terminal, pin]) =>
|
||||
validatePinRef(pin, `/elc/keys/${index}/terminals/${terminal}`),
|
||||
),
|
||||
);
|
||||
p.elc.ledChains?.forEach((chain, index) => validatePinRef(chain.data, `/elc/ledChains/${index}/data`));
|
||||
p.output.matrix?.rowPins.forEach((pin, index) => validatePinRef(pin, `/output/matrix/rowPins/${index}`));
|
||||
p.output.matrix?.colPins.forEach((pin, index) => validatePinRef(pin, `/output/matrix/colPins/${index}`));
|
||||
const profileIds = new Set(p.phy.profiles.map((x) => x.id));
|
||||
const checkProfiles = (ns: Node[]) =>
|
||||
ns.forEach((n, i) => {
|
||||
if (n.type === "key" && !profileIds.has(n.profile))
|
||||
out.push({
|
||||
severity: "blocksSave",
|
||||
code: "missing-profile",
|
||||
message: `Unknown profile: ${n.profile}`,
|
||||
path: `/phy/key/${n.id}/profile`,
|
||||
ids: [n.id, n.profile],
|
||||
});
|
||||
if (n.type === "cluster") checkProfiles(n.children);
|
||||
if (n.type === "variantGroup") n.children.forEach((v) => checkProfiles(v.children));
|
||||
});
|
||||
checkProfiles(p.phy.root);
|
||||
for (const [i, pr] of p.phy.profiles.entries()) {
|
||||
if (pr.unitSize.x <= 0 || pr.unitSize.y <= 0)
|
||||
out.push({
|
||||
severity: "blocksSave",
|
||||
code: "positive-unit-size",
|
||||
message: "unitSize values must be positive",
|
||||
path: `/phy/profiles/${i}/unitSize`,
|
||||
});
|
||||
}
|
||||
const keyWalk = (ns: Node[]) =>
|
||||
ns.forEach((n) => {
|
||||
if (n.type === "key" && (n.size.w <= 0 || n.size.h <= 0))
|
||||
out.push({
|
||||
severity: "blocksSave",
|
||||
code: "positive-key-size",
|
||||
message: "Key size values must be positive",
|
||||
path: `/phy/key/${n.id}/size`,
|
||||
ids: [n.id],
|
||||
});
|
||||
if (n.type === "cluster") keyWalk(n.children);
|
||||
if (n.type === "variantGroup") n.children.forEach((v) => keyWalk(v.children));
|
||||
});
|
||||
keyWalk(p.phy.root);
|
||||
const unreg = unregisteredKeys(p.phy, p.idx);
|
||||
for (const id of unreg)
|
||||
out.push({
|
||||
severity: "blocksOutput",
|
||||
code: "idx-unregistered",
|
||||
message: "Eligible key is not in IDX order",
|
||||
ids: [id],
|
||||
});
|
||||
const profileSizes = p.phy.profiles.map((x) => `${x.unitSize.x},${x.unitSize.y}`);
|
||||
if (new Set(profileSizes).size > 1)
|
||||
out.push({
|
||||
severity: "warning",
|
||||
code: "unit-size-mismatch",
|
||||
message: "Profile unitSize values differ; geometry editing is restricted",
|
||||
path: "/phy/profiles",
|
||||
});
|
||||
let active: string[] = [];
|
||||
try {
|
||||
active = flattenKeys(p.phy, p.output.variantSelection)
|
||||
.filter((x) => !x.key.decal)
|
||||
.map((x) => x.key.id);
|
||||
} catch (e) {
|
||||
out.push({ severity: "blocksSave", code: "invalid-variant-selection", message: String(e) });
|
||||
}
|
||||
for (const id of active) {
|
||||
if (!p.elc.keys.some((k) => k.key === id))
|
||||
out.push({
|
||||
severity: "blocksOutput",
|
||||
code: "unwired-key",
|
||||
message: "Selected key has no wiring",
|
||||
ids: [id],
|
||||
});
|
||||
for (const l of p.map.layers)
|
||||
if (!l.keymap.some((a) => a.keyId === id))
|
||||
out.push({
|
||||
severity: "blocksOutput",
|
||||
code: "unassigned-key",
|
||||
message: `Selected key is not assigned in layer ${l.name}`,
|
||||
ids: [id, l.name],
|
||||
});
|
||||
}
|
||||
const branches = new Map<string, Array<[string, string]>>();
|
||||
const exclusivity = (ns: Node[], branch: Array<[string, string]>) =>
|
||||
ns.forEach((n) => {
|
||||
if (n.type === "key") branches.set(n.id, branch);
|
||||
if (n.type === "cluster") exclusivity(n.children, branch);
|
||||
if (n.type === "variantGroup")
|
||||
for (const v of n.children) exclusivity(v.children, [...branch, [n.id, v.id]]);
|
||||
});
|
||||
exclusivity(p.phy.root, []);
|
||||
const mutuallyExclusive = (a: string, b: string) => {
|
||||
for (const [group, variant] of branches.get(a) ?? [])
|
||||
if ((branches.get(b) ?? []).some(([g, v]) => g === group && v !== variant)) return true;
|
||||
return false;
|
||||
};
|
||||
const unordered = (a: string, b: string) => (a < b ? `${a}\0${b}` : `${b}\0${a}`);
|
||||
const contacts = p.elc.keys.filter((w) => w.detect === "contact");
|
||||
for (let i = 0; i < contacts.length; i++)
|
||||
for (let j = i + 1; j < contacts.length; j++) {
|
||||
const a = contacts[i]!,
|
||||
b = contacts[j]!;
|
||||
if (a.key === b.key || mutuallyExclusive(a.key, b.key)) continue;
|
||||
const ap = a.diode
|
||||
? a.diode === "a-to-b"
|
||||
? [a.terminals.a, a.terminals.b]
|
||||
: [a.terminals.b, a.terminals.a]
|
||||
: null;
|
||||
const bp = b.diode
|
||||
? b.diode === "a-to-b"
|
||||
? [b.terminals.a, b.terminals.b]
|
||||
: [b.terminals.b, b.terminals.a]
|
||||
: null;
|
||||
const same =
|
||||
ap && bp
|
||||
? ap[0] === bp[0] && ap[1] === bp[1]
|
||||
: unordered(a.terminals.a, a.terminals.b) === unordered(b.terminals.a, b.terminals.b);
|
||||
if (same)
|
||||
out.push({
|
||||
severity: "blocksOutput",
|
||||
code: "wiring-collision",
|
||||
message: "Non-exclusive keys share the same electrical connection",
|
||||
ids: [a.key, b.key],
|
||||
});
|
||||
}
|
||||
const layerNames = new Set<string>();
|
||||
for (const [i, l] of p.map.layers.entries()) {
|
||||
if (layerNames.has(l.name))
|
||||
out.push({
|
||||
severity: "blocksSave",
|
||||
code: "duplicate-layer-name",
|
||||
message: "Layer names must be unique",
|
||||
path: `/map/layers/${i}/name`,
|
||||
ids: [l.name],
|
||||
});
|
||||
layerNames.add(l.name);
|
||||
}
|
||||
for (const [li, l] of p.map.layers.entries()) {
|
||||
const assignments = new Map<string, number>();
|
||||
for (const [ai, a] of l.keymap.entries()) {
|
||||
const prev = assignments.get(a.keyId);
|
||||
if (prev !== undefined)
|
||||
out.push({
|
||||
severity: "blocksSave",
|
||||
code: "duplicate-map-key",
|
||||
message: "A key may occur only once in a layer keymap",
|
||||
path: `/map/layers/${li}/keymap/${ai}/keyId`,
|
||||
ids: [a.keyId, l.name],
|
||||
});
|
||||
assignments.set(a.keyId, ai);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
declare module "*.vue" {
|
||||
import type { DefineComponent } from "vue";
|
||||
const component: DefineComponent<object, object, unknown>;
|
||||
export default component;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/** RFC 8785 JCS の UTF-8 対象文字列を生成する。T-12。 */
|
||||
export function canonicalize(value: unknown): string {
|
||||
return encode(value);
|
||||
}
|
||||
function encode(v: unknown): string {
|
||||
if (v === null) return "null";
|
||||
if (typeof v === "string") return JSON.stringify(v);
|
||||
if (typeof v === "boolean") return v ? "true" : "false";
|
||||
if (typeof v === "number") {
|
||||
if (!Number.isFinite(v)) throw new TypeError("JCS does not support non-finite numbers");
|
||||
return JSON.stringify(Object.is(v, -0) ? 0 : v);
|
||||
}
|
||||
if (Array.isArray(v)) return `[${v.map(encode).join(",")}]`;
|
||||
if (typeof v === "object") {
|
||||
const o = v as Record<string, unknown>;
|
||||
const keys = Object.keys(o).sort();
|
||||
return `{${keys.map((k) => `${JSON.stringify(k)}:${encode(o[k])}`).join(",")}}`;
|
||||
}
|
||||
throw new TypeError(`Unsupported JCS value: ${typeof v}`);
|
||||
}
|
||||
/** JCS正規化したUTF-8をSHA-256し、指定形式で返す。T-12。 */
|
||||
export async function sha256Jcs(value: unknown): Promise<string> {
|
||||
const bytes = new TextEncoder().encode(canonicalize(value));
|
||||
const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
|
||||
return `sha256-jcs:${Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("")}`;
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { FlatKey, KleCompatibility, PhyFile } from "../domain/phy";
|
||||
import { flattenKeys } from "../domain/geometry";
|
||||
import { labelsToKle } from "./kleImport";
|
||||
|
||||
type Obj = Record<string, unknown>;
|
||||
const defaults: KleCompatibility = { c: "#cccccc", t: "#000000", p: "", a: 4, f: 3, sm: "", sb: "", st: "" };
|
||||
|
||||
/** PHYをバリアント選択に従ってKLE JSONへ平坦化する。座標は6桁丸め。T-20。 */
|
||||
export function exportKle(phy: PhyFile, variantSelection: Record<string, string> = {}): unknown[] {
|
||||
const keys = flattenKeys(phy, variantSelection);
|
||||
const order = [...keys].sort((a, b) => a.rotation - b.rotation || a.y - b.y || a.x - b.x);
|
||||
const centers = new Map<number, { x: number; y: number }>();
|
||||
for (const key of order) if (!centers.has(key.rotation)) centers.set(key.rotation, { x: key.x, y: key.y });
|
||||
const previous: KleCompatibility = { ...defaults };
|
||||
let previousGhost = false;
|
||||
const rows: unknown[] = [];
|
||||
|
||||
for (const flat of order) {
|
||||
const key = flat.key;
|
||||
const center = centers.get(flat.rotation)!;
|
||||
const rad = (flat.rotation * Math.PI) / 180;
|
||||
const dx = flat.x - center.x;
|
||||
const dy = flat.y - center.y;
|
||||
const localX = center.x + Math.cos(rad) * dx + Math.sin(rad) * dy;
|
||||
const localY = center.y - Math.sin(rad) * dx + Math.cos(rad) * dy;
|
||||
const compat = { ...defaults, ...(key.kleCompatibility ?? {}) };
|
||||
const cfg: Obj = {
|
||||
r: flat.rotation,
|
||||
rx: round(center.x),
|
||||
ry: round(center.y),
|
||||
x: round(localX - center.x),
|
||||
y: round(localY - center.y),
|
||||
};
|
||||
|
||||
for (const field of ["c", "t", "p", "a", "sm", "sb", "st"] as const) {
|
||||
const next = compat[field];
|
||||
if (!same(next, previous[field])) cfg[field] = structuredClone(next);
|
||||
previous[field] = structuredClone(next);
|
||||
}
|
||||
const oldOverride = previous.fa !== undefined ? "fa" : previous.f2 !== undefined ? "f2" : "none";
|
||||
const nextOverride = compat.fa !== undefined ? "fa" : compat.f2 !== undefined ? "f2" : "none";
|
||||
const fontChanged = !same(compat.f, previous.f);
|
||||
if (fontChanged || (nextOverride === "none" && oldOverride !== "none")) cfg.f = compat.f;
|
||||
if (nextOverride === "fa" && (oldOverride !== "fa" || !same(compat.fa, previous.fa)))
|
||||
cfg.fa = structuredClone(compat.fa);
|
||||
if (nextOverride === "f2" && (oldOverride !== "f2" || !same(compat.f2, previous.f2)))
|
||||
cfg.f2 = structuredClone(compat.f2);
|
||||
previous.f = structuredClone(compat.f);
|
||||
delete previous.f2;
|
||||
delete previous.fa;
|
||||
if (nextOverride === "fa") previous.fa = structuredClone(compat.fa);
|
||||
if (nextOverride === "f2") previous.f2 = structuredClone(compat.f2);
|
||||
|
||||
if (key.ghost !== previousGhost) {
|
||||
cfg.g = key.ghost === true;
|
||||
previousGhost = key.ghost === true;
|
||||
}
|
||||
if (key.decal) cfg.d = true;
|
||||
if (compat.l === true) cfg.l = true;
|
||||
if (compat.n === true) cfg.n = true;
|
||||
|
||||
const w = key.size.w;
|
||||
const h = key.size.h;
|
||||
if (w !== 1) cfg.w = round(w);
|
||||
if (h !== 1) cfg.h = round(h);
|
||||
if (key.size.x2 !== undefined && key.size.x2 !== 0) cfg.x2 = round(key.size.x2);
|
||||
if (key.size.y2 !== undefined && key.size.y2 !== 0) cfg.y2 = round(key.size.y2);
|
||||
const w2 = key.size.w2 ?? w;
|
||||
const h2 = key.size.h2 ?? h;
|
||||
if (w2 !== w) cfg.w2 = round(w2);
|
||||
if (h2 !== h) cfg.h2 = round(h2);
|
||||
|
||||
rows.push([cfg, labelsToKle(key.labels, typeof compat.a === "number" ? compat.a : 4)]);
|
||||
}
|
||||
if (phy.kleCompatibility) rows.unshift(structuredClone(phy.kleCompatibility));
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** KLE JSON文字列を生成する。 */
|
||||
export function stringifyKle(phy: PhyFile, selection: Record<string, string> = {}): string {
|
||||
return JSON.stringify(exportKle(phy, selection));
|
||||
}
|
||||
function same(a: unknown, b: unknown): boolean {
|
||||
return JSON.stringify(a) === JSON.stringify(b);
|
||||
}
|
||||
function round(value: number): number {
|
||||
return Number(value.toFixed(6));
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
import type { KleCompatibility, KeyNode, PhyFile } from "../domain/phy";
|
||||
import { createNodeId } from "../domain/ids";
|
||||
|
||||
type Obj = Record<string, unknown>;
|
||||
type Atom = string | Obj;
|
||||
|
||||
// Output slot -> newline-field index. These fixed tables reproduce KLE's a=0..7 layout.
|
||||
const labelMap: readonly (readonly (number | null)[])[] = [
|
||||
[0, 8, 2, 6, 9, 7, 1, 10, 3, 4, 11, 5],
|
||||
[null, 0, null, null, 6, null, null, 1, null, 4, 11, 5],
|
||||
[null, null, null, 0, 8, 2, null, null, null, 4, 11, 5],
|
||||
[null, null, null, null, 0, null, null, null, null, 4, 11, 5],
|
||||
[0, 8, 2, 6, 9, 7, 1, 10, 3, null, 4, null],
|
||||
[null, 0, null, null, 6, null, null, 1, null, null, 4, null],
|
||||
[null, null, null, 0, 8, 2, null, null, null, null, 4, null],
|
||||
[null, null, null, null, 0, null, null, null, null, null, 4, null],
|
||||
];
|
||||
|
||||
const fileDefaults: Obj = {
|
||||
backcolor: "#eeeeee",
|
||||
name: "",
|
||||
author: "",
|
||||
notes: "",
|
||||
background: null,
|
||||
radii: "",
|
||||
switchMount: "",
|
||||
switchBrand: "",
|
||||
switchType: "",
|
||||
};
|
||||
const keyDefaults: Obj = { c: "#cccccc", t: "#000000", p: "", a: 4, f: 3, sm: "", sb: "", st: "" };
|
||||
|
||||
function isObj(value: unknown): value is Obj {
|
||||
return !!value && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
function num(value: unknown, fallback: number): number {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
||||
}
|
||||
function labelsFromKle(serialized: string, alignment: number): string[] {
|
||||
const fields = serialized.split("\n");
|
||||
if (fields.length > 12) throw new Error("A KLE label cannot exceed 12 slots");
|
||||
const map = labelMap[alignment] ?? labelMap[4]!;
|
||||
const labels = Array<string>(12).fill("");
|
||||
map.forEach((field, slot) => {
|
||||
if (field !== null && field < fields.length) labels[slot] = fields[field]!;
|
||||
});
|
||||
while (labels.at(-1) === "") labels.pop();
|
||||
return labels;
|
||||
}
|
||||
function oneShotArray(state: Obj, key: string): void {
|
||||
delete state[key];
|
||||
}
|
||||
|
||||
/** KLEの厳密JSON(またはVIA layouts.keymap)を新規PHYへ取り込む。T-7/T-18/T-20。 */
|
||||
export function importKle(
|
||||
input: unknown,
|
||||
options: { idGenerator?: () => string; name?: string } = {},
|
||||
): { phy: PhyFile; keyOrder: string[] } {
|
||||
let data: unknown = input;
|
||||
if (isObj(data)) {
|
||||
const layouts = data.layouts;
|
||||
if (isObj(layouts) && Array.isArray(layouts.keymap)) data = layouts.keymap;
|
||||
else throw new Error("Expected KLE array or VIA layouts.keymap");
|
||||
}
|
||||
if (!Array.isArray(data)) throw new Error("KLE input must be a JSON array");
|
||||
const rows = [...data] as unknown[];
|
||||
let rawMeta: Obj = {};
|
||||
if (rows.length && isObj(rows[0])) rawMeta = rows.shift() as Obj;
|
||||
|
||||
const gen = options.idGenerator ?? (() => globalThis.crypto.randomUUID());
|
||||
const state: Obj = { ...keyDefaults };
|
||||
let cursorX = 0;
|
||||
let cursorY = 0;
|
||||
let rotation = 0;
|
||||
let rotationX = 0;
|
||||
let rotationY = 0;
|
||||
const root: KeyNode[] = [];
|
||||
const keyOrder: string[] = [];
|
||||
|
||||
for (const row of rows) {
|
||||
if (!Array.isArray(row)) throw new Error("KLE rows must be arrays");
|
||||
cursorX = rotationX;
|
||||
for (const atom of row as Atom[]) {
|
||||
if (typeof atom === "string") {
|
||||
const w = num(state.w, 1);
|
||||
const h = num(state.h, 1);
|
||||
cursorX += num(state.x, 0);
|
||||
cursorY += num(state.y, 0);
|
||||
const radians = (rotation * Math.PI) / 180;
|
||||
const dx = cursorX - rotationX;
|
||||
const dy = cursorY - rotationY;
|
||||
const x = rotationX + Math.cos(radians) * dx - Math.sin(radians) * dy;
|
||||
const y = rotationY + Math.sin(radians) * dx + Math.cos(radians) * dy;
|
||||
const a = num(state.a, 4);
|
||||
const id = createNodeId("key", gen);
|
||||
const labels = labelsFromKle(atom, a);
|
||||
const compatibility: KleCompatibility = {
|
||||
c: structuredClone(state.c),
|
||||
t: structuredClone(state.t),
|
||||
p: structuredClone(state.p),
|
||||
a,
|
||||
f: num(state.f, 3),
|
||||
...(state.f2 === undefined ? {} : { f2: structuredClone(state.f2) }),
|
||||
...(state.fa === undefined ? {} : { fa: structuredClone(state.fa) }),
|
||||
l: state.l === true,
|
||||
n: state.n === true,
|
||||
sm: structuredClone(state.sm),
|
||||
sb: structuredClone(state.sb),
|
||||
st: structuredClone(state.st),
|
||||
};
|
||||
const w2 = num(state.w2, 0) || w;
|
||||
const h2 = num(state.h2, 0) || h;
|
||||
const key: KeyNode = {
|
||||
type: "key",
|
||||
id,
|
||||
profile: "default",
|
||||
transform: { x, y, rotation },
|
||||
size: {
|
||||
w,
|
||||
h,
|
||||
...(num(state.x2, 0) === 0 ? {} : { x2: num(state.x2, 0) }),
|
||||
...(num(state.y2, 0) === 0 ? {} : { y2: num(state.y2, 0) }),
|
||||
...(w2 === w ? {} : { w2 }),
|
||||
...(h2 === h ? {} : { h2 }),
|
||||
},
|
||||
labels,
|
||||
kleCompatibility: compatibility,
|
||||
};
|
||||
if (state.d === true) key.decal = true;
|
||||
if (state.g === true) key.ghost = true;
|
||||
root.push(key);
|
||||
if (!key.decal) keyOrder.push(id);
|
||||
|
||||
cursorX += w;
|
||||
for (const field of ["w", "h", "x", "y", "x2", "y2", "w2", "h2", "d", "l", "n"])
|
||||
oneShotArray(state, field);
|
||||
} else if (isObj(atom)) {
|
||||
for (const [key, value] of Object.entries(atom)) {
|
||||
if (key === "r") rotation = num(value, rotation);
|
||||
else if (key === "rx") {
|
||||
rotationX = num(value, rotationX);
|
||||
cursorX = rotationX;
|
||||
cursorY = rotationY;
|
||||
} else if (key === "ry") {
|
||||
rotationY = num(value, rotationY);
|
||||
cursorX = rotationX;
|
||||
cursorY = rotationY;
|
||||
} else if (key === "f") {
|
||||
state.f = value;
|
||||
delete state.f2;
|
||||
delete state.fa;
|
||||
} else if (key === "f2") {
|
||||
state.f2 = value;
|
||||
delete state.fa;
|
||||
} else if (key === "fa") {
|
||||
state.fa = structuredClone(value);
|
||||
delete state.f2;
|
||||
} else state[key] = structuredClone(value);
|
||||
}
|
||||
} else throw new Error("KLE row entries must be strings or objects");
|
||||
}
|
||||
cursorY += 1;
|
||||
}
|
||||
|
||||
const metadata = { ...fileDefaults, ...structuredClone(rawMeta) };
|
||||
const phy: PhyFile = {
|
||||
version: "0.1.0",
|
||||
metadata: { ...(options.name ? { name: options.name } : {}) },
|
||||
profiles: [{ id: "default", name: "Default", unitSize: { x: 19.05, y: 19.05 } }],
|
||||
root,
|
||||
kleCompatibility: metadata,
|
||||
};
|
||||
return { phy, keyOrder };
|
||||
}
|
||||
|
||||
/** JSON文字列を厳密にパースして KLE を取り込む。 */
|
||||
export function parseKleJson(
|
||||
json: string,
|
||||
options: { idGenerator?: () => string; name?: string } = {},
|
||||
): ReturnType<typeof importKle> {
|
||||
return importKle(JSON.parse(json) as unknown, options);
|
||||
}
|
||||
|
||||
/** 正準12欄のラベルをKLEのa別固定欄順に戻す。 */
|
||||
export function labelsToKle(labels: string[] | undefined, alignment: number): string {
|
||||
const map = labelMap[alignment] ?? labelMap[4]!;
|
||||
const fields = Array<string>(12).fill("");
|
||||
map.forEach((sourceSlot, slot) => {
|
||||
if (sourceSlot !== null) fields[sourceSlot] = labels?.[slot] ?? "";
|
||||
});
|
||||
while (fields.at(-1) === "") fields.pop();
|
||||
return fields.join("\n");
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import type { ProjectFile } from "../domain/project";
|
||||
import { validateProject, type ValidationIssue } from "../domain/validate";
|
||||
import { makePhyReference, phyReferenceMatches } from "../domain/phyReference";
|
||||
import { validateSchema, type LayerName } from "./validateSchema";
|
||||
|
||||
export type ProjectReadResult = { project?: ProjectFile; errors: ValidationIssue[] };
|
||||
export type ProjectSaveResult = { json?: string; errors: ValidationIssue[] };
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/** Validates project and output container shapes before semantic checks. T-10/T-16. */
|
||||
function validateProjectShape(value: unknown): ValidationIssue[] {
|
||||
const errors: ValidationIssue[] = [];
|
||||
if (!isRecord(value))
|
||||
return [{ severity: "blocksSave", code: "schema", message: "Expected a ProjectFile object", path: "/" }];
|
||||
const required = ["format", "version", "projectId", "phy", "idx", "elc", "map", "output"];
|
||||
for (const field of required)
|
||||
if (!(field in value))
|
||||
errors.push({
|
||||
severity: "blocksSave",
|
||||
code: "schema",
|
||||
message: `Missing required ProjectFile field: ${field}`,
|
||||
path: `/${field}`,
|
||||
});
|
||||
if (value.format !== "beyond-kle-mock-project")
|
||||
errors.push({
|
||||
severity: "blocksSave",
|
||||
code: "schema",
|
||||
message: "Invalid ProjectFile format",
|
||||
path: "/format",
|
||||
});
|
||||
if (typeof value.version !== "string")
|
||||
errors.push({ severity: "blocksSave", code: "schema", message: "Expected a string", path: "/version" });
|
||||
if (typeof value.projectId !== "string")
|
||||
errors.push({ severity: "blocksSave", code: "schema", message: "Expected a string", path: "/projectId" });
|
||||
for (const layer of ["phy", "idx", "elc", "map"] as const) {
|
||||
if (!(layer in value)) continue;
|
||||
for (const issue of validateSchema(layer, value[layer]))
|
||||
errors.push({
|
||||
severity: "blocksSave",
|
||||
code: "schema",
|
||||
message: issue.message,
|
||||
path: `/${layer}${issue.path === "/" ? "" : issue.path}`,
|
||||
});
|
||||
}
|
||||
const output = value.output;
|
||||
if (!isRecord(output)) {
|
||||
errors.push({ severity: "blocksSave", code: "schema", message: "Expected an object", path: "/output" });
|
||||
} else {
|
||||
if (!isRecord(output.variantSelection))
|
||||
errors.push({
|
||||
severity: "blocksSave",
|
||||
code: "schema",
|
||||
message: "Expected an object of variant IDs",
|
||||
path: "/output/variantSelection",
|
||||
});
|
||||
else
|
||||
for (const [key, variant] of Object.entries(output.variantSelection))
|
||||
if (typeof variant !== "string")
|
||||
errors.push({
|
||||
severity: "blocksSave",
|
||||
code: "schema",
|
||||
message: "Expected a variant ID string",
|
||||
path: `/output/variantSelection/${key}`,
|
||||
});
|
||||
if (output.matrix !== undefined) {
|
||||
if (!isRecord(output.matrix))
|
||||
errors.push({
|
||||
severity: "blocksSave",
|
||||
code: "schema",
|
||||
message: "Expected an object",
|
||||
path: "/output/matrix",
|
||||
});
|
||||
else {
|
||||
for (const field of ["rowPins", "colPins"] as const) {
|
||||
const pins = output.matrix[field];
|
||||
if (!Array.isArray(pins) || pins.some((pin) => typeof pin !== "string"))
|
||||
errors.push({
|
||||
severity: "blocksSave",
|
||||
code: "schema",
|
||||
message: "Expected an array of pin references",
|
||||
path: `/output/matrix/${field}`,
|
||||
});
|
||||
}
|
||||
if (
|
||||
output.matrix.kind !== undefined &&
|
||||
!["matrix", "charlieplexing", "direct"].includes(String(output.matrix.kind))
|
||||
)
|
||||
errors.push({
|
||||
severity: "blocksSave",
|
||||
code: "schema",
|
||||
message: "Unknown output scan mode",
|
||||
path: "/output/matrix/kind",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
/** Serializes a project and refreshes PHY references unless T-16 blocks saving. T-12/T-13. */
|
||||
export async function saveProject(project: ProjectFile, pretty = false): Promise<ProjectSaveResult> {
|
||||
const shapeErrors = validateProjectShape(project);
|
||||
if (shapeErrors.length) return { errors: shapeErrors };
|
||||
const errors = validateProject(project);
|
||||
if (errors.some((issue) => issue.severity === "blocksSave")) return { errors };
|
||||
|
||||
const p = structuredClone(project);
|
||||
const ref = await makePhyReference(p.phy);
|
||||
for (const layer of ["idx", "elc", "map"] as const)
|
||||
p[layer].phyReference = { ...p[layer].phyReference, ...ref };
|
||||
return { json: JSON.stringify(p, null, pretty ? 2 : undefined), errors };
|
||||
}
|
||||
|
||||
/** Parses a project, checking all schemas before semantic validation and retaining unknown fields. T-13/T-14. */
|
||||
export async function loadProject(json: string): Promise<ProjectReadResult> {
|
||||
let data: unknown;
|
||||
try {
|
||||
data = JSON.parse(json) as unknown;
|
||||
} catch (e) {
|
||||
return { errors: [{ severity: "blocksSave", code: "invalid-json", message: String(e) }] };
|
||||
}
|
||||
const errors = validateProjectShape(data);
|
||||
if (errors.length) return { errors };
|
||||
|
||||
const project = data as ProjectFile;
|
||||
const semantic = validateProject(project);
|
||||
const unsupportedVersion = semantic.filter((issue) => issue.code === "version");
|
||||
if (unsupportedVersion.length) return { errors: semantic };
|
||||
for (const layer of ["idx", "elc", "map"] as const)
|
||||
if (!(await phyReferenceMatches(project.phy, project[layer].phyReference)))
|
||||
semantic.push({
|
||||
severity: "warning",
|
||||
code: "phy-reference-mismatch",
|
||||
message: `${layer} PHY checksum does not match the current PHY`,
|
||||
path: `/${layer}/phyReference`,
|
||||
});
|
||||
return { project, errors: semantic };
|
||||
}
|
||||
|
||||
/** Writes a single layer as JSON. */
|
||||
export function writeLayer(layer: LayerName, value: unknown, pretty = false): string {
|
||||
const errors = validateSchema(layer, value);
|
||||
if (errors.length) throw new Error(errors.map((issue) => `${issue.path} ${issue.message}`).join("; "));
|
||||
return JSON.stringify(value, null, pretty ? 2 : undefined);
|
||||
}
|
||||
|
||||
/** Reads and schema-validates one layer file. */
|
||||
export function readLayer(layer: LayerName, json: string): { value?: unknown; errors: ValidationIssue[] } {
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(json) as unknown;
|
||||
} catch (e) {
|
||||
return { errors: [{ severity: "blocksSave", code: "invalid-json", message: String(e) }] };
|
||||
}
|
||||
const errors = validateSchema(layer, value).map((issue) => ({
|
||||
severity: "blocksSave" as const,
|
||||
code: "schema",
|
||||
message: issue.message,
|
||||
path: issue.path,
|
||||
}));
|
||||
if (
|
||||
value &&
|
||||
typeof value === "object" &&
|
||||
"version" in value &&
|
||||
(value as { version?: unknown }).version !== "0.1.0"
|
||||
)
|
||||
errors.push({
|
||||
severity: "blocksSave",
|
||||
code: "version",
|
||||
message: "Unsupported layer version",
|
||||
path: "/version",
|
||||
});
|
||||
return errors.length ? { errors } : { value, errors: [] };
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://beyond-kle.org/schemas/elc-layer.json",
|
||||
"title": "ELC Layer - Electrical Wiring",
|
||||
"description": "Wiring between provider pins and key terminals",
|
||||
"type": "object",
|
||||
"required": ["version", "phyReference", "providers", "keys"],
|
||||
"properties": {
|
||||
"version": { "type": "string" },
|
||||
"phyReference": {
|
||||
"type": "object",
|
||||
"required": ["source", "checksum"],
|
||||
"properties": {
|
||||
"source": { "type": "string" },
|
||||
"checksum": { "type": "string" }
|
||||
}
|
||||
},
|
||||
"providers": {
|
||||
"type": "array",
|
||||
"items": { "$ref": "#/$defs/provider" }
|
||||
},
|
||||
"keys": {
|
||||
"type": "array",
|
||||
"items": { "$ref": "#/$defs/keyWiring" }
|
||||
},
|
||||
"ledChains": {
|
||||
"type": "array",
|
||||
"items": { "$ref": "#/$defs/ledChain" }
|
||||
}
|
||||
},
|
||||
"$defs": {
|
||||
"pinRef": {
|
||||
"type": "string",
|
||||
"pattern": "^(VCC|GND|[^.]+\\.[^.]+)$",
|
||||
"description": "\"<provider id>.<pin name>\", or the reserved power rails VCC / GND"
|
||||
},
|
||||
"provider": {
|
||||
"oneOf": [{ "$ref": "#/$defs/mcuProvider" }, { "$ref": "#/$defs/analogMuxProvider" }]
|
||||
},
|
||||
"mcuProvider": {
|
||||
"type": "object",
|
||||
"required": ["id", "kind", "part"],
|
||||
"properties": {
|
||||
"id": { "type": "string" },
|
||||
"kind": { "const": "mcu" },
|
||||
"part": {
|
||||
"type": "string",
|
||||
"description": "Part number. Used to interpret pin names"
|
||||
}
|
||||
}
|
||||
},
|
||||
"analogMuxProvider": {
|
||||
"type": "object",
|
||||
"required": ["id", "kind", "channels", "select", "common"],
|
||||
"properties": {
|
||||
"id": { "type": "string" },
|
||||
"kind": { "const": "analog-mux" },
|
||||
"channels": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"description": "Number of logical pins provided. Pin names are \"0\"..\"channels-1\""
|
||||
},
|
||||
"select": {
|
||||
"type": "array",
|
||||
"items": { "$ref": "#/$defs/pinRef" },
|
||||
"description": "Select pins, least significant bit first"
|
||||
},
|
||||
"common": { "$ref": "#/$defs/pinRef" },
|
||||
"enable": { "$ref": "#/$defs/pinRef" }
|
||||
}
|
||||
},
|
||||
"keyWiring": {
|
||||
"oneOf": [{ "$ref": "#/$defs/contactKey" }, { "$ref": "#/$defs/analogKey" }]
|
||||
},
|
||||
"contactKey": {
|
||||
"type": "object",
|
||||
"required": ["key", "detect", "terminals"],
|
||||
"properties": {
|
||||
"key": {
|
||||
"type": "string",
|
||||
"description": "Reference to PHY layer key ID"
|
||||
},
|
||||
"detect": { "const": "contact" },
|
||||
"terminals": {
|
||||
"type": "object",
|
||||
"description": "Non-polar. a and b carry no ordering meaning",
|
||||
"required": ["a", "b"],
|
||||
"properties": {
|
||||
"a": { "$ref": "#/$defs/pinRef" },
|
||||
"b": { "$ref": "#/$defs/pinRef" }
|
||||
}
|
||||
},
|
||||
"diode": {
|
||||
"type": "string",
|
||||
"enum": ["a-to-b", "b-to-a"],
|
||||
"description": "Anode side comes first. Omitted means no diode"
|
||||
}
|
||||
}
|
||||
},
|
||||
"analogKey": {
|
||||
"type": "object",
|
||||
"required": ["key", "detect", "terminals"],
|
||||
"properties": {
|
||||
"key": {
|
||||
"type": "string",
|
||||
"description": "Reference to PHY layer key ID"
|
||||
},
|
||||
"detect": { "const": "analog" },
|
||||
"terminals": {
|
||||
"type": "object",
|
||||
"required": ["out", "vcc", "gnd"],
|
||||
"properties": {
|
||||
"out": { "$ref": "#/$defs/pinRef" },
|
||||
"vcc": { "$ref": "#/$defs/pinRef" },
|
||||
"gnd": { "$ref": "#/$defs/pinRef" }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"ledChain": {
|
||||
"type": "object",
|
||||
"required": ["id", "data", "order"],
|
||||
"properties": {
|
||||
"id": { "type": "string" },
|
||||
"data": { "$ref": "#/$defs/pinRef" },
|
||||
"order": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" },
|
||||
"description": "PHY node IDs. The position in the array is the LED number"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://beyond-kle.org/schemas/idx-layer.json",
|
||||
"title": "IDX Layer - Key Identification",
|
||||
"description": "Ordered PHY key IDs across all variants. Output key numbers are contiguous positions after filtering by variant selection",
|
||||
"type": "object",
|
||||
"required": ["version", "phyReference", "order"],
|
||||
"properties": {
|
||||
"version": { "type": "string" },
|
||||
"phyReference": {
|
||||
"type": "object",
|
||||
"required": ["source", "checksum"],
|
||||
"properties": {
|
||||
"source": { "type": "string" },
|
||||
"checksum": { "type": "string" }
|
||||
}
|
||||
},
|
||||
"order": {
|
||||
"type": "array",
|
||||
"uniqueItems": true,
|
||||
"description": "Each PHY key has its own entry, including mutually exclusive keys wired to the same terminals. Variant selection does not modify this list",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"description": "Reference to PHY layer key ID"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://beyond-kle.org/schemas/map-layer.json",
|
||||
"title": "MAP Layer - Keymap Configuration",
|
||||
"description": "Key code assignments and layers",
|
||||
"type": "object",
|
||||
"required": ["version", "phyReference", "layers"],
|
||||
"properties": {
|
||||
"version": { "type": "string" },
|
||||
"phyReference": {
|
||||
"type": "object",
|
||||
"required": ["source", "checksum"],
|
||||
"properties": {
|
||||
"source": { "type": "string" },
|
||||
"checksum": { "type": "string" }
|
||||
}
|
||||
},
|
||||
"layers": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/layer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"$defs": {
|
||||
"layer": {
|
||||
"type": "object",
|
||||
"required": ["name", "keymap"],
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "Layer identifier, unique within the MAP. Layer order is the array order"
|
||||
},
|
||||
"keymap": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/keyAssignment"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"keyAssignment": {
|
||||
"type": "object",
|
||||
"required": ["keyId", "keycode"],
|
||||
"properties": {
|
||||
"keyId": {
|
||||
"type": "string",
|
||||
"description": "Reference to PHY layer key ID"
|
||||
},
|
||||
"keycode": { "type": "string" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://beyond-kle.org/schemas/phy-layer.json",
|
||||
"title": "PHY Layer - Physical Key Layout",
|
||||
"description": "Physical positioning and sizing of keys",
|
||||
"type": "object",
|
||||
"required": ["version", "metadata", "profiles", "root"],
|
||||
"properties": {
|
||||
"version": {
|
||||
"type": "string",
|
||||
"pattern": "^\\d+\\.\\d+\\.\\d+$",
|
||||
"description": "Schema version (semver)"
|
||||
},
|
||||
"metadata": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": { "type": "string" },
|
||||
"author": { "type": "string" },
|
||||
"description": { "type": "string" },
|
||||
"created": { "type": "string", "format": "date-time" },
|
||||
"modified": { "type": "string", "format": "date-time" }
|
||||
}
|
||||
},
|
||||
"kleCompatibility": {
|
||||
"type": "object",
|
||||
"description": "File-level opaque KLE fields kept for round-trip output (switchMount, switchBrand, switchType, backcolor, radii, background, css). Kept here for now; the eventual owning layer is deferred in backlog/README.md, PHY-P-6",
|
||||
"additionalProperties": true
|
||||
},
|
||||
"profiles": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"items": {
|
||||
"$ref": "#/$defs/profile"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"oneOf": [
|
||||
{ "$ref": "#/$defs/key" },
|
||||
{ "$ref": "#/$defs/cluster" },
|
||||
{ "$ref": "#/$defs/component" },
|
||||
{ "$ref": "#/$defs/variantGroup" }
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"$defs": {
|
||||
"transform": {
|
||||
"type": "object",
|
||||
"description": "Placement relative to the parent: rotate by rotation around the local origin, then translate by (x, y)",
|
||||
"required": ["x", "y", "rotation"],
|
||||
"properties": {
|
||||
"x": { "type": "number" },
|
||||
"y": { "type": "number" },
|
||||
"rotation": { "type": "number", "description": "Degrees" }
|
||||
}
|
||||
},
|
||||
"profile": {
|
||||
"type": "object",
|
||||
"required": ["id", "name", "unitSize"],
|
||||
"properties": {
|
||||
"id": { "type": "string" },
|
||||
"name": { "type": "string" },
|
||||
"unitSize": {
|
||||
"type": "object",
|
||||
"description": "Millimeters per 1U",
|
||||
"required": ["x", "y"],
|
||||
"properties": {
|
||||
"x": { "type": "number", "minimum": 0 },
|
||||
"y": { "type": "number", "minimum": 0 }
|
||||
}
|
||||
},
|
||||
"visualOffset": {
|
||||
"type": "object",
|
||||
"description": "Key top rectangle, in millimeters: inward distance from each edge of the outline, plus corner radius",
|
||||
"required": ["top", "right", "bottom", "left", "radius"],
|
||||
"properties": {
|
||||
"top": { "type": "number" },
|
||||
"right": { "type": "number" },
|
||||
"bottom": { "type": "number" },
|
||||
"left": { "type": "number" },
|
||||
"radius": { "type": "number", "minimum": 0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"key": {
|
||||
"type": "object",
|
||||
"required": ["type", "id", "profile", "transform", "size"],
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "key"
|
||||
},
|
||||
"id": {
|
||||
"type": "string",
|
||||
"description": "Unique key identifier"
|
||||
},
|
||||
"profile": {
|
||||
"type": "string",
|
||||
"description": "Reference to profile ID"
|
||||
},
|
||||
"transform": { "$ref": "#/$defs/transform" },
|
||||
"size": {
|
||||
"type": "object",
|
||||
"description": "Local size. Not affected by the parent transform",
|
||||
"required": ["w", "h"],
|
||||
"properties": {
|
||||
"w": { "type": "number", "minimum": 0 },
|
||||
"h": { "type": "number", "minimum": 0 },
|
||||
"x2": {
|
||||
"type": "number",
|
||||
"description": "Second rectangle for non-rectangular keys, relative to the local origin"
|
||||
},
|
||||
"y2": { "type": "number" },
|
||||
"w2": { "type": "number", "minimum": 0 },
|
||||
"h2": { "type": "number", "minimum": 0 }
|
||||
}
|
||||
},
|
||||
"switchOffset": {
|
||||
"type": "object",
|
||||
"description": "Switch position, offset from the center of the (w, h) rectangle. Key local coordinates, unit U. Defaults to 0",
|
||||
"required": ["x", "y"],
|
||||
"properties": {
|
||||
"x": { "type": "number" },
|
||||
"y": { "type": "number" }
|
||||
}
|
||||
},
|
||||
"partGroup": {
|
||||
"type": "string",
|
||||
"description": "Label grouping keys that use the same part. Not interpreted by Beyond KLE"
|
||||
},
|
||||
"orientation": {
|
||||
"type": "integer",
|
||||
"enum": [0, 90, 180, 270],
|
||||
"default": 0,
|
||||
"description": "Switch orientation in the key local coordinates"
|
||||
},
|
||||
"perKeyLED": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "Whether a per-key LED is mounted"
|
||||
},
|
||||
"decal": { "type": "boolean", "default": false },
|
||||
"ghost": { "type": "boolean", "default": false },
|
||||
"labels": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" },
|
||||
"description": "Reference information. Used for matching on KLE JSON import"
|
||||
},
|
||||
"kleCompatibility": {
|
||||
"type": "object",
|
||||
"description": "Opaque KLE fields kept for round-trip output (c, t, p, a, f, f2, fa, l, n, sm, sb, st). Kept here for now; the eventual owning layer is deferred in backlog/README.md, PHY-P-6",
|
||||
"additionalProperties": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"component": {
|
||||
"type": "object",
|
||||
"description": "Non-key part placed by the designer (LED, OLED, encoder, screw hole, ...)",
|
||||
"required": ["type", "id", "transform"],
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "component"
|
||||
},
|
||||
"id": { "type": "string" },
|
||||
"transform": { "$ref": "#/$defs/transform" },
|
||||
"partGroup": {
|
||||
"type": "string",
|
||||
"description": "Names starting with @ are reserved for editor rendering"
|
||||
}
|
||||
}
|
||||
},
|
||||
"variantGroup": {
|
||||
"type": "object",
|
||||
"description": "Mutually exclusive layout alternatives. Children are variants only",
|
||||
"required": ["type", "id", "name", "transform", "default", "children"],
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "variantGroup"
|
||||
},
|
||||
"id": { "type": "string" },
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "Heading shown for the choice in the editor"
|
||||
},
|
||||
"transform": { "$ref": "#/$defs/transform" },
|
||||
"default": {
|
||||
"type": "string",
|
||||
"description": "id of the variant used when a single layout must be chosen"
|
||||
},
|
||||
"children": {
|
||||
"type": "array",
|
||||
"minItems": 2,
|
||||
"description": "Display order",
|
||||
"items": { "$ref": "#/$defs/variant" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"variant": {
|
||||
"type": "object",
|
||||
"description": "One alternative. Appears only directly under a variantGroup. Carries no transform",
|
||||
"required": ["type", "id", "name", "children"],
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "variant"
|
||||
},
|
||||
"id": { "type": "string" },
|
||||
"name": { "type": "string" },
|
||||
"children": {
|
||||
"type": "array",
|
||||
"description": "May be empty",
|
||||
"items": {
|
||||
"oneOf": [
|
||||
{ "$ref": "#/$defs/key" },
|
||||
{ "$ref": "#/$defs/cluster" },
|
||||
{ "$ref": "#/$defs/component" },
|
||||
{ "$ref": "#/$defs/variantGroup" }
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"cluster": {
|
||||
"type": "object",
|
||||
"required": ["type", "id", "transform", "children"],
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "cluster"
|
||||
},
|
||||
"id": { "type": "string" },
|
||||
"name": { "type": "string" },
|
||||
"transform": { "$ref": "#/$defs/transform" },
|
||||
"children": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"oneOf": [
|
||||
{ "$ref": "#/$defs/key" },
|
||||
{ "$ref": "#/$defs/cluster" },
|
||||
{ "$ref": "#/$defs/component" },
|
||||
{ "$ref": "#/$defs/variantGroup" }
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import Ajv2020 from "ajv/dist/2020";
|
||||
import addFormats from "ajv-formats";
|
||||
import phySchema from "./schemas/phy.schema.json";
|
||||
import idxSchema from "./schemas/idx.schema.json";
|
||||
import elcSchema from "./schemas/elc.schema.json";
|
||||
import mapSchema from "./schemas/map.schema.json";
|
||||
|
||||
export type LayerName = "phy" | "idx" | "elc" | "map";
|
||||
export type SchemaIssue = { path: string; message: string };
|
||||
const ajv = new Ajv2020({ allErrors: true, strict: false });
|
||||
addFormats(ajv);
|
||||
const validators = {
|
||||
phy: ajv.compile(phySchema),
|
||||
idx: ajv.compile(idxSchema),
|
||||
elc: ajv.compile(elcSchema),
|
||||
map: ajv.compile(mapSchema),
|
||||
};
|
||||
/** Validates one layer against its draft 2020-12 schema. */
|
||||
export function validateSchema(layer: LayerName, value: unknown): SchemaIssue[] {
|
||||
const valid = validators[layer](value);
|
||||
return valid
|
||||
? []
|
||||
: (validators[layer].errors ?? []).map((e) => ({
|
||||
path: `${e.instancePath || "/"}${e.params && "missingProperty" in e.params ? `/${e.params.missingProperty}` : ""}`,
|
||||
message: e.message ?? "Schema validation failed",
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { createApp } from "vue";
|
||||
import App from "./ui/App.vue";
|
||||
|
||||
createApp(App).mount("#app");
|
||||
@@ -0,0 +1,904 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref, shallowRef } from "vue";
|
||||
import { createProjectFromKle } from "../domain/project";
|
||||
import type { ProjectFile } from "../domain/project";
|
||||
import type { Node, KeyNode, Transform, VariantGroupNode } from "../domain/phy";
|
||||
import { flattenKeys } from "../domain/geometry";
|
||||
import {
|
||||
addKey,
|
||||
addComponent,
|
||||
moveNode,
|
||||
resizeKey,
|
||||
rotateNode,
|
||||
clusterNodes,
|
||||
uncluster,
|
||||
reparent,
|
||||
reparentToVariant,
|
||||
duplicateNode,
|
||||
createVariantGroup,
|
||||
addVariant,
|
||||
setDefaultVariant,
|
||||
reframe,
|
||||
} from "../domain/phyCommands";
|
||||
import { ProjectHistory } from "../domain/history";
|
||||
import { validateProject } from "../domain/validate";
|
||||
import { listDeleteReferences, deleteNodeCascade } from "../domain/deleteCascade";
|
||||
import { saveProject, loadProject } from "../io/projectFile";
|
||||
import { exportKle } from "../io/kleExport";
|
||||
import { defaultLayout } from "./defaultLayout";
|
||||
import type { Dispatch } from "./types";
|
||||
import PhyTree from "./phy/PhyTree.vue";
|
||||
import PhyCanvas from "./phy/PhyCanvas.vue";
|
||||
import { parentPoint, snappedDelta } from "./phy/dragMath";
|
||||
import IdxPanel from "./panels/IdxPanel.vue";
|
||||
import ElcPanel from "./panels/ElcPanel.vue";
|
||||
import MapPanel from "./panels/MapPanel.vue";
|
||||
import GeneratorPanel from "./panels/GeneratorPanel.vue";
|
||||
|
||||
const project = shallowRef<ProjectFile | null>(null);
|
||||
const activeTab = ref("PHY"),
|
||||
selection = ref<string[]>([]),
|
||||
variants = ref<Record<string, string>>({}),
|
||||
zoom = ref(1);
|
||||
const errorText = ref(""),
|
||||
pendingDelete = ref<{
|
||||
id: string;
|
||||
refs: ReturnType<typeof listDeleteReferences>;
|
||||
} | null>(null);
|
||||
const importInput = ref<HTMLInputElement>(),
|
||||
openInput = ref<HTMLInputElement>();
|
||||
let history: ProjectHistory | null = null;
|
||||
const historyEpoch = ref(0);
|
||||
let drag: {
|
||||
id: string;
|
||||
parent: SVGGElement;
|
||||
start: { x: number; y: number };
|
||||
origin: Transform;
|
||||
base: ProjectFile;
|
||||
} | null = null;
|
||||
const mismatch = computed(
|
||||
() =>
|
||||
!!project.value &&
|
||||
new Set(project.value.phy.profiles.map((p) => `${p.unitSize.x},${p.unitSize.y}`)).size > 1,
|
||||
);
|
||||
const issues = computed(() => (project.value ? validateProject(project.value) : []));
|
||||
const canUndo = computed(() => {
|
||||
historyEpoch.value;
|
||||
return !!history?.canUndo;
|
||||
}),
|
||||
canRedo = computed(() => {
|
||||
historyEpoch.value;
|
||||
return !!history?.canRedo;
|
||||
});
|
||||
const severity = ["blocksSave", "blocksOutput", "warning"] as const;
|
||||
const selectedNode = computed(() =>
|
||||
project.value && selection.value.length === 1
|
||||
? findNode(project.value.phy.root, selection.value[0]!)
|
||||
: null,
|
||||
);
|
||||
const keyCount = computed(() => (project.value ? flattenKeys(project.value.phy, variants.value).length : 0));
|
||||
const variantGroups = computed(() => {
|
||||
const groups: VariantGroupNode[] = [];
|
||||
if (project.value)
|
||||
visit(project.value.phy.root, (n) => {
|
||||
if (n.type === "variantGroup") groups.push(n);
|
||||
});
|
||||
return groups;
|
||||
});
|
||||
const dispatch: Dispatch = (label, update) => {
|
||||
if (!project.value) return;
|
||||
if (mismatch.value) return;
|
||||
const next = update(project.value);
|
||||
project.value = next;
|
||||
if (history) history.push(next);
|
||||
historyEpoch.value++;
|
||||
errorText.value = "";
|
||||
};
|
||||
function findNode(nodes: Node[], id: string): Node | null {
|
||||
for (const n of nodes) {
|
||||
if (n.id === id) return n;
|
||||
if (n.type === "cluster") {
|
||||
const x = findNode(n.children, id);
|
||||
if (x) return x;
|
||||
}
|
||||
if (n.type === "variantGroup")
|
||||
for (const v of n.children) {
|
||||
if (v.id === id) return n;
|
||||
const x = findNode(v.children, id);
|
||||
if (x) return x;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function visit(nodes: Node[], fn: (n: Node) => void) {
|
||||
for (const n of nodes) {
|
||||
fn(n);
|
||||
if (n.type === "cluster") visit(n.children, fn);
|
||||
if (n.type === "variantGroup") for (const v of n.children) visit(v.children, fn);
|
||||
}
|
||||
}
|
||||
function parents() {
|
||||
const out: { id: string; label: string }[] = [{ id: "", label: "root" }];
|
||||
if (project.value)
|
||||
visit(project.value.phy.root, (n) => {
|
||||
if (n.type === "cluster") out.push({ id: n.id, label: `クラスター ${n.name || n.id}` });
|
||||
if (n.type === "variantGroup")
|
||||
for (const v of n.children) out.push({ id: v.id, label: `${n.name} / ${v.name}` });
|
||||
});
|
||||
return out;
|
||||
}
|
||||
function setSelected(id: string, additive: boolean) {
|
||||
selection.value = additive
|
||||
? selection.value.includes(id)
|
||||
? selection.value.filter((x) => x !== id)
|
||||
: [...selection.value, id]
|
||||
: [id];
|
||||
const n = project.value ? findNode(project.value.phy.root, id) : null;
|
||||
if (n?.type === "cluster")
|
||||
promptValue.value = { x: n.transform.x, y: n.transform.y, r: n.transform.rotation };
|
||||
}
|
||||
async function initialize() {
|
||||
const p = await createProjectFromKle(defaultLayout, { name: "New keyboard" });
|
||||
project.value = p;
|
||||
history = new ProjectHistory(p);
|
||||
historyEpoch.value++;
|
||||
variants.value = { ...p.output.variantSelection };
|
||||
}
|
||||
onMounted(() => {
|
||||
void initialize();
|
||||
window.addEventListener("keydown", keyHandler);
|
||||
});
|
||||
onUnmounted(() => window.removeEventListener("keydown", keyHandler));
|
||||
function keyHandler(e: KeyboardEvent) {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "z") {
|
||||
e.preventDefault();
|
||||
e.shiftKey ? redo() : undo();
|
||||
} else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "y") {
|
||||
e.preventDefault();
|
||||
redo();
|
||||
}
|
||||
}
|
||||
function undo() {
|
||||
if (history?.canUndo) {
|
||||
project.value = history.undo();
|
||||
historyEpoch.value++;
|
||||
variants.value = { ...project.value.output.variantSelection };
|
||||
selection.value = selection.value.filter(
|
||||
(id) => !!project.value && !!findNode(project.value.phy.root, id),
|
||||
);
|
||||
}
|
||||
}
|
||||
function redo() {
|
||||
if (history?.canRedo) {
|
||||
project.value = history.redo();
|
||||
historyEpoch.value++;
|
||||
variants.value = { ...project.value.output.variantSelection };
|
||||
}
|
||||
}
|
||||
async function readFile(file: File, mode: "project" | "kle") {
|
||||
try {
|
||||
const json = JSON.parse(await file.text()) as unknown;
|
||||
if (mode === "kle") {
|
||||
const p = await createProjectFromKle(json, { name: file.name });
|
||||
project.value = p;
|
||||
history = new ProjectHistory(p);
|
||||
variants.value = { ...p.output.variantSelection };
|
||||
selection.value = [];
|
||||
} else {
|
||||
const result = await loadProject(JSON.stringify(json));
|
||||
if (!result.project) throw Error(result.errors.map((x) => x.message).join("; "));
|
||||
project.value = result.project;
|
||||
history = new ProjectHistory(result.project);
|
||||
variants.value = { ...result.project.output.variantSelection };
|
||||
selection.value = [];
|
||||
errorText.value = result.errors.map((x) => x.message).join("; ");
|
||||
}
|
||||
historyEpoch.value++;
|
||||
} catch (e) {
|
||||
errorText.value = String(e);
|
||||
}
|
||||
}
|
||||
function download(name: string, text: string) {
|
||||
const a = document.createElement("a");
|
||||
a.href = URL.createObjectURL(new Blob([text], { type: "application/json" }));
|
||||
a.download = name;
|
||||
a.click();
|
||||
URL.revokeObjectURL(a.href);
|
||||
}
|
||||
async function save() {
|
||||
if (project.value) {
|
||||
const result = await saveProject(project.value, true);
|
||||
if (result.json) download(`${project.value.phy.metadata.name || "project"}.bkle.json`, result.json);
|
||||
else errorText.value = result.errors.map((x) => x.message).join("; ");
|
||||
}
|
||||
}
|
||||
function exportSelected() {
|
||||
if (project.value)
|
||||
download("layout.kle.json", JSON.stringify(exportKle(project.value.phy, variants.value), null, 2));
|
||||
}
|
||||
function nodeDown(event: PointerEvent, id: string, parent: SVGGElement) {
|
||||
if (mismatch.value || !project.value) return;
|
||||
const node = findNode(project.value.phy.root, id);
|
||||
if (!node) return;
|
||||
event.preventDefault();
|
||||
const p = parentPoint(parent, event.clientX, event.clientY);
|
||||
history?.begin();
|
||||
historyEpoch.value++;
|
||||
drag = { id, parent, start: p, origin: { ...node.transform }, base: project.value };
|
||||
window.addEventListener("pointermove", movePointer);
|
||||
window.addEventListener("pointerup", endPointer, { once: true });
|
||||
}
|
||||
function movePointer(e: PointerEvent) {
|
||||
if (!drag) return;
|
||||
const p = parentPoint(drag.parent, e.clientX, e.clientY),
|
||||
delta = snappedDelta(drag.start, p);
|
||||
const next = moveNode(drag.base.phy, drag.id, delta.x, delta.y);
|
||||
project.value = { ...drag.base, phy: next };
|
||||
history?.replaceTop(project.value);
|
||||
}
|
||||
function endPointer() {
|
||||
window.removeEventListener("pointermove", movePointer);
|
||||
if (project.value) history?.commit(project.value);
|
||||
historyEpoch.value++;
|
||||
drag = null;
|
||||
}
|
||||
function keyAdd() {
|
||||
if (!project.value) return;
|
||||
dispatch("キー追加", (p) => ({ ...p, phy: addKey(p.phy, { x: 0, y: 0, rotation: 0 }, { w: 1, h: 1 }) }));
|
||||
const n = project.value.phy.root.at(-1);
|
||||
if (n) selection.value = [n.id];
|
||||
}
|
||||
function componentAdd(group: string) {
|
||||
if (!project.value) return;
|
||||
dispatch("部品追加", (p) => ({
|
||||
...p,
|
||||
phy: addComponent(p.phy, { x: 0, y: 0, rotation: 0 }, group || undefined),
|
||||
}));
|
||||
const n = project.value.phy.root.at(-1);
|
||||
if (n) selection.value = [n.id];
|
||||
}
|
||||
function updateTransform(field: keyof Transform, value: number) {
|
||||
if (mismatch.value || !project.value || selection.value.length !== 1 || !selectedNode.value) return;
|
||||
const id = selectedNode.value.id;
|
||||
dispatch("変換変更", (p) => {
|
||||
const phy = structuredClone(p.phy),
|
||||
n = findNode(phy.root, id);
|
||||
if (n) n.transform[field] = value;
|
||||
return { ...p, phy };
|
||||
});
|
||||
}
|
||||
function increment(field: keyof Transform, step: number) {
|
||||
if (!selectedNode.value) return;
|
||||
const n = selectedNode.value;
|
||||
updateTransform(field, n.transform[field] + step);
|
||||
}
|
||||
function updateSize(field: "w" | "h", value: number) {
|
||||
if (mismatch.value || !project.value || !selectedNode.value || selectedNode.value.type !== "key") return;
|
||||
const id = selectedNode.value.id;
|
||||
dispatch("キーサイズ変更", (p) => ({
|
||||
...p,
|
||||
phy: resizeKey(p.phy, id, { ...(findNode(p.phy.root, id) as KeyNode).size, [field]: value }),
|
||||
}));
|
||||
}
|
||||
function updateLabel(value: string) {
|
||||
if (mismatch.value || !project.value || !selectedNode.value || selectedNode.value.type !== "key") return;
|
||||
const id = selectedNode.value.id;
|
||||
dispatch("ラベル変更", (p) => {
|
||||
const phy = structuredClone(p.phy),
|
||||
n = findNode(phy.root, id);
|
||||
if (n && n.type === "key") n.labels = [value];
|
||||
return { ...p, phy };
|
||||
});
|
||||
}
|
||||
function rotateSelected() {
|
||||
if (mismatch.value || !project.value) return;
|
||||
const ids = [...selection.value].filter((id) => findNode(project.value!.phy.root, id));
|
||||
if (!ids.length) return;
|
||||
dispatch("回転", (p) => ({ ...p, phy: ids.reduce((phy, id) => rotateNode(phy, id, 15), p.phy) }));
|
||||
}
|
||||
function makeCluster() {
|
||||
if (!project.value || selection.value.length < 1) return;
|
||||
try {
|
||||
dispatch("クラスター化", (p) => ({ ...p, phy: clusterNodes(p.phy, selection.value) }));
|
||||
const n = project.value.phy.root.find((n) => n.type === "cluster");
|
||||
if (n) selection.value = [n.id];
|
||||
} catch (e) {
|
||||
errorText.value = String(e);
|
||||
}
|
||||
}
|
||||
function ungroup() {
|
||||
if (mismatch.value || !project.value || selectedNode.value?.type !== "cluster") return;
|
||||
const id = selectedNode.value.id;
|
||||
dispatch("クラスター解除", (p) => ({ ...p, phy: uncluster(p.phy, id) }));
|
||||
selection.value = [];
|
||||
}
|
||||
function duplicate() {
|
||||
if (!project.value || selection.value.length !== 1) return;
|
||||
const id = selection.value[0]!;
|
||||
dispatch("複製", (p) => ({ ...p, phy: duplicateNode(p.phy, id) }));
|
||||
}
|
||||
function reparentTo(target: string) {
|
||||
if (mismatch.value || !project.value || selection.value.length !== 1) return;
|
||||
const id = selection.value[0]!;
|
||||
try {
|
||||
dispatch("reparent", (p) => ({
|
||||
...p,
|
||||
phy: target.startsWith("v-")
|
||||
? reparentToVariant(p.phy, id, target)
|
||||
: reparent(p.phy, id, target || null),
|
||||
}));
|
||||
} catch (e) {
|
||||
errorText.value = String(e);
|
||||
}
|
||||
}
|
||||
function createVariants() {
|
||||
if (!project.value || selection.value.length === 0) return;
|
||||
const first = findNode(project.value.phy.root, selection.value[0]!);
|
||||
if (!first) return;
|
||||
try {
|
||||
dispatch("VariantGroup作成", (p) => {
|
||||
let phy = createVariantGroup(p.phy, "Layout", { ...first.transform }, [
|
||||
{ name: "Option A" },
|
||||
{ name: "Option B" },
|
||||
]);
|
||||
const vg = phy.root.at(-1);
|
||||
if (vg?.type === "variantGroup") {
|
||||
for (const id of selection.value) phy = reparentToVariant(phy, id, vg.children[0]!.id);
|
||||
return {
|
||||
...p,
|
||||
phy,
|
||||
output: { ...p.output, variantSelection: { ...p.output.variantSelection, [vg.id]: vg.default } },
|
||||
};
|
||||
}
|
||||
return { ...p, phy };
|
||||
});
|
||||
selection.value = [];
|
||||
if (project.value) variants.value = { ...project.value.output.variantSelection };
|
||||
} catch (e) {
|
||||
errorText.value = String(e);
|
||||
}
|
||||
}
|
||||
function addVariantUi(groupId: string) {
|
||||
if (!project.value) return;
|
||||
dispatch("Variant追加", (p) => ({
|
||||
...p,
|
||||
phy: addVariant(
|
||||
p.phy,
|
||||
groupId,
|
||||
`Option ${String.fromCharCode(65 + (findNode(p.phy.root, groupId) as Node & { children: Node[] }).children.length)}`,
|
||||
),
|
||||
}));
|
||||
}
|
||||
function removeVariantUi(variantId: string) {
|
||||
if (!project.value) return;
|
||||
pendingDelete.value = { id: variantId, refs: listDeleteReferences(project.value, variantId) };
|
||||
}
|
||||
function changeDefault(groupId: string, id: string) {
|
||||
if (!project.value) return;
|
||||
dispatch("既定Variant変更", (p) => ({ ...p, phy: setDefaultVariant(p.phy, groupId, id) }));
|
||||
}
|
||||
function confirmDelete() {
|
||||
if (!pendingDelete.value || !project.value) return;
|
||||
const { id } = pendingDelete.value;
|
||||
try {
|
||||
dispatch("ノード削除", (p) => deleteNodeCascade(p, id));
|
||||
if (project.value) variants.value = { ...project.value.output.variantSelection };
|
||||
selection.value = [];
|
||||
pendingDelete.value = null;
|
||||
} catch (e) {
|
||||
errorText.value = String(e);
|
||||
}
|
||||
}
|
||||
function requestDelete() {
|
||||
if (mismatch.value || !project.value || selection.value.length !== 1) return;
|
||||
const id = selection.value[0]!;
|
||||
pendingDelete.value = { id, refs: listDeleteReferences(project.value, id) };
|
||||
}
|
||||
function changeFrame() {
|
||||
if (mismatch.value || !project.value || selectedNode.value?.type !== "cluster") return;
|
||||
const id = selectedNode.value.id;
|
||||
const x = Number(promptValue.value.x),
|
||||
y = Number(promptValue.value.y),
|
||||
rotation = Number(promptValue.value.r);
|
||||
dispatch("座標枠変更", (p) => ({ ...p, phy: reframe(p.phy, id, { x, y, rotation }) }));
|
||||
}
|
||||
const promptValue = ref({ x: 0, y: 0, r: 0 });
|
||||
function changeVariant(groupId: string, id: string) {
|
||||
variants.value = { ...variants.value, [groupId]: id };
|
||||
if (!mismatch.value)
|
||||
dispatch("表示構成変更", (p) => ({
|
||||
...p,
|
||||
output: { ...p.output, variantSelection: { ...variants.value } },
|
||||
}));
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="app-shell" :class="{ locked: mismatch }" v-if="project">
|
||||
<header class="toolbar">
|
||||
<strong>Beyond KLE</strong><button @click="importInput?.click()">KLE JSONから新規</button
|
||||
><input
|
||||
ref="importInput"
|
||||
hidden
|
||||
type="file"
|
||||
accept=".json,application/json"
|
||||
@change="
|
||||
(e) => {
|
||||
const f = (e.target as HTMLInputElement).files?.[0];
|
||||
if (f) void readFile(f, 'kle');
|
||||
(e.target as HTMLInputElement).value = '';
|
||||
}
|
||||
"
|
||||
/><button @click="openInput?.click()">プロジェクトを開く</button
|
||||
><input
|
||||
ref="openInput"
|
||||
hidden
|
||||
type="file"
|
||||
accept=".bkle.json,.json,application/json"
|
||||
@change="
|
||||
(e) => {
|
||||
const f = (e.target as HTMLInputElement).files?.[0];
|
||||
if (f) void readFile(f, 'project');
|
||||
(e.target as HTMLInputElement).value = '';
|
||||
}
|
||||
"
|
||||
/><button @click="save">プロジェクトを保存</button
|
||||
><button @click="exportSelected">KLE JSONを出力</button
|
||||
><button :disabled="!canUndo" @click="undo">Undo</button
|
||||
><button :disabled="!canRedo" @click="redo">Redo</button
|
||||
><span v-if="errorText" class="error">{{ errorText }}</span>
|
||||
</header>
|
||||
<nav class="tabs">
|
||||
<button
|
||||
v-for="tab in ['PHY', 'IDX', 'ELC', 'MAP', 'Generator']"
|
||||
:key="tab"
|
||||
:class="{ active: activeTab === tab }"
|
||||
@click="activeTab = tab"
|
||||
>
|
||||
{{ tab }}
|
||||
</button>
|
||||
</nav>
|
||||
<section v-if="activeTab === 'PHY'" class="workspace">
|
||||
<aside class="tree pane">
|
||||
<h2>PHYの木</h2>
|
||||
<div class="commands">
|
||||
<button :disabled="mismatch" @click="keyAdd">キー追加</button
|
||||
><select
|
||||
id="part-group"
|
||||
:disabled="mismatch"
|
||||
@change="componentAdd(($event.target as HTMLSelectElement).value)"
|
||||
>
|
||||
<option value="">部品追加…</option>
|
||||
<option>@led</option>
|
||||
<option>@encoder</option>
|
||||
<option>@screw</option>
|
||||
<option>@oled</option>
|
||||
<option>custom</option></select
|
||||
><button :disabled="mismatch || selection.length === 0" @click="makeCluster">クラスター化</button
|
||||
><button :disabled="mismatch || selectedNode?.type !== 'cluster'" @click="ungroup">解除</button
|
||||
><button :disabled="mismatch || selection.length !== 1" @click="duplicate">複製</button
|
||||
><button :disabled="mismatch || selection.length !== 1" @click="requestDelete">削除</button
|
||||
><select
|
||||
:disabled="mismatch || selection.length !== 1"
|
||||
@change="reparentTo(($event.target as HTMLSelectElement).value)"
|
||||
>
|
||||
<option value="">reparent先…</option>
|
||||
<option v-for="p in parents()" :key="p.id" :value="p.id">{{ p.label }}</option></select
|
||||
><button :disabled="mismatch || selection.length === 0" @click="createVariants">
|
||||
選択からVariantGroup
|
||||
</button>
|
||||
</div>
|
||||
<PhyTree
|
||||
:nodes="project.phy.root"
|
||||
:selected="selection"
|
||||
@select="(id, add) => setSelected(id, add)"
|
||||
/>
|
||||
<div v-if="pendingDelete" class="confirm-box">
|
||||
<strong>削除の確認: {{ pendingDelete.id }}</strong>
|
||||
<p>削除される参照 {{ pendingDelete.refs.length }} 件 (T-15)</p>
|
||||
<ul>
|
||||
<li v-for="(r, i) in pendingDelete.refs" :key="i">
|
||||
{{ r.layer }} · {{ r.id }} · {{ r.location }}
|
||||
</li>
|
||||
</ul>
|
||||
<button :disabled="mismatch" @click="confirmDelete">参照と一緒に削除</button
|
||||
><button @click="pendingDelete = null">キャンセル</button>
|
||||
</div>
|
||||
</aside>
|
||||
<section class="canvas-pane pane">
|
||||
<div class="canvas-head">
|
||||
<strong>レイアウト · {{ keyCount }} keys</strong
|
||||
><label>Zoom <input type="range" min="0.5" max="2" step="0.1" v-model.number="zoom" /></label
|
||||
><label v-for="n in variantGroups" :key="n.id"
|
||||
>{{ n.name }}
|
||||
<select
|
||||
:value="variants[n.id] ?? n.default"
|
||||
@change="changeVariant(n.id, ($event.target as HTMLSelectElement).value)"
|
||||
>
|
||||
<option v-for="v in n.children" :key="v.id" :value="v.id">{{ v.name }}</option></select
|
||||
><button :disabled="mismatch" @click="addVariantUi(n.id)">+</button
|
||||
><button :disabled="mismatch" @click="changeDefault(n.id, variants[n.id] ?? n.default)">
|
||||
default</button
|
||||
><button :disabled="mismatch" @click="removeVariantUi(variants[n.id] ?? n.default)">
|
||||
−
|
||||
</button></label
|
||||
>
|
||||
</div>
|
||||
<p v-if="mismatch" class="warning">unitSize が揃っていないPHYは編集できません。</p>
|
||||
<PhyCanvas
|
||||
:nodes="project.phy.root"
|
||||
:selected="selection"
|
||||
:variants="variants"
|
||||
:zoom="zoom"
|
||||
@select="(id, add) => setSelected(id, add)"
|
||||
@drag-start="nodeDown"
|
||||
/>
|
||||
</section>
|
||||
<aside class="properties pane">
|
||||
<h2>プロパティ</h2>
|
||||
<template v-if="selectedNode"
|
||||
><p>
|
||||
<b>{{ selectedNode.type }}</b
|
||||
><br /><small>{{ selectedNode.id }}</small>
|
||||
</p>
|
||||
<label
|
||||
>X
|
||||
<input
|
||||
type="number"
|
||||
step="any"
|
||||
:value="selectedNode.transform.x"
|
||||
@change="updateTransform('x', Number(($event.target as HTMLInputElement).value))"
|
||||
/><button @click="increment('x', 0.25)">±.25U</button></label
|
||||
><label
|
||||
>Y
|
||||
<input
|
||||
type="number"
|
||||
step="any"
|
||||
:value="selectedNode.transform.y"
|
||||
@change="updateTransform('y', Number(($event.target as HTMLInputElement).value))"
|
||||
/><button @click="increment('y', 0.25)">±.25U</button></label
|
||||
><label
|
||||
>Rotation
|
||||
<input
|
||||
type="number"
|
||||
step="any"
|
||||
:value="selectedNode.transform.rotation"
|
||||
@change="updateTransform('rotation', Number(($event.target as HTMLInputElement).value))"
|
||||
/><button @click="increment('rotation', 15)">±15°</button></label
|
||||
><button @click="rotateSelected">+15°回転</button
|
||||
><template v-if="selectedNode.type === 'key'"
|
||||
><label
|
||||
>Width
|
||||
<input
|
||||
type="number"
|
||||
step="any"
|
||||
:value="selectedNode.size.w"
|
||||
@change="updateSize('w', Number(($event.target as HTMLInputElement).value))" /></label
|
||||
><label
|
||||
>Height
|
||||
<input
|
||||
type="number"
|
||||
step="any"
|
||||
:value="selectedNode.size.h"
|
||||
@change="updateSize('h', Number(($event.target as HTMLInputElement).value))" /></label
|
||||
><label
|
||||
>Label
|
||||
<input
|
||||
:value="selectedNode.labels?.filter(Boolean)[0]"
|
||||
@change="updateLabel(($event.target as HTMLInputElement).value)" /></label></template
|
||||
><template v-if="selectedNode.type === 'cluster'"
|
||||
><h3>座標枠変更</h3>
|
||||
<label>原点 X <input type="number" v-model.number="promptValue.x" /></label
|
||||
><label>原点 Y <input type="number" v-model.number="promptValue.y" /></label
|
||||
><label>角度 <input type="number" v-model.number="promptValue.r" /></label
|
||||
><button @click="changeFrame">適用</button></template
|
||||
></template
|
||||
>
|
||||
<template v-else-if="selection.length > 1">
|
||||
<p>{{ selection.length }}件を選択中</p>
|
||||
<button :disabled="mismatch" @click="rotateSelected">選択を+15°回転</button>
|
||||
</template>
|
||||
<p v-else>ノードを選択してください。Shift+クリックで複数選択。</p>
|
||||
</aside>
|
||||
</section>
|
||||
<section v-else class="other-panel">
|
||||
<IdxPanel v-if="activeTab === 'IDX'" :project="project" :dispatch="dispatch" /><ElcPanel
|
||||
v-else-if="activeTab === 'ELC'"
|
||||
:project="project"
|
||||
:dispatch="dispatch"
|
||||
/><MapPanel
|
||||
v-else-if="activeTab === 'MAP'"
|
||||
:project="project"
|
||||
:dispatch="dispatch"
|
||||
:editable="!mismatch"
|
||||
/><GeneratorPanel v-else :project="project" :dispatch="dispatch" />
|
||||
</section>
|
||||
<div v-if="activeTab === 'PHY' && selectedNode" class="nudge-controls">
|
||||
<button :disabled="mismatch" @click="increment('x', -0.25)">X −.25U</button
|
||||
><button :disabled="mismatch" @click="increment('x', 0.25)">X +.25U</button
|
||||
><button :disabled="mismatch" @click="increment('y', -0.25)">Y −.25U</button
|
||||
><button :disabled="mismatch" @click="increment('y', 0.25)">Y +.25U</button
|
||||
><button :disabled="mismatch" @click="increment('rotation', -15)">回転 −15°</button
|
||||
><button :disabled="mismatch" @click="increment('rotation', 15)">回転 +15°</button>
|
||||
</div>
|
||||
<aside class="validation pane">
|
||||
<h2>検証結果</h2>
|
||||
<p v-if="issues.some((x) => x.severity === 'blocksSave')" class="warning" data-testid="save-blocked">
|
||||
保存できない状態です。blocksSave の問題を解消してください。
|
||||
</p>
|
||||
<div class="issues">
|
||||
<section v-for="s in severity" :key="s">
|
||||
<h3>
|
||||
{{ s }} <small>({{ issues.filter((x) => x.severity === s).length }})</small>
|
||||
</h3>
|
||||
<button
|
||||
v-for="(issue, i) in issues.filter((x) => x.severity === s)"
|
||||
:key="i"
|
||||
class="issue"
|
||||
@click="issue.ids?.[0] && setSelected(issue.ids[0], false)"
|
||||
>
|
||||
<b>{{ issue.code }}</b> {{ issue.message }} <small>{{ issue.path }}</small>
|
||||
</button>
|
||||
<p v-if="!issues.some((x) => x.severity === s)" class="muted">なし</p>
|
||||
</section>
|
||||
</div>
|
||||
</aside>
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
font:
|
||||
14px system-ui,
|
||||
sans-serif;
|
||||
color: #20242b;
|
||||
background: #edf0f4;
|
||||
}
|
||||
.app-shell {
|
||||
height: 100vh;
|
||||
display: grid;
|
||||
grid-template-rows: 52px 42px minmax(300px, 1fr) 180px;
|
||||
gap: 8px;
|
||||
padding: 8px;
|
||||
}
|
||||
.app-shell.locked .properties {
|
||||
pointer-events: none;
|
||||
opacity: 0.55;
|
||||
}
|
||||
.toolbar,
|
||||
.tabs,
|
||||
.pane,
|
||||
.placeholder {
|
||||
background: white;
|
||||
border: 1px solid #cbd1da;
|
||||
border-radius: 6px;
|
||||
}
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 7px;
|
||||
}
|
||||
.toolbar strong {
|
||||
margin-right: auto;
|
||||
}
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
padding: 4px;
|
||||
}
|
||||
.tabs button.active {
|
||||
background: #dce9ff;
|
||||
}
|
||||
.workspace {
|
||||
min-height: 0;
|
||||
display: grid;
|
||||
grid-template-columns: 260px minmax(300px, 1fr) 250px;
|
||||
gap: 8px;
|
||||
}
|
||||
.pane {
|
||||
padding: 10px;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
}
|
||||
.tree h2,
|
||||
.properties h2,
|
||||
.validation h2 {
|
||||
font-size: 16px;
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
.commands {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
.commands button,
|
||||
.commands select {
|
||||
font-size: 12px;
|
||||
}
|
||||
.tree-list {
|
||||
padding-left: 14px;
|
||||
list-style: none;
|
||||
margin: 3px 0;
|
||||
}
|
||||
.tree-node {
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
padding: 4px;
|
||||
}
|
||||
.tree-node small {
|
||||
color: #778;
|
||||
}
|
||||
.tree-node.chosen {
|
||||
background: #dce9ff;
|
||||
}
|
||||
.canvas-pane {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.canvas-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.canvas-head label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
.canvas {
|
||||
width: 1152px;
|
||||
height: 896px;
|
||||
min-height: 240px;
|
||||
flex: none;
|
||||
background-color: #fbfcfe;
|
||||
background-image:
|
||||
linear-gradient(#e7ebf1 1px, transparent 1px), linear-gradient(90deg, #e7ebf1 1px, transparent 1px);
|
||||
background-size: 64px 64px;
|
||||
touch-action: none;
|
||||
}
|
||||
.phy-node {
|
||||
cursor: grab;
|
||||
}
|
||||
.phy-node:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
.key-face {
|
||||
fill: #f8cc78;
|
||||
stroke: #5b4a2b;
|
||||
stroke-width: 0.025;
|
||||
vector-effect: non-scaling-stroke;
|
||||
}
|
||||
.secondary {
|
||||
fill: #ffe7ad;
|
||||
}
|
||||
.key-label {
|
||||
font-size: 0.13px;
|
||||
fill: #29251e;
|
||||
pointer-events: none;
|
||||
}
|
||||
.ghost {
|
||||
opacity: 0.4;
|
||||
}
|
||||
.decal .key-face {
|
||||
fill: #fff;
|
||||
stroke-dasharray: 0.08 0.06;
|
||||
}
|
||||
.chosen > .key-face,
|
||||
.chosen > .part {
|
||||
stroke: #1769d2;
|
||||
stroke-width: 0.055;
|
||||
}
|
||||
.part {
|
||||
fill: #b4d5ef;
|
||||
stroke: #315d7a;
|
||||
stroke-width: 0.03;
|
||||
}
|
||||
.part-label {
|
||||
font-size: 0.12px;
|
||||
fill: #333;
|
||||
}
|
||||
.selection-box {
|
||||
fill: none;
|
||||
stroke: #1769d2;
|
||||
stroke-width: 0.025;
|
||||
stroke-dasharray: 0.04;
|
||||
}
|
||||
.group-origin {
|
||||
fill: #d33;
|
||||
pointer-events: none;
|
||||
}
|
||||
.properties label {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
margin: 8px 0;
|
||||
}
|
||||
.properties input {
|
||||
width: 105px;
|
||||
margin-left: auto;
|
||||
}
|
||||
.nudge-controls {
|
||||
position: fixed;
|
||||
right: 270px;
|
||||
bottom: 194px;
|
||||
z-index: 4;
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
flex-wrap: wrap;
|
||||
max-width: calc(100vw - 540px);
|
||||
padding: 6px;
|
||||
background: #fff;
|
||||
border: 1px solid #adb8c8;
|
||||
border-radius: 6px;
|
||||
}
|
||||
.validation {
|
||||
grid-row: 4;
|
||||
overflow: hidden;
|
||||
}
|
||||
.issues {
|
||||
display: flex;
|
||||
gap: 20px;
|
||||
overflow: auto;
|
||||
}
|
||||
.issues section {
|
||||
min-width: 240px;
|
||||
}
|
||||
.issues h3 {
|
||||
font-size: 13px;
|
||||
}
|
||||
.issue {
|
||||
display: block;
|
||||
text-align: left;
|
||||
width: 100%;
|
||||
margin: 3px 0;
|
||||
border: 0;
|
||||
background: #f4f6f9;
|
||||
padding: 5px;
|
||||
}
|
||||
.issue small {
|
||||
display: block;
|
||||
color: #667;
|
||||
}
|
||||
.muted {
|
||||
color: #778;
|
||||
}
|
||||
.warning,
|
||||
.error {
|
||||
color: #9a4c00;
|
||||
}
|
||||
.error {
|
||||
max-width: 240px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.confirm-box {
|
||||
margin-top: 12px;
|
||||
padding: 8px;
|
||||
background: #fff2dc;
|
||||
border: 1px solid #db9d39;
|
||||
}
|
||||
.confirm-box ul {
|
||||
max-height: 90px;
|
||||
overflow: auto;
|
||||
padding-left: 18px;
|
||||
}
|
||||
.other-panel {
|
||||
min-height: 0;
|
||||
}
|
||||
.placeholder {
|
||||
padding: 20px;
|
||||
}
|
||||
.canvas-pane .warning {
|
||||
margin: 4px 0;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,135 @@
|
||||
<script setup lang="ts">
|
||||
// 選択構成の平坦な配置を読み取り専用で描く。IDX・ELC・MAP・Generatorのパネルで共有する。
|
||||
import { computed } from "vue";
|
||||
import { flattenKeys } from "../../domain/geometry";
|
||||
import type { FlatKey, PhyFile } from "../../domain/phy";
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
phy: PhyFile;
|
||||
selection: Record<string, string>;
|
||||
/** キーの中央に出す文字列。省略時は先頭のラベル */
|
||||
keyText?: (keyId: string) => string;
|
||||
/** キーに付けるCSSクラス(状態の色分け) */
|
||||
keyClass?: (keyId: string) => string | undefined;
|
||||
selectedIds?: string[];
|
||||
unit?: number;
|
||||
}>(),
|
||||
{ selectedIds: () => [], unit: 48 },
|
||||
);
|
||||
const emit = defineEmits<{ keyClick: [keyId: string, event: MouseEvent] }>();
|
||||
|
||||
const keys = computed<FlatKey[]>(() => flattenKeys(props.phy, props.selection));
|
||||
|
||||
// 回転を含めた四隅から表示範囲を求める
|
||||
const viewBox = computed(() => {
|
||||
let minX = Infinity,
|
||||
minY = Infinity,
|
||||
maxX = -Infinity,
|
||||
maxY = -Infinity;
|
||||
for (const k of keys.value) {
|
||||
const r = (k.rotation * Math.PI) / 180,
|
||||
c = Math.cos(r),
|
||||
s = Math.sin(r);
|
||||
const { w, h } = k.key.size;
|
||||
for (const [lx, ly] of [
|
||||
[0, 0],
|
||||
[w, 0],
|
||||
[0, h],
|
||||
[w, h],
|
||||
] as const) {
|
||||
const x = k.x + lx * c - ly * s,
|
||||
y = k.y + lx * s + ly * c;
|
||||
minX = Math.min(minX, x);
|
||||
minY = Math.min(minY, y);
|
||||
maxX = Math.max(maxX, x);
|
||||
maxY = Math.max(maxY, y);
|
||||
}
|
||||
}
|
||||
if (!isFinite(minX)) return "0 0 4 2";
|
||||
const pad = 0.25;
|
||||
return `${minX - pad} ${minY - pad} ${maxX - minX + pad * 2} ${maxY - minY + pad * 2}`;
|
||||
});
|
||||
const width = computed(() => {
|
||||
const parts = viewBox.value.split(" ").map(Number);
|
||||
return (parts[2] ?? 4) * props.unit;
|
||||
});
|
||||
|
||||
function text(k: FlatKey): string {
|
||||
return props.keyText ? props.keyText(k.key.id) : (k.key.labels?.find((l) => l) ?? "");
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<svg class="keyboard-view" :viewBox="viewBox" :width="width" data-testid="keyboard-view">
|
||||
<g
|
||||
v-for="k in keys"
|
||||
:key="k.key.id"
|
||||
:transform="`translate(${k.x},${k.y}) rotate(${k.rotation})`"
|
||||
:class="[
|
||||
'kv-key',
|
||||
keyClass?.(k.key.id),
|
||||
{ selected: selectedIds.includes(k.key.id), decal: k.key.decal, ghost: k.key.ghost },
|
||||
]"
|
||||
:data-key-id="k.key.id"
|
||||
@click="emit('keyClick', k.key.id, $event)"
|
||||
>
|
||||
<rect x="0.03" y="0.03" :width="k.key.size.w - 0.06" :height="k.key.size.h - 0.06" rx="0.08" />
|
||||
<rect
|
||||
v-if="k.key.size.w2 !== undefined || k.key.size.h2 !== undefined"
|
||||
:x="(k.key.size.x2 ?? 0) + 0.03"
|
||||
:y="(k.key.size.y2 ?? 0) + 0.03"
|
||||
:width="(k.key.size.w2 ?? k.key.size.w) - 0.06"
|
||||
:height="(k.key.size.h2 ?? k.key.size.h) - 0.06"
|
||||
rx="0.08"
|
||||
/>
|
||||
<text :x="k.key.size.w / 2" :y="k.key.size.h / 2" text-anchor="middle" dominant-baseline="central">
|
||||
{{ text(k) }}
|
||||
</text>
|
||||
</g>
|
||||
</svg>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.keyboard-view {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
user-select: none;
|
||||
}
|
||||
.kv-key {
|
||||
cursor: pointer;
|
||||
}
|
||||
.kv-key rect {
|
||||
fill: #f3f4f6;
|
||||
stroke: #6b7280;
|
||||
stroke-width: 0.02;
|
||||
}
|
||||
.kv-key text {
|
||||
font-size: 0.22px;
|
||||
fill: #111827;
|
||||
pointer-events: none;
|
||||
}
|
||||
.kv-key.selected rect {
|
||||
stroke: #2563eb;
|
||||
stroke-width: 0.06;
|
||||
}
|
||||
.kv-key.decal rect {
|
||||
stroke-dasharray: 0.06 0.04;
|
||||
fill: none;
|
||||
}
|
||||
.kv-key.ghost {
|
||||
opacity: 0.45;
|
||||
}
|
||||
.kv-key.warn rect {
|
||||
fill: #fde68a;
|
||||
}
|
||||
.kv-key.error rect {
|
||||
fill: #fecaca;
|
||||
}
|
||||
.kv-key.ok rect {
|
||||
fill: #d1fae5;
|
||||
}
|
||||
.kv-key.muted rect {
|
||||
fill: #e5e7eb;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,2 @@
|
||||
/** Small 4x4 starter layout, kept in src/ui rather than the test fixtures. */
|
||||
export const defaultLayout: unknown[] = Array.from({ length: 4 }, () => ["", "", "", ""]);
|
||||
@@ -0,0 +1,564 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { flattenKeys } from "../../domain/geometry";
|
||||
import {
|
||||
mcuPinCandidates,
|
||||
removeKeyWiring,
|
||||
setKeyWiring,
|
||||
setProvider,
|
||||
removeProvider,
|
||||
createLedChain,
|
||||
setLedOrder,
|
||||
} from "../../domain/elc";
|
||||
import type { ContactWiring, McuProvider, AnalogMuxProvider, PinRef } from "../../domain/elc";
|
||||
import { defaultVariantSelection, type ProjectFile } from "../../domain/project";
|
||||
import type { Node } from "../../domain/phy";
|
||||
import { validateProject } from "../../domain/validate";
|
||||
import { wireMatrixKeys } from "../../domain/elcMatrix";
|
||||
import type { Dispatch } from "../types";
|
||||
import KeyboardView from "../common/KeyboardView.vue";
|
||||
|
||||
const props = defineProps<{ project: ProjectFile; dispatch: Dispatch }>();
|
||||
const variants = computed(() => ({
|
||||
...defaultVariantSelection(props.project.phy),
|
||||
...props.project.output.variantSelection,
|
||||
}));
|
||||
const keys = computed(() =>
|
||||
flattenKeys(props.project.phy, variants.value)
|
||||
.filter((x) => !x.key.decal)
|
||||
.map((x) => x.key),
|
||||
);
|
||||
const selectedKeyId = ref("");
|
||||
const selectedKey = computed(() => keys.value.find((x) => x.id === selectedKeyId.value));
|
||||
const wired = computed(() => new Map(props.project.elc.keys.map((x) => [x.key, x])));
|
||||
const collisionIds = computed(
|
||||
() =>
|
||||
new Set(
|
||||
validateProject(props.project)
|
||||
.filter((x) => x.code === "wiring-collision")
|
||||
.flatMap((x) => x.ids ?? []),
|
||||
),
|
||||
);
|
||||
const unwired = computed(() => keys.value.filter((k) => !wired.value.has(k.id)).map((k) => k.id));
|
||||
const wiring = ref({ a: "", b: "", diode: "" as "" | "a-to-b" | "b-to-a" });
|
||||
watch(selectedKeyId, (id) => {
|
||||
const current = props.project.elc.keys.find((x) => x.key === id);
|
||||
wiring.value =
|
||||
current?.detect === "contact"
|
||||
? { a: current.terminals.a, b: current.terminals.b, diode: current.diode ?? "" }
|
||||
: { a: "", b: "", diode: "" };
|
||||
});
|
||||
const providerId = ref("MCU"),
|
||||
providerPart = ref("RP2040"),
|
||||
providerError = ref("");
|
||||
const providerCandidates = computed(() => {
|
||||
const p = { id: providerId.value, kind: "mcu" as const, part: providerPart.value };
|
||||
return mcuPinCandidates(p).map((name) => `${p.id}.${name}`);
|
||||
});
|
||||
const pinRefs = computed(() => [
|
||||
"VCC",
|
||||
"GND",
|
||||
...props.project.elc.providers.flatMap((p) =>
|
||||
p.kind === "mcu"
|
||||
? mcuPinCandidates(p).map((pin) => `${p.id}.${pin}`)
|
||||
: Array.from({ length: p.channels }, (_, i) => `${p.id}.${i}`),
|
||||
),
|
||||
]);
|
||||
const providerRows = computed(() => props.project.elc.providers);
|
||||
const mux = ref({ id: "MUX", channels: 8, select: "", common: "", enable: "" });
|
||||
const chainId = ref("LED"),
|
||||
chainData = ref(""),
|
||||
selectedChainId = ref("");
|
||||
const batchKeyIds = ref<string[]>([]),
|
||||
batchRows = ref<string[]>([]),
|
||||
batchCols = ref<string[]>([]);
|
||||
const batchRow = ref(""),
|
||||
batchCol = ref(""),
|
||||
batchDiode = ref<"" | "a-to-b" | "b-to-a">("a-to-b");
|
||||
const batchPreviewOpen = ref(false),
|
||||
batchError = ref("");
|
||||
const chains = computed(() => props.project.elc.ledChains ?? []);
|
||||
const nodes = computed(() => {
|
||||
const result: Array<{ id: string; label: string }> = [];
|
||||
const visit = (ns: Node[]) =>
|
||||
ns.forEach((n) => {
|
||||
if (n.type === "key" && n.perKeyLED) result.push({ id: n.id, label: `${n.id} · per-key LED` });
|
||||
else if (n.type === "component" && n.partGroup === "@led")
|
||||
result.push({ id: n.id, label: `${n.id} · @led` });
|
||||
else if (n.type === "cluster") visit(n.children);
|
||||
else if (n.type === "variantGroup") n.children.forEach((v) => visit(v.children));
|
||||
});
|
||||
visit(props.project.phy.root);
|
||||
return result;
|
||||
});
|
||||
const chain = computed(() => chains.value.find((x) => x.id === selectedChainId.value));
|
||||
const chainSelection = ref<string[]>([]);
|
||||
watch(selectedChainId, () => {
|
||||
chainSelection.value = [];
|
||||
});
|
||||
function clickKey(id: string) {
|
||||
selectedKeyId.value = id;
|
||||
if (chain.value && nodes.value.some((n) => n.id === id) && !chain.value.order.includes(id))
|
||||
setOrder([...chain.value.order, id]);
|
||||
}
|
||||
function keyClass(id: string) {
|
||||
return collisionIds.value.has(id) ? "error" : !wired.value.has(id) ? "warn" : "ok";
|
||||
}
|
||||
function commitWiring() {
|
||||
if (!selectedKeyId.value || !wiring.value.a || !wiring.value.b) return;
|
||||
const next: ContactWiring = {
|
||||
key: selectedKeyId.value,
|
||||
detect: "contact",
|
||||
terminals: { a: wiring.value.a, b: wiring.value.b },
|
||||
...(wiring.value.diode ? { diode: wiring.value.diode } : {}),
|
||||
};
|
||||
props.dispatch("接点配線", (p) => ({ ...p, elc: setKeyWiring(p.elc, next) }));
|
||||
}
|
||||
function removeWiring() {
|
||||
if (selectedKeyId.value)
|
||||
props.dispatch("配線解除", (p) => ({ ...p, elc: removeKeyWiring(p.elc, selectedKeyId.value) }));
|
||||
}
|
||||
function addMcu() {
|
||||
providerError.value = "";
|
||||
if (!providerId.value || providerId.value.includes(".")) {
|
||||
providerError.value = "IDは空欄にできず、'.'を含められません";
|
||||
return;
|
||||
}
|
||||
const p: McuProvider = { id: providerId.value, kind: "mcu", part: providerPart.value };
|
||||
props.dispatch("MCU追加・編集", (project) => ({ ...project, elc: setProvider(project.elc, p) }));
|
||||
}
|
||||
function editProvider(id: string) {
|
||||
const p = props.project.elc.providers.find((x) => x.id === id);
|
||||
if (p?.kind === "mcu") {
|
||||
providerId.value = p.id;
|
||||
providerPart.value = p.part;
|
||||
}
|
||||
}
|
||||
function addMux() {
|
||||
if (!mux.value.id || mux.value.id.includes(".")) {
|
||||
providerError.value = "IDは空欄にできず、'.'を含められません";
|
||||
return;
|
||||
}
|
||||
const p: AnalogMuxProvider = {
|
||||
id: mux.value.id,
|
||||
kind: "analog-mux",
|
||||
channels: Number(mux.value.channels),
|
||||
select: mux.value.select
|
||||
.split(",")
|
||||
.map((x) => x.trim())
|
||||
.filter(Boolean),
|
||||
common: mux.value.common,
|
||||
...(mux.value.enable ? { enable: mux.value.enable } : {}),
|
||||
};
|
||||
props.dispatch("analog-mux追加・編集", (project) => ({ ...project, elc: setProvider(project.elc, p) }));
|
||||
}
|
||||
function removeProviderUi(id: string) {
|
||||
props.dispatch("提供者削除", (p) => ({ ...p, elc: removeProvider(p.elc, id) }));
|
||||
}
|
||||
function makeChain() {
|
||||
if (!chainId.value || !chainData.value) return;
|
||||
try {
|
||||
props.dispatch("LEDチェーン作成", (p) => ({
|
||||
...p,
|
||||
elc: createLedChain(p.elc, chainId.value, chainData.value),
|
||||
}));
|
||||
selectedChainId.value = chainId.value;
|
||||
} catch (e) {
|
||||
providerError.value = String(e);
|
||||
}
|
||||
}
|
||||
function setOrder(order: string[]) {
|
||||
if (chain.value)
|
||||
props.dispatch("LED順序", (p) => ({ ...p, elc: setLedOrder(p.elc, chain.value!.id, order) }));
|
||||
}
|
||||
function moveLed(index: number, direction: number) {
|
||||
const order = [...(chain.value?.order ?? [])];
|
||||
const to = index + direction;
|
||||
if (to < 0 || to >= order.length) return;
|
||||
[order[index], order[to]] = [order[to]!, order[index]!];
|
||||
setOrder(order);
|
||||
}
|
||||
function removeLed(index: number) {
|
||||
const order = [...(chain.value?.order ?? [])];
|
||||
order.splice(index, 1);
|
||||
setOrder(order);
|
||||
}
|
||||
function toggleBatchKey(id: string) {
|
||||
batchKeyIds.value = batchKeyIds.value.includes(id)
|
||||
? batchKeyIds.value.filter((x) => x !== id)
|
||||
: [...batchKeyIds.value, id];
|
||||
}
|
||||
function moveBatchPin(kind: "row" | "col", index: number, delta: number) {
|
||||
const list = kind === "row" ? batchRows.value : batchCols.value;
|
||||
const nextIndex = index + delta;
|
||||
if (nextIndex < 0 || nextIndex >= list.length) return;
|
||||
[list[index], list[nextIndex]] = [list[nextIndex]!, list[index]!];
|
||||
}
|
||||
function batchWire() {
|
||||
if (!batchKeyIds.value.length || !batchRows.value.length || !batchCols.value.length) return;
|
||||
// Matrix assignment follows the visible PHY key order, regardless of click order.
|
||||
const orderedKeys = keys.value.map((k) => k.id).filter((id) => batchKeyIds.value.includes(id));
|
||||
try {
|
||||
props.dispatch("一括配線", (p) => ({
|
||||
...p,
|
||||
elc: wireMatrixKeys(
|
||||
p.elc,
|
||||
orderedKeys,
|
||||
batchRows.value,
|
||||
batchCols.value,
|
||||
batchDiode.value || undefined,
|
||||
),
|
||||
}));
|
||||
batchError.value = "";
|
||||
batchPreviewOpen.value = false;
|
||||
} catch (e) {
|
||||
batchError.value = e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
}
|
||||
const batchOrderedKeys = computed(() =>
|
||||
keys.value.map((k) => k.id).filter((id) => batchKeyIds.value.includes(id)),
|
||||
);
|
||||
const batchCapacityError = computed(
|
||||
() => batchOrderedKeys.value.length > batchRows.value.length * batchCols.value.length,
|
||||
);
|
||||
const batchPreview = computed(() =>
|
||||
batchOrderedKeys.value.map((key, i) => ({
|
||||
key,
|
||||
row: batchRows.value[Math.floor(i / batchCols.value.length)],
|
||||
col: batchCols.value[i % batchCols.value.length],
|
||||
overwrite: wired.value.has(key),
|
||||
})),
|
||||
);
|
||||
const ledCandidate = ref("");
|
||||
function addLedCandidate() {
|
||||
if (
|
||||
chain.value &&
|
||||
nodes.value.some((n) => n.id === ledCandidate.value) &&
|
||||
!chain.value.order.includes(ledCandidate.value)
|
||||
)
|
||||
setOrder([...chain.value.order, ledCandidate.value]);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="elc-panel">
|
||||
<h2>Wiring Editor</h2>
|
||||
<div class="elc-grid">
|
||||
<section class="box">
|
||||
<h3>ピン提供者</h3>
|
||||
<ul>
|
||||
<li v-for="p in providerRows" :key="p.id">
|
||||
<button @click="editProvider(p.id)">
|
||||
{{ p.id }} · {{ p.kind }} · {{ p.kind === "mcu" ? p.part : `${p.channels} channels` }}
|
||||
</button>
|
||||
<button @click="removeProviderUi(p.id)">削除</button>
|
||||
<div v-if="p.kind === 'analog-mux'">
|
||||
select {{ p.select.join(", ") }} / common {{ p.common
|
||||
}}<span v-if="p.enable"> / enable {{ p.enable }}</span> (データ保持のみ)
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<label>ID <input v-model="providerId" data-testid="provider-id" /></label
|
||||
><label
|
||||
>MCU品番 <input v-model="providerPart" list="mcu-parts" /><datalist id="mcu-parts">
|
||||
<option>RP2040</option>
|
||||
</datalist></label
|
||||
><button @click="addMcu">MCUを追加・更新</button>
|
||||
<p v-if="providerCandidates.length">候補: {{ providerCandidates.join(", ") }}</p>
|
||||
<p v-else>未知の品番はピン名を自由入力します。</p>
|
||||
<hr />
|
||||
<h4>analog-mux (保持のみ)</h4>
|
||||
<label>ID <input v-model="mux.id" /></label
|
||||
><label>channels <input type="number" min="1" v-model.number="mux.channels" /></label
|
||||
><label>select (カンマ区切り) <input v-model="mux.select" /></label
|
||||
><label>common <input v-model="mux.common" /></label
|
||||
><label>enable <input v-model="mux.enable" /></label
|
||||
><button @click="addMux">analog-muxを追加・更新</button>
|
||||
<p v-if="providerError" class="error-text">{{ providerError }}</p>
|
||||
</section>
|
||||
<section class="box wiring-box">
|
||||
<h3>選択構成のキー配線</h3>
|
||||
<p>
|
||||
未配線: <b data-testid="unwired-count">{{ unwired.length }}</b> / {{ keys.length }}
|
||||
</p>
|
||||
<KeyboardView
|
||||
:phy="project.phy"
|
||||
:selection="variants"
|
||||
:selected-ids="selectedKeyId ? [selectedKeyId] : []"
|
||||
:key-class="keyClass"
|
||||
:key-text="
|
||||
(id) => {
|
||||
const w = wired.get(id);
|
||||
return w?.detect === 'contact'
|
||||
? `${w.terminals.a.split('.').at(-1)}/${w.terminals.b.split('.').at(-1)}`
|
||||
: w
|
||||
? 'analog'
|
||||
: id.slice(-3);
|
||||
}
|
||||
"
|
||||
@key-click="(id) => clickKey(id)"
|
||||
/>
|
||||
<p>
|
||||
色: <span class="warn-text">黄 未配線</span> · <span class="error-text">赤 衝突</span> · 緑 配線済み
|
||||
</p>
|
||||
<div v-if="selectedKey" class="edit-form">
|
||||
<h4>{{ selectedKey.id }} · 接点端子</h4>
|
||||
<label
|
||||
>a
|
||||
<select v-model="wiring.a">
|
||||
<option value="">選択…</option>
|
||||
<option v-for="pin in pinRefs" :key="`a${pin}`" :value="pin">{{ pin }}</option></select
|
||||
><input v-model="wiring.a" aria-label="a端子自由入力" placeholder="自由入力: provider.pin"
|
||||
/></label>
|
||||
<label
|
||||
>b
|
||||
<select v-model="wiring.b">
|
||||
<option value="">選択…</option>
|
||||
<option v-for="pin in pinRefs" :key="`b${pin}`" :value="pin">{{ pin }}</option></select
|
||||
><input v-model="wiring.b" aria-label="b端子自由入力" placeholder="自由入力: provider.pin"
|
||||
/></label>
|
||||
<label
|
||||
>ダイオード
|
||||
<select v-model="wiring.diode">
|
||||
<option value="">なし</option>
|
||||
<option value="a-to-b">a-to-b</option>
|
||||
<option value="b-to-a">b-to-a</option>
|
||||
</select></label
|
||||
><button @click="commitWiring">配線を保存</button><button @click="removeWiring">配線解除</button>
|
||||
</div>
|
||||
<p v-else>キーをクリックして端子を編集します。</p>
|
||||
<h4>未配線・衝突</h4>
|
||||
<p>未配線 ({{ unwired.length }}): {{ unwired.join(", ") || "なし" }}</p>
|
||||
<ul>
|
||||
<li
|
||||
v-for="issue in validateProject(project).filter((x) => x.code === 'wiring-collision')"
|
||||
:key="issue.ids?.join('-')"
|
||||
>
|
||||
{{ issue.code }}: {{ issue.ids?.join(" ↔ ") }}
|
||||
</li>
|
||||
</ul>
|
||||
<hr />
|
||||
<h4>一括配線</h4>
|
||||
<p>
|
||||
キーを選び、row/colピンの順序を指定して配線します。選択キーにはPHY表示順でrowを進め、各row内でcolを進めます。
|
||||
</p>
|
||||
<KeyboardView
|
||||
:phy="project.phy"
|
||||
:selection="variants"
|
||||
:selected-ids="batchKeyIds"
|
||||
:key-text="(id) => id.slice(-3)"
|
||||
@key-click="(id) => toggleBatchKey(id)"
|
||||
/>
|
||||
<p>選択キー: {{ batchKeyIds.length }}</p>
|
||||
<div class="batch-controls">
|
||||
<label
|
||||
>rowピン<select v-model="batchRow" data-testid="batch-row-select">
|
||||
<option value="">選択…</option>
|
||||
<option
|
||||
v-for="pin in pinRefs.filter((x) => x !== 'VCC' && x !== 'GND')"
|
||||
:key="`br-${pin}`"
|
||||
:value="pin"
|
||||
>
|
||||
{{ pin }}
|
||||
</option>
|
||||
</select></label
|
||||
>
|
||||
<button
|
||||
@click="
|
||||
if (batchRow && !batchRows.includes(batchRow)) batchRows.push(batchRow);
|
||||
batchRow = '';
|
||||
"
|
||||
>
|
||||
rowへ追加
|
||||
</button>
|
||||
<ol>
|
||||
<li v-for="(pin, i) in batchRows" :key="`br-${i}-${pin}`">
|
||||
{{ i }}: {{ pin }} <button @click="moveBatchPin('row', i, -1)">↑</button
|
||||
><button @click="moveBatchPin('row', i, 1)">↓</button
|
||||
><button @click="batchRows.splice(i, 1)">除去</button>
|
||||
</li>
|
||||
</ol>
|
||||
<label
|
||||
>colピン<select v-model="batchCol" data-testid="batch-col-select">
|
||||
<option value="">選択…</option>
|
||||
<option
|
||||
v-for="pin in pinRefs.filter((x) => x !== 'VCC' && x !== 'GND')"
|
||||
:key="`bc-${pin}`"
|
||||
:value="pin"
|
||||
>
|
||||
{{ pin }}
|
||||
</option>
|
||||
</select></label
|
||||
>
|
||||
<button
|
||||
@click="
|
||||
if (batchCol && !batchCols.includes(batchCol)) batchCols.push(batchCol);
|
||||
batchCol = '';
|
||||
"
|
||||
>
|
||||
colへ追加
|
||||
</button>
|
||||
<ol>
|
||||
<li v-for="(pin, i) in batchCols" :key="`bc-${i}-${pin}`">
|
||||
{{ i }}: {{ pin }} <button @click="moveBatchPin('col', i, -1)">↑</button
|
||||
><button @click="moveBatchPin('col', i, 1)">↓</button
|
||||
><button @click="batchCols.splice(i, 1)">除去</button>
|
||||
</li>
|
||||
</ol>
|
||||
<label
|
||||
>ダイオード<select v-model="batchDiode">
|
||||
<option value="">なし</option>
|
||||
<option value="a-to-b">a-to-b</option>
|
||||
<option value="b-to-a">b-to-a</option>
|
||||
</select></label
|
||||
>
|
||||
<button
|
||||
data-testid="batch-wire"
|
||||
:disabled="!batchKeyIds.length || !batchRows.length || !batchCols.length"
|
||||
@click="
|
||||
batchPreviewOpen = true;
|
||||
batchError = '';
|
||||
"
|
||||
>
|
||||
割当プレビュー
|
||||
</button>
|
||||
<p v-if="batchCapacityError" role="alert" data-testid="batch-capacity-error">
|
||||
容量不足: {{ batchOrderedKeys.length }} keys / {{ batchRows.length * batchCols.length }} positions
|
||||
</p>
|
||||
<p v-if="batchError" role="alert">{{ batchError }}</p>
|
||||
<section v-if="batchPreviewOpen" data-testid="batch-preview">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>キー</th>
|
||||
<th>rowピン</th>
|
||||
<th>colピン</th>
|
||||
<th>既存配線</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="item in batchPreview" :key="item.key">
|
||||
<td>{{ item.key }}</td>
|
||||
<td>{{ item.row }}</td>
|
||||
<td>{{ item.col }}</td>
|
||||
<td>{{ item.overwrite ? "上書き" : "新規" }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<button data-testid="batch-confirm" :disabled="batchCapacityError" @click="batchWire">
|
||||
この内容で確定
|
||||
</button>
|
||||
<button @click="batchPreviewOpen = false">キャンセル</button>
|
||||
</section>
|
||||
</div>
|
||||
</section>
|
||||
<section class="box">
|
||||
<h3>LEDチェーン</h3>
|
||||
<label>チェーンID <input v-model="chainId" /></label
|
||||
><label>データピン <input v-model="chainData" list="pin-options" placeholder="provider.pin" /></label
|
||||
><datalist id="pin-options">
|
||||
<option v-for="pin in pinRefs" :key="pin">{{ pin }}</option></datalist
|
||||
><button @click="makeChain">作成</button>
|
||||
<label
|
||||
>編集するチェーン
|
||||
<select v-model="selectedChainId">
|
||||
<option value="">選択…</option>
|
||||
<option v-for="c in chains" :key="c.id" :value="c.id">{{ c.id }}</option>
|
||||
</select></label
|
||||
>
|
||||
<p>対象は全バリアントのper-key LEDキーと@led部品ノードです。</p>
|
||||
<label
|
||||
>追加するLED
|
||||
<select v-model="ledCandidate" data-testid="led-candidate">
|
||||
<option value="">選択…</option>
|
||||
<option v-for="n in nodes" :key="n.id" :value="n.id">{{ n.label }}</option>
|
||||
</select></label
|
||||
>
|
||||
<button data-testid="led-add" :disabled="!ledCandidate || !chain" @click="addLedCandidate">
|
||||
チェーン末尾へ追加
|
||||
</button>
|
||||
<KeyboardView
|
||||
v-if="chain"
|
||||
:phy="project.phy"
|
||||
:selection="variants"
|
||||
:selected-ids="chain.order"
|
||||
:key-text="(id) => String(chain!.order.indexOf(id) + 1 || '')"
|
||||
@key-click="
|
||||
(id) => {
|
||||
if (nodes.some((n) => n.id === id) && !chain!.order.includes(id))
|
||||
setOrder([...chain!.order, id]);
|
||||
}
|
||||
"
|
||||
/>
|
||||
<ol>
|
||||
<li v-for="(id, i) in chain?.order ?? []" :key="`${id}-${i}`">
|
||||
{{ i }} · {{ id }} <button @click="moveLed(i, -1)">↑</button
|
||||
><button @click="moveLed(i, 1)">↓</button><button @click="removeLed(i)">除去</button>
|
||||
</li>
|
||||
</ol>
|
||||
</section>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.elc-panel {
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
padding: 12px;
|
||||
background: #fff;
|
||||
border: 1px solid #cbd1da;
|
||||
border-radius: 6px;
|
||||
}
|
||||
.elc-grid {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(230px, 1fr) minmax(320px, 1.5fr) minmax(230px, 1fr);
|
||||
gap: 10px;
|
||||
}
|
||||
.box {
|
||||
padding: 10px;
|
||||
border: 1px solid #d2d7df;
|
||||
border-radius: 5px;
|
||||
overflow: auto;
|
||||
}
|
||||
.box label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin: 6px 0;
|
||||
}
|
||||
.box input,
|
||||
.box select {
|
||||
max-width: 170px;
|
||||
}
|
||||
.wiring-box {
|
||||
min-width: 0;
|
||||
}
|
||||
.edit-form {
|
||||
border-top: 1px solid #ddd;
|
||||
padding-top: 6px;
|
||||
}
|
||||
.edit-form label {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.batch-controls {
|
||||
padding: 8px;
|
||||
background: #f6f8fa;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.batch-controls ol {
|
||||
margin-top: 4px;
|
||||
}
|
||||
.warn-text {
|
||||
color: #985c00;
|
||||
}
|
||||
.error-text {
|
||||
color: #b42318;
|
||||
}
|
||||
.warn :deep(rect) {
|
||||
fill: #fde68a;
|
||||
}
|
||||
.error :deep(rect) {
|
||||
fill: #fecaca;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,275 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { defaultVariantSelection, type ProjectFile } from "../../domain/project";
|
||||
import type { Node, VariantGroupNode } from "../../domain/phy";
|
||||
import { flattenKeys } from "../../domain/geometry";
|
||||
import { mcuPinCandidates } from "../../domain/elc";
|
||||
import { generateMockTarget } from "../../domain/generator";
|
||||
import type { Dispatch } from "../types";
|
||||
import KeyboardView from "../common/KeyboardView.vue";
|
||||
|
||||
const props = defineProps<{ project: ProjectFile; dispatch: Dispatch }>();
|
||||
const selection = computed(() => ({
|
||||
...defaultVariantSelection(props.project.phy),
|
||||
...props.project.output.variantSelection,
|
||||
}));
|
||||
const groups = computed(() => {
|
||||
const all: VariantGroupNode[] = [];
|
||||
const visit = (ns: Node[]) =>
|
||||
ns.forEach((n) => {
|
||||
if (n.type === "cluster") visit(n.children);
|
||||
else if (n.type === "variantGroup") {
|
||||
all.push(n);
|
||||
n.children.forEach((v) => visit(v.children));
|
||||
}
|
||||
});
|
||||
visit(props.project.phy.root);
|
||||
return all;
|
||||
});
|
||||
const pins = computed(() => [
|
||||
...new Set(
|
||||
props.project.elc.providers.flatMap((p) =>
|
||||
p.kind === "mcu"
|
||||
? mcuPinCandidates(p).map((x) => `${p.id}.${x}`)
|
||||
: Array.from({ length: p.channels }, (_, i) => `${p.id}.${i}`),
|
||||
),
|
||||
),
|
||||
]);
|
||||
const rowAdd = ref(""),
|
||||
colAdd = ref("");
|
||||
const result = ref<ReturnType<typeof generateMockTarget> | null>(null);
|
||||
watch(
|
||||
() => props.project,
|
||||
() => {
|
||||
result.value = null;
|
||||
},
|
||||
);
|
||||
const rows = computed(() => props.project.output.matrix?.rowPins ?? []),
|
||||
cols = computed(() => props.project.output.matrix?.colPins ?? []);
|
||||
const flatKeys = computed(() => flattenKeys(props.project.phy, selection.value).filter((x) => !x.key.decal));
|
||||
const mappingById = computed(() => new Map((result.value?.target?.mapping ?? []).map((m) => [m.keyId, m])));
|
||||
function setVariant(groupId: string, variantId: string) {
|
||||
props.dispatch("出力構成", (p) => ({
|
||||
...p,
|
||||
output: { ...p.output, variantSelection: { ...selection.value, [groupId]: variantId } },
|
||||
}));
|
||||
result.value = null;
|
||||
}
|
||||
function setPins(kind: "rowPins" | "colPins", value: string[]) {
|
||||
props.dispatch(kind === "rowPins" ? "rowピン順序" : "colピン順序", (p) => ({
|
||||
...p,
|
||||
output: {
|
||||
...p.output,
|
||||
matrix: {
|
||||
...p.output.matrix,
|
||||
kind: "matrix",
|
||||
rowPins: [...(p.output.matrix?.rowPins ?? [])],
|
||||
colPins: [...(p.output.matrix?.colPins ?? [])],
|
||||
[kind]: value,
|
||||
},
|
||||
},
|
||||
}));
|
||||
result.value = null;
|
||||
}
|
||||
function addPin(kind: "rowPins" | "colPins", pin: string) {
|
||||
if (!pin) return;
|
||||
const current = kind === "rowPins" ? rows.value : cols.value;
|
||||
if (current.includes(pin)) return;
|
||||
setPins(kind, [...current, pin]);
|
||||
if (kind === "rowPins") rowAdd.value = "";
|
||||
else colAdd.value = "";
|
||||
}
|
||||
function movePin(kind: "rowPins" | "colPins", index: number, d: number) {
|
||||
const next = [...(kind === "rowPins" ? rows.value : cols.value)],
|
||||
to = index + d;
|
||||
if (to < 0 || to >= next.length) return;
|
||||
[next[index], next[to]] = [next[to]!, next[index]!];
|
||||
setPins(kind, next);
|
||||
}
|
||||
function removePin(kind: "rowPins" | "colPins", index: number) {
|
||||
const next = [...(kind === "rowPins" ? rows.value : cols.value)];
|
||||
next.splice(index, 1);
|
||||
setPins(kind, next);
|
||||
}
|
||||
function generate() {
|
||||
result.value = generateMockTarget(props.project);
|
||||
}
|
||||
function download() {
|
||||
if (!result.value?.target) return;
|
||||
const blob = new Blob([JSON.stringify(result.value.target, null, 2)], { type: "application/json" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = "mock-target.json";
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
function keyText(id: string) {
|
||||
const m = mappingById.value.get(id);
|
||||
return m ? `${m.number}\nr${m.row} c${m.col}` : id.slice(-3);
|
||||
}
|
||||
function keyClass(id: string) {
|
||||
return mappingById.value.has(id) ? "ok" : "muted";
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="generator-panel">
|
||||
<h2>Generator · プレビュー</h2>
|
||||
<p class="notice">
|
||||
これは検証用の <code>mock-target.json</code> です。QMKにそのまま渡せる生成物ではありません。
|
||||
</p>
|
||||
<div class="settings">
|
||||
<section class="box">
|
||||
<h3>出力構成</h3>
|
||||
<label v-for="g in groups" :key="g.id"
|
||||
>{{ g.name }}
|
||||
<select
|
||||
:value="selection[g.id] ?? g.default"
|
||||
@change="setVariant(g.id, ($event.target as HTMLSelectElement).value)"
|
||||
>
|
||||
<option v-for="v in g.children" :key="v.id" :value="v.id">{{ v.name }}</option>
|
||||
</select></label
|
||||
>
|
||||
<p v-if="!groups.length">バリアントグループなし</p>
|
||||
</section>
|
||||
<section class="box">
|
||||
<h3>Matrix row / col</h3>
|
||||
<p>ELCで使うピン候補から順序を設定します。番号はリスト順です。</p>
|
||||
<h4>rowPins</h4>
|
||||
<ol>
|
||||
<li v-for="(pin, i) in rows" :key="`${pin}-${i}`">
|
||||
{{ i }}: {{ pin }} <button @click="movePin('rowPins', i, -1)">↑</button
|
||||
><button @click="movePin('rowPins', i, 1)">↓</button
|
||||
><button @click="removePin('rowPins', i)">削除</button>
|
||||
</li>
|
||||
</ol>
|
||||
<select v-model="rowAdd" data-testid="row-pin-select">
|
||||
<option value="">ピンを選択…</option>
|
||||
<option v-for="pin in pins" :key="`r${pin}`">{{ pin }}</option></select
|
||||
><button @click="addPin('rowPins', rowAdd)">row追加</button>
|
||||
<h4>colPins</h4>
|
||||
<ol>
|
||||
<li v-for="(pin, i) in cols" :key="`${pin}-${i}`">
|
||||
{{ i }}: {{ pin }} <button @click="movePin('colPins', i, -1)">↑</button
|
||||
><button @click="movePin('colPins', i, 1)">↓</button
|
||||
><button @click="removePin('colPins', i)">削除</button>
|
||||
</li>
|
||||
</ol>
|
||||
<select v-model="colAdd" data-testid="col-pin-select">
|
||||
<option value="">ピンを選択…</option>
|
||||
<option v-for="pin in pins" :key="`c${pin}`">{{ pin }}</option></select
|
||||
><button @click="addPin('colPins', colAdd)">col追加</button>
|
||||
<p v-if="!pins.length">ELCのピン提供者を先に追加してください。</p>
|
||||
</section>
|
||||
<section class="box preview">
|
||||
<h3>生成結果</h3>
|
||||
<button data-testid="generate-button" @click="generate">生成</button
|
||||
><span v-if="result?.target" data-testid="mapping-count"> {{ result.target.mapping.length }}行</span>
|
||||
<div v-if="result && !result.target" class="errors">
|
||||
<h4>生成を止めた理由 ({{ result.errors.length }})</h4>
|
||||
<ul>
|
||||
<li v-for="(e, i) in result.errors" :key="`${e.code}-${i}`">
|
||||
<b>{{ e.code }}</b> {{ e.message }} <small>{{ e.ids?.join(", ") }}</small>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<template v-if="result?.target"
|
||||
><button data-testid="download-target" @click="download">mock-target.jsonをダウンロード</button>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>出力番号</th>
|
||||
<th>keyId</th>
|
||||
<th>row</th>
|
||||
<th>col</th>
|
||||
<th>ラベル</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="m in result.target.mapping" :key="m.keyId">
|
||||
<td>{{ m.number }}</td>
|
||||
<td>{{ m.keyId }}</td>
|
||||
<td>{{ m.row }}</td>
|
||||
<td>{{ m.col }}</td>
|
||||
<td>{{ m.label }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<h4>レイヤー配列</h4>
|
||||
<section v-for="layer in result.target.keymaps" :key="layer.name">
|
||||
<b>{{ layer.name }}</b
|
||||
><code class="array">{{ JSON.stringify(layer.keycodes) }}</code>
|
||||
</section>
|
||||
</template>
|
||||
</section>
|
||||
</div>
|
||||
<section class="layout-box">
|
||||
<h3>選択構成 · 番号 / row,col</h3>
|
||||
<KeyboardView :phy="project.phy" :selection="selection" :key-text="keyText" :key-class="keyClass" />
|
||||
</section>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.generator-panel {
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
padding: 12px;
|
||||
background: #fff;
|
||||
border: 1px solid #cbd1da;
|
||||
border-radius: 6px;
|
||||
}
|
||||
.notice {
|
||||
padding: 8px;
|
||||
background: #fff4d6;
|
||||
}
|
||||
.settings {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(220px, 0.8fr) minmax(260px, 1fr) minmax(380px, 1.5fr);
|
||||
gap: 10px;
|
||||
}
|
||||
.box,
|
||||
.layout-box {
|
||||
padding: 10px;
|
||||
border: 1px solid #d2d7df;
|
||||
border-radius: 5px;
|
||||
overflow: auto;
|
||||
}
|
||||
.box label {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
margin: 8px 0;
|
||||
}
|
||||
.box h3,
|
||||
.layout-box h3 {
|
||||
margin-top: 0;
|
||||
}
|
||||
.preview table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.preview th,
|
||||
.preview td {
|
||||
border: 1px solid #d8dde5;
|
||||
padding: 3px 5px;
|
||||
text-align: left;
|
||||
}
|
||||
.errors {
|
||||
color: #9b1c1c;
|
||||
}
|
||||
.array {
|
||||
display: block;
|
||||
overflow-wrap: anywhere;
|
||||
margin: 5px 0 10px;
|
||||
}
|
||||
.layout-box {
|
||||
margin-top: 10px;
|
||||
}
|
||||
.layout-box :deep(.kv-key text) {
|
||||
font-size: 0.16px;
|
||||
white-space: pre;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,254 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from "vue";
|
||||
import { flattenKeys } from "../../domain/geometry";
|
||||
import type { Node, VariantGroupNode } from "../../domain/phy";
|
||||
import { appendKeys, excludeKey, reorderKeys, unregisteredKeys } from "../../domain/idx";
|
||||
import { defaultVariantSelection, type ProjectFile } from "../../domain/project";
|
||||
import type { Dispatch } from "../types";
|
||||
import KeyboardView from "../common/KeyboardView.vue";
|
||||
|
||||
const props = defineProps<{ project: ProjectFile; dispatch: Dispatch }>();
|
||||
const selectedKey = ref("");
|
||||
const selection = computed(() => ({
|
||||
...defaultVariantSelection(props.project.phy),
|
||||
...props.project.output.variantSelection,
|
||||
}));
|
||||
const groups = computed(() => {
|
||||
const out: VariantGroupNode[] = [];
|
||||
const walk = (nodes: Node[]) =>
|
||||
nodes.forEach((n) => {
|
||||
if (n.type === "cluster") walk(n.children);
|
||||
if (n.type === "variantGroup") {
|
||||
out.push(n);
|
||||
n.children.forEach((v) => walk(v.children));
|
||||
}
|
||||
});
|
||||
walk(props.project.phy.root);
|
||||
return out;
|
||||
});
|
||||
type Entry = { id: string; label: string; path: string; pathIds: string[] };
|
||||
const entries = computed<Entry[]>(() => {
|
||||
const out: Entry[] = [];
|
||||
const walk = (nodes: Node[], path: string[]) =>
|
||||
nodes.forEach((n) => {
|
||||
if (n.type === "cluster") walk(n.children, [...path, n.name || n.id]);
|
||||
else if (n.type === "key") {
|
||||
if (!n.decal)
|
||||
out.push({
|
||||
id: n.id,
|
||||
label: n.labels?.find(Boolean) || "(ラベルなし)",
|
||||
path: path.join(" / ") || "ルート",
|
||||
pathIds: path,
|
||||
});
|
||||
} else if (n.type === "variantGroup") {
|
||||
n.children.forEach((v) => walk(v.children, [...path, `${n.name} / ${v.name}`]));
|
||||
}
|
||||
});
|
||||
walk(props.project.phy.root, []);
|
||||
return out;
|
||||
});
|
||||
const byId = computed(() => new Map(entries.value.map((e) => [e.id, e])));
|
||||
const unregistered = computed(() => new Set(unregisteredKeys(props.project.phy, props.project.idx)));
|
||||
const displayKeys = computed(() =>
|
||||
flattenKeys(props.project.phy, selection.value).filter((k) => !k.key.decal),
|
||||
);
|
||||
const outputNumbers = computed(() => {
|
||||
const active = new Set(displayKeys.value.map((k) => k.key.id));
|
||||
return new Map(props.project.idx.order.filter((id) => active.has(id)).map((id, index) => [id, index]));
|
||||
});
|
||||
const rowEntries = computed(() =>
|
||||
props.project.idx.order.map(
|
||||
(id) => byId.value.get(id) ?? { id, label: "(PHYに存在しないキー)", path: "不明", pathIds: [] },
|
||||
),
|
||||
);
|
||||
function setVariant(groupId: string, variantId: string) {
|
||||
props.dispatch("IDX出力構成変更", (p) => ({
|
||||
...p,
|
||||
output: { ...p.output, variantSelection: { ...p.output.variantSelection, [groupId]: variantId } },
|
||||
}));
|
||||
}
|
||||
function register(id: string) {
|
||||
props.dispatch("IDXキー登録", (p) => ({ ...p, idx: appendKeys(p.idx, [id]) }));
|
||||
}
|
||||
function exclude(id: string) {
|
||||
props.dispatch("IDXキー除外", (p) => ({ ...p, idx: excludeKey(p.idx, id) }));
|
||||
}
|
||||
function move(id: string, delta: number) {
|
||||
const i = props.project.idx.order.indexOf(id),
|
||||
j = i + delta;
|
||||
if (j < 0 || j >= props.project.idx.order.length) return;
|
||||
const order = [...props.project.idx.order];
|
||||
[order[i], order[j]] = [order[j]!, order[i]!];
|
||||
props.dispatch("IDX順序変更", (p) => ({ ...p, idx: reorderKeys(p.idx, order) }));
|
||||
}
|
||||
function registerAll() {
|
||||
props.dispatch("IDX未登録キーを登録", (p) => ({
|
||||
...p,
|
||||
idx: appendKeys(p.idx, unregisteredKeys(p.phy, p.idx)),
|
||||
}));
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="idx-panel">
|
||||
<h2>Key Indexer</h2>
|
||||
<div class="idx-layout">
|
||||
<div class="idx-list">
|
||||
<div class="idx-head">
|
||||
<h3>IDX order</h3>
|
||||
<button data-testid="idx-register-all" :disabled="!unregistered.size" @click="registerAll">
|
||||
未登録をすべて登録
|
||||
</button>
|
||||
</div>
|
||||
<p>選択構成での出力番号をプレビューします。</p>
|
||||
<ol>
|
||||
<li
|
||||
v-for="(entry, i) in rowEntries"
|
||||
:key="entry.id"
|
||||
:data-testid="`idx-row-${entry.id}`"
|
||||
:class="{ chosen: selectedKey === entry.id }"
|
||||
>
|
||||
<span class="idx-number" :aria-label="`保存順 ${i}`">保存順 {{ i }}</span
|
||||
><b>{{ entry.id }}</b
|
||||
><span>{{ entry.label }}</span
|
||||
><small>{{ entry.path }}</small
|
||||
><span>{{
|
||||
outputNumbers.has(entry.id) ? `出力 ${outputNumbers.get(entry.id)}` : "出力対象外"
|
||||
}}</span>
|
||||
<button :aria-label="`${entry.id}を上へ`" :disabled="i === 0" @click="move(entry.id, -1)">
|
||||
↑
|
||||
</button>
|
||||
<button
|
||||
:aria-label="`${entry.id}を下へ`"
|
||||
:disabled="i === rowEntries.length - 1"
|
||||
@click="move(entry.id, 1)"
|
||||
>
|
||||
↓
|
||||
</button>
|
||||
<button :aria-label="`${entry.id}を除外`" @click="exclude(entry.id)">除外</button>
|
||||
</li>
|
||||
</ol>
|
||||
<h3>全バリアントのキー</h3>
|
||||
<ul class="idx-all-keys">
|
||||
<li
|
||||
v-for="entry in entries"
|
||||
:key="entry.id"
|
||||
:data-testid="`idx-key-${entry.id}`"
|
||||
:class="{ chosen: selectedKey === entry.id, unregistered: unregistered.has(entry.id) }"
|
||||
>
|
||||
<b>{{ entry.id }}</b> · {{ entry.label }} <small>— {{ entry.path }}</small>
|
||||
<strong v-if="unregistered.has(entry.id)">未登録</strong>
|
||||
<span v-else-if="outputNumbers.has(entry.id)" class="idx-preview"
|
||||
>出力 {{ outputNumbers.get(entry.id) }}</span
|
||||
>
|
||||
<span v-else class="idx-preview muted">選択構成外</span>
|
||||
<button v-if="unregistered.has(entry.id)" @click="register(entry.id)">登録</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<aside class="idx-preview-pane">
|
||||
<h3>出力構成</h3>
|
||||
<label v-for="group in groups" :key="group.id"
|
||||
>{{ group.name }}
|
||||
<select
|
||||
:aria-label="`${group.name} 出力バリアント`"
|
||||
:value="selection[group.id] ?? group.default"
|
||||
@change="setVariant(group.id, ($event.target as HTMLSelectElement).value)"
|
||||
>
|
||||
<option v-for="variant in group.children" :key="variant.id" :value="variant.id">
|
||||
{{ variant.name }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<KeyboardView
|
||||
:phy="project.phy"
|
||||
:selection="selection"
|
||||
:selected-ids="selectedKey ? [selectedKey] : []"
|
||||
:key-text="(id) => (outputNumbers.has(id) ? String(outputNumbers.get(id)) : '')"
|
||||
@key-click="(id) => (selectedKey = id)"
|
||||
/>
|
||||
</aside>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.idx-panel {
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
padding: 10px;
|
||||
background: #fff;
|
||||
border: 1px solid #cbd1da;
|
||||
border-radius: 6px;
|
||||
}
|
||||
.idx-layout {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(440px, 1.2fr) minmax(320px, 1fr);
|
||||
gap: 18px;
|
||||
}
|
||||
.idx-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
.idx-panel h2 {
|
||||
margin: 0 0 10px;
|
||||
}
|
||||
.idx-panel h3 {
|
||||
margin: 12px 0 6px;
|
||||
}
|
||||
.idx-panel ol,
|
||||
.idx-all-keys {
|
||||
padding-left: 24px;
|
||||
}
|
||||
.idx-panel li {
|
||||
padding: 5px;
|
||||
margin: 3px 0;
|
||||
}
|
||||
.idx-panel ol li {
|
||||
display: grid;
|
||||
grid-template-columns: 86px minmax(95px, auto) 1fr 1fr auto auto auto auto;
|
||||
gap: 5px;
|
||||
align-items: center;
|
||||
}
|
||||
.idx-panel small {
|
||||
color: #586273;
|
||||
}
|
||||
.idx-number {
|
||||
font-weight: bold;
|
||||
}
|
||||
.idx-all-keys {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
}
|
||||
.idx-all-keys li {
|
||||
border-bottom: 1px solid #e3e6eb;
|
||||
}
|
||||
.idx-panel .chosen {
|
||||
background: #dce9ff;
|
||||
}
|
||||
.idx-all-keys .unregistered {
|
||||
background: #fff1d6;
|
||||
}
|
||||
.idx-all-keys strong {
|
||||
color: #9a4c00;
|
||||
margin: 0 8px;
|
||||
}
|
||||
.idx-preview-pane {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
align-self: start;
|
||||
}
|
||||
.idx-preview-pane label {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin: 5px 0;
|
||||
}
|
||||
.idx-preview {
|
||||
font-size: 12px;
|
||||
color: #1769d2;
|
||||
}
|
||||
.muted {
|
||||
color: #778;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,337 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from "vue";
|
||||
import { flattenKeys } from "../../domain/geometry";
|
||||
import {
|
||||
assignKey,
|
||||
deleteLayer,
|
||||
isEditableKeycode,
|
||||
parseKeycode,
|
||||
reorderLayer,
|
||||
renameLayer,
|
||||
unassignKey,
|
||||
unassignedKeys,
|
||||
addLayer,
|
||||
} from "../../domain/map";
|
||||
import { defaultVariantSelection, type ProjectFile } from "../../domain/project";
|
||||
import { getKeycodeLabel } from "../../domain/keycodeLabels";
|
||||
import { qmkBasicKeycodes } from "../../domain/qmkBasicKeycodes";
|
||||
import type { Dispatch } from "../types";
|
||||
import KeyboardView from "../common/KeyboardView.vue";
|
||||
|
||||
const props = defineProps<{ project: ProjectFile; dispatch: Dispatch; editable?: boolean }>();
|
||||
const selectedLayer = ref("Base"),
|
||||
selectedKey = ref(""),
|
||||
draft = ref(""),
|
||||
newLayerName = ref(""),
|
||||
renameValue = ref(""),
|
||||
error = ref("");
|
||||
const selection = computed(() => ({
|
||||
...defaultVariantSelection(props.project.phy),
|
||||
...props.project.output.variantSelection,
|
||||
}));
|
||||
const keys = computed(() => flattenKeys(props.project.phy, selection.value).filter((k) => !k.key.decal));
|
||||
const layer = computed(
|
||||
() => props.project.map.layers.find((x) => x.name === selectedLayer.value) ?? props.project.map.layers[0],
|
||||
);
|
||||
const keyLabels = computed(
|
||||
() => new Map(keys.value.map((x) => [x.key.id, x.key.labels?.find(Boolean) || x.key.id])),
|
||||
);
|
||||
const assignments = computed(() => new Map((layer.value?.keymap ?? []).map((a) => [a.keyId, a.keycode])));
|
||||
const selectedCode = computed(() => assignments.value.get(selectedKey.value) ?? "");
|
||||
const selectedCodeEditable = computed(() => !selectedCode.value || isEditableKeycode(selectedCode.value));
|
||||
const missing = computed(() =>
|
||||
unassignedKeys(
|
||||
props.project.map,
|
||||
layer.value?.name ?? "",
|
||||
keys.value.map((x) => x.key.id),
|
||||
),
|
||||
);
|
||||
const candidates = computed(() => {
|
||||
const keycodes = qmkBasicKeycodes
|
||||
.filter((entry) => entry.group === "basic" || entry.group === "modifiers" || entry.group === "internal")
|
||||
.map((entry) => entry.key);
|
||||
const modifierFunctions = ["LCTL", "LSFT", "LALT", "LGUI", "RCTL", "RSFT", "RALT", "RGUI"];
|
||||
const out = [...keycodes];
|
||||
for (const l of props.project.map.layers)
|
||||
for (const code of ["MO", "TG", "TO", "TT", "DF", "OSL"]) out.push(`${code}(${l.name})`);
|
||||
for (const l of props.project.map.layers) for (const kc of keycodes) out.push(`LT(${l.name}, ${kc})`);
|
||||
for (const mod of modifierFunctions) for (const kc of keycodes) out.push(`${mod}(${kc})`);
|
||||
return [...new Set(out)];
|
||||
});
|
||||
function fail(e: unknown) {
|
||||
error.value = e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
function pickLayer(name: string) {
|
||||
selectedLayer.value = name;
|
||||
selectedKey.value = "";
|
||||
error.value = "";
|
||||
}
|
||||
function chooseKey(id: string) {
|
||||
selectedKey.value = id;
|
||||
draft.value = assignments.value.get(id) ?? "";
|
||||
error.value = "";
|
||||
}
|
||||
function saveAssignment() {
|
||||
if (props.editable === false || !selectedKey.value || !layer.value || !selectedCodeEditable.value) return;
|
||||
if (draft.value.trim() === selectedCode.value) return;
|
||||
try {
|
||||
props.dispatch("MAPキー割り当て", (p) => ({
|
||||
...p,
|
||||
map: assignKey(p.map, layer.value!.name, selectedKey.value, draft.value.trim()),
|
||||
}));
|
||||
error.value = "";
|
||||
} catch (e) {
|
||||
fail(e);
|
||||
}
|
||||
}
|
||||
function add() {
|
||||
if (props.editable === false) return;
|
||||
if (!newLayerName.value.trim()) {
|
||||
error.value = "レイヤー名を入力してください。";
|
||||
return;
|
||||
}
|
||||
try {
|
||||
props.dispatch("MAPレイヤー追加", (p) => ({ ...p, map: addLayer(p.map, newLayerName.value.trim()) }));
|
||||
selectedLayer.value = newLayerName.value.trim();
|
||||
newLayerName.value = "";
|
||||
error.value = "";
|
||||
} catch (e) {
|
||||
fail(e);
|
||||
}
|
||||
}
|
||||
function rename() {
|
||||
if (props.editable === false) return;
|
||||
if (!layer.value) return;
|
||||
if (!renameValue.value.trim()) {
|
||||
error.value = "新しいレイヤー名を入力してください。";
|
||||
return;
|
||||
}
|
||||
try {
|
||||
props.dispatch("MAPレイヤー改名", (p) => ({
|
||||
...p,
|
||||
map: renameLayer(p.map, layer.value!.name, renameValue.value.trim()),
|
||||
}));
|
||||
selectedLayer.value = renameValue.value.trim();
|
||||
renameValue.value = "";
|
||||
error.value = "";
|
||||
} catch (e) {
|
||||
fail(e);
|
||||
}
|
||||
}
|
||||
function remove() {
|
||||
if (props.editable === false) return;
|
||||
if (!layer.value) return;
|
||||
try {
|
||||
props.dispatch("MAPレイヤー削除", (p) => ({ ...p, map: deleteLayer(p.map, layer.value!.name) }));
|
||||
selectedLayer.value = props.project.map.layers[0]?.name ?? "";
|
||||
error.value = "";
|
||||
} catch (e) {
|
||||
fail(e);
|
||||
}
|
||||
}
|
||||
function move(delta: number) {
|
||||
if (props.editable === false) return;
|
||||
if (!layer.value) return;
|
||||
const i = props.project.map.layers.findIndex((x) => x.name === layer.value!.name),
|
||||
j = i + delta;
|
||||
if (j < 0 || j >= props.project.map.layers.length) return;
|
||||
props.dispatch("MAPレイヤー順序変更", (p) => ({ ...p, map: reorderLayer(p.map, layer.value!.name, j) }));
|
||||
}
|
||||
function unassign() {
|
||||
if (props.editable === false || !layer.value || !selectedKey.value || !selectedCodeEditable.value) return;
|
||||
props.dispatch("MAP割り当て解除", (p) => ({
|
||||
...p,
|
||||
map: unassignKey(p.map, layer.value!.name, selectedKey.value),
|
||||
}));
|
||||
draft.value = "";
|
||||
error.value = "";
|
||||
}
|
||||
function keyText(id: string) {
|
||||
const code = assignments.value.get(id);
|
||||
if (!code) return "";
|
||||
const parsed = parseKeycode(code);
|
||||
const label = parsed.kind === "basic" ? getKeycodeLabel(code) : undefined;
|
||||
return label ? `${code}\n${label}` : code;
|
||||
}
|
||||
function keyClass(id: string) {
|
||||
const code = assignments.value.get(id);
|
||||
if (!code) return "warn";
|
||||
return isEditableKeycode(code) ? undefined : "muted";
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="map-panel">
|
||||
<h2>Keymap Designer</h2>
|
||||
<div class="map-columns">
|
||||
<aside class="map-layers">
|
||||
<h3>レイヤー</h3>
|
||||
<div class="layer-tabs" role="tablist">
|
||||
<button
|
||||
v-for="(item, i) in project.map.layers"
|
||||
:key="item.name"
|
||||
role="tab"
|
||||
:aria-selected="selectedLayer === item.name"
|
||||
:class="{ active: selectedLayer === item.name }"
|
||||
@click="pickLayer(item.name)"
|
||||
>
|
||||
{{ item.name }}
|
||||
</button>
|
||||
</div>
|
||||
<label
|
||||
>追加する名前
|
||||
<input
|
||||
v-model="newLayerName"
|
||||
aria-label="追加するレイヤー名"
|
||||
:disabled="editable === false" /></label
|
||||
><button data-testid="map-add-layer" :disabled="editable === false" @click="add">追加</button>
|
||||
<label
|
||||
>新しい名前
|
||||
<input
|
||||
v-model="renameValue"
|
||||
aria-label="新しい名前"
|
||||
:placeholder="layer?.name"
|
||||
:disabled="editable === false" /></label
|
||||
><button data-testid="map-rename-layer" :disabled="editable === false" @click="rename">改名</button>
|
||||
<div>
|
||||
<button
|
||||
aria-label="レイヤーを上へ"
|
||||
:disabled="editable === false || !layer || project.map.layers[0]?.name === layer.name"
|
||||
@click="move(-1)"
|
||||
>
|
||||
↑</button
|
||||
><button
|
||||
aria-label="レイヤーを下へ"
|
||||
:disabled="editable === false || !layer || project.map.layers.at(-1)?.name === layer.name"
|
||||
@click="move(1)"
|
||||
>
|
||||
↓</button
|
||||
><button data-testid="map-delete-layer" :disabled="editable === false" @click="remove">削除</button>
|
||||
</div>
|
||||
<p v-if="error" role="alert" class="map-error">{{ error }}</p>
|
||||
</aside>
|
||||
<main class="map-editor">
|
||||
<h3>{{ layer?.name }} · キーマップ</h3>
|
||||
<KeyboardView
|
||||
:phy="project.phy"
|
||||
:selection="selection"
|
||||
:selected-ids="selectedKey ? [selectedKey] : []"
|
||||
:key-text="keyText"
|
||||
:key-class="keyClass"
|
||||
@key-click="(id) => chooseKey(id)"
|
||||
/>
|
||||
<div v-if="selectedKey" class="map-assignment">
|
||||
<strong>{{ keyLabels.get(selectedKey) }} · {{ selectedKey }}</strong>
|
||||
<label
|
||||
>キーコード
|
||||
<input
|
||||
v-model="draft"
|
||||
list="map-keycode-candidates"
|
||||
aria-label="キーコード"
|
||||
@keydown.enter.prevent="saveAssignment"
|
||||
:disabled="editable === false || !selectedCodeEditable"
|
||||
/></label>
|
||||
<datalist id="map-keycode-candidates">
|
||||
<option v-for="value in candidates" :key="value" :value="value" />
|
||||
</datalist>
|
||||
<button @click="saveAssignment" :disabled="editable === false || !selectedCodeEditable">
|
||||
割り当て</button
|
||||
><button @click="unassign" :disabled="editable === false || !selectedCodeEditable">
|
||||
割り当て解除
|
||||
</button>
|
||||
<p v-if="selectedCode && !selectedCodeEditable" role="status">
|
||||
未知のキーコードは保持し、表示のみです。
|
||||
</p>
|
||||
<p v-if="draft && !isEditableKeycode(draft.trim())" class="map-error">
|
||||
このキーコードは編集対象外です。
|
||||
</p>
|
||||
</div>
|
||||
<section class="map-missing">
|
||||
<h3>未割り当て · {{ missing.length }} keys</h3>
|
||||
<ul>
|
||||
<li v-for="id in missing" :key="id">
|
||||
<button @click="chooseKey(id)">{{ keyLabels.get(id) }} · {{ id }}</button>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.map-panel {
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
padding: 10px;
|
||||
background: #fff;
|
||||
border: 1px solid #cbd1da;
|
||||
border-radius: 6px;
|
||||
}
|
||||
.map-panel h2 {
|
||||
margin: 0 0 10px;
|
||||
}
|
||||
.map-columns {
|
||||
display: grid;
|
||||
grid-template-columns: 260px minmax(400px, 1fr);
|
||||
gap: 16px;
|
||||
}
|
||||
.map-layers {
|
||||
border-right: 1px solid #d5dae2;
|
||||
padding-right: 12px;
|
||||
}
|
||||
.map-layers h3,
|
||||
.map-editor h3 {
|
||||
margin: 8px 0;
|
||||
}
|
||||
.map-layers label,
|
||||
.map-assignment label {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
margin: 9px 0;
|
||||
align-items: center;
|
||||
}
|
||||
.map-layers input {
|
||||
min-width: 0;
|
||||
width: 120px;
|
||||
}
|
||||
.layer-tabs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin: 8px 0;
|
||||
}
|
||||
.layer-tabs button.active {
|
||||
background: #dce9ff;
|
||||
}
|
||||
.map-editor {
|
||||
min-width: 0;
|
||||
}
|
||||
.map-assignment {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin: 12px 0;
|
||||
padding: 8px;
|
||||
background: #f5f7fa;
|
||||
}
|
||||
.map-assignment input {
|
||||
width: 240px;
|
||||
}
|
||||
.map-missing ul {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 5px;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
.map-error {
|
||||
color: #a21d16;
|
||||
background: #fff0ef;
|
||||
padding: 6px;
|
||||
}
|
||||
.map-panel :deep(.keyboard-view) {
|
||||
max-height: 48vh;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,35 @@
|
||||
<script setup lang="ts">
|
||||
import type { Node } from "../../domain/phy";
|
||||
import PhyNodeView from "./PhyNodeView.vue";
|
||||
defineProps<{ nodes: Node[]; selected: string[]; variants: Record<string, string>; zoom: number }>();
|
||||
const emit = defineEmits<{
|
||||
select: [id: string, additive: boolean];
|
||||
dragStart: [event: PointerEvent, id: string, parent: SVGGElement];
|
||||
}>();
|
||||
function visible(n: Node, selection: Record<string, string>) {
|
||||
return n.type !== "variantGroup" || !!n.children.find((v) => v.id === (selection[n.id] ?? n.default));
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<svg
|
||||
class="canvas"
|
||||
data-testid="phy-canvas"
|
||||
:viewBox="`-64 -64 ${1152 / zoom} ${896 / zoom}`"
|
||||
width="1152"
|
||||
height="896"
|
||||
preserveAspectRatio="xMinYMin meet"
|
||||
>
|
||||
<g class="layout" transform="scale(64)">
|
||||
<g v-for="n in nodes" :key="n.id">
|
||||
<PhyNodeView
|
||||
:node="n"
|
||||
:selected="selected"
|
||||
:variants="variants"
|
||||
:visible="visible(n, variants)"
|
||||
@select="(id, additive) => emit('select', id, additive)"
|
||||
@drag-start="(event, id, parent) => emit('dragStart', event, id, parent)"
|
||||
/>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
</template>
|
||||
@@ -0,0 +1,126 @@
|
||||
<script setup lang="ts">
|
||||
import type { Node } from "../../domain/phy";
|
||||
const props = defineProps<{
|
||||
node: Node;
|
||||
selected: string[];
|
||||
variants: Record<string, string>;
|
||||
visible: boolean;
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
select: [id: string, additive: boolean];
|
||||
dragStart: [event: PointerEvent, id: string, parent: SVGGElement];
|
||||
}>();
|
||||
function children(n: Node): Node[] {
|
||||
if (n.type === "cluster") return n.children;
|
||||
if (n.type === "variantGroup")
|
||||
return n.children.find((v) => v.id === (props.variants[n.id] ?? n.default))?.children ?? [];
|
||||
return [];
|
||||
}
|
||||
function partShape(part?: string) {
|
||||
return part === "@led"
|
||||
? "led"
|
||||
: part === "@encoder"
|
||||
? "encoder"
|
||||
: part === "@screw"
|
||||
? "screw"
|
||||
: part === "@oled"
|
||||
? "oled"
|
||||
: "other";
|
||||
}
|
||||
function pointer(event: PointerEvent) {
|
||||
const parent = (event.currentTarget as SVGGElement).parentElement as unknown as SVGGElement;
|
||||
emit("dragStart", event, props.node.id, parent);
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<g
|
||||
v-if="visible"
|
||||
class="phy-node"
|
||||
:class="[
|
||||
{
|
||||
chosen: selected.includes(node.id),
|
||||
ghost: node.type === 'key' && node.ghost,
|
||||
decal: node.type === 'key' && node.decal,
|
||||
},
|
||||
`node-${node.type}`,
|
||||
]"
|
||||
:data-node-id="node.id"
|
||||
:data-node-type="node.type"
|
||||
:transform="`translate(${node.transform.x},${node.transform.y}) rotate(${node.transform.rotation})`"
|
||||
@pointerdown.stop="pointer"
|
||||
@click.stop="emit('select', node.id, $event.shiftKey)"
|
||||
>
|
||||
<template v-if="node.type === 'key'"
|
||||
><rect
|
||||
class="key-face"
|
||||
x="0.04"
|
||||
y="0.04"
|
||||
:width="Math.max(0.1, node.size.w - 0.08)"
|
||||
:height="Math.max(0.1, node.size.h - 0.08)"
|
||||
rx="0.08"
|
||||
/><rect
|
||||
v-if="node.size.w2 || node.size.h2 || node.size.x2 || node.size.y2"
|
||||
class="key-face secondary"
|
||||
:x="node.size.x2 || 0"
|
||||
:y="node.size.y2 || 0"
|
||||
:width="node.size.w2 || node.size.w"
|
||||
:height="node.size.h2 || node.size.h"
|
||||
rx="0.06"
|
||||
/><text class="key-label" x="0.12" y="0.3">{{
|
||||
node.labels?.filter(Boolean).slice(0, 2).join(" / ")
|
||||
}}</text></template
|
||||
>
|
||||
<template v-else-if="node.type === 'component'"
|
||||
><circle v-if="partShape(node.partGroup) === 'led'" class="part led" r="0.25" /><circle
|
||||
v-else-if="partShape(node.partGroup) === 'screw'"
|
||||
class="part screw"
|
||||
r="0.18"
|
||||
/><rect
|
||||
v-else-if="partShape(node.partGroup) === 'oled'"
|
||||
class="part oled"
|
||||
x="-0.35"
|
||||
y="-0.22"
|
||||
width="0.7"
|
||||
height="0.44"
|
||||
/><g v-else-if="partShape(node.partGroup) === 'encoder'"
|
||||
><circle class="part encoder" r="0.27" /><path d="M-.1 -.18 L.12 0 -.1 .18" /></g
|
||||
><path v-else class="part" d="M0 -.22 L.22 0 0 .22 -.22 0 Z" /><text
|
||||
class="part-label"
|
||||
x="0.28"
|
||||
y="0.05"
|
||||
>{{ node.partGroup || "part" }}</text
|
||||
></template
|
||||
>
|
||||
<g v-else-if="node.type === 'cluster'" class="cluster-content"
|
||||
><PhyNodeView
|
||||
v-for="c in node.children"
|
||||
:key="c.id"
|
||||
:node="c"
|
||||
:selected="selected"
|
||||
:variants="variants"
|
||||
:visible="true"
|
||||
@select="(id, additive) => emit('select', id, additive)"
|
||||
@drag-start="(event, id, parent) => emit('dragStart', event, id, parent)"
|
||||
/></g>
|
||||
<g v-else-if="node.type === 'variantGroup'" class="variant-content"
|
||||
><PhyNodeView
|
||||
v-for="c in children(node)"
|
||||
:key="c.id"
|
||||
:node="c"
|
||||
:selected="selected"
|
||||
:variants="variants"
|
||||
:visible="true"
|
||||
@select="(id, additive) => emit('select', id, additive)"
|
||||
@drag-start="(event, id, parent) => emit('dragStart', event, id, parent)"
|
||||
/></g>
|
||||
<circle v-if="node.type === 'cluster' || node.type === 'variantGroup'" class="group-origin" r="0.07" />
|
||||
<rect
|
||||
v-if="selected.includes(node.id) && node.type !== 'key'"
|
||||
class="selection-box"
|
||||
x="-0.12"
|
||||
y="-0.12"
|
||||
width="0.24"
|
||||
height="0.24"
|
||||
/>
|
||||
</g>
|
||||
</template>
|
||||
@@ -0,0 +1,54 @@
|
||||
<script setup lang="ts">
|
||||
import type { Node, Variant } from "../../domain/phy";
|
||||
type Item = Node | Variant;
|
||||
defineProps<{ nodes: Item[]; selected: string[]; expanded?: boolean }>();
|
||||
const emit = defineEmits<{ select: [id: string, additive: boolean] }>();
|
||||
function kind(n: Item) {
|
||||
switch (n.type) {
|
||||
case "variantGroup":
|
||||
return "VariantGroup";
|
||||
case "cluster":
|
||||
return "Cluster";
|
||||
case "component":
|
||||
return "部品";
|
||||
case "key":
|
||||
return "キー";
|
||||
case "variant":
|
||||
return "Variant";
|
||||
}
|
||||
}
|
||||
function title(n: Item) {
|
||||
switch (n.type) {
|
||||
case "key":
|
||||
return n.labels?.filter(Boolean)[0] || "無題キー";
|
||||
case "component":
|
||||
return n.partGroup || "部品";
|
||||
case "variantGroup":
|
||||
case "cluster":
|
||||
case "variant":
|
||||
return n.name || n.type;
|
||||
}
|
||||
}
|
||||
function children(n: Item): Item[] {
|
||||
return n.type === "cluster" || n.type === "variantGroup" || n.type === "variant" ? n.children : [];
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<ul class="tree-list">
|
||||
<li v-for="n in nodes" :key="n.id">
|
||||
<button
|
||||
class="tree-node"
|
||||
:class="{ chosen: selected.includes(n.id) }"
|
||||
:data-tree-id="n.id"
|
||||
@click="emit('select', n.id, $event.shiftKey)"
|
||||
>
|
||||
{{ kind(n) }} · {{ title(n) }} <small>{{ n.id }}</small></button
|
||||
><PhyTree
|
||||
v-if="children(n).length"
|
||||
:nodes="children(n)"
|
||||
:selected="selected"
|
||||
@select="(id, additive) => emit('select', id, additive)"
|
||||
/>
|
||||
</li>
|
||||
</ul>
|
||||
</template>
|
||||
@@ -0,0 +1,13 @@
|
||||
export type Point = { x: number; y: number };
|
||||
export function snapFromStart(_start: number, delta: number, step = 0.25): number {
|
||||
return Math.round(delta / step) * step;
|
||||
}
|
||||
export function parentPoint(parent: SVGGraphicsElement, clientX: number, clientY: number): Point {
|
||||
const matrix = parent.getScreenCTM();
|
||||
if (!matrix) throw new Error("SVG parent has no screen transform");
|
||||
const point = new DOMPoint(clientX, clientY).matrixTransform(matrix.inverse());
|
||||
return { x: point.x, y: point.y };
|
||||
}
|
||||
export function snappedDelta(start: Point, current: Point): Point {
|
||||
return { x: snapFromStart(0, current.x - start.x), y: snapFromStart(0, current.y - start.y) };
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
import type { ProjectFile } from "../domain/project";
|
||||
export type Dispatch = (label: string, update: (project: ProjectFile) => ProjectFile) => void;
|
||||
Reference in New Issue
Block a user