-
Notifications
You must be signed in to change notification settings - Fork 0
Feat/zpl fe templates #92
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
9c078d0
feat(zpl): ^FE field-number embed character — parser + generator + re…
u8array d5e6422
feat(ui): Insert-variable picker for content fields
u8array 19c2984
feat(variables): template-aware bindings (counts + rename ripple)
u8array 47229ff
perf(variables): O(N+V) map lookups in template resolve + header pass
u8array File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| import { useEffect, useRef, useState } from "react"; | ||
| import { useT } from "../../lib/useT"; | ||
| import { useLabelStore } from "../../store/labelStore"; | ||
| import { inputCls } from "./styles"; | ||
|
|
||
| interface Props { | ||
| value: string; | ||
| onChange: (next: string) => void; | ||
| /** Optional sanitiser for restricted-charset fields (e.g. numeric-only | ||
| * barcodes). Applied to typed input only — template markers are | ||
| * inserted verbatim regardless. */ | ||
| sanitise?: (raw: string) => string; | ||
| placeholder?: string; | ||
| maxLength?: number; | ||
| } | ||
|
|
||
| /** | ||
| * Text input + "Insert variable" button. The button opens a small | ||
| * dropdown listing every defined Variable; picking one splices its | ||
| * `«name»` marker into the input at the current cursor position. | ||
| * Templates resolve at render time via applyBindingToObject — see | ||
| * lib/fnTemplate + lib/variableBinding. | ||
| * | ||
| * Used by Text and 1D-barcode properties panels in place of the | ||
| * plain input so non-technical users can compose multi-variable | ||
| * fields without typing the marker syntax by hand. | ||
| */ | ||
| export function TemplateContentInput({ | ||
| value, | ||
| onChange, | ||
| sanitise, | ||
| placeholder, | ||
| maxLength, | ||
| }: Props) { | ||
| const t = useT(); | ||
| const variables = useLabelStore((s) => s.variables); | ||
| const inputRef = useRef<HTMLInputElement>(null); | ||
| const rootRef = useRef<HTMLDivElement>(null); | ||
| const [open, setOpen] = useState(false); | ||
|
|
||
| // Click-outside + Esc close. Mounted only while open so the | ||
| // listeners don't fire for every other open menu in the panel. | ||
| useEffect(() => { | ||
| if (!open) return; | ||
| const onPointerDown = (e: PointerEvent) => { | ||
| if (!rootRef.current?.contains(e.target as Node)) setOpen(false); | ||
| }; | ||
| const onKey = (e: KeyboardEvent) => { | ||
| if (e.key === "Escape") setOpen(false); | ||
| }; | ||
| document.addEventListener("pointerdown", onPointerDown); | ||
| document.addEventListener("keydown", onKey); | ||
| return () => { | ||
| document.removeEventListener("pointerdown", onPointerDown); | ||
| document.removeEventListener("keydown", onKey); | ||
| }; | ||
| }, [open]); | ||
|
|
||
| const insertMarker = (name: string) => { | ||
| const input = inputRef.current; | ||
| const marker = `«${name}»`; | ||
| const cursor = input?.selectionStart ?? value.length; | ||
| const end = input?.selectionEnd ?? cursor; | ||
| const next = value.slice(0, cursor) + marker + value.slice(end); | ||
| onChange(next); | ||
| setOpen(false); | ||
| // Restore focus + place cursor right after the inserted marker. | ||
| queueMicrotask(() => { | ||
| if (!input) return; | ||
| const pos = cursor + marker.length; | ||
| input.focus(); | ||
| input.setSelectionRange(pos, pos); | ||
| }); | ||
| }; | ||
|
|
||
| return ( | ||
| <div ref={rootRef} className="relative flex gap-1"> | ||
| <input | ||
| ref={inputRef} | ||
| className={`${inputCls} flex-1`} | ||
| value={value} | ||
| maxLength={maxLength} | ||
| placeholder={placeholder} | ||
| onChange={(e) => onChange(sanitise ? sanitise(e.target.value) : e.target.value)} | ||
| /> | ||
| <button | ||
| type="button" | ||
| className="px-2 rounded border border-border bg-surface-2 text-xs font-mono text-muted hover:text-text hover:border-accent transition-colors" | ||
| title={t.app.insertVariable} | ||
| disabled={variables.length === 0} | ||
| onClick={() => setOpen((o) => !o)} | ||
| > | ||
| {"{x}"} | ||
| </button> | ||
| {open && variables.length > 0 && ( | ||
| <div | ||
| className="absolute right-0 top-full mt-1 z-10 min-w-[8rem] max-h-48 overflow-y-auto rounded border border-border bg-surface shadow-lg" | ||
| role="menu" | ||
| > | ||
| {variables.map((v) => ( | ||
| <button | ||
| key={v.id} | ||
| type="button" | ||
| className="block w-full text-left px-2 py-1 text-xs font-mono text-text hover:bg-surface-2 transition-colors" | ||
| onClick={() => insertMarker(v.name)} | ||
| > | ||
| «{v.name}» | ||
| </button> | ||
| ))} | ||
| </div> | ||
| )} | ||
| </div> | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| import { describe, it, expect } from "vitest"; | ||
| import { | ||
| hasTemplateMarkers, | ||
| extractTemplateRefs, | ||
| resolveTemplateMarkers, | ||
| embedsToMarkers, | ||
| markersToEmbeds, | ||
| pickEmbedChar, | ||
| } from "./fnTemplate"; | ||
| import type { Variable } from "../types/Variable"; | ||
|
|
||
| const vars: Variable[] = [ | ||
| { id: "a", name: "sku", fnNumber: 1, defaultValue: "DEFAULT-1" }, | ||
| { id: "b", name: "price", fnNumber: 2, defaultValue: "9.99" }, | ||
| { id: "c", name: "lot", fnNumber: 5, defaultValue: "X" }, | ||
| ]; | ||
|
|
||
| describe("hasTemplateMarkers", () => { | ||
| it("matches single marker", () => { | ||
| expect(hasTemplateMarkers("hello «sku»")).toBe(true); | ||
| }); | ||
| it("matches multiple markers", () => { | ||
| expect(hasTemplateMarkers("«a» and «b»")).toBe(true); | ||
| }); | ||
| it("returns false on plain text", () => { | ||
| expect(hasTemplateMarkers("plain text")).toBe(false); | ||
| }); | ||
| it("does not match an opening guillemet alone", () => { | ||
| expect(hasTemplateMarkers("« no closer")).toBe(false); | ||
| }); | ||
| }); | ||
|
|
||
| describe("extractTemplateRefs", () => { | ||
| it("preserves source order and duplicates", () => { | ||
| expect(extractTemplateRefs("«a» and «b» again «a»")).toEqual(["a", "b", "a"]); | ||
| }); | ||
| }); | ||
|
|
||
| describe("resolveTemplateMarkers", () => { | ||
| it("substitutes each marker via the resolver", () => { | ||
| const r = resolveTemplateMarkers("«sku»-«price»", (n) => | ||
| n === "sku" ? "ABC" : n === "price" ? "19.99" : undefined, | ||
| ); | ||
| expect(r).toBe("ABC-19.99"); | ||
| }); | ||
| it("leaves unknown markers literal", () => { | ||
| const r = resolveTemplateMarkers("«known»/«missing»", (n) => (n === "known" ? "v" : undefined)); | ||
| expect(r).toBe("v/«missing»"); | ||
| }); | ||
| }); | ||
|
|
||
| describe("embedsToMarkers", () => { | ||
| const fnToName = new Map([ | ||
| [1, "sku"], | ||
| [2, "price"], | ||
| ]); | ||
| it("converts whole-field embeds with default # delimiter", () => { | ||
| expect(embedsToMarkers("Hello #1#-#2#", "#", fnToName)).toBe("Hello «sku»-«price»"); | ||
| }); | ||
| it("converts substring embeds (slice args discarded)", () => { | ||
| expect(embedsToMarkers("#1,0,3#", "#", fnToName)).toBe("«sku»"); | ||
| }); | ||
| it("respects a custom embedChar set via ^FE", () => { | ||
| expect(embedsToMarkers("Hello @1@-@2@", "@", fnToName)).toBe("Hello «sku»-«price»"); | ||
| }); | ||
| it("leaves embeds for unknown FN numbers literal (loss-less round-trip)", () => { | ||
| expect(embedsToMarkers("#9#", "#", fnToName)).toBe("#9#"); | ||
| }); | ||
| }); | ||
|
|
||
| describe("markersToEmbeds", () => { | ||
| it("emits embeds for known variable names + reports the fnNumbers used", () => { | ||
| const r = markersToEmbeds("«sku»-«price»", vars, "#"); | ||
| expect(r.payload).toBe("#1#-#2#"); | ||
| expect([...r.referencedFnNumbers].sort()).toEqual([1, 2]); | ||
| }); | ||
| it("leaves markers literal when the named variable does not exist", () => { | ||
| const r = markersToEmbeds("«sku»-«gone»", vars, "#"); | ||
| expect(r.payload).toBe("#1#-«gone»"); | ||
| expect([...r.referencedFnNumbers]).toEqual([1]); | ||
| }); | ||
| it("dedupes referencedFnNumbers when the same name appears twice", () => { | ||
| const r = markersToEmbeds("«sku»/«sku»", vars, "#"); | ||
| expect(r.payload).toBe("#1#/#1#"); | ||
| expect([...r.referencedFnNumbers]).toEqual([1]); | ||
| }); | ||
| it("uses a non-default embedChar passed by the caller", () => { | ||
| const r = markersToEmbeds("«sku»-«price»", vars, "@"); | ||
| expect(r.payload).toBe("@1@-@2@"); | ||
| }); | ||
| }); | ||
|
|
||
| describe("pickEmbedChar", () => { | ||
| it("returns # when no payload contains it", () => { | ||
| expect(pickEmbedChar(["plain text", "more"])).toBe("#"); | ||
| }); | ||
| it("falls back to next candidate when # appears in any payload", () => { | ||
| expect(pickEmbedChar(["Item #SKU-1", "other"])).toBe("@"); | ||
| }); | ||
| it("returns null when every candidate is taken", () => { | ||
| expect(pickEmbedChar(["#@|%&?!"])).toBe(null); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.