Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/openpl-oracle", "crates/openpl-core", "app/src-tauri"]

[workspace.package]
version = "1.0.0-beta.6"
version = "1.0.0-beta.7"
edition = "2021"
license = "Apache-2.0 OR MIT"

Expand Down
4 changes: 2 additions & 2 deletions app/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion app/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "openpl",
"private": true,
"version": "1.0.0-beta.6",
"version": "1.0.0-beta.7",
"type": "module",
"scripts": {
"dev": "vite",
Expand Down
2 changes: 1 addition & 1 deletion app/src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "OpenPL",
"version": "1.0.0-beta.6",
"version": "1.0.0-beta.7",
"identifier": "org.openpl.app",
"build": {
"beforeDevCommand": "npm run dev",
Expand Down
64 changes: 64 additions & 0 deletions app/src/components/ProgramEditor.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,70 @@ describe("menú contextual", () => {
});
});

describe("insertar en paquetes", () => {
const body = "PACKAGE BODY pkg_ventas AS\n \nEND pkg_ventas;";
const emptyLine = "PACKAGE BODY pkg_ventas AS\n".length;
const inserts = ["Insertar función", "Insertar procedimiento", "Insertar cursor", "Insertar tipo registro",
"Insertar excepción", "Insertar constante"];

function open(kind: string, source: string, readOnly = false) {
let view: EditorView | null = null;
render(
<ProgramEditor
part={{ kind, source, last_ddl_time: null, diagnostics: [] }}
label="Cuerpo" readOnly={readOnly} onView={(v) => { if (v) view = v; }} onChange={() => {}} activate={() => {}}
/>,
);
return view!;
}
const labels = () => Array.from(screen.getByRole("menu", { name: "Editor" }).querySelectorAll(".menu-label"),
(label) => label.textContent);

afterEach(() => vi.restoreAllMocks());

it("en una línea vacía del cuerpo muestra Insertar y la función queda implementada", () => {
vi.spyOn(EditorView.prototype, "posAndSideAtCoords").mockReturnValue({ pos: emptyLine + 1, assoc: 1 });
const view = open("PACKAGE BODY", body);
fireEvent.contextMenu(view.contentDOM, { clientX: 100, clientY: 120 });
expect(labels().slice(0, 6)).toEqual(inserts);
fireEvent.click(screen.getByRole("menuitem", { name: "Insertar función" }));
expect(view.state.doc.toString()).toBe(
"PACKAGE BODY pkg_ventas AS\n FUNCTION nueva_funcion RETURN NUMBER IS\n BEGIN\n RETURN NULL;\n"
+ " END nueva_funcion;\nEND pkg_ventas;",
);
const { from, to } = view.state.selection.main;
expect(view.state.sliceDoc(from, to)).toBe("nueva_funcion");
undo(view);
expect(view.state.doc.toString()).toBe(body);
});

it("en la especificación inserta la declaración", () => {
vi.spyOn(EditorView.prototype, "posAndSideAtCoords").mockReturnValue({ pos: "PACKAGE pkg AS\n".length, assoc: 1 });
const view = open("PACKAGE", "PACKAGE pkg AS\n\nEND pkg;");
fireEvent.contextMenu(view.contentDOM, { clientX: 100, clientY: 120 });
fireEvent.click(screen.getByRole("menuitem", { name: "Insertar procedimiento" }));
expect(view.state.doc.toString()).toBe("PACKAGE pkg AS\nPROCEDURE nuevo_procedimiento;\nEND pkg;");
});

it("en una línea con texto no aparece", () => {
vi.spyOn(EditorView.prototype, "posAndSideAtCoords").mockReturnValue({ pos: 3, assoc: 1 });
const view = open("PACKAGE BODY", body);
fireEvent.contextMenu(view.contentDOM, { clientX: 100, clientY: 120 });
expect(labels()).not.toContain("Insertar función");
});

it("fuera de un paquete o en solo lectura no aparece", () => {
vi.spyOn(EditorView.prototype, "posAndSideAtCoords").mockReturnValue({ pos: emptyLine + 1, assoc: 1 });
const procedure = open("PROCEDURE", body);
fireEvent.contextMenu(procedure.contentDOM, { clientX: 100, clientY: 120 });
expect(labels()).not.toContain("Insertar función");
fireEvent.keyDown(document, { key: "Escape" });
const locked = open("PACKAGE BODY", body, true);
fireEvent.contextMenu(locked.contentDOM, { clientX: 100, clientY: 120 });
expect(labels()).not.toContain("Insertar función");
});
});

describe("paquete grande", () => {
const source = ["PACKAGE BODY PKG_VENTAS AS", ...Array.from({ length: 20000 }, (_, i) => ` -- línea ${i}`), "END;"].join("\n");

Expand Down
36 changes: 31 additions & 5 deletions app/src/components/ProgramEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { catalogCompletion, keywordCompletion, type CompletionCatalog } from "..
import { editorSearch } from "./EditorSearch";
import { editorMenuItems } from "../editorMenu";
import { ContextMenu, type ContextItem } from "./ContextMenu";
import { isPackageKind, packageSnippet, packageSnippetItems } from "../packageSnippets";

export const programSyntax = HighlightStyle.define([
{ tag: tags.keyword, color: "var(--kw)" },
Expand Down Expand Up @@ -96,6 +97,29 @@ function sameSource(doc: Text, source: string, cache: { source: string; doc: Tex
return { same, cache: same ? { source, doc } : known };
}

/** Ítems "Insertar" de un paquete sobre una línea vacía; reemplazan la línea en una sola transacción. */
function insertItems(view: EditorView, kind: string, lineNumber: number | null): ContextItem[] {
if (lineNumber === null || lineNumber > view.state.doc.lines || view.state.readOnly || !isPackageKind(kind)) return [];
const line = view.state.doc.line(lineNumber);
if (line.text.trim()) return [];
return packageSnippetItems.map(({ id, label }) => ({
label: `Insertar ${label.toLowerCase()}`,
run: () => {
const snippet = packageSnippet(kind, id, line.text);
view.dispatch({
changes: { from: line.from, to: line.to, insert: snippet.text },
selection: { anchor: line.from + snippet.name.from, head: line.from + snippet.name.to },
scrollIntoView: true, userEvent: "input",
});
view.focus();
},
}));
}

function menuExtra(inserts: ContextItem[], extra: (ContextItem | "sep")[] = []): (ContextItem | "sep")[] {
return inserts.length && extra.length ? [...inserts, "sep", ...extra] : [...inserts, ...extra];
}

export interface EditorMarker {
from: number;
to: number;
Expand All @@ -108,7 +132,7 @@ export function ProgramEditor(props: Props) {
const viewRef = useRef<EditorView | null>(null);
const sourceDoc = useRef<{ source: string; doc: Text } | null>(null);
const editing = useRef(new Compartment()).current;
const [menu, setMenu] = useState<{ x: number; y: number } | null>(null);
const [menu, setMenu] = useState<{ x: number; y: number; line: number | null } | null>(null);
const closeMenu = useCallback(() => setMenu(null), []);
latest.current = props;
const { part, label, readOnly } = props;
Expand Down Expand Up @@ -164,7 +188,9 @@ export function ProgramEditor(props: Props) {
event.preventDefault();
latest.current.activate();
const open = latest.current.onObjectContext;
const point = open && !keyboard ? editor.posAndSideAtCoords({ x: event.clientX, y: event.clientY }) : null;
const point = keyboard ? null : editor.posAndSideAtCoords({ x: event.clientX, y: event.clientY });
const head = point ? point.pos : editor.state.selection.main.head;
const line = keyboard || point ? editor.state.doc.lineAt(head).number : null;
if (open && point) {
const position = Math.max(0, point.pos + (point.assoc === -1 ? -1 : 0));
const reference = editorReference(editor.state, position);
Expand All @@ -176,9 +202,9 @@ export function ProgramEditor(props: Props) {
}
if (keyboard) {
const coords = editor.coordsAtPos(editor.state.selection.main.head) ?? editor.contentDOM.getBoundingClientRect();
setMenu({ x: coords.left, y: coords.bottom });
setMenu({ x: coords.left, y: coords.bottom, line });
} else {
setMenu({ x: event.clientX, y: event.clientY });
setMenu({ x: event.clientX, y: event.clientY, line });
}
return true;
},
Expand Down Expand Up @@ -240,7 +266,7 @@ export function ProgramEditor(props: Props) {
<div className="program-editor" ref={host} />
{menu && view && (
<ContextMenu x={menu.x} y={menu.y} label="Editor" onClose={closeMenu}
items={editorMenuItems(view, { readOnly, extra: props.menuExtra })} />
items={editorMenuItems(view, { readOnly, extra: menuExtra(insertItems(view, part.kind, menu.line), props.menuExtra) })} />
)}
</>
);
Expand Down
45 changes: 45 additions & 0 deletions app/src/packageSnippets.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { describe, expect, it } from "vitest";
import { isPackageKind, packageSnippet, packageSnippetItems } from "./packageSnippets";

describe("packageSnippets", () => {
it("solo los paquetes tienen plantillas", () => {
expect(isPackageKind("PACKAGE")).toBe(true);
expect(isPackageKind("PACKAGE BODY")).toBe(true);
expect(isPackageKind("PROCEDURE")).toBe(false);
expect(isPackageKind("SQL")).toBe(false);
});

it("ofrece los seis ítems en orden", () => {
expect(packageSnippetItems.map((item) => item.label))
.toEqual(["Función", "Procedimiento", "Cursor", "Tipo registro", "Excepción", "Constante"]);
});

it.each([
["function", "FUNCTION nueva_funcion RETURN NUMBER;", "nueva_funcion"],
["procedure", "PROCEDURE nuevo_procedimiento;", "nuevo_procedimiento"],
["cursor", "CURSOR c_nuevo IS SELECT * FROM dual;", "c_nuevo"],
["record", "TYPE t_nuevo IS RECORD (\n campo NUMBER\n);", "t_nuevo"],
["exception", "e_nueva EXCEPTION;", "e_nueva"],
["constant", "c_nueva CONSTANT NUMBER := 0;", "c_nueva"],
] as const)("spec: %s declara", (id, text, name) => {
const snippet = packageSnippet("PACKAGE", id, "");
expect(snippet.text).toBe(text);
expect(snippet.text.slice(snippet.name.from, snippet.name.to)).toBe(name);
});

it("body: función y procedimiento con implementación", () => {
expect(packageSnippet("PACKAGE BODY", "function", "").text)
.toBe("FUNCTION nueva_funcion RETURN NUMBER IS\nBEGIN\n RETURN NULL;\nEND nueva_funcion;");
expect(packageSnippet("PACKAGE BODY", "procedure", "").text)
.toBe("PROCEDURE nuevo_procedimiento IS\nBEGIN\n NULL;\nEND nuevo_procedimiento;");
expect(packageSnippet("PACKAGE BODY", "cursor", "").text).toBe("CURSOR c_nuevo IS SELECT * FROM dual;");
});

it("cada línea lleva la indentación de la línea", () => {
const snippet = packageSnippet("PACKAGE BODY", "procedure", " ");
expect(snippet.text)
.toBe(" PROCEDURE nuevo_procedimiento IS\n BEGIN\n NULL;\n END nuevo_procedimiento;");
expect(snippet.text.slice(snippet.name.from, snippet.name.to)).toBe("nuevo_procedimiento");
expect(snippet.name.from).toBe(" PROCEDURE ".length);
});
});
39 changes: 39 additions & 0 deletions app/src/packageSnippets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Plantillas de "Insertar" en paquetes. Sintaxis Oracle genérica; el nombre queda seleccionado para cambiarlo.

export type PackageSnippetId = "function" | "procedure" | "cursor" | "record" | "exception" | "constant";

export const packageSnippetItems: { id: PackageSnippetId; label: string }[] = [
{ id: "function", label: "Función" },
{ id: "procedure", label: "Procedimiento" },
{ id: "cursor", label: "Cursor" },
{ id: "record", label: "Tipo registro" },
{ id: "exception", label: "Excepción" },
{ id: "constant", label: "Constante" },
];

const declarations: Record<PackageSnippetId, { name: string; text: string }> = {
function: { name: "nueva_funcion", text: "FUNCTION nueva_funcion RETURN NUMBER;" },
procedure: { name: "nuevo_procedimiento", text: "PROCEDURE nuevo_procedimiento;" },
cursor: { name: "c_nuevo", text: "CURSOR c_nuevo IS SELECT * FROM dual;" },
record: { name: "t_nuevo", text: "TYPE t_nuevo IS RECORD (\n campo NUMBER\n);" },
exception: { name: "e_nueva", text: "e_nueva EXCEPTION;" },
constant: { name: "c_nueva", text: "c_nueva CONSTANT NUMBER := 0;" },
};

const bodies: Partial<Record<PackageSnippetId, string>> = {
function: "FUNCTION nueva_funcion RETURN NUMBER IS\nBEGIN\n RETURN NULL;\nEND nueva_funcion;",
procedure: "PROCEDURE nuevo_procedimiento IS\nBEGIN\n NULL;\nEND nuevo_procedimiento;",
};

export function isPackageKind(kind: string) {
return kind === "PACKAGE" || kind === "PACKAGE BODY";
}

/** Texto con la indentación en cada línea y la posición del nombre dentro de ese texto. */
export function packageSnippet(kind: string, id: PackageSnippetId, indent: string) {
const { name } = declarations[id];
const base = (kind === "PACKAGE BODY" && bodies[id]) || declarations[id].text;
const text = base.split("\n").map((line) => indent + line).join("\n");
const from = text.indexOf(name);
return { text, name: { from, to: from + name.length } };
}
Loading