Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
95ae588283 | ||
|
|
c1c0cd4ca6 | ||
|
|
57c93fe0cd | ||
|
|
ccdf677141 | ||
|
|
7cd3228eba | ||
|
|
f4b316f5cd | ||
|
|
20ca9ed3f4 | ||
|
|
c886650840 | ||
|
|
99ef3c61e5 | ||
|
|
3c693fc049 | ||
|
|
c10a5b9aa5 | ||
|
|
f41bf2d83c | ||
|
|
c18b9a1da0 | ||
|
|
6ae294f909 | ||
|
|
8a282c0d30 | ||
|
|
16c39c187d | ||
|
|
62684ba706 | ||
|
|
6ba69b284a | ||
|
|
80b141e5f5 | ||
|
|
0cdd6776ee | ||
|
|
8fca517b9c | ||
|
|
a4c3beebdf |
@@ -208,18 +208,6 @@
|
||||
"moduleName": ".*",
|
||||
"moduleLicense": "The W3C License"
|
||||
},
|
||||
{
|
||||
"moduleName": "com.google.re2j:re2j",
|
||||
"moduleLicense": "Go License"
|
||||
},
|
||||
{
|
||||
"moduleName": "com.hubspot:algebra",
|
||||
"moduleLicense": null
|
||||
},
|
||||
{
|
||||
"moduleName": "com.hubspot.immutables:immutables-exceptions",
|
||||
"moduleLicense": null
|
||||
},
|
||||
{
|
||||
"moduleName": ".*",
|
||||
"moduleLicense": "UnRar License"
|
||||
|
||||
@@ -94,5 +94,12 @@ public class FormFieldWithCoordinates {
|
||||
|
||||
@Schema(description = "Font size in PDF points")
|
||||
private Float fontSize;
|
||||
|
||||
@Schema(
|
||||
description =
|
||||
"CropBox height in PDF points. Lets the frontend reverse the backend's"
|
||||
+ " Y-flip when sending new widget coordinates back for"
|
||||
+ " create/modify operations.")
|
||||
private Float cropBoxHeight;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,10 @@ import java.util.stream.Collectors;
|
||||
import org.apache.pdfbox.cos.COSName;
|
||||
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
|
||||
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB;
|
||||
import org.apache.pdfbox.pdmodel.interactive.action.PDActionNamed;
|
||||
import org.apache.pdfbox.pdmodel.interactive.action.PDActionResetForm;
|
||||
import org.apache.pdfbox.pdmodel.interactive.action.PDActionSubmitForm;
|
||||
import org.apache.pdfbox.pdmodel.interactive.action.PDActionURI;
|
||||
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
|
||||
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceCharacteristicsDictionary;
|
||||
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
|
||||
@@ -59,6 +63,24 @@ public enum FormFieldTypeSupport {
|
||||
List<String> options)
|
||||
throws IOException {
|
||||
PDTextField textField = (PDTextField) field;
|
||||
if (definition.fontSize() != null && definition.fontSize() > 0) {
|
||||
textField.setDefaultAppearance("/Helv " + definition.fontSize() + " Tf 0 g");
|
||||
}
|
||||
if (Boolean.TRUE.equals(definition.multiline())) {
|
||||
textField.setMultiline(true);
|
||||
}
|
||||
// Comb field: evenly spaced character cells (e.g. SSN, phone). Requires
|
||||
// a positive MaxLen and is mutually exclusive with multiline.
|
||||
if (definition.maxLength() != null && definition.maxLength() > 0) {
|
||||
textField.setMaxLen(definition.maxLength());
|
||||
if (!Boolean.TRUE.equals(definition.multiline())) {
|
||||
try {
|
||||
textField.setComb(true);
|
||||
} catch (Exception e) {
|
||||
log.debug("Unable to set comb flag: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
String defaultValue = Optional.ofNullable(definition.defaultValue()).orElse("");
|
||||
if (!defaultValue.isBlank()) {
|
||||
FormUtils.setTextValue(textField, defaultValue);
|
||||
@@ -272,12 +294,81 @@ public enum FormFieldTypeSupport {
|
||||
PDTerminalField createField(PDAcroForm acroForm) {
|
||||
return new PDSignatureField(acroForm);
|
||||
}
|
||||
|
||||
@Override
|
||||
boolean doesNotsupportsDefinitionCreation() {
|
||||
return false;
|
||||
}
|
||||
// Empty signature placeholder: no value to apply (signed later by a sign tool).
|
||||
},
|
||||
BUTTON("button", "pushButton", PDPushButton.class) {
|
||||
@Override
|
||||
PDTerminalField createField(PDAcroForm acroForm) {
|
||||
return new PDPushButton(acroForm);
|
||||
}
|
||||
|
||||
@Override
|
||||
boolean doesNotsupportsDefinitionCreation() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
void applyNewFieldDefinition(
|
||||
PDTerminalField field,
|
||||
FormUtils.NewFormFieldDefinition definition,
|
||||
List<String> options)
|
||||
throws IOException {
|
||||
if (field.getWidgets().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
PDAnnotationWidget widget = field.getWidgets().get(0);
|
||||
|
||||
// Visible caption (/MK /CA).
|
||||
String caption = definition.label();
|
||||
if (caption == null || caption.isBlank()) {
|
||||
caption = definition.name();
|
||||
}
|
||||
if (caption != null && !caption.isBlank()) {
|
||||
PDAppearanceCharacteristicsDictionary mk = widget.getAppearanceCharacteristics();
|
||||
if (mk == null) {
|
||||
mk = new PDAppearanceCharacteristicsDictionary(widget.getCOSObject());
|
||||
widget.setAppearanceCharacteristics(mk);
|
||||
}
|
||||
mk.setNormalCaption(caption);
|
||||
}
|
||||
widget.setPrinted(true);
|
||||
|
||||
applyButtonAction(widget, definition.buttonAction());
|
||||
}
|
||||
|
||||
private void applyButtonAction(PDAnnotationWidget widget, String action) {
|
||||
if (action == null || action.isBlank()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String spec = action.trim();
|
||||
String lower = spec.toLowerCase();
|
||||
if (lower.equals("reset")) {
|
||||
widget.getCOSObject()
|
||||
.setItem(COSName.A, new PDActionResetForm().getCOSObject());
|
||||
} else if (lower.equals("print")) {
|
||||
PDActionNamed named = new PDActionNamed();
|
||||
named.setN("Print");
|
||||
widget.getCOSObject().setItem(COSName.A, named.getCOSObject());
|
||||
} else if (lower.startsWith("uri:")) {
|
||||
PDActionURI uri = new PDActionURI();
|
||||
uri.setURI(spec.substring(4));
|
||||
widget.getCOSObject().setItem(COSName.A, uri.getCOSObject());
|
||||
} else if (lower.startsWith("submit:")) {
|
||||
PDActionSubmitForm submit = new PDActionSubmitForm();
|
||||
// Store the target URL on the action dictionary's /F entry.
|
||||
submit.getCOSObject().setString(COSName.F, spec.substring(7));
|
||||
widget.getCOSObject().setItem(COSName.A, submit.getCOSObject());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("Unable to apply button action '{}': {}", action, e.getMessage());
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private static final Map<String, FormFieldTypeSupport> BY_TYPE =
|
||||
|
||||
@@ -460,6 +460,7 @@ public class FormUtils {
|
||||
.height(finalH)
|
||||
.exportValue(exportValue)
|
||||
.fontSize(extractFontSize(field))
|
||||
.cropBoxHeight(cropHeight)
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -1463,16 +1464,29 @@ public class FormUtils {
|
||||
return tooltipLabel;
|
||||
}
|
||||
|
||||
// Only check options for choice-type fields (combobox, listbox, radio)
|
||||
if (CHOICE_FIELD_TYPES.contains(type) && options != null && !options.isEmpty()) {
|
||||
// A clearly meaningful field name describes the whole field and matches
|
||||
// the name shown in the editor, so it is the best label.
|
||||
String humanized = cleanLabel(humanizeName(name));
|
||||
if (humanized != null && !looksGeneric(humanized)) {
|
||||
return humanized;
|
||||
}
|
||||
|
||||
// Only when the name is an auto-generated identifier ("Field_5", "t12", a
|
||||
// UUID) is an option more descriptive than the name. A human-typed name -
|
||||
// even a generic-sounding word like "Choice" or "Name" - is preferred just
|
||||
// below so the viewer label stays in sync with the editor's field name. This
|
||||
// stops a radio group named "Choice" with options Yes/No reading as "Yes".
|
||||
if (CHOICE_FIELD_TYPES.contains(type)
|
||||
&& options != null
|
||||
&& !options.isEmpty()
|
||||
&& looksAutoGenerated(name)) {
|
||||
String optionCandidate = cleanLabel(options.get(0));
|
||||
if (optionCandidate != null && !looksGeneric(optionCandidate)) {
|
||||
return optionCandidate;
|
||||
}
|
||||
}
|
||||
|
||||
String humanized = cleanLabel(humanizeName(name));
|
||||
if (humanized != null && !looksGeneric(humanized)) {
|
||||
if (humanized != null && !looksAutoGenerated(name)) {
|
||||
return humanized;
|
||||
}
|
||||
|
||||
@@ -1509,6 +1523,29 @@ public class FormUtils {
|
||||
|| patterns.getOptionalTNumericPattern().matcher(simplified).matches();
|
||||
}
|
||||
|
||||
/**
|
||||
* True only for structurally auto-generated identifiers - "Field_5", "F12", "t3", bare numbers,
|
||||
* UUIDs. Unlike {@link #looksGeneric}, this does NOT reject human-typed placeholder words such
|
||||
* as "Choice", "Name" or "Value"; those are still usable labels and must not be discarded in
|
||||
* favour of an option value, so the viewer label keeps matching the editor's field name.
|
||||
*/
|
||||
private boolean looksAutoGenerated(String value) {
|
||||
if (value == null) return true;
|
||||
|
||||
RegexPatternUtils patterns = RegexPatternUtils.getInstance();
|
||||
String simplified = patterns.getPunctuationPattern().matcher(value).replaceAll(" ").trim();
|
||||
if (simplified.isEmpty()) return true;
|
||||
|
||||
String nospaces = WHITESPACE_PATTERN.matcher(simplified).replaceAll("");
|
||||
if (nospaces.length() >= 32 && HEX_UUID_PATTERN.matcher(nospaces).matches()) return true;
|
||||
|
||||
return patterns.getPattern("^field(\\s*\\d+)?$", Pattern.CASE_INSENSITIVE)
|
||||
.matcher(simplified)
|
||||
.matches()
|
||||
|| patterns.getSimpleFormFieldPattern().matcher(simplified).matches()
|
||||
|| patterns.getOptionalTNumericPattern().matcher(simplified).matches();
|
||||
}
|
||||
|
||||
private String humanizeName(String name) {
|
||||
if (name == null) return null;
|
||||
|
||||
@@ -1598,7 +1635,8 @@ public class FormUtils {
|
||||
|
||||
if (!typeChanging) {
|
||||
try {
|
||||
modifyFieldPropertiesInPlace(originalField, modification, desiredName);
|
||||
modifyFieldPropertiesInPlace(
|
||||
document, originalField, modification, desiredName);
|
||||
log.debug("Successfully modified field '{}' in-place", lookupName);
|
||||
continue; // Skip the remove-and-recreate process
|
||||
} catch (Exception e) {
|
||||
@@ -1625,7 +1663,12 @@ public class FormUtils {
|
||||
modification.multiSelect(),
|
||||
modification.options(),
|
||||
modification.defaultValue(),
|
||||
modification.tooltip());
|
||||
modification.tooltip(),
|
||||
modification.fontSize(),
|
||||
modification.readOnly(),
|
||||
modification.multiline(),
|
||||
modification.maxLength(),
|
||||
null);
|
||||
|
||||
List<String> sanitizedOptions = sanitizeOptions(modification.options());
|
||||
|
||||
@@ -1665,7 +1708,10 @@ public class FormUtils {
|
||||
}
|
||||
|
||||
private void modifyFieldPropertiesInPlace(
|
||||
PDField field, ModifyFormFieldDefinition modification, String newName)
|
||||
PDDocument document,
|
||||
PDField field,
|
||||
ModifyFormFieldDefinition modification,
|
||||
String newName)
|
||||
throws IOException {
|
||||
if (newName != null && !newName.equals(field.getPartialName())) {
|
||||
field.setPartialName(newName);
|
||||
@@ -1715,6 +1761,124 @@ public class FormUtils {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update read-only flag
|
||||
if (modification.readOnly() != null) {
|
||||
field.setReadOnly(modification.readOnly());
|
||||
}
|
||||
|
||||
// Update multiline flag (text fields only)
|
||||
if (modification.multiline() != null && field instanceof PDTextField tf) {
|
||||
tf.setMultiline(modification.multiline());
|
||||
}
|
||||
|
||||
// Update comb / max length (text fields only)
|
||||
if (modification.maxLength() != null
|
||||
&& modification.maxLength() > 0
|
||||
&& field instanceof PDTextField combTf) {
|
||||
combTf.setMaxLen(modification.maxLength());
|
||||
if (!combTf.isMultiline()) {
|
||||
try {
|
||||
combTf.setComb(true);
|
||||
} catch (Exception ignore) {
|
||||
// comb is best-effort
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update font size (variable-text fields only: text/combo/list)
|
||||
if (modification.fontSize() != null
|
||||
&& modification.fontSize() > 0
|
||||
&& field instanceof PDVariableText vt) {
|
||||
applyFontSizeToDefaultAppearance(vt, modification.fontSize());
|
||||
// Clear the cached appearance so ensureAppearances() regenerates it
|
||||
// with the new font size; otherwise viewers keep the old glyph sizing.
|
||||
removeWidgetAppearanceStreams(field);
|
||||
}
|
||||
|
||||
// Update widget geometry if any coordinate component was supplied.
|
||||
// The frontend sends CropBox-relative, lower-left-origin coordinates
|
||||
// (the reverse of what createWidgetCoordinates extracts). We add the
|
||||
// CropBox offset back to recover absolute PDF user-space coordinates.
|
||||
if (modification.x() != null
|
||||
|| modification.y() != null
|
||||
|| modification.width() != null
|
||||
|| modification.height() != null) {
|
||||
List<PDAnnotationWidget> widgets = field.getWidgets();
|
||||
if (widgets != null && !widgets.isEmpty()) {
|
||||
PDAnnotationWidget widget = widgets.get(0);
|
||||
PDRectangle rect = widget.getRectangle();
|
||||
if (rect != null) {
|
||||
PDPage page = resolveWidgetPage(document, widget, null);
|
||||
float offX = 0;
|
||||
float offY = 0;
|
||||
if (page != null) {
|
||||
PDRectangle cropBox = page.getCropBox();
|
||||
offX = cropBox.getLowerLeftX();
|
||||
offY = cropBox.getLowerLeftY();
|
||||
}
|
||||
float newX =
|
||||
modification.x() != null
|
||||
? modification.x() + offX
|
||||
: rect.getLowerLeftX();
|
||||
float newY =
|
||||
modification.y() != null
|
||||
? modification.y() + offY
|
||||
: rect.getLowerLeftY();
|
||||
float newW =
|
||||
modification.width() != null ? modification.width() : rect.getWidth();
|
||||
float newH =
|
||||
modification.height() != null
|
||||
? modification.height()
|
||||
: rect.getHeight();
|
||||
widget.setRectangle(new PDRectangle(newX, newY, newW, newH));
|
||||
|
||||
// Remove the stale appearance stream so ensureAppearances()
|
||||
// generates a fresh one matching the new rectangle. Without
|
||||
// this, PDF viewers (pdf.js, Evince) stretch the old appearance
|
||||
// (built for the previous BBox) to fit the new widget rectangle,
|
||||
// making fields look distorted/stretched.
|
||||
widget.getCOSObject().removeItem(COSName.AP);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the font size inside a variable-text field's default appearance (DA) string while
|
||||
* preserving the font name and colour operators. If no DA is present a Helvetica default is
|
||||
* written.
|
||||
*/
|
||||
private void applyFontSizeToDefaultAppearance(PDVariableText field, float fontSize) {
|
||||
String da = field.getDefaultAppearance();
|
||||
if (da != null && !da.isBlank()) {
|
||||
// Replace the size token (the operand immediately before "Tf").
|
||||
String[] tokens = da.split("\\s+");
|
||||
boolean replaced = false;
|
||||
for (int i = 0; i < tokens.length; i++) {
|
||||
if ("Tf".equals(tokens[i]) && i > 0) {
|
||||
tokens[i - 1] = String.valueOf(fontSize);
|
||||
replaced = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (replaced) {
|
||||
field.setDefaultAppearance(String.join(" ", tokens));
|
||||
return;
|
||||
}
|
||||
}
|
||||
field.setDefaultAppearance("/Helv " + fontSize + " Tf 0 g");
|
||||
}
|
||||
|
||||
/** Drops cached /AP appearance streams from every widget of a field. */
|
||||
private void removeWidgetAppearanceStreams(PDField field) {
|
||||
List<PDAnnotationWidget> widgets = field.getWidgets();
|
||||
if (widgets == null) {
|
||||
return;
|
||||
}
|
||||
for (PDAnnotationWidget widget : widgets) {
|
||||
widget.getCOSObject().removeItem(COSName.AP);
|
||||
}
|
||||
}
|
||||
|
||||
private String fallbackLabelForType(String type, int typeIndex) {
|
||||
@@ -1842,6 +2006,220 @@ public class FormUtils {
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds new form fields to a document from the supplied definitions. If the document has no
|
||||
* AcroForm one is created automatically. Coordinates in each definition are interpreted as
|
||||
* CropBox-relative, lower-left-origin PDF points (the reverse of what {@link
|
||||
* #createWidgetCoordinates} extracts); the CropBox offset is added back to obtain absolute PDF
|
||||
* user-space coordinates.
|
||||
*/
|
||||
public void addNewFields(PDDocument document, List<NewFormFieldDefinition> definitions)
|
||||
throws IOException {
|
||||
if (document == null || definitions == null || definitions.isEmpty()) return;
|
||||
|
||||
PDAcroForm acroForm = getAcroFormSafely(document);
|
||||
if (acroForm == null) {
|
||||
// Create a new AcroForm for PDFs that don't have one yet
|
||||
acroForm = new PDAcroForm(document);
|
||||
document.getDocumentCatalog().setAcroForm(acroForm);
|
||||
}
|
||||
|
||||
Set<String> existingNames = collectExistingFieldNames(acroForm);
|
||||
int pageCount = document.getNumberOfPages();
|
||||
|
||||
for (NewFormFieldDefinition definition : definitions) {
|
||||
if (definition == null) continue;
|
||||
|
||||
String resolvedType =
|
||||
Optional.ofNullable(definition.type())
|
||||
.map(FormUtils::normalizeFieldType)
|
||||
.orElse(FIELD_TYPE_TEXT);
|
||||
|
||||
int pageIdx = definition.pageIndex() != null ? definition.pageIndex() : 0;
|
||||
if (pageIdx < 0 || pageIdx >= pageCount) {
|
||||
log.warn(
|
||||
"Page index {} out of range (0-{}); clamping to last page",
|
||||
pageIdx,
|
||||
pageCount - 1);
|
||||
pageIdx = Math.max(0, pageCount - 1);
|
||||
}
|
||||
PDPage page = document.getPage(pageIdx);
|
||||
PDRectangle cropBox = page.getCropBox();
|
||||
|
||||
// CropBox-relative, lower-left-origin -> absolute PDF user space.
|
||||
float x = (definition.x() != null ? definition.x() : 0f) + cropBox.getLowerLeftX();
|
||||
float y = (definition.y() != null ? definition.y() : 0f) + cropBox.getLowerLeftY();
|
||||
float w = definition.width() != null ? definition.width() : 150f;
|
||||
float h = definition.height() != null ? definition.height() : 20f;
|
||||
PDRectangle rectangle = new PDRectangle(x, y, w, h);
|
||||
|
||||
String baseName =
|
||||
Optional.ofNullable(definition.name())
|
||||
.map(String::trim)
|
||||
.filter(s -> !s.isEmpty())
|
||||
.orElse("field");
|
||||
String uniqueName = generateUniqueFieldName(baseName, existingNames);
|
||||
existingNames.add(uniqueName);
|
||||
|
||||
List<String> options = sanitizeOptions(definition.options());
|
||||
|
||||
try {
|
||||
if (FIELD_TYPE_RADIO.equals(resolvedType)) {
|
||||
// Radio is a single field with one widget per option; it can't go
|
||||
// through the single-widget createNewField path.
|
||||
createRadioField(acroForm, page, rectangle, uniqueName, definition, options);
|
||||
} else {
|
||||
FormFieldTypeSupport handler = FormFieldTypeSupport.forTypeName(resolvedType);
|
||||
if (handler == null || handler.doesNotsupportsDefinitionCreation()) {
|
||||
log.warn(
|
||||
"Unsupported or non-creatable field type '{}'; defaulting to text",
|
||||
resolvedType);
|
||||
handler = FormFieldTypeSupport.TEXT;
|
||||
}
|
||||
createNewField(
|
||||
handler, acroForm, page, rectangle, uniqueName, definition, options);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn(
|
||||
"Failed to create field '{}' of type '{}': {}",
|
||||
uniqueName,
|
||||
resolvedType,
|
||||
e.getMessage(),
|
||||
e);
|
||||
}
|
||||
}
|
||||
|
||||
ensureAppearances(acroForm);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a radio-button group with one widget per option, stacked vertically starting at
|
||||
* {@code baseRect}. Each widget's "on" state name is the sanitized export value, so the group
|
||||
* behaves as a single selectable field.
|
||||
*/
|
||||
private void createRadioField(
|
||||
PDAcroForm acroForm,
|
||||
PDPage page,
|
||||
PDRectangle baseRect,
|
||||
String name,
|
||||
NewFormFieldDefinition definition,
|
||||
List<String> options)
|
||||
throws IOException {
|
||||
|
||||
List<String> values = (options == null || options.isEmpty()) ? List.of("1", "2") : options;
|
||||
|
||||
PDRadioButton radio = new PDRadioButton(acroForm);
|
||||
radio.setPartialName(name);
|
||||
if (definition.label() != null && !definition.label().isBlank()) {
|
||||
try {
|
||||
radio.setAlternateFieldName(definition.label());
|
||||
} catch (Exception ignore) {
|
||||
// alternate name is best-effort
|
||||
}
|
||||
}
|
||||
radio.setRequired(Boolean.TRUE.equals(definition.required()));
|
||||
if (Boolean.TRUE.equals(definition.readOnly())) {
|
||||
radio.setReadOnly(true);
|
||||
}
|
||||
|
||||
float w = baseRect.getWidth();
|
||||
float h = baseRect.getHeight();
|
||||
float gap = Math.max(4f, h * 0.5f);
|
||||
float topY = baseRect.getLowerLeftY();
|
||||
|
||||
List<PDAnnotationWidget> widgets = new ArrayList<>();
|
||||
List<String> exportValues = new ArrayList<>();
|
||||
Set<String> usedStates = new HashSet<>();
|
||||
for (int i = 0; i < values.size(); i++) {
|
||||
String onState = sanitizeOnState(values.get(i), i, usedStates);
|
||||
exportValues.add(onState);
|
||||
|
||||
// Stack downwards from the drawn rectangle.
|
||||
float wy = topY - i * (h + gap);
|
||||
PDRectangle rect = new PDRectangle(baseRect.getLowerLeftX(), wy, w, h);
|
||||
|
||||
PDAnnotationWidget widget = new PDAnnotationWidget();
|
||||
widget.setRectangle(rect);
|
||||
widget.setPage(page);
|
||||
widget.getCOSObject().setItem(COSName.P, page.getCOSObject());
|
||||
widget.getCOSObject().setItem(COSName.TYPE, COSName.getPDFName("Annot"));
|
||||
widget.getCOSObject().setItem(COSName.SUBTYPE, COSName.getPDFName("Widget"));
|
||||
widget.setParent(radio);
|
||||
// The widget's appearance state is "Off" until the group value selects it.
|
||||
widget.getCOSObject().setName(COSName.AS, "Off");
|
||||
widgets.add(widget);
|
||||
|
||||
List<PDAnnotation> annotations = page.getAnnotations();
|
||||
if (annotations == null) {
|
||||
annotations = new ArrayList<>();
|
||||
page.setAnnotations(annotations);
|
||||
}
|
||||
annotations.add(widget);
|
||||
}
|
||||
|
||||
radio.setWidgets(widgets);
|
||||
try {
|
||||
radio.setExportValues(exportValues);
|
||||
} catch (Exception e) {
|
||||
log.debug("Unable to set radio export values for '{}': {}", name, e.getMessage());
|
||||
}
|
||||
|
||||
String defaultValue = definition.defaultValue();
|
||||
if (defaultValue != null
|
||||
&& !defaultValue.isBlank()
|
||||
&& exportValues.contains(defaultValue)) {
|
||||
try {
|
||||
radio.setValue(defaultValue);
|
||||
} catch (Exception e) {
|
||||
log.debug("Unable to set radio default '{}': {}", defaultValue, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
acroForm.getFields().add(radio);
|
||||
}
|
||||
|
||||
/** Builds a unique, PDF-name-safe "on" state for a radio widget. */
|
||||
private String sanitizeOnState(String raw, int index, Set<String> used) {
|
||||
String base =
|
||||
Optional.ofNullable(raw)
|
||||
.map(String::trim)
|
||||
.filter(s -> !s.isEmpty())
|
||||
.map(s -> s.replaceAll("[^A-Za-z0-9_-]", "_"))
|
||||
.orElse("Option" + (index + 1));
|
||||
if ("Off".equalsIgnoreCase(base)) {
|
||||
base = "Option" + (index + 1);
|
||||
}
|
||||
String candidate = base;
|
||||
int suffix = 1;
|
||||
while (!used.add(candidate)) {
|
||||
candidate = base + "_" + suffix++;
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a mixed batch of field edits to a document in a single pass: existing fields are
|
||||
* modified, then deleted, then new fields are added (so newly-generated names dedupe against
|
||||
* the surviving set). Lets the UI commit create/modify/delete in one request.
|
||||
*/
|
||||
public void applyFieldEdits(
|
||||
PDDocument document,
|
||||
List<NewFormFieldDefinition> adds,
|
||||
List<ModifyFormFieldDefinition> modifies,
|
||||
List<String> deletes)
|
||||
throws IOException {
|
||||
if (document == null) return;
|
||||
if (modifies != null && !modifies.isEmpty()) {
|
||||
modifyFormFields(document, modifies);
|
||||
}
|
||||
if (deletes != null && !deletes.isEmpty()) {
|
||||
deleteFormFields(document, deletes);
|
||||
}
|
||||
if (adds != null && !adds.isEmpty()) {
|
||||
addNewFields(document, adds);
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteFormFields(PDDocument document, List<String> fieldNames) {
|
||||
if (document == null || fieldNames == null || fieldNames.isEmpty()) return;
|
||||
|
||||
@@ -2247,9 +2625,33 @@ public class FormUtils {
|
||||
}
|
||||
}
|
||||
field.setRequired(Boolean.TRUE.equals(definition.required()));
|
||||
if (Boolean.TRUE.equals(definition.readOnly())) {
|
||||
field.setReadOnly(true);
|
||||
}
|
||||
|
||||
PDAnnotationWidget widget =
|
||||
existingWidget != null ? existingWidget : new PDAnnotationWidget();
|
||||
// A brand-new terminal field with no /Kids is represented by a single
|
||||
// "merged" widget that shares the field's own dictionary. Configure THAT
|
||||
// widget so the /Rect, /P and appearance live on the field dictionary and
|
||||
// survive serialization. Building a SEPARATE PDAnnotationWidget and adding
|
||||
// it to getWidgets() does not link it via /Kids, so its /Rect is dropped on
|
||||
// save and the field renders at 0x0 (the symptom reported on PR #5777).
|
||||
boolean reuseFieldDict;
|
||||
PDAnnotationWidget widget;
|
||||
if (existingWidget != null) {
|
||||
widget = existingWidget;
|
||||
reuseFieldDict = false;
|
||||
} else {
|
||||
List<PDAnnotationWidget> current = field.getWidgets();
|
||||
if (current != null && !current.isEmpty()) {
|
||||
widget = current.get(0);
|
||||
} else {
|
||||
widget = new PDAnnotationWidget();
|
||||
}
|
||||
reuseFieldDict = widget.getCOSObject() == field.getCOSObject();
|
||||
// Make sure the shared dictionary is recognised as a widget annotation.
|
||||
widget.getCOSObject().setItem(COSName.TYPE, COSName.getPDFName("Annot"));
|
||||
widget.getCOSObject().setItem(COSName.SUBTYPE, COSName.getPDFName("Widget"));
|
||||
}
|
||||
|
||||
// Ensure rectangle is valid and set before any appearance-related operations
|
||||
// please note removal of this might cause **subtle** issues
|
||||
@@ -2262,10 +2664,10 @@ public class FormUtils {
|
||||
}
|
||||
widget.setRectangle(validRectangle);
|
||||
widget.setPage(page);
|
||||
|
||||
if (existingWidget == null) {
|
||||
widget.setPrinted(true);
|
||||
}
|
||||
// Explicitly set the /P entry so the widget keeps a valid page reference
|
||||
// after save/reload (some viewers rely on it to resolve the widget page).
|
||||
widget.getCOSObject().setItem(COSName.P, page.getCOSObject());
|
||||
widget.setPrinted(true);
|
||||
|
||||
if (definition.tooltip() != null && !definition.tooltip().isBlank()) {
|
||||
widget.getCOSObject().setString(COSName.TU, definition.tooltip());
|
||||
@@ -2277,13 +2679,25 @@ public class FormUtils {
|
||||
}
|
||||
}
|
||||
|
||||
field.getWidgets().add(widget);
|
||||
widget.setParent(field);
|
||||
// Only link a SEPARATE widget into the field; the merged widget IS the
|
||||
// field dictionary and is already its own widget.
|
||||
if (!reuseFieldDict) {
|
||||
List<PDAnnotationWidget> widgets = new ArrayList<>(field.getWidgets());
|
||||
if (!widgets.contains(widget)) {
|
||||
widgets.add(widget);
|
||||
field.setWidgets(widgets);
|
||||
}
|
||||
widget.setParent(field);
|
||||
}
|
||||
|
||||
List<PDAnnotation> annotations = page.getAnnotations();
|
||||
if (annotations == null) {
|
||||
page.getAnnotations().add(widget);
|
||||
} else if (!annotations.contains(widget)) {
|
||||
// page.getAnnotations() can return null; calling it again and adding
|
||||
// would NPE. Initialise the list and attach it to the page first.
|
||||
annotations = new ArrayList<>();
|
||||
page.setAnnotations(annotations);
|
||||
}
|
||||
if (!annotations.contains(widget)) {
|
||||
annotations.add(widget);
|
||||
}
|
||||
acroForm.getFields().add(field);
|
||||
@@ -2411,7 +2825,12 @@ public class FormUtils {
|
||||
Boolean multiSelect,
|
||||
List<String> options,
|
||||
String defaultValue,
|
||||
String tooltip) {}
|
||||
String tooltip,
|
||||
Float fontSize,
|
||||
Boolean readOnly,
|
||||
Boolean multiline,
|
||||
Integer maxLength,
|
||||
String buttonAction) {}
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public record ModifyFormFieldDefinition(
|
||||
@@ -2419,11 +2838,27 @@ public class FormUtils {
|
||||
String name,
|
||||
String label,
|
||||
String type,
|
||||
Integer pageIndex,
|
||||
Float x,
|
||||
Float y,
|
||||
Float width,
|
||||
Float height,
|
||||
Boolean required,
|
||||
Boolean multiSelect,
|
||||
List<String> options,
|
||||
String defaultValue,
|
||||
String tooltip) {}
|
||||
String tooltip,
|
||||
Float fontSize,
|
||||
Boolean readOnly,
|
||||
Boolean multiline,
|
||||
Integer maxLength) {}
|
||||
|
||||
/** A mixed batch of field edits applied in one request via {@link #applyFieldEdits}. */
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public record FieldEditBatch(
|
||||
List<NewFormFieldDefinition> add,
|
||||
List<ModifyFormFieldDefinition> modify,
|
||||
List<String> delete) {}
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public record FormFieldInfo(
|
||||
|
||||
+6
-4
@@ -130,13 +130,15 @@ class FormFieldTypeSupportTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotSupportsDefinitionCreation_signatureReturnsTrue() {
|
||||
assertTrue(FormFieldTypeSupport.SIGNATURE.doesNotsupportsDefinitionCreation());
|
||||
void doesNotSupportsDefinitionCreation_signatureReturnsFalse() {
|
||||
// Signature placeholders are now creatable via the editor.
|
||||
assertFalse(FormFieldTypeSupport.SIGNATURE.doesNotsupportsDefinitionCreation());
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotSupportsDefinitionCreation_buttonReturnsTrue() {
|
||||
assertTrue(FormFieldTypeSupport.BUTTON.doesNotsupportsDefinitionCreation());
|
||||
void doesNotSupportsDefinitionCreation_buttonReturnsFalse() {
|
||||
// Push buttons (with actions) are now creatable via the editor.
|
||||
assertFalse(FormFieldTypeSupport.BUTTON.doesNotsupportsDefinitionCreation());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,397 @@
|
||||
package stirling.software.common.util;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.pdfbox.Loader;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDPage;
|
||||
import org.apache.pdfbox.pdmodel.PDResources;
|
||||
import org.apache.pdfbox.pdmodel.common.PDRectangle;
|
||||
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
|
||||
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
|
||||
import org.apache.pdfbox.pdmodel.interactive.form.PDPushButton;
|
||||
import org.apache.pdfbox.pdmodel.interactive.form.PDRadioButton;
|
||||
import org.apache.pdfbox.pdmodel.interactive.form.PDSignatureField;
|
||||
import org.apache.pdfbox.pdmodel.interactive.form.PDTextField;
|
||||
import org.apache.pdfbox.pdmodel.interactive.form.PDVariableText;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Round-trip coverage for the structural form-editing additions from PR #5777: {@link
|
||||
* FormUtils#addNewFields}, geometry/font/flag changes in {@link FormUtils#modifyFormFields}, and
|
||||
* the CropBox-offset coordinate handling.
|
||||
*
|
||||
* <p>Assertions are made after a save → reload cycle because PDFBox synthesises widgets for fields
|
||||
* that have no explicit {@code /Kids}; only the serialised document authoritatively reflects what a
|
||||
* viewer (or the next API call) sees.
|
||||
*/
|
||||
class FormUtilsEditingTest {
|
||||
|
||||
private static PDAcroForm setupForm(PDDocument document, PDRectangle pageSize) {
|
||||
PDPage page = new PDPage(pageSize);
|
||||
document.addPage(page);
|
||||
PDAcroForm acroForm = new PDAcroForm(document);
|
||||
acroForm.setDefaultResources(new PDResources());
|
||||
document.getDocumentCatalog().setAcroForm(acroForm);
|
||||
return acroForm;
|
||||
}
|
||||
|
||||
private static byte[] save(PDDocument document) throws IOException {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
document.save(baos);
|
||||
return baos.toByteArray();
|
||||
}
|
||||
|
||||
private static FormUtils.NewFormFieldDefinition newText(
|
||||
String name, float x, float y, float w, float h) {
|
||||
return new FormUtils.NewFormFieldDefinition(
|
||||
name, null, "text", 0, x, y, w, h, null, null, null, null, null, null, null, null,
|
||||
null, null);
|
||||
}
|
||||
|
||||
private static FormUtils.NewFormFieldDefinition newField(
|
||||
String type,
|
||||
String name,
|
||||
float x,
|
||||
float y,
|
||||
float w,
|
||||
float h,
|
||||
List<String> options,
|
||||
Integer maxLength,
|
||||
String buttonAction) {
|
||||
return new FormUtils.NewFormFieldDefinition(
|
||||
name,
|
||||
null,
|
||||
type,
|
||||
0,
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
null,
|
||||
null,
|
||||
options,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
maxLength,
|
||||
buttonAction);
|
||||
}
|
||||
|
||||
private static PDRectangle firstWidgetRect(PDAcroForm acroForm, String name) {
|
||||
PDField field = acroForm.getField(name);
|
||||
assertNotNull(field, "field '" + name + "' should exist");
|
||||
assertTrue(!field.getWidgets().isEmpty(), "field should have at least one widget");
|
||||
return field.getWidgets().get(0).getRectangle();
|
||||
}
|
||||
|
||||
@Test
|
||||
void addNewFields_createsTextFieldAtRequestedRectangle() throws IOException {
|
||||
byte[] saved;
|
||||
try (PDDocument document = new PDDocument()) {
|
||||
setupForm(document, PDRectangle.A4);
|
||||
FormUtils.addNewFields(document, List.of(newText("created", 50, 700, 200, 20)));
|
||||
saved = save(document);
|
||||
}
|
||||
|
||||
try (PDDocument reloaded = Loader.loadPDF(saved)) {
|
||||
PDAcroForm acroForm = reloaded.getDocumentCatalog().getAcroForm(null);
|
||||
assertNotNull(acroForm, "AcroForm should exist after reload");
|
||||
assertTrue(acroForm.getField("created") instanceof PDTextField);
|
||||
PDRectangle rect = firstWidgetRect(acroForm, "created");
|
||||
assertNotNull(rect, "created widget should keep its rectangle after reload");
|
||||
assertEquals(50f, rect.getLowerLeftX(), 0.5f);
|
||||
assertEquals(700f, rect.getLowerLeftY(), 0.5f);
|
||||
assertEquals(200f, rect.getWidth(), 0.5f);
|
||||
assertEquals(20f, rect.getHeight(), 0.5f);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void addNewFields_appliesCropBoxOffsetToCoordinates() throws IOException {
|
||||
byte[] saved;
|
||||
try (PDDocument document = new PDDocument()) {
|
||||
setupForm(document, PDRectangle.A4);
|
||||
// Shift the CropBox origin; the frontend sends CropBox-relative coords.
|
||||
document.getPage(0).setCropBox(new PDRectangle(10, 20, 500, 700));
|
||||
FormUtils.addNewFields(document, List.of(newText("shifted", 5, 5, 100, 15)));
|
||||
saved = save(document);
|
||||
}
|
||||
|
||||
try (PDDocument reloaded = Loader.loadPDF(saved)) {
|
||||
PDAcroForm acroForm = reloaded.getDocumentCatalog().getAcroForm(null);
|
||||
PDRectangle rect = firstWidgetRect(acroForm, "shifted");
|
||||
// Absolute = CropBox-relative + CropBox lower-left offset.
|
||||
assertEquals(15f, rect.getLowerLeftX(), 0.5f);
|
||||
assertEquals(25f, rect.getLowerLeftY(), 0.5f);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void addNewFields_appliesReadOnlyFontSizeAndMultiline() throws IOException {
|
||||
byte[] saved;
|
||||
try (PDDocument document = new PDDocument()) {
|
||||
setupForm(document, PDRectangle.A4);
|
||||
FormUtils.NewFormFieldDefinition def =
|
||||
new FormUtils.NewFormFieldDefinition(
|
||||
"opts",
|
||||
null,
|
||||
"text",
|
||||
0,
|
||||
10f,
|
||||
10f,
|
||||
120f,
|
||||
18f,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
18f,
|
||||
Boolean.TRUE,
|
||||
Boolean.TRUE,
|
||||
null,
|
||||
null);
|
||||
FormUtils.addNewFields(document, List.of(def));
|
||||
saved = save(document);
|
||||
}
|
||||
|
||||
try (PDDocument reloaded = Loader.loadPDF(saved)) {
|
||||
PDAcroForm acroForm = reloaded.getDocumentCatalog().getAcroForm(null);
|
||||
PDField field = acroForm.getField("opts");
|
||||
assertNotNull(field);
|
||||
assertTrue(field.isReadOnly(), "read-only flag should survive reload");
|
||||
assertTrue(field instanceof PDTextField);
|
||||
assertTrue(((PDTextField) field).isMultiline(), "multiline flag should survive reload");
|
||||
String da = ((PDVariableText) field).getDefaultAppearance();
|
||||
assertTrue(da.contains("18"), "default appearance should carry the font size: " + da);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyFormFields_movesAndResizesWidget() throws IOException {
|
||||
byte[] saved;
|
||||
try (PDDocument document = new PDDocument()) {
|
||||
setupForm(document, PDRectangle.A4);
|
||||
FormUtils.addNewFields(document, List.of(newText("movable", 50, 700, 200, 20)));
|
||||
|
||||
FormUtils.ModifyFormFieldDefinition mod =
|
||||
new FormUtils.ModifyFormFieldDefinition(
|
||||
"movable", null, null, null, 0, 100f, 600f, 150f, 30f, null, null, null,
|
||||
null, null, null, null, null, null);
|
||||
FormUtils.modifyFormFields(document, List.of(mod));
|
||||
saved = save(document);
|
||||
}
|
||||
|
||||
try (PDDocument reloaded = Loader.loadPDF(saved)) {
|
||||
PDAcroForm acroForm = reloaded.getDocumentCatalog().getAcroForm(null);
|
||||
PDRectangle rect = firstWidgetRect(acroForm, "movable");
|
||||
assertEquals(100f, rect.getLowerLeftX(), 0.5f);
|
||||
assertEquals(600f, rect.getLowerLeftY(), 0.5f);
|
||||
assertEquals(150f, rect.getWidth(), 0.5f);
|
||||
assertEquals(30f, rect.getHeight(), 0.5f);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyFormFields_setsReadOnlyAndFontSize() throws IOException {
|
||||
byte[] saved;
|
||||
try (PDDocument document = new PDDocument()) {
|
||||
setupForm(document, PDRectangle.A4);
|
||||
FormUtils.addNewFields(document, List.of(newText("editable", 50, 700, 200, 20)));
|
||||
|
||||
FormUtils.ModifyFormFieldDefinition mod =
|
||||
new FormUtils.ModifyFormFieldDefinition(
|
||||
"editable",
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
22f,
|
||||
Boolean.TRUE,
|
||||
null,
|
||||
null);
|
||||
FormUtils.modifyFormFields(document, List.of(mod));
|
||||
saved = save(document);
|
||||
}
|
||||
|
||||
try (PDDocument reloaded = Loader.loadPDF(saved)) {
|
||||
PDAcroForm acroForm = reloaded.getDocumentCatalog().getAcroForm(null);
|
||||
PDField field = acroForm.getField("editable");
|
||||
assertNotNull(field);
|
||||
assertTrue(field.isReadOnly(), "read-only flag should survive reload");
|
||||
String da = ((PDVariableText) field).getDefaultAppearance();
|
||||
assertTrue(da.contains("22"), "font size should be reflected in DA: " + da);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteFormFields_removesField() throws IOException {
|
||||
byte[] saved;
|
||||
try (PDDocument document = new PDDocument()) {
|
||||
PDAcroForm acroForm = setupForm(document, PDRectangle.A4);
|
||||
FormUtils.addNewFields(document, List.of(newText("temp", 50, 700, 200, 20)));
|
||||
FormUtils.deleteFormFields(document, List.of("temp"));
|
||||
// After delete the AcroForm may still exist; the field must be gone.
|
||||
if (acroForm != null) {
|
||||
assertNull(acroForm.getField("temp"));
|
||||
}
|
||||
saved = save(document);
|
||||
}
|
||||
|
||||
try (PDDocument reloaded = Loader.loadPDF(saved)) {
|
||||
PDAcroForm acroForm = reloaded.getDocumentCatalog().getAcroForm(null);
|
||||
assertTrue(acroForm == null || acroForm.getField("temp") == null);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void addNewFields_createsRadioGroupWithOneWidgetPerOption() throws IOException {
|
||||
byte[] saved;
|
||||
try (PDDocument document = new PDDocument()) {
|
||||
setupForm(document, PDRectangle.A4);
|
||||
FormUtils.addNewFields(
|
||||
document,
|
||||
List.of(
|
||||
newField(
|
||||
"radio",
|
||||
"choice",
|
||||
60,
|
||||
700,
|
||||
16,
|
||||
16,
|
||||
List.of("Yes", "No"),
|
||||
null,
|
||||
null)));
|
||||
saved = save(document);
|
||||
}
|
||||
|
||||
try (PDDocument reloaded = Loader.loadPDF(saved)) {
|
||||
PDAcroForm acroForm = reloaded.getDocumentCatalog().getAcroForm(null);
|
||||
PDField field = acroForm.getField("choice");
|
||||
assertNotNull(field, "radio field should exist");
|
||||
assertTrue(field instanceof PDRadioButton, "should be a radio button group");
|
||||
assertEquals(2, field.getWidgets().size(), "one widget per option");
|
||||
assertTrue(((PDRadioButton) field).getExportValues().contains("Yes"));
|
||||
assertTrue(((PDRadioButton) field).getExportValues().contains("No"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractFormFields_prefersFieldNameOverFirstOptionForChoiceLabel() throws IOException {
|
||||
// A radio group named "Choice" with options Yes/No must be labelled
|
||||
// "Choice" (its name), not "Yes" (its first option). Otherwise the label
|
||||
// shown in the viewer disagrees with the field name shown in the editor.
|
||||
byte[] saved;
|
||||
try (PDDocument document = new PDDocument()) {
|
||||
setupForm(document, PDRectangle.A4);
|
||||
FormUtils.addNewFields(
|
||||
document,
|
||||
List.of(
|
||||
newField(
|
||||
"radio",
|
||||
"Choice",
|
||||
60,
|
||||
700,
|
||||
16,
|
||||
16,
|
||||
List.of("Yes", "No"),
|
||||
null,
|
||||
null)));
|
||||
saved = save(document);
|
||||
}
|
||||
|
||||
try (PDDocument reloaded = Loader.loadPDF(saved)) {
|
||||
FormUtils.FormFieldInfo choice =
|
||||
FormUtils.extractFormFields(reloaded).stream()
|
||||
.filter(f -> "Choice".equals(f.name()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
assertNotNull(choice, "radio field should be extracted");
|
||||
assertEquals(
|
||||
"Choice", choice.label(), "field name should win over the first option value");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void addNewFields_createsCombTextField() throws IOException {
|
||||
byte[] saved;
|
||||
try (PDDocument document = new PDDocument()) {
|
||||
setupForm(document, PDRectangle.A4);
|
||||
FormUtils.addNewFields(
|
||||
document, List.of(newField("text", "ssn", 50, 700, 200, 20, null, 9, null)));
|
||||
saved = save(document);
|
||||
}
|
||||
|
||||
try (PDDocument reloaded = Loader.loadPDF(saved)) {
|
||||
PDAcroForm acroForm = reloaded.getDocumentCatalog().getAcroForm(null);
|
||||
PDTextField field = (PDTextField) acroForm.getField("ssn");
|
||||
assertNotNull(field);
|
||||
assertEquals(9, field.getMaxLen(), "comb max length should persist");
|
||||
assertTrue(field.isComb(), "comb flag should be set");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void addNewFields_createsSignatureAndButton() throws IOException {
|
||||
byte[] saved;
|
||||
try (PDDocument document = new PDDocument()) {
|
||||
setupForm(document, PDRectangle.A4);
|
||||
FormUtils.addNewFields(
|
||||
document,
|
||||
List.of(
|
||||
newField("signature", "sig", 50, 600, 200, 60, null, null, null),
|
||||
newField("button", "btn", 50, 500, 120, 24, null, null, "reset")));
|
||||
saved = save(document);
|
||||
}
|
||||
|
||||
try (PDDocument reloaded = Loader.loadPDF(saved)) {
|
||||
PDAcroForm acroForm = reloaded.getDocumentCatalog().getAcroForm(null);
|
||||
assertTrue(
|
||||
acroForm.getField("sig") instanceof PDSignatureField,
|
||||
"signature placeholder should exist");
|
||||
assertTrue(
|
||||
acroForm.getField("btn") instanceof PDPushButton, "push button should exist");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void applyFieldEdits_addsModifiesAndDeletesInOnePass() throws IOException {
|
||||
byte[] saved;
|
||||
try (PDDocument document = new PDDocument()) {
|
||||
setupForm(document, PDRectangle.A4);
|
||||
FormUtils.addNewFields(document, List.of(newText("old", 50, 700, 200, 20)));
|
||||
|
||||
FormUtils.applyFieldEdits(
|
||||
document,
|
||||
List.of(newText("fresh", 50, 600, 200, 20)),
|
||||
List.of(),
|
||||
List.of("old"));
|
||||
saved = save(document);
|
||||
}
|
||||
|
||||
try (PDDocument reloaded = Loader.loadPDF(saved)) {
|
||||
PDAcroForm acroForm = reloaded.getDocumentCatalog().getAcroForm(null);
|
||||
assertNotNull(acroForm.getField("fresh"), "added field should be present");
|
||||
assertNull(acroForm.getField("old"), "deleted field should be gone");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -705,10 +705,19 @@ class FormUtilsGapTest {
|
||||
"newName",
|
||||
"New Label",
|
||||
null, // keep type (text) -> in-place path
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
Boolean.TRUE,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
FormUtils.modifyFormFields(doc, List.of(mod));
|
||||
@@ -731,7 +740,8 @@ class FormUtilsGapTest {
|
||||
|
||||
FormUtils.ModifyFormFieldDefinition mod =
|
||||
new FormUtils.ModifyFormFieldDefinition(
|
||||
"missing", null, null, null, null, null, null, null, null);
|
||||
"missing", null, null, null, null, null, null, null, null, null,
|
||||
null, null, null, null, null, null, null, null);
|
||||
|
||||
FormUtils.modifyFormFields(doc, List.of(mod));
|
||||
|
||||
@@ -754,7 +764,8 @@ class FormUtilsGapTest {
|
||||
mods.add(null);
|
||||
mods.add(
|
||||
new FormUtils.ModifyFormFieldDefinition(
|
||||
" ", null, null, null, null, null, null, null, null));
|
||||
" ", null, null, null, null, null, null, null, null, null, null,
|
||||
null, null, null, null, null, null, null));
|
||||
|
||||
FormUtils.modifyFormFields(doc, mods);
|
||||
assertEquals(1, FormUtils.extractFormFields(doc).size());
|
||||
|
||||
@@ -476,8 +476,17 @@ class FormUtilsMoreTest {
|
||||
"combobox",
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
List.of("One", "Two"),
|
||||
"One",
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
FormUtils.modifyFormFields(doc, List.of(mod));
|
||||
@@ -505,10 +514,19 @@ class FormUtilsMoreTest {
|
||||
null,
|
||||
"listbox", // same type -> in-place path
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
Boolean.TRUE,
|
||||
List.of("X", "Y", "Z"),
|
||||
null,
|
||||
"Choose items");
|
||||
"Choose items",
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
FormUtils.modifyFormFields(doc, List.of(mod));
|
||||
|
||||
@@ -529,7 +547,24 @@ class FormUtilsMoreTest {
|
||||
|
||||
FormUtils.ModifyFormFieldDefinition mod =
|
||||
new FormUtils.ModifyFormFieldDefinition(
|
||||
"keep", null, null, "bogusType", null, null, null, null, null);
|
||||
"keep",
|
||||
null,
|
||||
null,
|
||||
"bogusType",
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
FormUtils.modifyFormFields(doc, List.of(mod));
|
||||
// The field is preserved unchanged because the target type is unsupported.
|
||||
@@ -554,7 +589,8 @@ class FormUtilsMoreTest {
|
||||
// Rename beta -> alpha; should be uniquified to avoid the collision.
|
||||
FormUtils.ModifyFormFieldDefinition mod =
|
||||
new FormUtils.ModifyFormFieldDefinition(
|
||||
"beta", "alpha", null, null, null, null, null, null, null);
|
||||
"beta", "alpha", null, null, null, null, null, null, null, null,
|
||||
null, null, null, null, null, null, null, null);
|
||||
|
||||
FormUtils.modifyFormFields(doc, List.of(mod));
|
||||
|
||||
@@ -575,7 +611,8 @@ class FormUtilsMoreTest {
|
||||
doc.addPage(new PDPage());
|
||||
FormUtils.ModifyFormFieldDefinition mod =
|
||||
new FormUtils.ModifyFormFieldDefinition(
|
||||
"x", null, null, null, null, null, null, null, null);
|
||||
"x", null, null, null, null, null, null, null, null, null, null,
|
||||
null, null, null, null, null, null, null);
|
||||
FormUtils.modifyFormFields(doc, List.of(mod));
|
||||
}
|
||||
}
|
||||
|
||||
+81
@@ -257,6 +257,87 @@ public class FormFillController {
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping(value = "/add-fields", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@Operation(
|
||||
summary = "Add new form fields",
|
||||
description =
|
||||
"Creates new form fields in the provided PDF and returns the updated file")
|
||||
public ResponseEntity<Resource> addFields(
|
||||
@Parameter(
|
||||
description = "The input PDF file",
|
||||
required = true,
|
||||
content =
|
||||
@Content(
|
||||
mediaType = MediaType.APPLICATION_PDF_VALUE,
|
||||
schema = @Schema(type = "string", format = "binary")))
|
||||
@RequestParam("file")
|
||||
MultipartFile file,
|
||||
@Parameter(
|
||||
description = "JSON array of new field definitions",
|
||||
example =
|
||||
"[{\"name\":\"NewField\",\"type\":\"text\",\"pageIndex\":0,"
|
||||
+ "\"x\":50,\"y\":700,\"width\":200,\"height\":20}]")
|
||||
@RequestPart(value = "fields", required = false)
|
||||
byte[] fieldsPayload)
|
||||
throws IOException {
|
||||
|
||||
String rawFields = decodePart(fieldsPayload);
|
||||
List<FormUtils.NewFormFieldDefinition> definitions =
|
||||
FormPayloadParser.parseNewFieldDefinitions(objectMapper, rawFields);
|
||||
if (definitions.isEmpty()) {
|
||||
throw ExceptionUtils.createIllegalArgumentException(
|
||||
"error.dataRequired",
|
||||
"{0} must contain at least one definition",
|
||||
"fields payload");
|
||||
}
|
||||
|
||||
return processSingleFile(
|
||||
file, "updated", document -> FormUtils.addNewFields(document, definitions));
|
||||
}
|
||||
|
||||
@PostMapping(value = "/edit-fields", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@Operation(
|
||||
summary = "Apply a batch of form field edits",
|
||||
description =
|
||||
"Adds, modifies, and deletes form fields in a single request (one document"
|
||||
+ " load/save) and returns the updated file")
|
||||
public ResponseEntity<Resource> editFields(
|
||||
@Parameter(
|
||||
description = "The input PDF file",
|
||||
required = true,
|
||||
content =
|
||||
@Content(
|
||||
mediaType = MediaType.APPLICATION_PDF_VALUE,
|
||||
schema = @Schema(type = "string", format = "binary")))
|
||||
@RequestParam("file")
|
||||
MultipartFile file,
|
||||
@Parameter(
|
||||
description =
|
||||
"JSON object with optional 'add', 'modify' and 'delete'"
|
||||
+ " sections",
|
||||
example =
|
||||
"{\"add\":[{\"name\":\"f\",\"type\":\"text\",\"pageIndex\":0,"
|
||||
+ "\"x\":50,\"y\":700,\"width\":200,\"height\":20}],"
|
||||
+ "\"modify\":[],\"delete\":[]}")
|
||||
@RequestPart(value = "edits", required = false)
|
||||
byte[] editsPayload)
|
||||
throws IOException {
|
||||
|
||||
String rawEdits = decodePart(editsPayload);
|
||||
FormUtils.FieldEditBatch batch = FormPayloadParser.parseFieldEdits(objectMapper, rawEdits);
|
||||
if (batch.add().isEmpty() && batch.modify().isEmpty() && batch.delete().isEmpty()) {
|
||||
throw ExceptionUtils.createIllegalArgumentException(
|
||||
"error.dataRequired", "{0} must contain at least one edit", "edits payload");
|
||||
}
|
||||
|
||||
return processSingleFile(
|
||||
file,
|
||||
"updated",
|
||||
document ->
|
||||
FormUtils.applyFieldEdits(
|
||||
document, batch.add(), batch.modify(), batch.delete()));
|
||||
}
|
||||
|
||||
@PostMapping(value = "/modify-fields", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@Operation(
|
||||
summary = "Modify existing form fields",
|
||||
|
||||
+39
@@ -28,6 +28,8 @@ final class FormPayloadParser {
|
||||
private static final TypeReference<Map<String, Object>> MAP_TYPE = new TypeReference<>() {};
|
||||
private static final TypeReference<List<FormUtils.ModifyFormFieldDefinition>>
|
||||
MODIFY_FIELD_LIST_TYPE = new TypeReference<>() {};
|
||||
private static final TypeReference<List<FormUtils.NewFormFieldDefinition>> NEW_FIELD_LIST_TYPE =
|
||||
new TypeReference<>() {};
|
||||
private static final TypeReference<List<String>> STRING_LIST_TYPE = new TypeReference<>() {};
|
||||
|
||||
private FormPayloadParser() {}
|
||||
@@ -94,6 +96,43 @@ final class FormPayloadParser {
|
||||
return objectMapper.readValue(json, MODIFY_FIELD_LIST_TYPE);
|
||||
}
|
||||
|
||||
static List<FormUtils.NewFormFieldDefinition> parseNewFieldDefinitions(
|
||||
ObjectMapper objectMapper, String json) {
|
||||
if (json == null || json.isBlank()) {
|
||||
return List.of();
|
||||
}
|
||||
return objectMapper.readValue(json, NEW_FIELD_LIST_TYPE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a combined edit batch: {@code {"add":[...],"modify":[...],"delete":[...]}}. Each
|
||||
* section is optional. The delete section accepts the same shapes as {@link #parseNameList}.
|
||||
*/
|
||||
static FormUtils.FieldEditBatch parseFieldEdits(ObjectMapper objectMapper, String json) {
|
||||
if (json == null || json.isBlank()) {
|
||||
return new FormUtils.FieldEditBatch(List.of(), List.of(), List.of());
|
||||
}
|
||||
final JsonNode root = objectMapper.readTree(json);
|
||||
List<FormUtils.NewFormFieldDefinition> adds = List.of();
|
||||
List<FormUtils.ModifyFormFieldDefinition> modifies = List.of();
|
||||
List<String> deletes = List.of();
|
||||
if (root != null && root.isObject()) {
|
||||
final JsonNode addNode = root.get("add");
|
||||
if (addNode != null && addNode.isArray()) {
|
||||
adds = objectMapper.readValue(addNode.toString(), NEW_FIELD_LIST_TYPE);
|
||||
}
|
||||
final JsonNode modifyNode = root.get("modify");
|
||||
if (modifyNode != null && modifyNode.isArray()) {
|
||||
modifies = objectMapper.readValue(modifyNode.toString(), MODIFY_FIELD_LIST_TYPE);
|
||||
}
|
||||
final JsonNode deleteNode = root.get("delete");
|
||||
if (deleteNode != null && !deleteNode.isNull()) {
|
||||
deletes = parseNameList(objectMapper, deleteNode.toString());
|
||||
}
|
||||
}
|
||||
return new FormUtils.FieldEditBatch(adds, modifies, deletes);
|
||||
}
|
||||
|
||||
static List<String> parseNameList(ObjectMapper objectMapper, String json) {
|
||||
if (json == null || json.isBlank()) {
|
||||
return List.of();
|
||||
|
||||
+79
@@ -330,6 +330,85 @@ class FormFillControllerTest {
|
||||
}
|
||||
}
|
||||
|
||||
// ── addFields ──────────────────────────────────────────────────────
|
||||
|
||||
@Nested
|
||||
@DisplayName("addFields")
|
||||
class AddFields {
|
||||
|
||||
@Test
|
||||
@DisplayName("throws when fields payload is null")
|
||||
void nullPayload() {
|
||||
assertThatThrownBy(() -> controller.addFields(pdfFile(), null))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("throws when fields payload is an empty list")
|
||||
void emptyPayload() {
|
||||
assertThatThrownBy(() -> controller.addFields(pdfFile(), "[]".getBytes()))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("processes a valid new-field payload")
|
||||
void validPayload() throws Exception {
|
||||
MockMultipartFile file = pdfFile();
|
||||
PDDocument doc = createMinimalPdf();
|
||||
when(pdfDocumentFactory.load(eq(file))).thenReturn(doc);
|
||||
|
||||
String json =
|
||||
"[{\"name\":\"NewField\",\"type\":\"text\",\"pageIndex\":0,"
|
||||
+ "\"x\":50,\"y\":700,\"width\":200,\"height\":20}]";
|
||||
ResponseEntity<Resource> response = controller.addFields(file, json.getBytes());
|
||||
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(response.getBody()).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
// ── editFields (combined) ──────────────────────────────────────────
|
||||
|
||||
@Nested
|
||||
@DisplayName("editFields")
|
||||
class EditFields {
|
||||
|
||||
@Test
|
||||
@DisplayName("throws when edits payload is null")
|
||||
void nullPayload() {
|
||||
assertThatThrownBy(() -> controller.editFields(pdfFile(), null))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("throws when all sections are empty")
|
||||
void emptyBatch() {
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
controller.editFields(
|
||||
pdfFile(),
|
||||
"{\"add\":[],\"modify\":[],\"delete\":[]}".getBytes()))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("processes a combined add/delete batch")
|
||||
void validBatch() throws Exception {
|
||||
MockMultipartFile file = pdfFile();
|
||||
PDDocument doc = createMinimalPdf();
|
||||
when(pdfDocumentFactory.load(eq(file))).thenReturn(doc);
|
||||
|
||||
String json =
|
||||
"{\"add\":[{\"name\":\"f\",\"type\":\"text\",\"pageIndex\":0,\"x\":50,"
|
||||
+ "\"y\":700,\"width\":200,\"height\":20}],\"modify\":[],"
|
||||
+ "\"delete\":[]}";
|
||||
ResponseEntity<Resource> response = controller.editFields(file, json.getBytes());
|
||||
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(response.getBody()).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
// ── buildBaseName ──────────────────────────────────────────────────
|
||||
|
||||
@Nested
|
||||
|
||||
+88
@@ -170,6 +170,94 @@ class FormPayloadParserTest {
|
||||
}
|
||||
}
|
||||
|
||||
// ── parseNewFieldDefinitions ───────────────────────────────────────
|
||||
|
||||
@Nested
|
||||
@DisplayName("parseNewFieldDefinitions")
|
||||
class ParseNewFieldDefinitions {
|
||||
|
||||
@Test
|
||||
@DisplayName("returns empty list for null input")
|
||||
void nullInput() {
|
||||
List<FormUtils.NewFormFieldDefinition> result =
|
||||
FormPayloadParser.parseNewFieldDefinitions(objectMapper, null);
|
||||
assertThat(result).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("returns empty list for blank input")
|
||||
void blankInput() {
|
||||
List<FormUtils.NewFormFieldDefinition> result =
|
||||
FormPayloadParser.parseNewFieldDefinitions(objectMapper, " ");
|
||||
assertThat(result).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("parses a valid new-field list including geometry and flags")
|
||||
void validNewFields() {
|
||||
String json =
|
||||
"[{\"name\":\"NewField\",\"type\":\"text\",\"pageIndex\":0,"
|
||||
+ "\"x\":50,\"y\":700,\"width\":200,\"height\":20,"
|
||||
+ "\"fontSize\":14,\"readOnly\":true,\"multiline\":true}]";
|
||||
List<FormUtils.NewFormFieldDefinition> result =
|
||||
FormPayloadParser.parseNewFieldDefinitions(objectMapper, json);
|
||||
assertThat(result).hasSize(1);
|
||||
FormUtils.NewFormFieldDefinition def = result.get(0);
|
||||
assertThat(def.name()).isEqualTo("NewField");
|
||||
assertThat(def.type()).isEqualTo("text");
|
||||
assertThat(def.pageIndex()).isEqualTo(0);
|
||||
assertThat(def.x()).isEqualTo(50f);
|
||||
assertThat(def.y()).isEqualTo(700f);
|
||||
assertThat(def.width()).isEqualTo(200f);
|
||||
assertThat(def.height()).isEqualTo(20f);
|
||||
assertThat(def.fontSize()).isEqualTo(14f);
|
||||
assertThat(def.readOnly()).isTrue();
|
||||
assertThat(def.multiline()).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
// ── parseFieldEdits ────────────────────────────────────────────────
|
||||
|
||||
@Nested
|
||||
@DisplayName("parseFieldEdits")
|
||||
class ParseFieldEdits {
|
||||
|
||||
@Test
|
||||
@DisplayName("returns empty batch for null input")
|
||||
void nullInput() {
|
||||
FormUtils.FieldEditBatch batch = FormPayloadParser.parseFieldEdits(objectMapper, null);
|
||||
assertThat(batch.add()).isEmpty();
|
||||
assertThat(batch.modify()).isEmpty();
|
||||
assertThat(batch.delete()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("parses a combined add/modify/delete batch")
|
||||
void combinedBatch() {
|
||||
String json =
|
||||
"{\"add\":[{\"name\":\"new1\",\"type\":\"text\",\"pageIndex\":0,\"x\":1,"
|
||||
+ "\"y\":2,\"width\":3,\"height\":4}],"
|
||||
+ "\"modify\":[{\"targetName\":\"old1\",\"label\":\"L\"}],"
|
||||
+ "\"delete\":[\"gone1\",{\"name\":\"gone2\"}]}";
|
||||
FormUtils.FieldEditBatch batch = FormPayloadParser.parseFieldEdits(objectMapper, json);
|
||||
assertThat(batch.add()).hasSize(1);
|
||||
assertThat(batch.add().get(0).name()).isEqualTo("new1");
|
||||
assertThat(batch.modify()).hasSize(1);
|
||||
assertThat(batch.modify().get(0).targetName()).isEqualTo("old1");
|
||||
assertThat(batch.delete()).containsExactly("gone1", "gone2");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("tolerates missing sections")
|
||||
void missingSections() {
|
||||
FormUtils.FieldEditBatch batch =
|
||||
FormPayloadParser.parseFieldEdits(objectMapper, "{\"delete\":[\"x\"]}");
|
||||
assertThat(batch.add()).isEmpty();
|
||||
assertThat(batch.modify()).isEmpty();
|
||||
assertThat(batch.delete()).containsExactly("x");
|
||||
}
|
||||
}
|
||||
|
||||
// ── parseNameList ──────────────────────────────────────────────────
|
||||
|
||||
@Nested
|
||||
|
||||
@@ -66,20 +66,6 @@ dependencies {
|
||||
|
||||
implementation "com.google.code.gson:gson:${gsonVersion}"
|
||||
|
||||
// jinjava/jjwt transitively request older Jackson 2 versions; declare the current
|
||||
// version directly so it is selected consistently (root build.gradle pins are the fallback).
|
||||
runtimeOnly "com.fasterxml.jackson.core:jackson-core:${jackson2Version}"
|
||||
runtimeOnly "com.fasterxml.jackson.core:jackson-databind:${jackson2Version}"
|
||||
|
||||
implementation("com.hubspot.jinjava:jinjava:${jinjavaVersion}") {
|
||||
// Compile-time-only annotation artifacts (class-retention annotations, not needed at
|
||||
// runtime) whose declared licences (LGPL / none) fail the licence compatibility check.
|
||||
exclude group: 'com.google.code.findbugs', module: 'annotations'
|
||||
exclude group: 'org.derive4j', module: 'derive4j-annotation'
|
||||
exclude group: 'com.hubspot.immutables', module: 'hubspot-style'
|
||||
exclude group: 'com.hubspot.immutables', module: 'immutable-collection-encodings'
|
||||
}
|
||||
|
||||
api 'io.micrometer:micrometer-registry-prometheus'
|
||||
|
||||
api "io.jsonwebtoken:jjwt-api:${jwtVersion}"
|
||||
|
||||
-61
@@ -1,61 +0,0 @@
|
||||
package stirling.software.proprietary.classification;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.proprietary.classification.model.ClassificationLabel;
|
||||
import stirling.software.proprietary.classification.model.ClassificationLabels;
|
||||
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
/**
|
||||
* Supplies the classification vocabulary the classify tool sends to the AI engine. The set is a
|
||||
* fixed, built-in list bundled with the application ({@code
|
||||
* classification/classification-labels.json}) and shared by everyone — there is no per-team
|
||||
* customization or database. Loaded once at startup.
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class ClassificationLabelProvider {
|
||||
|
||||
private static final String RESOURCE = "classification/classification-labels.json";
|
||||
|
||||
private final List<ClassificationLabel> labels;
|
||||
|
||||
// Explicit @Autowired: the class has a second (private) constructor for tests, so Spring
|
||||
// can't infer which to use without it.
|
||||
@Autowired
|
||||
public ClassificationLabelProvider(ObjectMapper objectMapper) {
|
||||
this(load(objectMapper));
|
||||
}
|
||||
|
||||
private ClassificationLabelProvider(List<ClassificationLabel> labels) {
|
||||
this.labels = List.copyOf(labels);
|
||||
}
|
||||
|
||||
/** Build a provider with an explicit label set (tests). */
|
||||
public static ClassificationLabelProvider withLabels(List<ClassificationLabel> labels) {
|
||||
return new ClassificationLabelProvider(labels);
|
||||
}
|
||||
|
||||
/** The built-in vocabulary, in file order. */
|
||||
public List<ClassificationLabel> labels() {
|
||||
return labels;
|
||||
}
|
||||
|
||||
private static List<ClassificationLabel> load(ObjectMapper objectMapper) {
|
||||
try (InputStream in = new ClassPathResource(RESOURCE).getInputStream()) {
|
||||
ClassificationLabels parsed = objectMapper.readValue(in, ClassificationLabels.class);
|
||||
return parsed.labels();
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to load classification labels from {}", RESOURCE, e);
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
package stirling.software.proprietary.classification;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Hidden;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.service.UserServiceInterface;
|
||||
import stirling.software.proprietary.classification.model.ClassificationLabels;
|
||||
import stirling.software.proprietary.classification.model.LabelsValidator;
|
||||
import stirling.software.proprietary.classification.store.ClassificationLabelStore;
|
||||
import stirling.software.proprietary.classification.store.TeamLabelsEntity;
|
||||
import stirling.software.proprietary.policy.config.PolicyManagementAuthority;
|
||||
|
||||
/**
|
||||
* Read/write the team's classification label set — the flat vocabulary the document classifier runs
|
||||
* against. Shared and team-scoped exactly like policies: every user reads their own team's labels,
|
||||
* and only a user who may edit policies (a team leader on SaaS, the global admin self-hosted; see
|
||||
* {@link PolicyManagementAuthority}) may change it — gated only when login is enabled, since
|
||||
* single-user deployments trust the local operator. A team with no stored labels reads as {@code
|
||||
* 204}; that team has no vocabulary, so its documents are not classified (there is no built-in
|
||||
* default on the backend or the engine — the label data lives only in the frontend).
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/classification/labels")
|
||||
@Hidden
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "Classification", description = "Team-scoped document-classification labels")
|
||||
@ConditionalOnBooleanProperty(name = "policies.enabled")
|
||||
public class ClassificationLabelsController {
|
||||
|
||||
private final ClassificationLabelStore labelStore;
|
||||
private final PolicyManagementAuthority policyManagementAuthority;
|
||||
private final ApplicationProperties applicationProperties;
|
||||
private final UserServiceInterface userService;
|
||||
|
||||
@GetMapping
|
||||
@Operation(
|
||||
summary = "Get the team's classification labels",
|
||||
description =
|
||||
"Returns the caller's team label set, or 204 when the team has none (its"
|
||||
+ " documents are then not classified).")
|
||||
public ResponseEntity<ClassificationLabels> getTeamLabels() {
|
||||
return labelStore
|
||||
.findByTeam(currentTeamId())
|
||||
.map(ResponseEntity::ok)
|
||||
.orElseGet(() -> ResponseEntity.noContent().build());
|
||||
}
|
||||
|
||||
@PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
@Operation(
|
||||
summary = "Save the team's classification labels",
|
||||
description =
|
||||
"Validates and stores the label set for the caller's team, shared by everyone"
|
||||
+ " on the team. Requires the policy-editor role for the team.")
|
||||
public ResponseEntity<ClassificationLabels> saveTeamLabels(
|
||||
@RequestBody ClassificationLabels labels) {
|
||||
requireEditingAllowed();
|
||||
validate(labels);
|
||||
ClassificationLabels saved = labelStore.save(currentTeamId(), labels, currentUsername());
|
||||
return ResponseEntity.ok(saved);
|
||||
}
|
||||
|
||||
@DeleteMapping
|
||||
@Operation(
|
||||
summary = "Reset the team's classification labels",
|
||||
description =
|
||||
"Removes the team's stored label set; its documents are then not classified"
|
||||
+ " until labels are saved again. Requires the policy-editor role for the"
|
||||
+ " team.")
|
||||
public ResponseEntity<Void> resetTeamLabels() {
|
||||
requireEditingAllowed();
|
||||
labelStore.deleteByTeam(currentTeamId());
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
private static void validate(ClassificationLabels labels) {
|
||||
try {
|
||||
LabelsValidator.validate(labels);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Editing the team labels requires the editor role for the caller's team — the same gate
|
||||
* policies use (team leader on SaaS, global admin self-hosted). Single-user deployments (login
|
||||
* disabled) have no such role, so they trust the local operator.
|
||||
*/
|
||||
private void requireEditingAllowed() {
|
||||
if (!applicationProperties.getSecurity().isEnableLogin()) {
|
||||
return;
|
||||
}
|
||||
if (!policyManagementAuthority.canEditPolicies()) {
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.FORBIDDEN,
|
||||
"The team classification labels may only be changed by a team leader");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The caller's team key. With login disabled the single operator owns the {@link
|
||||
* TeamLabelsEntity#NO_TEAM} sentinel row; with login enabled a caller with no resolvable team
|
||||
* is an error rather than being dropped into the shared sentinel bucket (which would let
|
||||
* unteamed users read and overwrite each other's "team" labels).
|
||||
*/
|
||||
private Long currentTeamId() {
|
||||
Long teamId = policyManagementAuthority.currentUserTeamId();
|
||||
if (teamId != null) {
|
||||
return teamId;
|
||||
}
|
||||
if (!applicationProperties.getSecurity().isEnableLogin()) {
|
||||
return TeamLabelsEntity.NO_TEAM;
|
||||
}
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.UNAUTHORIZED, "Could not resolve the current user's team");
|
||||
}
|
||||
|
||||
private String currentUsername() {
|
||||
return userService == null ? null : userService.getCurrentUsername();
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -3,10 +3,10 @@ package stirling.software.proprietary.classification.model;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A flat multi-label classification vocabulary — the set of labels a document may be assigned. The
|
||||
* classifier runs against these label names. The vocabulary is a fixed, built-in set shared by
|
||||
* everyone (see {@link stirling.software.proprietary.classification.ClassificationLabelProvider});
|
||||
* this record is the JSON parse target for that bundled resource.
|
||||
* A flat multi-label classification vocabulary — the set of labels a document may be assigned.
|
||||
* Stored per team (admin-edited, shared by everyone on the team); the classifier runs against these
|
||||
* label names. A team with no stored set has no vocabulary, so its documents are not classified —
|
||||
* neither the backend nor the engine holds a default of its own.
|
||||
*/
|
||||
public record ClassificationLabels(List<ClassificationLabel> labels) {
|
||||
|
||||
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package stirling.software.proprietary.classification.model;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Structural validation for a user- or admin-supplied label set, run before it is stored so a
|
||||
* malformed vocabulary can never reach the classifier. Mirrors the invariants the engine relies on:
|
||||
* non-blank ids and names, each unique within the set (ids exactly, names case-insensitively).
|
||||
*/
|
||||
public final class LabelsValidator {
|
||||
|
||||
private LabelsValidator() {}
|
||||
|
||||
// Generous upper bounds so a legitimate label set is never blocked, but a single team or user
|
||||
// can't store an unbounded blob that would bloat the row, balloon the classifier prompt, or
|
||||
// exhaust memory on deserialize.
|
||||
static final int MAX_LABELS = 500;
|
||||
static final int MAX_TEXT_LENGTH = 128;
|
||||
|
||||
// Icon is a Material Symbols key (lowercase, digits, hyphens). Enforce the SHAPE server-side —
|
||||
// the exact allowlist lives in the frontend — so a client bypassing the UI can't store
|
||||
// arbitrary
|
||||
// text that would render as garbage (or worse) in every teammate's sidebar.
|
||||
private static final Pattern ICON_KEY = Pattern.compile("^[a-z0-9-]+$");
|
||||
|
||||
/**
|
||||
* @throws IllegalArgumentException with a human-readable message when the label set is invalid.
|
||||
*/
|
||||
public static void validate(ClassificationLabels labels) {
|
||||
if (labels == null || labels.labels() == null) {
|
||||
throw new IllegalArgumentException("Labels are required");
|
||||
}
|
||||
if (labels.labels().size() > MAX_LABELS) {
|
||||
throw new IllegalArgumentException("Too many labels (max " + MAX_LABELS + ")");
|
||||
}
|
||||
Set<String> ids = new HashSet<>();
|
||||
Set<String> names = new HashSet<>();
|
||||
for (ClassificationLabel label : labels.labels()) {
|
||||
requireText(label.id(), "Label id");
|
||||
requireText(label.name(), "Label name");
|
||||
if (label.icon() != null && !label.icon().isEmpty()) {
|
||||
if (label.icon().length() > MAX_TEXT_LENGTH) {
|
||||
throw new IllegalArgumentException(
|
||||
"Label icon is too long (max " + MAX_TEXT_LENGTH + " characters)");
|
||||
}
|
||||
if (!ICON_KEY.matcher(label.icon()).matches()) {
|
||||
throw new IllegalArgumentException("Invalid label icon: " + label.icon());
|
||||
}
|
||||
}
|
||||
if (!ids.add(label.id().trim())) {
|
||||
throw new IllegalArgumentException("Duplicate label id: " + label.id());
|
||||
}
|
||||
if (!names.add(label.name().trim().toLowerCase(Locale.ROOT))) {
|
||||
throw new IllegalArgumentException("Duplicate label name: " + label.name());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireText(String value, String field) {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new IllegalArgumentException(field + " must not be blank");
|
||||
}
|
||||
if (value.trim().length() > MAX_TEXT_LENGTH) {
|
||||
throw new IllegalArgumentException(
|
||||
field + " is too long (max " + MAX_TEXT_LENGTH + " characters)");
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package stirling.software.proprietary.classification.store;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import stirling.software.proprietary.classification.model.ClassificationLabels;
|
||||
|
||||
/**
|
||||
* Stores one {@link ClassificationLabels} set per team. A {@code null} teamId addresses the
|
||||
* unteamed set (login disabled / no resolvable team), mirroring how the policy store treats a null
|
||||
* team.
|
||||
*/
|
||||
public interface ClassificationLabelStore {
|
||||
|
||||
/** The team's stored labels, or empty when it has none (callers then skip classification). */
|
||||
Optional<ClassificationLabels> findByTeam(Long teamId);
|
||||
|
||||
/** Create or replace the team's labels. Returns the stored value. */
|
||||
ClassificationLabels save(Long teamId, ClassificationLabels labels, String updatedBy);
|
||||
|
||||
/** Remove the team's labels (reset to default). Returns whether a set existed. */
|
||||
boolean deleteByTeam(Long teamId);
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package stirling.software.proprietary.classification.store;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import stirling.software.proprietary.classification.model.ClassificationLabels;
|
||||
|
||||
/**
|
||||
* In-memory {@link ClassificationLabelStore} for tests and any future no-database mode. {@link
|
||||
* JpaClassificationLabelStore} is the runtime bean.
|
||||
*/
|
||||
public class InProcessClassificationLabelStore implements ClassificationLabelStore {
|
||||
|
||||
private final Map<Long, ClassificationLabels> byTeam = new ConcurrentHashMap<>();
|
||||
|
||||
@Override
|
||||
public Optional<ClassificationLabels> findByTeam(Long teamId) {
|
||||
return Optional.ofNullable(byTeam.get(key(teamId)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ClassificationLabels save(Long teamId, ClassificationLabels labels, String updatedBy) {
|
||||
byTeam.put(key(teamId), labels);
|
||||
return labels;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean deleteByTeam(Long teamId) {
|
||||
return byTeam.remove(key(teamId)) != null;
|
||||
}
|
||||
|
||||
private static long key(Long teamId) {
|
||||
return teamId == null ? TeamLabelsEntity.NO_TEAM : teamId;
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package stirling.software.proprietary.classification.store;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.proprietary.classification.model.ClassificationLabels;
|
||||
|
||||
import tools.jackson.core.JacksonException;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
/**
|
||||
* Durable {@link ClassificationLabelStore} backed by JPA; the runtime store. Gated on {@code
|
||||
* policies.enabled} — stored labels only matter when the Classification policy can run — so it
|
||||
* shares the policy subsystem's on/off switch. Each label set is persisted as JSON via {@link
|
||||
* TeamLabelsEntity}.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnBooleanProperty(name = "policies.enabled")
|
||||
public class JpaClassificationLabelStore implements ClassificationLabelStore {
|
||||
|
||||
private final TeamLabelsRepository teamRepository;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
public Optional<ClassificationLabels> findByTeam(Long teamId) {
|
||||
return teamRepository
|
||||
.findById(key(teamId))
|
||||
.flatMap(entity -> parse(entity.getLabelsJson(), "team " + teamId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ClassificationLabels save(Long teamId, ClassificationLabels labels, String updatedBy) {
|
||||
TeamLabelsEntity entity = new TeamLabelsEntity();
|
||||
entity.setTeamId(key(teamId));
|
||||
entity.setLabelsJson(objectMapper.writeValueAsString(labels));
|
||||
entity.setUpdatedAt(Instant.now());
|
||||
entity.setUpdatedBy(updatedBy);
|
||||
teamRepository.save(entity);
|
||||
return labels;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean deleteByTeam(Long teamId) {
|
||||
long id = key(teamId);
|
||||
if (!teamRepository.existsById(id)) {
|
||||
return false;
|
||||
}
|
||||
teamRepository.deleteById(id);
|
||||
return true;
|
||||
}
|
||||
|
||||
private Optional<ClassificationLabels> parse(String json, String owner) {
|
||||
try {
|
||||
return Optional.of(objectMapper.readValue(json, ClassificationLabels.class));
|
||||
} catch (JacksonException e) {
|
||||
// A stored label set that no longer parses (corruption / manual DB edit) must not break
|
||||
// classification: drop it so the caller treats the team as having no labels (and skips
|
||||
// classification) rather than surfacing a 500 on every upload.
|
||||
log.warn("Discarding unparseable stored labels for {}: {}", owner, e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/** Map the nullable team id onto the entity's non-null key (sentinel for the unteamed case). */
|
||||
private static long key(Long teamId) {
|
||||
return teamId == null ? TeamLabelsEntity.NO_TEAM : teamId;
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package stirling.software.proprietary.classification.store;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.Instant;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* JPA row for a team's classification labels — one row per team. The label set lives as JSON in
|
||||
* {@code labelsJson} (authoritative on read). {@code teamId} is the natural key; the sentinel
|
||||
* {@link #NO_TEAM} stands in for the unteamed (login-disabled / self-hosted single-team) case,
|
||||
* since a primary key can't be null (policies store a nullable {@code team_id}, but this table is
|
||||
* keyed one-per-team). Kept decoupled from the security entities — {@code teamId} is a plain value,
|
||||
* not a foreign key — so classification can be enabled or disabled without touching them.
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "classification_labels")
|
||||
@NoArgsConstructor
|
||||
@Getter
|
||||
@Setter
|
||||
public class TeamLabelsEntity implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** Sentinel key for the unteamed label set (login disabled / no resolvable team). */
|
||||
public static final long NO_TEAM = 0L;
|
||||
|
||||
@Id
|
||||
@Column(name = "team_id")
|
||||
private long teamId;
|
||||
|
||||
@Column(name = "labels_json", columnDefinition = "text")
|
||||
private String labelsJson;
|
||||
|
||||
@Column(name = "updated_at")
|
||||
private Instant updatedAt;
|
||||
|
||||
@Column(name = "updated_by")
|
||||
private String updatedBy;
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package stirling.software.proprietary.classification.store;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface TeamLabelsRepository extends JpaRepository<TeamLabelsEntity, Long> {}
|
||||
+32
-14
@@ -31,9 +31,10 @@ import stirling.software.common.service.PdfMetadataService;
|
||||
import stirling.software.common.service.UserServiceInterface;
|
||||
import stirling.software.common.util.TempFileManager;
|
||||
import stirling.software.common.util.WebResponseUtils;
|
||||
import stirling.software.proprietary.classification.ClassificationLabelProvider;
|
||||
import stirling.software.proprietary.classification.model.ClassificationLabel;
|
||||
import stirling.software.proprietary.classification.store.ClassificationLabelStore;
|
||||
import stirling.software.proprietary.model.api.ai.AiPageText;
|
||||
import stirling.software.proprietary.policy.config.PolicyManagementAuthority;
|
||||
import stirling.software.proprietary.service.AiEngineClient;
|
||||
import stirling.software.proprietary.service.PdfContentExtractor;
|
||||
|
||||
@@ -45,7 +46,7 @@ import tools.jackson.databind.node.ObjectNode;
|
||||
* Dispatchable tool that classifies a PDF and writes the result into its metadata.
|
||||
*
|
||||
* <p>Runs as a Classification-policy pipeline step: it reads a bounded page window, asks the AI
|
||||
* engine to classify the document against the built-in label set, and stores the engine's JSON
|
||||
* engine to classify the document against the caller's team label set, and stores the engine's JSON
|
||||
* answer — minus the transport-only {@code outcome} field — in the custom Info-dictionary key
|
||||
* {@link PdfMetadataService#CLASSIFICATION_KEY}. Returns the labelled PDF. Not intended for direct
|
||||
* client use.
|
||||
@@ -71,9 +72,13 @@ public class ClassifyLabelController {
|
||||
private final UserServiceInterface userService;
|
||||
|
||||
/**
|
||||
* The fixed, built-in vocabulary shared by everyone — see {@link ClassificationLabelProvider}.
|
||||
* Present only when the policy subsystem is enabled ({@code policies.enabled}); the store and
|
||||
* team authority are gated on it. Null otherwise, in which case there are no team labels to
|
||||
* classify against and the document is passed through unlabelled.
|
||||
*/
|
||||
private final ClassificationLabelProvider labelProvider;
|
||||
private final ClassificationLabelStore labelStore;
|
||||
|
||||
private final PolicyManagementAuthority policyManagementAuthority;
|
||||
|
||||
public ClassifyLabelController(
|
||||
CustomPDFDocumentFactory pdfDocumentFactory,
|
||||
@@ -82,16 +87,18 @@ public class ClassifyLabelController {
|
||||
PdfMetadataService pdfMetadataService,
|
||||
AiEngineClient aiEngineClient,
|
||||
ObjectMapper objectMapper,
|
||||
ClassificationLabelProvider labelProvider,
|
||||
@Autowired(required = false) UserServiceInterface userService) {
|
||||
@Autowired(required = false) UserServiceInterface userService,
|
||||
@Autowired(required = false) ClassificationLabelStore labelStore,
|
||||
@Autowired(required = false) PolicyManagementAuthority policyManagementAuthority) {
|
||||
this.pdfDocumentFactory = pdfDocumentFactory;
|
||||
this.tempFileManager = tempFileManager;
|
||||
this.pdfContentExtractor = pdfContentExtractor;
|
||||
this.pdfMetadataService = pdfMetadataService;
|
||||
this.aiEngineClient = aiEngineClient;
|
||||
this.objectMapper = objectMapper;
|
||||
this.labelProvider = labelProvider;
|
||||
this.userService = userService;
|
||||
this.labelStore = labelStore;
|
||||
this.policyManagementAuthority = policyManagementAuthority;
|
||||
}
|
||||
|
||||
@PostMapping(value = "/classify-and-label", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@@ -109,9 +116,9 @@ public class ClassifyLabelController {
|
||||
|
||||
List<EngineLabel> allowed = resolveAllowedLabels();
|
||||
if (allowed.isEmpty()) {
|
||||
// No vocabulary to classify against: pass the file through unlabelled rather than
|
||||
// ask the engine to classify against nothing.
|
||||
log.debug("[classify-and-label] {} has no labels; skipping", fileName);
|
||||
// No vocabulary to classify against (the team stored no labels): pass the file
|
||||
// through unlabelled rather than ask the engine to classify against nothing.
|
||||
log.debug("[classify-and-label] {} has no team labels; skipping", fileName);
|
||||
return WebResponseUtils.pdfDocToWebResponse(document, fileName, tempFileManager);
|
||||
}
|
||||
|
||||
@@ -168,13 +175,24 @@ public class ClassifyLabelController {
|
||||
}
|
||||
|
||||
/**
|
||||
* The built-in vocabulary as {@code {id, name}} pairs, de-duplicated by id. The engine shows
|
||||
* the model the names and returns the ids (icons are presentational and never sent). The engine
|
||||
* holds no default vocabulary of its own, so this bundled set is the only source.
|
||||
* The allowed labels for the caller's team as {@code {id, name}} pairs, de-duplicated by id.
|
||||
* The engine shows the model the names and returns the ids (icons are presentational and never
|
||||
* sent). Returns an empty list — the caller then skips classification — when the policy
|
||||
* subsystem is disabled (no store) or the team has no stored labels. The engine holds no
|
||||
* default vocabulary of its own, so a team's stored labels are the only source.
|
||||
*/
|
||||
private List<EngineLabel> resolveAllowedLabels() {
|
||||
if (labelStore == null) {
|
||||
return List.of();
|
||||
}
|
||||
Long teamId =
|
||||
policyManagementAuthority == null
|
||||
? null
|
||||
: policyManagementAuthority.currentUserTeamId();
|
||||
|
||||
Map<String, EngineLabel> byId = new LinkedHashMap<>();
|
||||
collectLabels(labelProvider.labels(), byId);
|
||||
labelStore.findByTeam(teamId).ifPresent(labels -> collectLabels(labels.labels(), byId));
|
||||
|
||||
return List.copyOf(byId.values());
|
||||
}
|
||||
|
||||
|
||||
+17
-38
@@ -8,14 +8,12 @@ import java.util.List;
|
||||
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import io.github.pixee.security.Filenames;
|
||||
import io.swagger.v3.oas.annotations.Hidden;
|
||||
@@ -26,24 +24,18 @@ import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.configuration.RuntimePathConfig;
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||
import stirling.software.common.util.ProcessExecutor;
|
||||
import stirling.software.common.util.TempFile;
|
||||
import stirling.software.common.util.TempFileManager;
|
||||
import stirling.software.common.util.WebResponseUtils;
|
||||
import stirling.software.proprietary.model.api.ai.create.AiDocument;
|
||||
import stirling.software.proprietary.service.AiDocumentHtmlRenderer;
|
||||
|
||||
import tools.jackson.core.JacksonException;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
/**
|
||||
* Dispatchable tool that converts an AI-generated document model to a PDF via WeasyPrint.
|
||||
* Dispatchable tool that converts an AI-generated HTML string to a PDF via WeasyPrint.
|
||||
*
|
||||
* <p>Called by {@link stirling.software.proprietary.service.AiWorkflowService} when the engine
|
||||
* emits a {@code CREATE_PDF_FROM_HTML_AGENT} plan step. The engine supplies the document as
|
||||
* structured fields; the HTML is built here from a fixed template.
|
||||
* emits a {@code CREATE_PDF_FROM_HTML_AGENT} plan step. The HTML comes from a trusted Jinja
|
||||
* template so sanitization is intentionally skipped.
|
||||
*/
|
||||
@Slf4j
|
||||
@Hidden
|
||||
@@ -56,9 +48,6 @@ public class CreatePdfAgentController {
|
||||
private final TempFileManager tempFileManager;
|
||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||
private final RuntimePathConfig runtimePathConfig;
|
||||
private final ApplicationProperties applicationProperties;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final AiDocumentHtmlRenderer htmlRenderer;
|
||||
|
||||
/**
|
||||
* Returns true only when WeasyPrint is definitively unavailable — either the binary could not
|
||||
@@ -85,42 +74,32 @@ public class CreatePdfAgentController {
|
||||
value = "/create-pdf-from-html-agent",
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@Operation(
|
||||
summary = "Convert an AI-generated document to a PDF",
|
||||
summary = "Convert AI-generated HTML to a PDF",
|
||||
description =
|
||||
"Accepts a structured document as a JSON parameter and returns a PDF. This"
|
||||
+ " endpoint is dispatched by the AI workflow orchestrator as a plan"
|
||||
+ " step; it is not intended for direct client use.")
|
||||
public ResponseEntity<Resource> createPdf(
|
||||
@RequestParam("document") String document, @RequestParam("filename") String filename)
|
||||
"Accepts an HTML document as a plain-text parameter and returns a PDF."
|
||||
+ " This endpoint is dispatched by the AI workflow orchestrator as a"
|
||||
+ " plan step; it is not intended for direct client use.")
|
||||
public ResponseEntity<Resource> createPdfFromHtml(
|
||||
@RequestParam("htmlContent") String htmlContent,
|
||||
@RequestParam("filename") String filename)
|
||||
throws Exception {
|
||||
|
||||
if (!applicationProperties.getAiEngine().isEnabled()) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
AiDocument model;
|
||||
try {
|
||||
model = objectMapper.readValue(document, AiDocument.class);
|
||||
} catch (JacksonException e) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
String html = htmlRenderer.render(model);
|
||||
|
||||
log.info(
|
||||
"[create-pdf-agent] converting document to PDF via WeasyPrint — html_bytes={}",
|
||||
html.length());
|
||||
"[create-pdf-agent] converting HTML to PDF via WeasyPrint — html_bytes={}",
|
||||
htmlContent.length());
|
||||
|
||||
try (TempFile htmlFile = tempFileManager.createManagedTempFile(".html");
|
||||
TempFile pdfFile = tempFileManager.createManagedTempFile(".pdf")) {
|
||||
|
||||
Files.writeString(htmlFile.getPath(), html, StandardCharsets.UTF_8);
|
||||
Files.writeString(htmlFile.getPath(), htmlContent, StandardCharsets.UTF_8);
|
||||
|
||||
List<String> command = new ArrayList<>();
|
||||
command.add(runtimePathConfig.getWeasyPrintPath());
|
||||
command.add("-e");
|
||||
command.add("utf-8");
|
||||
command.add("-v");
|
||||
// SSRF: the HTML is self-contained and the engine validates style colours, so no
|
||||
// external url() reaches WeasyPrint. For full isolation, run it network-isolated.
|
||||
command.add(htmlFile.getAbsolutePath());
|
||||
command.add(pdfFile.getAbsolutePath());
|
||||
|
||||
@@ -147,8 +126,8 @@ public class CreatePdfAgentController {
|
||||
// avoids materialising the whole document as a byte[] twice (read-all + re-serialise),
|
||||
// which matters for large generated documents.
|
||||
TempFile tempOut = tempFileManager.createManagedTempFile(".pdf");
|
||||
try (PDDocument pdDocument = pdfDocumentFactory.load(pdfFile.getPath())) {
|
||||
pdDocument.save(tempOut.getPath().toFile());
|
||||
try (PDDocument document = pdfDocumentFactory.load(pdfFile.getPath())) {
|
||||
document.save(tempOut.getPath().toFile());
|
||||
} catch (Exception e) {
|
||||
tempOut.close();
|
||||
throw e;
|
||||
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
package stirling.software.proprietary.model.api.ai.create;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class AiDocument {
|
||||
|
||||
private String title;
|
||||
private String subtitle;
|
||||
private String referenceNumber;
|
||||
private Style style;
|
||||
private List<Section> sections;
|
||||
|
||||
@Data
|
||||
public static class Style {
|
||||
private String primaryColor;
|
||||
private String backgroundColor;
|
||||
private String bodyTextColor;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Section {
|
||||
private String type;
|
||||
private String heading;
|
||||
private String body;
|
||||
private List<List<String>> pairs;
|
||||
private List<String> columns;
|
||||
private List<List<String>> rows;
|
||||
private List<String> totalRow;
|
||||
private List<String> items;
|
||||
private List<String> signatories;
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -37,7 +37,8 @@ import stirling.software.common.model.exception.UnsupportedProviderException;
|
||||
"stirling.software.proprietary.policy.ledger",
|
||||
"stirling.software.proprietary.accountlink",
|
||||
"stirling.software.proprietary.access.repository",
|
||||
"stirling.software.proprietary.integration.repository"
|
||||
"stirling.software.proprietary.integration.repository",
|
||||
"stirling.software.proprietary.classification.store"
|
||||
})
|
||||
@EntityScan({
|
||||
"stirling.software.proprietary.security.model",
|
||||
@@ -49,7 +50,8 @@ import stirling.software.common.model.exception.UnsupportedProviderException;
|
||||
"stirling.software.proprietary.policy.ledger",
|
||||
"stirling.software.proprietary.accountlink",
|
||||
"stirling.software.proprietary.access.model",
|
||||
"stirling.software.proprietary.integration.model"
|
||||
"stirling.software.proprietary.integration.model",
|
||||
"stirling.software.proprietary.classification.store"
|
||||
})
|
||||
public class DatabaseConfig {
|
||||
|
||||
|
||||
-135
@@ -1,135 +0,0 @@
|
||||
package stirling.software.proprietary.service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.hubspot.jinjava.Jinjava;
|
||||
import com.hubspot.jinjava.JinjavaConfig;
|
||||
|
||||
import stirling.software.proprietary.model.api.ai.create.AiDocument;
|
||||
|
||||
/** Renders an {@link AiDocument} to HTML using a Jinja template loaded from the classpath. */
|
||||
@Component
|
||||
public class AiDocumentHtmlRenderer {
|
||||
|
||||
private static final String TEMPLATE_PATH = "templates/ai/create/document.html.jinja2";
|
||||
|
||||
private static final Pattern SAFE_COLOR = Pattern.compile("^#[0-9a-fA-F]{6}$");
|
||||
|
||||
private final Jinjava jinjava;
|
||||
private final String template;
|
||||
|
||||
public AiDocumentHtmlRenderer() {
|
||||
JinjavaConfig config =
|
||||
JinjavaConfig.newBuilder().withNestedInterpretationEnabled(false).build();
|
||||
this.jinjava = new Jinjava(config);
|
||||
this.template = loadTemplate();
|
||||
}
|
||||
|
||||
public String render(AiDocument doc) {
|
||||
return jinjava.render(template, buildContext(doc));
|
||||
}
|
||||
|
||||
private static Map<String, Object> buildContext(AiDocument doc) {
|
||||
Map<String, Object> context = new LinkedHashMap<>();
|
||||
context.put("title", doc.getTitle());
|
||||
context.put("subtitle", doc.getSubtitle());
|
||||
context.put("reference_number", doc.getReferenceNumber());
|
||||
|
||||
AiDocument.Style style = doc.getStyle();
|
||||
if (style != null) {
|
||||
context.put("style_primary", safeColor(style.getPrimaryColor()));
|
||||
context.put("style_background", safeColor(style.getBackgroundColor()));
|
||||
context.put("style_body", safeColor(style.getBodyTextColor()));
|
||||
}
|
||||
|
||||
List<Map<String, Object>> sections = new ArrayList<>();
|
||||
if (doc.getSections() != null) {
|
||||
for (AiDocument.Section section : doc.getSections()) {
|
||||
if (section != null && section.getType() != null) {
|
||||
sections.add(buildSection(section));
|
||||
}
|
||||
}
|
||||
}
|
||||
context.put("sections", sections);
|
||||
return context;
|
||||
}
|
||||
|
||||
private static Map<String, Object> buildSection(AiDocument.Section section) {
|
||||
Map<String, Object> node = new LinkedHashMap<>();
|
||||
node.put("type", section.getType());
|
||||
node.put("heading", section.getHeading());
|
||||
switch (section.getType()) {
|
||||
case "text" -> node.put("paragraphs", paragraphs(section.getBody()));
|
||||
case "key_value" -> node.put("pairs", pairs(section.getPairs()));
|
||||
case "line_items" -> {
|
||||
node.put("columns", orEmpty(section.getColumns()));
|
||||
node.put("rows", orEmptyRows(section.getRows()));
|
||||
node.put("total_row", emptyToNull(section.getTotalRow()));
|
||||
}
|
||||
case "bullet_list" -> node.put("items", orEmpty(section.getItems()));
|
||||
case "signature" -> node.put("signatories", orEmpty(section.getSignatories()));
|
||||
default -> {}
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private static List<String> paragraphs(String body) {
|
||||
String text = body == null ? "" : body;
|
||||
List<String> out = new ArrayList<>();
|
||||
for (String paragraph : text.split("\n\n")) {
|
||||
out.add(paragraph.replace("\n", " "));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static List<Map<String, String>> pairs(List<List<String>> pairs) {
|
||||
List<Map<String, String>> out = new ArrayList<>();
|
||||
if (pairs != null) {
|
||||
for (List<String> pair : pairs) {
|
||||
Map<String, String> node = new LinkedHashMap<>();
|
||||
node.put("label", pair.isEmpty() ? "" : pair.get(0));
|
||||
node.put("value", pair.size() < 2 ? "" : pair.get(1));
|
||||
out.add(node);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static List<String> orEmpty(List<String> values) {
|
||||
return values == null ? List.of() : values;
|
||||
}
|
||||
|
||||
private static List<List<String>> orEmptyRows(List<List<String>> rows) {
|
||||
return rows == null ? List.of() : rows;
|
||||
}
|
||||
|
||||
private static List<String> emptyToNull(List<String> values) {
|
||||
return values == null || values.isEmpty() ? null : values;
|
||||
}
|
||||
|
||||
private static String safeColor(String value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
String trimmed = value.trim();
|
||||
return SAFE_COLOR.matcher(trimmed).matches() ? trimmed : null;
|
||||
}
|
||||
|
||||
private static String loadTemplate() {
|
||||
try {
|
||||
return new ClassPathResource(TEMPLATE_PATH).getContentAsString(StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+133
@@ -0,0 +1,133 @@
|
||||
package stirling.software.proprietary.classification;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.service.UserServiceInterface;
|
||||
import stirling.software.proprietary.classification.model.ClassificationLabel;
|
||||
import stirling.software.proprietary.classification.model.ClassificationLabels;
|
||||
import stirling.software.proprietary.classification.store.ClassificationLabelStore;
|
||||
import stirling.software.proprietary.classification.store.InProcessClassificationLabelStore;
|
||||
import stirling.software.proprietary.policy.config.PolicyManagementAuthority;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@DisplayName("ClassificationLabelsController")
|
||||
class ClassificationLabelsControllerTest {
|
||||
|
||||
private static final Long TEAM = 7L;
|
||||
|
||||
@Mock private PolicyManagementAuthority policyManagementAuthority;
|
||||
@Mock private UserServiceInterface userService;
|
||||
|
||||
private ClassificationLabelStore store;
|
||||
private ApplicationProperties applicationProperties;
|
||||
private ClassificationLabelsController controller;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
store = new InProcessClassificationLabelStore();
|
||||
applicationProperties = new ApplicationProperties();
|
||||
controller =
|
||||
new ClassificationLabelsController(
|
||||
store, policyManagementAuthority, applicationProperties, userService);
|
||||
}
|
||||
|
||||
private static ClassificationLabels sample() {
|
||||
return new ClassificationLabels(
|
||||
List.of(
|
||||
new ClassificationLabel("invoice", "Invoice", "receipt-long"),
|
||||
new ClassificationLabel("contract", "Contract", null)));
|
||||
}
|
||||
|
||||
private void loginEnabled(boolean enabled) {
|
||||
applicationProperties.getSecurity().setEnableLogin(enabled);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("GET returns 204 when the team has no labels")
|
||||
void getEmpty() {
|
||||
when(policyManagementAuthority.currentUserTeamId()).thenReturn(TEAM);
|
||||
ResponseEntity<ClassificationLabels> response = controller.getTeamLabels();
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("PUT then GET round-trips the team's labels (login disabled)")
|
||||
void saveThenGet() {
|
||||
loginEnabled(false);
|
||||
when(policyManagementAuthority.currentUserTeamId()).thenReturn(TEAM);
|
||||
|
||||
controller.saveTeamLabels(sample());
|
||||
ResponseEntity<ClassificationLabels> got = controller.getTeamLabels();
|
||||
|
||||
assertThat(got.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(got.getBody()).isNotNull();
|
||||
assertThat(got.getBody().labels()).hasSize(2);
|
||||
assertThat(got.getBody().labels().getFirst().name()).isEqualTo("Invoice");
|
||||
assertThat(got.getBody().labels().getFirst().icon()).isEqualTo("receipt-long");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("PUT is scoped per team")
|
||||
void perTeam() {
|
||||
loginEnabled(false);
|
||||
when(policyManagementAuthority.currentUserTeamId()).thenReturn(TEAM);
|
||||
controller.saveTeamLabels(sample());
|
||||
|
||||
when(policyManagementAuthority.currentUserTeamId()).thenReturn(99L);
|
||||
assertThat(controller.getTeamLabels().getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("PUT is rejected for a non-editor when login is enabled")
|
||||
void putForbiddenForNonEditor() {
|
||||
loginEnabled(true);
|
||||
when(policyManagementAuthority.canEditPolicies()).thenReturn(false);
|
||||
|
||||
assertThatThrownBy(() -> controller.saveTeamLabels(sample()))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.hasFieldOrPropertyWithValue("statusCode", HttpStatus.FORBIDDEN);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("PUT rejects an invalid label set with 400")
|
||||
void putInvalid() {
|
||||
loginEnabled(false);
|
||||
ClassificationLabels duplicate =
|
||||
new ClassificationLabels(
|
||||
List.of(
|
||||
new ClassificationLabel("invoice", "Invoice", null),
|
||||
new ClassificationLabel("invoice", "Invoice", null)));
|
||||
|
||||
assertThatThrownBy(() -> controller.saveTeamLabels(duplicate))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.hasFieldOrPropertyWithValue("statusCode", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("DELETE resets the team back to no stored labels")
|
||||
void deleteResets() {
|
||||
loginEnabled(false);
|
||||
when(policyManagementAuthority.currentUserTeamId()).thenReturn(TEAM);
|
||||
controller.saveTeamLabels(sample());
|
||||
|
||||
ResponseEntity<Void> response = controller.resetTeamLabels();
|
||||
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
|
||||
assertThat(controller.getTeamLabels().getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
package stirling.software.proprietary.classification.model;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@DisplayName("LabelsValidator")
|
||||
class LabelsValidatorTest {
|
||||
|
||||
private static ClassificationLabels labels(ClassificationLabel... labels) {
|
||||
return new ClassificationLabels(List.of(labels));
|
||||
}
|
||||
|
||||
private static ClassificationLabel label(String name) {
|
||||
return new ClassificationLabel(slug(name), name, null);
|
||||
}
|
||||
|
||||
private static String slug(String name) {
|
||||
return name.trim()
|
||||
.toLowerCase(Locale.ROOT)
|
||||
.replaceAll("[^a-z0-9]+", "-")
|
||||
.replaceAll("(^-|-$)", "");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("accepts a well-formed label set")
|
||||
void acceptsValid() {
|
||||
ClassificationLabels set =
|
||||
labels(
|
||||
new ClassificationLabel("invoice", "Invoice", "receipt-long"),
|
||||
label("Contract"));
|
||||
assertThatCode(() -> LabelsValidator.validate(set)).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("accepts an empty label set (reads as: use the default)")
|
||||
void acceptsEmpty() {
|
||||
assertThatCode(() -> LabelsValidator.validate(labels())).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("rejects a null label set")
|
||||
void rejectsNull() {
|
||||
assertThatThrownBy(() -> LabelsValidator.validate(null))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("Labels are required");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("rejects duplicate names (distinct ids)")
|
||||
void rejectsDuplicateNames() {
|
||||
ClassificationLabels set =
|
||||
labels(
|
||||
new ClassificationLabel("invoice-a", "Invoice", null),
|
||||
new ClassificationLabel("invoice-b", "Invoice", null));
|
||||
assertThatThrownBy(() -> LabelsValidator.validate(set))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("Duplicate label name");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("rejects duplicate names differing only by case")
|
||||
void rejectsDuplicateNamesCaseInsensitive() {
|
||||
ClassificationLabels set =
|
||||
labels(
|
||||
new ClassificationLabel("invoice-a", "Invoice", null),
|
||||
new ClassificationLabel("invoice-b", "INVOICE", null));
|
||||
assertThatThrownBy(() -> LabelsValidator.validate(set))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("Duplicate label name");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("rejects duplicate ids")
|
||||
void rejectsDuplicateIds() {
|
||||
ClassificationLabels set =
|
||||
labels(
|
||||
new ClassificationLabel("invoice", "Invoice", null),
|
||||
new ClassificationLabel("invoice", "Sales invoice", null));
|
||||
assertThatThrownBy(() -> LabelsValidator.validate(set))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("Duplicate label id");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("rejects a blank name")
|
||||
void rejectsBlankName() {
|
||||
ClassificationLabels set = labels(new ClassificationLabel("blank", " ", null));
|
||||
assertThatThrownBy(() -> LabelsValidator.validate(set))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("Label name must not be blank");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("rejects a blank id")
|
||||
void rejectsBlankId() {
|
||||
ClassificationLabels set = labels(new ClassificationLabel(" ", "Invoice", null));
|
||||
assertThatThrownBy(() -> LabelsValidator.validate(set))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("Label id must not be blank");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("rejects an over-long name")
|
||||
void rejectsOverLongName() {
|
||||
ClassificationLabels set =
|
||||
labels(
|
||||
new ClassificationLabel(
|
||||
"x", "x".repeat(LabelsValidator.MAX_TEXT_LENGTH + 1), null));
|
||||
assertThatThrownBy(() -> LabelsValidator.validate(set))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("too long");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("rejects an over-long icon (a null icon is fine)")
|
||||
void rejectsOverLongIcon() {
|
||||
ClassificationLabels set =
|
||||
labels(
|
||||
new ClassificationLabel(
|
||||
"invoice",
|
||||
"Invoice",
|
||||
"x".repeat(LabelsValidator.MAX_TEXT_LENGTH + 1)));
|
||||
assertThatThrownBy(() -> LabelsValidator.validate(set))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("icon is too long");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("rejects more labels than the cap")
|
||||
void rejectsTooManyLabels() {
|
||||
List<ClassificationLabel> tooMany =
|
||||
IntStream.rangeClosed(0, LabelsValidator.MAX_LABELS)
|
||||
.mapToObj(i -> label("label" + i))
|
||||
.toList();
|
||||
assertThatThrownBy(() -> LabelsValidator.validate(new ClassificationLabels(tooMany)))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("Too many labels");
|
||||
}
|
||||
}
|
||||
+34
-15
@@ -14,6 +14,7 @@ import static org.mockito.Mockito.when;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
@@ -26,8 +27,10 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||
import stirling.software.common.service.PdfMetadataService;
|
||||
import stirling.software.common.util.TempFileManager;
|
||||
import stirling.software.proprietary.classification.ClassificationLabelProvider;
|
||||
import stirling.software.proprietary.classification.model.ClassificationLabel;
|
||||
import stirling.software.proprietary.classification.model.ClassificationLabels;
|
||||
import stirling.software.proprietary.classification.store.InProcessClassificationLabelStore;
|
||||
import stirling.software.proprietary.policy.config.PolicyManagementAuthority;
|
||||
import stirling.software.proprietary.service.AiEngineClient;
|
||||
import stirling.software.proprietary.service.PdfContentExtractor;
|
||||
|
||||
@@ -39,16 +42,22 @@ import tools.jackson.databind.json.JsonMapper;
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class ClassifyLabelControllerTest {
|
||||
|
||||
private static final Long TEAM = 7L;
|
||||
|
||||
@Mock private CustomPDFDocumentFactory pdfDocumentFactory;
|
||||
@Mock private TempFileManager tempFileManager;
|
||||
@Mock private PdfContentExtractor pdfContentExtractor;
|
||||
@Mock private PdfMetadataService pdfMetadataService;
|
||||
@Mock private AiEngineClient aiEngineClient;
|
||||
@Mock private PolicyManagementAuthority policyManagementAuthority;
|
||||
|
||||
private final ObjectMapper objectMapper = JsonMapper.builder().build();
|
||||
private InProcessClassificationLabelStore labelStore;
|
||||
private ClassifyLabelController controller;
|
||||
|
||||
private void withLabels(List<ClassificationLabel> labels) {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
labelStore = new InProcessClassificationLabelStore();
|
||||
controller =
|
||||
new ClassifyLabelController(
|
||||
pdfDocumentFactory,
|
||||
@@ -57,8 +66,9 @@ class ClassifyLabelControllerTest {
|
||||
pdfMetadataService,
|
||||
aiEngineClient,
|
||||
objectMapper,
|
||||
ClassificationLabelProvider.withLabels(labels),
|
||||
null);
|
||||
null,
|
||||
labelStore,
|
||||
policyManagementAuthority);
|
||||
}
|
||||
|
||||
private void stubSinglePageDocument() throws Exception {
|
||||
@@ -88,7 +98,12 @@ class ClassifyLabelControllerTest {
|
||||
|
||||
@Test
|
||||
void classifyAndLabel_writesClassificationWithoutOutcome() throws Exception {
|
||||
withLabels(List.of(new ClassificationLabel("invoice", "Invoice", null)));
|
||||
when(policyManagementAuthority.currentUserTeamId()).thenReturn(TEAM);
|
||||
labelStore.save(
|
||||
TEAM,
|
||||
new ClassificationLabels(
|
||||
List.of(new ClassificationLabel("invoice", "Invoice", null))),
|
||||
"admin");
|
||||
|
||||
stubSinglePageDocument();
|
||||
|
||||
@@ -103,12 +118,16 @@ class ClassifyLabelControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void classifyAndLabel_sendsLabelIdsAndNames() throws Exception {
|
||||
withLabels(
|
||||
List.of(
|
||||
new ClassificationLabel("invoice", "Invoice", "receipt-long"),
|
||||
new ClassificationLabel("contract", "Contract", null),
|
||||
new ClassificationLabel("timesheet", "Timesheet", null)));
|
||||
void classifyAndLabel_sendsTeamLabelIdsAndNames() throws Exception {
|
||||
when(policyManagementAuthority.currentUserTeamId()).thenReturn(TEAM);
|
||||
labelStore.save(
|
||||
TEAM,
|
||||
new ClassificationLabels(
|
||||
List.of(
|
||||
new ClassificationLabel("invoice", "Invoice", "receipt-long"),
|
||||
new ClassificationLabel("contract", "Contract", null),
|
||||
new ClassificationLabel("timesheet", "Timesheet", null))),
|
||||
"admin");
|
||||
|
||||
stubSinglePageDocument();
|
||||
|
||||
@@ -133,13 +152,13 @@ class ClassifyLabelControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void classifyAndLabel_skipsClassificationWhenNoLabels() throws Exception {
|
||||
withLabels(List.of());
|
||||
void classifyAndLabel_skipsClassificationWhenNothingStored() throws Exception {
|
||||
when(policyManagementAuthority.currentUserTeamId()).thenReturn(TEAM);
|
||||
|
||||
stubSinglePageDocument();
|
||||
|
||||
// No vocabulary, and the engine holds no default of its own, so the file is passed through
|
||||
// unlabelled: neither the engine nor the metadata write is invoked.
|
||||
// No team labels stored, and the engine holds no default of its own, so the file is passed
|
||||
// through unlabelled: neither the engine nor the metadata write is invoked.
|
||||
verify(aiEngineClient, never()).post(anyString(), anyString(), any());
|
||||
verify(pdfMetadataService, never())
|
||||
.setClassificationMetadata(any(PDDocument.class), anyString());
|
||||
|
||||
+2
-2
@@ -166,8 +166,8 @@ class PolicyExecutorTest {
|
||||
new PipelineStep(
|
||||
createPdf,
|
||||
Map.of(
|
||||
"document",
|
||||
"{\"title\":\"PO\",\"sections\":[]}",
|
||||
"htmlContent",
|
||||
"<p>hi</p>",
|
||||
"filename",
|
||||
"purchase-order.pdf"))),
|
||||
PolicyInputs.of(List.of()),
|
||||
|
||||
-139
@@ -1,139 +0,0 @@
|
||||
package stirling.software.proprietary.service;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import stirling.software.proprietary.model.api.ai.create.AiDocument;
|
||||
|
||||
class AiDocumentHtmlRendererTest {
|
||||
|
||||
private final AiDocumentHtmlRenderer renderer = new AiDocumentHtmlRenderer();
|
||||
|
||||
private static AiDocument.Section section(String type) {
|
||||
AiDocument.Section s = new AiDocument.Section();
|
||||
s.setType(type);
|
||||
return s;
|
||||
}
|
||||
|
||||
private static AiDocument document(String title, List<AiDocument.Section> sections) {
|
||||
AiDocument doc = new AiDocument();
|
||||
doc.setTitle(title);
|
||||
doc.setSections(sections);
|
||||
return doc;
|
||||
}
|
||||
|
||||
@Test
|
||||
void rendersAllSectionTypes() {
|
||||
AiDocument.Section text = section("text");
|
||||
text.setBody("Some prose text.");
|
||||
AiDocument.Section kv = section("key_value");
|
||||
kv.setPairs(List.of(List.of("Key", "Value")));
|
||||
AiDocument.Section items = section("line_items");
|
||||
items.setColumns(List.of("A", "B"));
|
||||
items.setRows(List.of(List.of("1", "2")));
|
||||
AiDocument.Section bullets = section("bullet_list");
|
||||
bullets.setItems(List.of("item one"));
|
||||
AiDocument.Section sign = section("signature");
|
||||
sign.setSignatories(List.of("Alice"));
|
||||
|
||||
String html = renderer.render(document("All", List.of(text, kv, items, bullets, sign)));
|
||||
|
||||
assertTrue(html.contains("<!DOCTYPE html>"));
|
||||
assertTrue(html.contains("Some prose text."));
|
||||
assertTrue(html.contains("Key") && html.contains("Value"));
|
||||
assertTrue(html.contains("<th>"));
|
||||
assertTrue(html.contains("item one"));
|
||||
assertTrue(html.contains("Alice"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rendersMarkupCharactersAsText() {
|
||||
AiDocument.Section text = section("text");
|
||||
text.setBody("a <b>x</b> & y");
|
||||
|
||||
String html = renderer.render(document("Doc", List.of(text)));
|
||||
|
||||
assertFalse(html.contains("<b>"));
|
||||
assertTrue(html.contains("<b>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void totalRowRenderedWhenPresent() {
|
||||
AiDocument.Section items = section("line_items");
|
||||
items.setColumns(List.of("Item", "Total"));
|
||||
items.setRows(List.of(List.of("Widget", "$10")));
|
||||
items.setTotalRow(List.of("Total", "$10"));
|
||||
|
||||
assertTrue(
|
||||
renderer.render(document("Table", List.of(items)))
|
||||
.contains("<tr class=\"total-row\">"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void totalRowAbsentWhenNotProvided() {
|
||||
AiDocument.Section items = section("line_items");
|
||||
items.setColumns(List.of("Item"));
|
||||
items.setRows(List.of(List.of("Widget")));
|
||||
|
||||
assertFalse(
|
||||
renderer.render(document("Table", List.of(items)))
|
||||
.contains("<tr class=\"total-row\">"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rendersSubtitleAndReference() {
|
||||
AiDocument doc = document("My Doc", List.of());
|
||||
doc.setSubtitle("Subtitle Here");
|
||||
doc.setReferenceNumber("REF-42");
|
||||
|
||||
String html = renderer.render(doc);
|
||||
|
||||
assertTrue(html.contains("Subtitle Here"));
|
||||
assertTrue(html.contains("REF-42"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void appliesHexColourOverride() {
|
||||
AiDocument doc = document("Styled", List.of());
|
||||
AiDocument.Style style = new AiDocument.Style();
|
||||
style.setPrimaryColor("#ff00ff");
|
||||
style.setBackgroundColor("#111111");
|
||||
doc.setStyle(style);
|
||||
|
||||
String html = renderer.render(doc);
|
||||
|
||||
assertTrue(html.contains("--color-primary: #ff00ff"));
|
||||
assertTrue(html.contains("--color-bg: #111111"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ignoresColourWithDisallowedCharacters() {
|
||||
AiDocument doc = document("Styled", List.of());
|
||||
AiDocument.Style style = new AiDocument.Style();
|
||||
style.setPrimaryColor("rgb(255, 0, 0)");
|
||||
doc.setStyle(style);
|
||||
|
||||
String html = renderer.render(doc);
|
||||
|
||||
assertFalse(html.contains("rgb("));
|
||||
assertTrue(html.contains("<!DOCTYPE html>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ignoresNonHexColour() {
|
||||
AiDocument doc = document("Styled", List.of());
|
||||
AiDocument.Style style = new AiDocument.Style();
|
||||
style.setPrimaryColor("magenta");
|
||||
style.setBackgroundColor("#fff");
|
||||
doc.setStyle(style);
|
||||
|
||||
String html = renderer.render(doc);
|
||||
|
||||
assertFalse(html.contains("--color-primary: magenta"));
|
||||
assertFalse(html.contains("--color-bg: #fff;"));
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
-- Classification labels are now a fixed, built-in set bundled with the app and sent to the engine
|
||||
-- per request (see ClassificationLabelProvider); the per-team classification_labels table (created
|
||||
-- in V30) is no longer read or written. Drop it.
|
||||
--
|
||||
-- Forward migration: V30 is kept so any DB that already applied it still validates. This runs after
|
||||
-- V30 in every case, so it drops the table whether V30 just created it (fresh DB) or it was created
|
||||
-- and populated on an earlier deploy. IF EXISTS only guards the edge case where the table is already
|
||||
-- absent, keeping the migration safe to apply regardless of prior state.
|
||||
|
||||
DROP TABLE IF EXISTS classification_labels;
|
||||
@@ -36,8 +36,6 @@ ext {
|
||||
okhttpBomVersion = "5.3.2"
|
||||
gsonVersion = "2.14.0"
|
||||
guavaVersion = "33.6.0-jre"
|
||||
jinjavaVersion = "2.8.3"
|
||||
jackson2Version = "2.21.2"
|
||||
bucket4jVersion = "8.19.0"
|
||||
archunitVersion = "1.4.2"
|
||||
batikVersion = "1.19"
|
||||
@@ -224,13 +222,6 @@ subprojects {
|
||||
resolutionStrategy.force "org.apache.commons:commons-lang3:${commonsLang3}"
|
||||
// CVE-2024-47554: commons-io DoS prevention
|
||||
resolutionStrategy.force "commons-io:commons-io:${commonsIoVersion}"
|
||||
// Jackson 2 is transitive-only here (jinjava, opensaml, jjwt request older versions);
|
||||
// pin the family to a current release and keep modules aligned.
|
||||
resolutionStrategy.force "com.fasterxml.jackson.core:jackson-core:${jackson2Version}"
|
||||
resolutionStrategy.force "com.fasterxml.jackson.core:jackson-databind:${jackson2Version}"
|
||||
resolutionStrategy.force "com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:${jackson2Version}"
|
||||
resolutionStrategy.force "com.fasterxml.jackson.datatype:jackson-datatype-jdk8:${jackson2Version}"
|
||||
resolutionStrategy.force "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:${jackson2Version}"
|
||||
// Keep BouncyCastle modules aligned to avoid runtime linkage errors
|
||||
resolutionStrategy.force "org.bouncycastle:bcprov-jdk18on:${bouncycastleVersion}"
|
||||
resolutionStrategy.force "org.bouncycastle:bcpkix-jdk18on:${bouncycastleVersion}"
|
||||
|
||||
@@ -5,6 +5,7 @@ description = "AI Document Engine"
|
||||
requires-python = ">=3.13"
|
||||
dependencies = [
|
||||
"fastapi>=0.116.0",
|
||||
"jinja2>=3.1.0",
|
||||
"pgvector>=0.3.6",
|
||||
"psycopg[binary,pool]>=3.2",
|
||||
"pydantic>=2.0.0",
|
||||
|
||||
@@ -116,8 +116,8 @@ class DocumentClassifierAgent:
|
||||
)
|
||||
|
||||
async def classify(self, request: ClassifyDocumentRequest) -> ClassifyDocumentResponse:
|
||||
# The caller (the backend) always supplies the allowed vocabulary — its
|
||||
# fixed built-in label set — so the engine holds no vocabulary of its own.
|
||||
# The caller (the backend) always supplies the allowed vocabulary — the
|
||||
# team's stored labels — so the engine holds no vocabulary of its own.
|
||||
allowed = request.labels
|
||||
window = select_window(request.pages)
|
||||
prompt = self._build_prompt(request.file_name, allowed, window)
|
||||
|
||||
@@ -10,7 +10,7 @@ Flow:
|
||||
4. SectionWriterAgents (smart_model) run in parallel via asyncio.gather.
|
||||
Each returns a WrittenSections with fully populated DocumentSection objects.
|
||||
5. The assembler collects sections in plan order → GeneratedDocument.
|
||||
6. The assembled document is emitted as structured fields. The LLM never writes HTML.
|
||||
6. Jinja renders the document to HTML. The LLM never writes HTML.
|
||||
|
||||
The planner is split into two calls (meta then sections) so each LLM output schema
|
||||
stays small enough for grammar compilation on all model tiers including Haiku.
|
||||
@@ -22,7 +22,9 @@ import asyncio
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
from pydantic_ai import Agent
|
||||
from pydantic_ai.output import NativeOutput
|
||||
|
||||
@@ -49,6 +51,8 @@ from stirling.services import AppRuntime
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_TEMPLATES_DIR = Path(__file__).parent / "templates"
|
||||
|
||||
# ── Token budget ──────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
# Conservative per-section token estimates mapped from planner-assigned depth.
|
||||
@@ -162,13 +166,10 @@ Analyse the user's request and produce a DocumentMeta with:
|
||||
document, if the user provides one. Leave empty if the user provides no such context.
|
||||
|
||||
- style_primary_color: accent and heading colour. Set ONLY when the user explicitly names a
|
||||
colour or colour scheme (e.g. "make it red", "use navy blue"). Express it as a 6-digit hex
|
||||
code in #RRGGBB format (map any named colour to its hex value yourself, e.g. "navy" →
|
||||
"#000080"). No other format is accepted. Leave null if no colour is stated.
|
||||
- style_background_color: page background colour, same #RRGGBB format. Set only if explicitly
|
||||
requested.
|
||||
- style_body_text_color: body text colour, same #RRGGBB format. Set only if explicitly
|
||||
requested.
|
||||
colour or colour scheme (e.g. "make it red", "use navy blue"). Use CSS named colours
|
||||
(e.g. "magenta", "navy", "crimson") or hex values. Leave null if no colour is stated.
|
||||
- style_background_color: page background colour. Set only if explicitly requested.
|
||||
- style_body_text_color: body text colour. Set only if explicitly requested.
|
||||
|
||||
- cannot_do_reason: set this ONLY when the request is not asking to create a document at all
|
||||
(e.g. a question, a greeting, an edit request to an existing document). Never set it
|
||||
@@ -298,6 +299,15 @@ def _build_writer_prompt(plan: DocumentPlan, chunk: _Chunk) -> str:
|
||||
# ── Helpers ───────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _build_jinja_env() -> Environment:
|
||||
return Environment(
|
||||
loader=FileSystemLoader(str(_TEMPLATES_DIR)),
|
||||
autoescape=True,
|
||||
trim_blocks=True,
|
||||
lstrip_blocks=True,
|
||||
)
|
||||
|
||||
|
||||
def _safe_filename(title: str) -> str:
|
||||
slug = re.sub(r"[^\w\s-]", "", title.lower())
|
||||
slug = re.sub(r"[\s_-]+", "-", slug).strip("-")
|
||||
@@ -310,6 +320,7 @@ def _safe_filename(title: str) -> str:
|
||||
class PdfCreateAgent:
|
||||
def __init__(self, runtime: AppRuntime) -> None:
|
||||
self.runtime = runtime
|
||||
self._jinja_env = _build_jinja_env()
|
||||
|
||||
self._meta_planner: Agent[None, DocumentMeta] = Agent(
|
||||
model=runtime.smart_model,
|
||||
@@ -390,12 +401,14 @@ class PdfCreateAgent:
|
||||
sections=all_sections,
|
||||
)
|
||||
|
||||
# ── Phase 6: emit ──────────────────────────────────────────────────────
|
||||
# ── Phase 6: render ────────────────────────────────────────────────────
|
||||
logger.info("[pdf-create] phase 6/6: rendering HTML")
|
||||
html = self._render(doc)
|
||||
filename = _safe_filename(plan.title)
|
||||
logger.info(
|
||||
"[pdf-create] done — filename=%r sections=%d",
|
||||
"[pdf-create] done — filename=%r html_bytes=%d",
|
||||
filename,
|
||||
len(all_sections),
|
||||
len(html),
|
||||
)
|
||||
|
||||
return EditPlanResponse(
|
||||
@@ -404,7 +417,7 @@ class PdfCreateAgent:
|
||||
ToolOperationStep(
|
||||
tool=AgentToolId.CREATE_PDF_FROM_HTML_AGENT,
|
||||
parameters=CreatePdfFromHtmlAgentParams(
|
||||
document=doc.model_dump_json(),
|
||||
html_content=html,
|
||||
filename=filename,
|
||||
),
|
||||
)
|
||||
@@ -424,3 +437,7 @@ class PdfCreateAgent:
|
||||
len(result.output.sections),
|
||||
)
|
||||
return result.output
|
||||
|
||||
def _render(self, doc: GeneratedDocument) -> str:
|
||||
template = self._jinja_env.get_template("document.html.jinja2")
|
||||
return template.render(doc=doc)
|
||||
|
||||
+19
-21
@@ -1,4 +1,3 @@
|
||||
{%- autoescape true -%}
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
@@ -176,18 +175,18 @@
|
||||
color: var(--color-label);
|
||||
}
|
||||
</style>
|
||||
{%- if style_primary or style_background or style_body %}
|
||||
{%- if doc.style %}
|
||||
<style>
|
||||
:root {
|
||||
{%- if style_primary %}
|
||||
--color-primary: {{ style_primary }};
|
||||
{%- if doc.style.primary_color %}
|
||||
--color-primary: {{ doc.style.primary_color }};
|
||||
{%- endif %}
|
||||
{%- if style_background %}
|
||||
--color-bg: {{ style_background }};
|
||||
{%- if doc.style.background_color %}
|
||||
--color-bg: {{ doc.style.background_color }};
|
||||
{%- endif %}
|
||||
{%- if style_body %}
|
||||
--color-body: {{ style_body }};
|
||||
--color-label: {{ style_body }};
|
||||
{%- if doc.style.body_text_color %}
|
||||
--color-body: {{ doc.style.body_text_color }};
|
||||
--color-label: {{ doc.style.body_text_color }};
|
||||
{%- endif %}
|
||||
}
|
||||
</style>
|
||||
@@ -196,16 +195,16 @@
|
||||
<body>
|
||||
|
||||
<div class="doc-header">
|
||||
<div class="doc-title">{{ title }}</div>
|
||||
{%- if subtitle %}
|
||||
<div class="doc-subtitle">{{ subtitle }}</div>
|
||||
<div class="doc-title">{{ doc.title }}</div>
|
||||
{%- if doc.subtitle %}
|
||||
<div class="doc-subtitle">{{ doc.subtitle }}</div>
|
||||
{%- endif %}
|
||||
{%- if reference_number %}
|
||||
<div class="doc-reference">{{ reference_number }}</div>
|
||||
{%- if doc.reference_number %}
|
||||
<div class="doc-reference">{{ doc.reference_number }}</div>
|
||||
{%- endif %}
|
||||
</div>
|
||||
|
||||
{%- for section in sections %}
|
||||
{%- for section in doc.sections %}
|
||||
|
||||
{%- if section.type == "text" %}
|
||||
<section>
|
||||
@@ -213,8 +212,8 @@
|
||||
<h2>{{ section.heading }}</h2>
|
||||
{%- endif %}
|
||||
<div class="text-body">
|
||||
{%- for para in section.paragraphs %}
|
||||
<p>{{ para }}</p>
|
||||
{%- for para in section.body.split('\n\n') %}
|
||||
<p>{{ para | replace('\n', ' ') }}</p>
|
||||
{%- endfor %}
|
||||
</div>
|
||||
</section>
|
||||
@@ -226,10 +225,10 @@
|
||||
{%- endif %}
|
||||
<table class="kv-table">
|
||||
<tbody>
|
||||
{%- for pair in section.pairs %}
|
||||
{%- for label, value in section.pairs %}
|
||||
<tr>
|
||||
<td class="kv-label">{{ pair.label }}</td>
|
||||
<td class="kv-value">{{ pair.value }}</td>
|
||||
<td class="kv-label">{{ label }}</td>
|
||||
<td class="kv-value">{{ value }}</td>
|
||||
</tr>
|
||||
{%- endfor %}
|
||||
</tbody>
|
||||
@@ -300,4 +299,3 @@
|
||||
|
||||
</body>
|
||||
</html>
|
||||
{%- endautoescape %}
|
||||
@@ -1,14 +1,14 @@
|
||||
"""Contracts for the PDF Create Agent.
|
||||
|
||||
The agent accepts a natural-language prompt and returns a single
|
||||
CREATE_PDF_FROM_HTML_AGENT plan step carrying the assembled document.
|
||||
CREATE_PDF_FROM_HTML_AGENT plan step carrying the rendered HTML.
|
||||
|
||||
Pipeline:
|
||||
1. PlannerAgent (smart_model) → DocumentPlan: structured skeleton, no body text.
|
||||
2. Python chunks the plan by token budget.
|
||||
3. SectionWriterAgents (smart_model, parallel) → WrittenSections per chunk.
|
||||
4. Assembler collects sections in plan order → GeneratedDocument.
|
||||
5. The document is emitted as structured fields. The LLM never writes HTML.
|
||||
5. Jinja renders GeneratedDocument → HTML. The LLM never writes HTML.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -81,12 +81,14 @@ type DocumentSection = Annotated[
|
||||
]
|
||||
|
||||
|
||||
# Colours must be a 6-digit hex code (#RRGGBB); anything else is dropped to None.
|
||||
_SAFE_COLOR_RE = re.compile(r"^#[0-9a-fA-F]{6}$")
|
||||
# Named colour or hex only — anything else is dropped so a colour can't inject CSS into the
|
||||
# <style> block (which would let WeasyPrint fetch an attacker-controlled url() → SSRF).
|
||||
_SAFE_COLOR_RE = re.compile(r"^#[0-9a-fA-F]{3,8}$|^[a-zA-Z]{1,30}$")
|
||||
|
||||
|
||||
class DocumentStyle(ApiModel):
|
||||
"""Document colours, inferred by the meta planner. Non-hex values are dropped to ``None``."""
|
||||
"""Document colours, inferred by the meta planner and rendered into the engine's Jinja
|
||||
template (never sent to Java). Unsafe colours are dropped to ``None``."""
|
||||
|
||||
primary_color: str | None = Field(default=None)
|
||||
background_color: str | None = Field(default=None)
|
||||
@@ -101,7 +103,7 @@ class DocumentStyle(ApiModel):
|
||||
|
||||
|
||||
class GeneratedDocument(ApiModel):
|
||||
"""The full document model emitted for rendering."""
|
||||
"""The full document model passed to Jinja for HTML rendering."""
|
||||
|
||||
title: str
|
||||
subtitle: str | None = None
|
||||
|
||||
@@ -29,7 +29,7 @@ class PdfCommentAgentParams(ApiModel):
|
||||
|
||||
|
||||
class CreatePdfFromHtmlAgentParams(ApiModel):
|
||||
document: str
|
||||
html_content: str
|
||||
filename: str = Field(pattern=r"^.+\.pdf$")
|
||||
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Coverage:
|
||||
1. Section model validation (each section type round-trips correctly)
|
||||
2. orchestrate() emits the assembled document as structured JSON
|
||||
2. Jinja rendering (_render produces valid HTML for each section type)
|
||||
3. _safe_filename produces clean slugs
|
||||
4. _make_chunks groups sections correctly by token budget
|
||||
5. orchestrate() produces the correct EditPlanResponse via planner + writer mocks
|
||||
@@ -12,8 +12,6 @@ Coverage:
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from conftest import build_app_settings
|
||||
from pydantic_ai.models.test import TestModel
|
||||
@@ -66,6 +64,37 @@ def agent(runtime: AppRuntime) -> PdfCreateAgent:
|
||||
# ── Helpers ───────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _invoice_doc() -> GeneratedDocument:
|
||||
return GeneratedDocument(
|
||||
title="Invoice",
|
||||
subtitle="Acme Corp",
|
||||
reference_number="Invoice #INV-001",
|
||||
sections=[
|
||||
KeyValueSection(
|
||||
heading="Details",
|
||||
pairs=[("Date", "2026-05-06"), ("Due", "2026-06-06"), ("Currency", "USD")],
|
||||
),
|
||||
LineItemsSection(
|
||||
heading="Line Items",
|
||||
columns=["Description", "Qty", "Unit Price", "Total"],
|
||||
rows=[
|
||||
["Consulting services", "10", "$500.00", "$5,000.00"],
|
||||
["Expenses", "1", "$200.00", "$200.00"],
|
||||
],
|
||||
total_row=["Total", "", "", "$5,200.00"],
|
||||
),
|
||||
TextSection(
|
||||
heading="Payment Terms",
|
||||
body="Payment is due within 30 days.\n\nPlease reference the invoice number.",
|
||||
),
|
||||
SignatureSection(
|
||||
heading="Authorised By",
|
||||
signatories=["Jane Smith, CEO", "Bob Jones, CFO"],
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def _simple_meta() -> DocumentMeta:
|
||||
return DocumentMeta(
|
||||
title="Invoice",
|
||||
@@ -170,6 +199,82 @@ def test_generated_document_optional_fields() -> None:
|
||||
assert doc.reference_number is None
|
||||
|
||||
|
||||
# ── Jinja rendering ───────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_render_produces_html(agent: PdfCreateAgent) -> None:
|
||||
doc = _invoice_doc()
|
||||
html = agent._render(doc)
|
||||
assert "<!DOCTYPE html>" in html
|
||||
assert "Invoice" in html
|
||||
assert "INV-001" in html
|
||||
|
||||
|
||||
def test_render_includes_all_section_types(agent: PdfCreateAgent) -> None:
|
||||
doc = GeneratedDocument(
|
||||
title="All Sections",
|
||||
sections=[
|
||||
TextSection(body="Some prose text."),
|
||||
KeyValueSection(pairs=[("Key", "Value")]),
|
||||
LineItemsSection(columns=["A", "B"], rows=[["1", "2"]]),
|
||||
BulletListSection(items=["item one"]),
|
||||
SignatureSection(signatories=["Alice"]),
|
||||
],
|
||||
)
|
||||
html = agent._render(doc)
|
||||
assert "Some prose text." in html
|
||||
assert "Key" in html and "Value" in html
|
||||
assert "<th>" in html
|
||||
assert "item one" in html
|
||||
assert "Alice" in html
|
||||
|
||||
|
||||
def test_render_escapes_html_in_content(agent: PdfCreateAgent) -> None:
|
||||
doc = GeneratedDocument(
|
||||
title="XSS Test",
|
||||
sections=[TextSection(body="<script>alert('xss')</script>")],
|
||||
)
|
||||
html = agent._render(doc)
|
||||
assert "<script>" not in html
|
||||
assert "<script>" in html
|
||||
|
||||
|
||||
def test_render_total_row_present(agent: PdfCreateAgent) -> None:
|
||||
doc = GeneratedDocument(
|
||||
title="Table",
|
||||
sections=[
|
||||
LineItemsSection(
|
||||
columns=["Item", "Total"],
|
||||
rows=[["Widget", "$10"]],
|
||||
total_row=["Total", "$10"],
|
||||
)
|
||||
],
|
||||
)
|
||||
html = agent._render(doc)
|
||||
assert "total-row" in html
|
||||
|
||||
|
||||
def test_render_no_total_row_skips_tfoot(agent: PdfCreateAgent) -> None:
|
||||
doc = GeneratedDocument(
|
||||
title="Table",
|
||||
sections=[LineItemsSection(columns=["Item"], rows=[["Widget"]])],
|
||||
)
|
||||
html = agent._render(doc)
|
||||
assert "<tfoot>" not in html
|
||||
|
||||
|
||||
def test_render_subtitle_and_reference(agent: PdfCreateAgent) -> None:
|
||||
doc = GeneratedDocument(
|
||||
title="My Doc",
|
||||
subtitle="Subtitle Here",
|
||||
reference_number="REF-42",
|
||||
sections=[TextSection(body="Content.")],
|
||||
)
|
||||
html = agent._render(doc)
|
||||
assert "Subtitle Here" in html
|
||||
assert "REF-42" in html
|
||||
|
||||
|
||||
# ── _safe_filename ────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -291,9 +396,8 @@ async def test_orchestrate_returns_plan_step(agent: PdfCreateAgent) -> None:
|
||||
assert step.tool == AgentToolId.CREATE_PDF_FROM_HTML_AGENT
|
||||
assert isinstance(step.parameters, CreatePdfFromHtmlAgentParams)
|
||||
assert step.parameters.filename.endswith(".pdf")
|
||||
parsed = json.loads(step.parameters.document)
|
||||
assert parsed["title"] == "Invoice"
|
||||
assert parsed["sections"]
|
||||
assert "<!DOCTYPE html>" in step.parameters.html_content
|
||||
assert "Invoice" in step.parameters.html_content
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -364,9 +468,9 @@ async def test_orchestrate_assembles_multiple_chunks(agent: PdfCreateAgent) -> N
|
||||
result = await agent.orchestrate(_orchestrator_request("Create a multi-chunk doc"))
|
||||
|
||||
assert isinstance(result, EditPlanResponse)
|
||||
document = result.steps[0].parameters.document # type: ignore[union-attr]
|
||||
assert "Introduction text." in document
|
||||
assert "Details" in document
|
||||
html = result.steps[0].parameters.html_content # type: ignore[union-attr]
|
||||
assert "Introduction text." in html
|
||||
assert "Details" in html
|
||||
|
||||
|
||||
# ── Style inference ───────────────────────────────────────────────────────────────────────────────
|
||||
@@ -378,7 +482,7 @@ async def test_orchestrate_applies_planner_inferred_style(agent: PdfCreateAgent)
|
||||
meta = DocumentMeta(
|
||||
title="Styled Doc",
|
||||
tone_brief="Professional.",
|
||||
style_primary_color="#ff00ff",
|
||||
style_primary_color="magenta",
|
||||
)
|
||||
sections = _simple_sections()
|
||||
written = _written_sections()
|
||||
@@ -395,35 +499,50 @@ async def test_orchestrate_applies_planner_inferred_style(agent: PdfCreateAgent)
|
||||
result = await agent.orchestrate(_orchestrator_request("Make an invoice, magenta styling"))
|
||||
|
||||
assert isinstance(result, EditPlanResponse)
|
||||
document = result.steps[0].parameters.document # type: ignore[union-attr]
|
||||
assert json.loads(document)["style"]["primaryColor"] == "#ff00ff"
|
||||
html = result.steps[0].parameters.html_content # type: ignore[union-attr]
|
||||
assert "magenta" in html
|
||||
|
||||
|
||||
def test_document_style_keeps_only_six_digit_hex() -> None:
|
||||
"""Only #RRGGBB hex is kept; named colours and other formats drop to None."""
|
||||
safe = DocumentStyle(primary_color="#1e3a5f", background_color="#ffffff", body_text_color="#1A1A1A")
|
||||
def test_render_applies_style(agent: PdfCreateAgent) -> None:
|
||||
"""DocumentStyle fields are injected as CSS custom properties in the rendered HTML."""
|
||||
doc = GeneratedDocument(
|
||||
title="Styled",
|
||||
sections=[TextSection(body="Content.")],
|
||||
style=DocumentStyle(primary_color="magenta", background_color="#111111"),
|
||||
)
|
||||
html = agent._render(doc)
|
||||
assert "--color-primary: magenta" in html
|
||||
assert "--color-bg: #111111" in html
|
||||
|
||||
|
||||
def test_document_style_drops_unsafe_colors() -> None:
|
||||
"""Unsafe colours (not named/hex) are dropped, closing the <style> url() injection."""
|
||||
safe = DocumentStyle(primary_color="navy", background_color="#1e3a5f", body_text_color="#fff")
|
||||
assert (safe.primary_color, safe.background_color, safe.body_text_color) == (
|
||||
"navy",
|
||||
"#1e3a5f",
|
||||
"#ffffff",
|
||||
"#1A1A1A",
|
||||
"#fff",
|
||||
)
|
||||
|
||||
assert DocumentStyle(primary_color="navy").primary_color is None
|
||||
assert DocumentStyle(primary_color="#fff").primary_color is None
|
||||
assert DocumentStyle(primary_color="#1e3a5f00").primary_color is None
|
||||
assert DocumentStyle(primary_color="rgb(255, 0, 0)").primary_color is None
|
||||
assert DocumentStyle(background_color="teal darken-2").background_color is None
|
||||
unsafe = DocumentStyle(
|
||||
primary_color="red; background: url(http://evil.test/steal)",
|
||||
background_color="expression(alert(1))",
|
||||
body_text_color="navy; }",
|
||||
)
|
||||
assert unsafe.primary_color is None
|
||||
assert unsafe.background_color is None
|
||||
assert unsafe.body_text_color is None
|
||||
# A trailing newline must not slip a value through (fullmatch, not $-before-newline).
|
||||
assert DocumentStyle(primary_color="#1e3a5f\n").primary_color is None
|
||||
assert DocumentStyle(primary_color="navy\n").primary_color is None
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_orchestrate_drops_non_hex_planner_colour(agent: PdfCreateAgent) -> None:
|
||||
"""A non-hex colour inferred by the meta planner is dropped before the document is emitted."""
|
||||
async def test_orchestrate_drops_unsafe_planner_color(agent: PdfCreateAgent) -> None:
|
||||
"""An unsafe colour inferred by the meta planner never reaches the rendered HTML."""
|
||||
meta = DocumentMeta(
|
||||
title="Doc",
|
||||
tone_brief="Professional.",
|
||||
style_primary_color="rgb(0, 0, 255)",
|
||||
style_primary_color="blue; background: url(http://evil.test/)",
|
||||
)
|
||||
sections = _simple_sections()
|
||||
written = _written_sections()
|
||||
@@ -440,6 +559,6 @@ async def test_orchestrate_drops_non_hex_planner_colour(agent: PdfCreateAgent) -
|
||||
result = await agent.orchestrate(_orchestrator_request("make it blue"))
|
||||
|
||||
assert isinstance(result, EditPlanResponse)
|
||||
document = result.steps[0].parameters.document # type: ignore[union-attr]
|
||||
assert "rgb(" not in document
|
||||
assert json.loads(document)["style"]["primaryColor"] is None
|
||||
html = result.steps[0].parameters.html_content # type: ignore[union-attr]
|
||||
assert "evil.test" not in html
|
||||
assert "url(" not in html
|
||||
|
||||
Generated
+2
@@ -604,6 +604,7 @@ version = "0.1.0"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "fastapi" },
|
||||
{ name = "jinja2" },
|
||||
{ name = "opentelemetry-sdk" },
|
||||
{ name = "pgvector" },
|
||||
{ name = "posthog" },
|
||||
@@ -630,6 +631,7 @@ dev = [
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "fastapi", specifier = ">=0.116.0" },
|
||||
{ name = "jinja2", specifier = ">=3.1.0" },
|
||||
{ name = "opentelemetry-sdk", specifier = ">=1.39.0" },
|
||||
{ name = "pgvector", specifier = ">=0.3.6" },
|
||||
{ name = "posthog", specifier = ">=3.0.0" },
|
||||
|
||||
@@ -3734,9 +3734,20 @@ uploadToServer = "Upload to server"
|
||||
versionHistory = "Version history"
|
||||
|
||||
[fileSidebar.groupsModal]
|
||||
add = "Add"
|
||||
addLabel = "Add a label…"
|
||||
categoryIconAria = "Choose an icon for {{name}}"
|
||||
createCategory = "Create category"
|
||||
delete = "Delete category"
|
||||
done = "Done"
|
||||
reset = "Show all"
|
||||
subtitle = "Show or hide categories in the files sidebar."
|
||||
hide = "Hide category"
|
||||
newCategory = "New category name…"
|
||||
removeLabel = "Remove {{name}}"
|
||||
rename = "Rename"
|
||||
reset = "Reset to defaults"
|
||||
search = "Search labels…"
|
||||
show = "Show category"
|
||||
subtitle = "Group your files into parent categories. Add existing or new labels to a category, rename it, or create your own. Files in none of your categories appear under “Other”."
|
||||
title = "Sidebar categories"
|
||||
|
||||
[filesPage]
|
||||
@@ -4076,6 +4087,7 @@ allSaved = "All saved"
|
||||
extractCsvError = "Failed to extract CSV"
|
||||
extractXlsxError = "Failed to extract XLSX"
|
||||
flattenAfterFilling = "Flatten after filling"
|
||||
page = "Page"
|
||||
requiredAbbreviation = "req"
|
||||
requiredFieldsError = "Please fill in all required fields"
|
||||
rescanFields = "Re-scan fields"
|
||||
@@ -4084,6 +4096,55 @@ save = "Save"
|
||||
saveShortcut = "Ctrl+S to save"
|
||||
unsavedChanges = "Unsaved changes"
|
||||
|
||||
[formFill.create]
|
||||
commit = "Add {{count}} field(s) to PDF"
|
||||
editField = "Edit field"
|
||||
empty = "No fields drawn yet."
|
||||
failed = "Failed to add fields"
|
||||
hint = "Pick a field type, then draw it on the page."
|
||||
placing = "Draw a {{type}} field on the page. Press Esc to stop."
|
||||
removeField = "Remove field"
|
||||
|
||||
[formFill.editor]
|
||||
action = "Button action"
|
||||
actionNone = "None"
|
||||
actionPrint = "Print"
|
||||
actionReset = "Reset form"
|
||||
actionSubmit = "Submit to URL"
|
||||
actionUri = "Open URL"
|
||||
actionUrl = "URL"
|
||||
addOption = "Add option"
|
||||
caption = "Button caption"
|
||||
defaultValue = "Default value"
|
||||
fontSize = "Font size"
|
||||
label = "Label"
|
||||
maxLength = "Max length (comb)"
|
||||
multiline = "Multi-line"
|
||||
multiSelect = "Allow multiple selection"
|
||||
name = "Field name"
|
||||
optionPlaceholder = "Option {{n}}"
|
||||
options = "Options"
|
||||
optionsEmpty = "Add at least one option."
|
||||
readOnly = "Read-only"
|
||||
removeOption = "Remove option"
|
||||
required = "Required"
|
||||
signatureNote = "Placeholder only - you don't sign here. It marks where a signature belongs so a PDF signer (Adobe Acrobat, a signing service, etc.) places the signature in this spot when the document is signed."
|
||||
tooltip = "Tooltip"
|
||||
type = "Type"
|
||||
|
||||
[formFill.mode]
|
||||
create = "Create"
|
||||
fill = "Fill"
|
||||
modify = "Modify"
|
||||
|
||||
[formFill.modify]
|
||||
commit = "Save {{count}} change(s)"
|
||||
delete = "Delete"
|
||||
empty = "This PDF has no form fields yet."
|
||||
failed = "Failed to save changes"
|
||||
hint = "Select a field to edit its properties, drag it on the page, or delete it."
|
||||
restore = "Restore"
|
||||
|
||||
[formFill.sidebar]
|
||||
close = "Close sidebar"
|
||||
|
||||
@@ -4405,8 +4466,8 @@ tags = "simplify,remove,interactive,flatten,flatten form,remove form fields,make
|
||||
title = "Flatten"
|
||||
|
||||
[home.formFill]
|
||||
desc = "Fill PDF form fields interactively with a visual editor"
|
||||
title = "Fill Form"
|
||||
desc = "Fill, create, edit, and delete PDF form fields with a visual editor"
|
||||
title = "Form Editor"
|
||||
|
||||
[home.getPdfInfo]
|
||||
desc = "Grabs any and all information possible on PDFs"
|
||||
@@ -6003,11 +6064,31 @@ summaryMore = "{{first}}, {{second}} and {{more}} more"
|
||||
summaryTwo = "{{first}} and {{second}}"
|
||||
|
||||
[policies.labels]
|
||||
categoryCount = "categories"
|
||||
hideCategory = "Hide category"
|
||||
labelCount = "labels"
|
||||
sharedNote = "These labels are built in and shared across your whole team."
|
||||
showCategory = "Show category"
|
||||
add = "Add"
|
||||
addPlaceholder = "Add a label…"
|
||||
customNote = "Customized for your team."
|
||||
defaultNote = "Using the built-in default, shared with your team."
|
||||
duplicate = "\"{{name}}\" already exists."
|
||||
edit = "Edit labels"
|
||||
empty = "No labels yet."
|
||||
export = "Export JSON"
|
||||
iconAria = "Choose an icon for {{name}}"
|
||||
import = "Import JSON"
|
||||
importError = "Couldn't import that file."
|
||||
managedNote = "Team labels are managed by your team leader."
|
||||
modalSubtitle = "Shared with your whole team. The classifier picks the labels that fit each document."
|
||||
modalTitle = "Classification labels"
|
||||
pickIcon = "Use {{label}} icon"
|
||||
removeAria = "Remove {{name}}"
|
||||
resetToDefault = "Reset to default"
|
||||
saveForTeam = "Save for team"
|
||||
saving = "Saving…"
|
||||
sectionLabel = "Classification labels"
|
||||
startFromScratch = "Start from scratch"
|
||||
teamCount = "team labels"
|
||||
tooLong = "Labels can be at most {{max}} characters."
|
||||
ungrouped = "Ungrouped"
|
||||
view = "View labels"
|
||||
|
||||
[policies.pii]
|
||||
account = "Account numbers (labelled)"
|
||||
@@ -7420,11 +7501,6 @@ title = "Policies"
|
||||
[portal.policies.card]
|
||||
comingSoon = "Upgrade to Enterprise"
|
||||
notSetUp = "Not set up"
|
||||
requiresAiEngine = "Requires AI engine"
|
||||
|
||||
[portal.policies.categories.classification]
|
||||
desc = "Identify each document's type on upload and tag its metadata for filing and search."
|
||||
label = "Classification"
|
||||
|
||||
[portal.policies.categories.compliance]
|
||||
desc = "Enforce HIPAA, GDPR, SOC 2, or FedRAMP requirements on every document."
|
||||
@@ -7449,13 +7525,6 @@ label = "Security"
|
||||
[portal.policies.config]
|
||||
scopeAll = "All documents"
|
||||
|
||||
[portal.policies.config.classification]
|
||||
summary = "Classifies every uploaded document against your team's labels and tags its metadata."
|
||||
|
||||
[portal.policies.config.classification.rules]
|
||||
0 = "Classify"
|
||||
1 = "Tag metadata"
|
||||
|
||||
[portal.policies.config.compliance]
|
||||
summary = "Validates documents against regulatory frameworks before they leave the system."
|
||||
|
||||
@@ -7550,7 +7619,6 @@ title = "No activity yet"
|
||||
[portal.policies.endpoints]
|
||||
addWatermark = "Watermark"
|
||||
autoRedact = "Redact PII"
|
||||
classifyAndLabel = "Classify"
|
||||
compressPdf = "Compress"
|
||||
flatten = "Flatten"
|
||||
ocrPdf = "OCR"
|
||||
@@ -7593,10 +7661,6 @@ continue = "Continue"
|
||||
enablePolicy = "Enable policy"
|
||||
saveChanges = "Save changes"
|
||||
|
||||
[portal.policies.wizard.capability.classify]
|
||||
desc = "Identifies the document's type from your team's labels and tags it, so it files and searches by category."
|
||||
label = "Classify the document"
|
||||
|
||||
[portal.policies.wizard.capability.compress]
|
||||
desc = "Compresses the document to a smaller file size."
|
||||
label = "Reduce file size"
|
||||
@@ -7621,10 +7685,6 @@ label = "Strip active content"
|
||||
desc = "Stamps a visible mark (e.g. “Confidential”) across every page."
|
||||
label = "Apply a watermark"
|
||||
|
||||
[portal.policies.wizard.classification]
|
||||
description = "Every uploaded document is classified against the built-in labels and tagged with the types that fit. The label set is shared across your whole team."
|
||||
labelsHeading = "Classification labels"
|
||||
|
||||
[portal.policies.wizard.errors]
|
||||
noTools = "Enable at least one tool in the workflow first."
|
||||
saveFailed = "Couldn't save the policy. Please try again."
|
||||
@@ -9046,9 +9106,7 @@ updateBehaviorError = "Could not change update behavior"
|
||||
updateBehaviorErrorLocked = "This setting is locked by your administrator."
|
||||
updateBehaviorLockedDescription = "Your administrator has configured how Stirling-PDF handles updates on this machine. Contact them to change this."
|
||||
updateBehaviorSaved = "Update behavior saved."
|
||||
versionMismatch = "The app frontend ({{frontendVersion}}) and backend ({{backendVersion}}) are running different versions. This usually happens briefly while an update is being applied."
|
||||
versionMismatchResolution = "Restart Stirling-PDF to finish applying the update. If the warning persists after restarting, reinstall the latest version to bring both components back in sync."
|
||||
versionMismatchTitle = "Version mismatch"
|
||||
versionMismatch = "Warning: A mismatch has been detected between the client version and the AppConfig version. Using different versions can lead to compatibility issues, errors, and security risks. Please ensure that server and client are using the same version."
|
||||
viewDetails = "View Details"
|
||||
|
||||
[settings.general.versionInfo]
|
||||
@@ -10867,7 +10925,7 @@ downloadAll = "Download All"
|
||||
exitRedaction = "Exit Redaction Mode"
|
||||
exportAll = "Export PDF"
|
||||
exportSelected = "Export Selected Pages"
|
||||
formFill = "Fill Form"
|
||||
formFill = "Form Editor"
|
||||
multiTool = "Multi-Tool"
|
||||
panMode = "Pan Mode"
|
||||
print = "Print PDF"
|
||||
|
||||
@@ -262,8 +262,8 @@
|
||||
},
|
||||
"formFill": {
|
||||
"image": "/og_images/form-fill.png",
|
||||
"title": "Fill Form - Stirling PDF",
|
||||
"description": "Fill PDF form fields interactively with a visual editor"
|
||||
"title": "Form Editor - Stirling PDF",
|
||||
"description": "Fill, create, edit, and delete PDF form fields with a visual editor"
|
||||
},
|
||||
"multiTool": {
|
||||
"image": "/og_images/multi-tool.png",
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
// Shared source of truth for a policy category's outline icon, keyed by category
|
||||
// id (not a parallel icon-name vocabulary). Used by the editor's policy
|
||||
// definitions and the portal's catalogue cards, summaries, and setup wizard.
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import type { SxProps, Theme } from "@mui/material";
|
||||
import LayersOutlinedIcon from "@mui/icons-material/LayersOutlined";
|
||||
import ShieldOutlinedIcon from "@mui/icons-material/ShieldOutlined";
|
||||
import LabelOutlinedIcon from "@mui/icons-material/LabelOutlined";
|
||||
import CheckCircleOutlinedIcon from "@mui/icons-material/CheckCircleOutlined";
|
||||
import AltRouteOutlinedIcon from "@mui/icons-material/AltRouteOutlined";
|
||||
import ScheduleOutlinedIcon from "@mui/icons-material/ScheduleOutlined";
|
||||
|
||||
type MuiIcon = React.ComponentType<{ sx?: SxProps<Theme>; className?: string }>;
|
||||
|
||||
/** Policy category id → outline glyph. */
|
||||
const POLICY_CATEGORY_ICONS: Record<string, MuiIcon> = {
|
||||
ingestion: LayersOutlinedIcon,
|
||||
security: ShieldOutlinedIcon,
|
||||
classification: LabelOutlinedIcon,
|
||||
compliance: CheckCircleOutlinedIcon,
|
||||
routing: AltRouteOutlinedIcon,
|
||||
retention: ScheduleOutlinedIcon,
|
||||
};
|
||||
|
||||
const FALLBACK_ICON = LabelOutlinedIcon;
|
||||
|
||||
// Defaults to inheriting the surrounding font-size so a wrapping box controls size.
|
||||
export function policyCategoryIcon(
|
||||
categoryId: string,
|
||||
sx: SxProps<Theme> = { fontSize: "inherit" },
|
||||
className?: string,
|
||||
): ReactNode {
|
||||
const Icon = POLICY_CATEGORY_ICONS[categoryId] ?? FALLBACK_ICON;
|
||||
return <Icon sx={sx} className={className} />;
|
||||
}
|
||||
+8
-43
@@ -11,7 +11,6 @@ import {
|
||||
Group,
|
||||
Anchor,
|
||||
Badge,
|
||||
Alert,
|
||||
} from "@mantine/core";
|
||||
import { Button } from "@app/ui/Button";
|
||||
import { ActionIcon } from "@app/ui/ActionIcon";
|
||||
@@ -305,6 +304,14 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({
|
||||
{frontendVersionLabel}
|
||||
</Text>
|
||||
</Text>
|
||||
{mismatchVersion && (
|
||||
<Text size="sm" c="red" mt={4}>
|
||||
{t(
|
||||
"settings.general.updates.versionMismatch",
|
||||
"Warning: A mismatch has been detected between the client version and the AppConfig version. Using different versions can lead to compatibility issues, errors, and security risks. Please ensure that server and client are using the same version.",
|
||||
)}
|
||||
</Text>
|
||||
)}
|
||||
</div>
|
||||
</Group>
|
||||
)}
|
||||
@@ -454,48 +461,6 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({
|
||||
/>
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
{/* Frontend/backend version mismatch notice. Informational, not an
|
||||
error, and deliberately separated from "Check for Updates" — the
|
||||
update check only looks for a newer *release* and cannot
|
||||
reconcile a mismatch between the app's bundled components. The
|
||||
mismatch is normally transient while an update is being applied,
|
||||
so the resolution is to restart (or reinstall) the app rather
|
||||
than to check for updates. */}
|
||||
{mismatchVersion && (
|
||||
<Alert
|
||||
variant="light"
|
||||
color="yellow"
|
||||
icon={
|
||||
<LocalIcon
|
||||
icon="info-outline-rounded"
|
||||
width="1.2rem"
|
||||
height="1.2rem"
|
||||
/>
|
||||
}
|
||||
title={t(
|
||||
"settings.general.updates.versionMismatchTitle",
|
||||
"Version mismatch",
|
||||
)}
|
||||
>
|
||||
<Text size="sm">
|
||||
{t(
|
||||
"settings.general.updates.versionMismatch",
|
||||
"The app frontend ({{frontendVersion}}) and backend ({{backendVersion}}) are running different versions. This usually happens briefly while an update is being applied.",
|
||||
{
|
||||
frontendVersion: frontendVersionLabel,
|
||||
backendVersion: config?.appVersion ?? "",
|
||||
},
|
||||
)}
|
||||
</Text>
|
||||
<Text size="sm" mt={4}>
|
||||
{t(
|
||||
"settings.general.updates.versionMismatchResolution",
|
||||
"Restart Stirling-PDF to finish applying the update. If the warning persists after restarting, reinstall the latest version to bring both components back in sync.",
|
||||
)}
|
||||
</Text>
|
||||
</Alert>
|
||||
)}
|
||||
</Stack>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
@@ -46,6 +46,7 @@ import type { PDFDict, PDFNumber } from "@cantoo/pdf-lib";
|
||||
import { useWheelZoom } from "@app/hooks/useWheelZoom";
|
||||
import { useFormFill } from "@app/tools/formFill/FormFillContext";
|
||||
import { FormSaveBar } from "@app/tools/formFill/FormSaveBar";
|
||||
import { FORM_APPLY_EVENT } from "@app/tools/formFill/formFillEvents";
|
||||
import { useViewerKeyCommand } from "@app/hooks/useViewerKeyCommand";
|
||||
import { usePolicyFileBadges } from "@app/hooks/usePolicyFileBadges";
|
||||
import { alert } from "@app/components/toast";
|
||||
@@ -868,8 +869,8 @@ const EmbedPdfViewerContent = ({
|
||||
handleFormApply(blob);
|
||||
}
|
||||
};
|
||||
window.addEventListener("formfill:apply", handler);
|
||||
return () => window.removeEventListener("formfill:apply", handler);
|
||||
window.addEventListener(FORM_APPLY_EVENT, handler);
|
||||
return () => window.removeEventListener(FORM_APPLY_EVENT, handler);
|
||||
}, [handleFormApply]);
|
||||
|
||||
// Apply layer visibility changes - reload the modified PDF into the viewer
|
||||
|
||||
@@ -101,6 +101,8 @@ import { DocumentReadyWrapper } from "@app/components/viewer/DocumentReadyWrappe
|
||||
import { ActiveDocumentProvider } from "@app/components/viewer/ActiveDocumentContext";
|
||||
import { pdfiumWasmUrl } from "@app/services/wasmPrecompiler";
|
||||
import { FormFieldOverlay } from "@app/tools/formFill/FormFieldOverlay";
|
||||
import { FormFieldCreationOverlay } from "@app/tools/formFill/FormFieldCreationOverlay";
|
||||
import { FormFieldEditOverlay } from "@app/tools/formFill/FormFieldEditOverlay";
|
||||
import { ButtonAppearanceOverlay } from "@app/tools/formFill/ButtonAppearanceOverlay";
|
||||
import SignatureFieldOverlay from "@app/components/viewer/SignatureFieldOverlay";
|
||||
import { CommentsSidebar } from "@app/components/viewer/CommentsSidebar";
|
||||
@@ -1110,6 +1112,28 @@ export function LocalEmbedPDF({
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Create-mode: drag to place new fields */}
|
||||
{enableFormFill && (
|
||||
<FormFieldCreationOverlay
|
||||
documentId={documentId}
|
||||
pageIndex={pageIndex}
|
||||
pageWidth={width}
|
||||
pageHeight={height}
|
||||
fileId={fileId}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Modify-mode: select / move / resize existing fields */}
|
||||
{enableFormFill && (
|
||||
<FormFieldEditOverlay
|
||||
documentId={documentId}
|
||||
pageIndex={pageIndex}
|
||||
pageWidth={width}
|
||||
pageHeight={height}
|
||||
fileId={fileId}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* SignatureFieldOverlay — bitmaps of digital-signature appearances */}
|
||||
{file && (
|
||||
<SignatureFieldOverlay
|
||||
|
||||
@@ -116,7 +116,7 @@ export function useViewerWorkbenchBarButtons(
|
||||
const layersLabel = t("workbenchBar.toggleLayers", "Toggle Layers");
|
||||
const commentsLabel = t("workbenchBar.toggleComments", "Comments");
|
||||
const annotationsLabel = t("workbenchBar.annotations", "Annotations");
|
||||
const formFillLabel = t("workbenchBar.formFill", "Fill Form");
|
||||
const formFillLabel = t("workbenchBar.formFill", "Form Editor");
|
||||
const rulerLabel = t("workbenchBar.ruler", "Ruler / Measure");
|
||||
const readAloudLabel = t("workbenchBar.readAloud", "Read Aloud");
|
||||
const readAloudSpeedLabel = t("workbenchBar.readAloudSpeed", "Speed");
|
||||
|
||||
@@ -451,11 +451,11 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
height="1.5rem"
|
||||
/>
|
||||
),
|
||||
name: t("home.formFill.title", "Fill Form"),
|
||||
name: t("home.formFill.title", "Form Editor"),
|
||||
component: lazy(() => import("@app/tools/formFill/FormFill")),
|
||||
description: t(
|
||||
"home.formFill.desc",
|
||||
"Fill PDF form fields interactively with a visual editor",
|
||||
"Fill, create, edit, and delete PDF form fields with a visual editor",
|
||||
),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.GENERAL,
|
||||
@@ -463,7 +463,19 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
endpoints: ["form-fill"],
|
||||
automationSettings: null,
|
||||
supportsAutomate: false,
|
||||
synonyms: ["form", "fill", "fillable", "input", "field", "acroform"],
|
||||
synonyms: [
|
||||
"form",
|
||||
"fill",
|
||||
"fillable",
|
||||
"input",
|
||||
"field",
|
||||
"acroform",
|
||||
"edit",
|
||||
"create",
|
||||
"editor",
|
||||
"modify",
|
||||
"builder",
|
||||
],
|
||||
},
|
||||
changePermissions: {
|
||||
icon: <LocalIcon icon="lock-outline" width="1.5rem" height="1.5rem" />,
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { test, expect } from "@app/tests/helpers/test-base";
|
||||
import { loginAndSetup } from "@app/tests/helpers/login";
|
||||
import { uploadFiles } from "@app/tests/helpers/ui-helpers";
|
||||
import type { Page } from "@playwright/test";
|
||||
import * as path from "path";
|
||||
import * as fs from "fs";
|
||||
|
||||
/**
|
||||
* Full-stack round-trip for the form field editor (PR #5777). Runs against a
|
||||
* real Spring Boot backend (the `live` Playwright project): a field drawn in
|
||||
* the browser is created by PDFBox, the viewer reloads the produced PDF, and
|
||||
* the new field is then visible in modify mode and removable again.
|
||||
*
|
||||
* The stubbed spec (`stubbed/form-field-editing.spec.ts`) covers the UI/API
|
||||
* contract without a backend; this one proves the bytes actually round-trip.
|
||||
*/
|
||||
|
||||
function fixture(filename: string): string {
|
||||
const candidates = [
|
||||
path.resolve(
|
||||
process.cwd(),
|
||||
"src",
|
||||
"core",
|
||||
"tests",
|
||||
"test-fixtures",
|
||||
filename,
|
||||
),
|
||||
path.resolve(
|
||||
process.cwd(),
|
||||
"frontend",
|
||||
"editor",
|
||||
"src",
|
||||
"core",
|
||||
"tests",
|
||||
"test-fixtures",
|
||||
filename,
|
||||
),
|
||||
];
|
||||
for (const p of candidates) {
|
||||
if (fs.existsSync(p)) return p;
|
||||
}
|
||||
throw new Error(`Test fixture not found: ${filename}`);
|
||||
}
|
||||
|
||||
function modeTab(page: Page, name: string) {
|
||||
return page
|
||||
.locator(".mantine-SegmentedControl-label")
|
||||
.filter({ hasText: name });
|
||||
}
|
||||
|
||||
test.describe("Form field editor — live round-trip", () => {
|
||||
test.describe.configure({ timeout: 120000 });
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await loginAndSetup(page);
|
||||
});
|
||||
|
||||
test("creates a field on the backend and shows it in modify mode", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.goto("/form-fill");
|
||||
await page.waitForLoadState("domcontentloaded");
|
||||
await uploadFiles(page, [fixture("sample.pdf")]);
|
||||
|
||||
// --- Create a text field by drawing on the rendered page ---
|
||||
await modeTab(page, "Create").click();
|
||||
await page.getByTestId("form-create-type-text").click();
|
||||
|
||||
const overlay = page.getByTestId("form-create-overlay-0");
|
||||
await expect(overlay).toBeVisible({ timeout: 30_000 });
|
||||
const box = await overlay.boundingBox();
|
||||
expect(box).not.toBeNull();
|
||||
const x = box!.x + box!.width * 0.3;
|
||||
const y = box!.y + box!.height * 0.3;
|
||||
await page.mouse.move(x, y);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(x + 140, y + 36, { steps: 8 });
|
||||
await page.mouse.up();
|
||||
|
||||
const commit = page.getByTestId("form-create-commit");
|
||||
await expect(commit).toBeEnabled();
|
||||
await commit.click();
|
||||
|
||||
// After the backend creates the field, the viewer reloads the PDF and the
|
||||
// tool re-fetches fields. Modify mode should now list at least one field.
|
||||
await modeTab(page, "Modify").click();
|
||||
const rows = page.locator('[data-testid^="form-modify-row-"]');
|
||||
await expect(rows.first()).toBeVisible({ timeout: 30_000 });
|
||||
expect(await rows.count()).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
test("deletes an existing field through the backend", async ({ page }) => {
|
||||
await page.goto("/form-fill");
|
||||
await page.waitForLoadState("domcontentloaded");
|
||||
await uploadFiles(page, [fixture("sample.pdf")]);
|
||||
|
||||
// Seed a field so there is something to delete (independent of fixtures).
|
||||
await modeTab(page, "Create").click();
|
||||
await page.getByTestId("form-create-type-text").click();
|
||||
const overlay = page.getByTestId("form-create-overlay-0");
|
||||
await expect(overlay).toBeVisible({ timeout: 30_000 });
|
||||
const box = await overlay.boundingBox();
|
||||
const x = box!.x + box!.width * 0.3;
|
||||
const y = box!.y + box!.height * 0.5;
|
||||
await page.mouse.move(x, y);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(x + 120, y + 30, { steps: 6 });
|
||||
await page.mouse.up();
|
||||
await page.getByTestId("form-create-commit").click();
|
||||
|
||||
// Switch to modify, mark every field for deletion, commit.
|
||||
await modeTab(page, "Modify").click();
|
||||
const rows = page.locator('[data-testid^="form-modify-row-"]');
|
||||
await expect(rows.first()).toBeVisible({ timeout: 30_000 });
|
||||
const initialCount = await rows.count();
|
||||
expect(initialCount).toBeGreaterThanOrEqual(1);
|
||||
|
||||
await page.locator('[data-testid^="form-modify-delete-"]').first().click();
|
||||
const commit = page.getByTestId("form-modify-commit");
|
||||
await expect(commit).toBeEnabled();
|
||||
await commit.click();
|
||||
|
||||
// The reloaded PDF should expose fewer fields than before.
|
||||
await expect
|
||||
.poll(async () => rows.count(), { timeout: 30_000 })
|
||||
.toBeLessThan(initialCount);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,299 @@
|
||||
import { test, expect } from "@app/tests/helpers/stub-test-base";
|
||||
import { uploadFiles } from "@app/tests/helpers/ui-helpers";
|
||||
import { readFileSync } from "fs";
|
||||
import path from "path";
|
||||
import type { Page, Route } from "@playwright/test";
|
||||
|
||||
/**
|
||||
* Stubbed coverage for the form field editor (PR #5777 — create / modify /
|
||||
* delete fields, plus radio/button/signature/comb types). The backend
|
||||
* `/api/v1/form/*` endpoints are mocked so these specs run without a Spring
|
||||
* Boot server; they exercise the panel UI, the staged-change bookkeeping, and
|
||||
* that committing fires the combined `/edit-fields` endpoint with the right
|
||||
* payload.
|
||||
*
|
||||
* The real PDFBox round-trip is covered by the live spec and the backend
|
||||
* JUnit tests.
|
||||
*/
|
||||
|
||||
const SAMPLE_PDF = path.join(__dirname, "../test-fixtures/sample.pdf");
|
||||
const PDF_BYTES = readFileSync(SAMPLE_PDF);
|
||||
|
||||
/** Two text fields on page 0, in the shape the backend emits. */
|
||||
const STUB_FIELDS = [
|
||||
{
|
||||
name: "firstName",
|
||||
label: "First name",
|
||||
type: "text",
|
||||
value: "",
|
||||
options: null,
|
||||
displayOptions: null,
|
||||
required: false,
|
||||
readOnly: false,
|
||||
multiSelect: false,
|
||||
multiline: false,
|
||||
tooltip: null,
|
||||
widgets: [
|
||||
{
|
||||
pageIndex: 0,
|
||||
x: 100,
|
||||
y: 100,
|
||||
width: 180,
|
||||
height: 20,
|
||||
fontSize: 12,
|
||||
cropBoxHeight: 792,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "lastName",
|
||||
label: "Last name",
|
||||
type: "text",
|
||||
value: "",
|
||||
options: null,
|
||||
displayOptions: null,
|
||||
required: false,
|
||||
readOnly: false,
|
||||
multiSelect: false,
|
||||
multiline: false,
|
||||
tooltip: null,
|
||||
widgets: [
|
||||
{
|
||||
pageIndex: 0,
|
||||
x: 100,
|
||||
y: 140,
|
||||
width: 180,
|
||||
height: 20,
|
||||
fontSize: 12,
|
||||
cropBoxHeight: 792,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Install form-endpoint stubs. `fields` is what the extraction endpoint returns
|
||||
* (default: none, so create-mode drags land on an unobstructed overlay).
|
||||
* Returns a record of captured request bodies.
|
||||
*/
|
||||
async function stubFormEndpoints(page: Page, fields: unknown[] = []) {
|
||||
const captured: Record<string, string> = {};
|
||||
|
||||
await page.route("**/api/v1/form/fields-with-coordinates", (route: Route) =>
|
||||
route.fulfill({ json: fields }),
|
||||
);
|
||||
|
||||
// The UI routes create/modify/delete commits through the combined endpoint.
|
||||
await page.route("**/api/v1/form/edit-fields", (route: Route) => {
|
||||
captured["edit-fields"] = route.request().postData() ?? "";
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/pdf",
|
||||
body: PDF_BYTES,
|
||||
});
|
||||
});
|
||||
|
||||
return captured;
|
||||
}
|
||||
|
||||
async function openFormTool(page: Page) {
|
||||
await page.goto("/form-fill");
|
||||
await page.waitForLoadState("domcontentloaded");
|
||||
await uploadFiles(page, SAMPLE_PDF);
|
||||
}
|
||||
|
||||
/** The Mantine SegmentedControl hides the radio input; the label is the target. */
|
||||
function modeTab(page: Page, name: string) {
|
||||
return page
|
||||
.locator(".mantine-SegmentedControl-label")
|
||||
.filter({ hasText: name });
|
||||
}
|
||||
|
||||
async function selectMode(page: Page, name: string) {
|
||||
await modeTab(page, name).click();
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw a rectangle on the create overlay for the currently-armed type, retrying
|
||||
* until a pending field registers (the commit button enables). Pointer drags
|
||||
* over the WASM-rendered page can occasionally drop under parallel load.
|
||||
*/
|
||||
async function drawField(page: Page) {
|
||||
const overlay = page.getByTestId("form-create-overlay-0");
|
||||
await expect(overlay).toBeVisible({ timeout: 30_000 });
|
||||
const commit = page.getByTestId("form-create-commit");
|
||||
for (let attempt = 0; attempt < 4; attempt++) {
|
||||
const box = await overlay.boundingBox();
|
||||
if (!box) continue;
|
||||
const startX = box.x + box.width * 0.25;
|
||||
const startY = box.y + box.height * 0.25;
|
||||
await page.mouse.move(startX, startY);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(startX + 60, startY + 20, { steps: 4 });
|
||||
await page.mouse.move(startX + 120, startY + 40, { steps: 4 });
|
||||
await page.mouse.up();
|
||||
try {
|
||||
await expect(commit).toBeEnabled({ timeout: 2000 });
|
||||
return;
|
||||
} catch {
|
||||
// drag dropped under load — try again
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test.describe("Form field editor", () => {
|
||||
test("exposes Fill / Create / Modify modes", async ({ page }) => {
|
||||
await stubFormEndpoints(page);
|
||||
await openFormTool(page);
|
||||
|
||||
await expect(modeTab(page, "Fill")).toBeVisible();
|
||||
await expect(modeTab(page, "Create")).toBeVisible();
|
||||
await expect(modeTab(page, "Modify")).toBeVisible();
|
||||
});
|
||||
|
||||
test("create mode: palette offers every creatable type", async ({ page }) => {
|
||||
await stubFormEndpoints(page);
|
||||
await openFormTool(page);
|
||||
|
||||
await selectMode(page, "Create");
|
||||
|
||||
for (const type of [
|
||||
"text",
|
||||
"checkbox",
|
||||
"combobox",
|
||||
"listbox",
|
||||
"radio",
|
||||
"button",
|
||||
"signature",
|
||||
]) {
|
||||
await expect(page.getByTestId(`form-create-type-${type}`)).toBeVisible();
|
||||
}
|
||||
|
||||
// Commit disabled with nothing queued.
|
||||
await expect(page.getByTestId("form-create-commit")).toBeDisabled();
|
||||
|
||||
// Arming a type reveals the "draw on the page" hint.
|
||||
await page.getByTestId("form-create-type-text").click();
|
||||
await expect(
|
||||
page.getByText(/Draw a Text field on the page/i),
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test("create mode: drawing a text field commits via /edit-fields", async ({
|
||||
page,
|
||||
}) => {
|
||||
const captured = await stubFormEndpoints(page);
|
||||
await openFormTool(page);
|
||||
|
||||
await selectMode(page, "Create");
|
||||
await page.getByTestId("form-create-type-text").click();
|
||||
await drawField(page);
|
||||
|
||||
// A queued field appears with a commit affordance enabled.
|
||||
await expect(page.getByTestId("form-create-commit")).toBeEnabled();
|
||||
|
||||
await page.getByTestId("form-create-commit").click();
|
||||
await expect.poll(() => captured["edit-fields"]).toBeTruthy();
|
||||
expect(captured["edit-fields"]).toContain('"add"');
|
||||
expect(captured["edit-fields"]).toContain('"type":"text"');
|
||||
});
|
||||
|
||||
test("create mode: drawing a radio field commits a radio definition", async ({
|
||||
page,
|
||||
}) => {
|
||||
const captured = await stubFormEndpoints(page);
|
||||
await openFormTool(page);
|
||||
|
||||
await selectMode(page, "Create");
|
||||
await page.getByTestId("form-create-type-radio").click();
|
||||
await drawField(page);
|
||||
|
||||
await expect(page.getByTestId("form-create-commit")).toBeEnabled();
|
||||
await page.getByTestId("form-create-commit").click();
|
||||
|
||||
await expect.poll(() => captured["edit-fields"]).toBeTruthy();
|
||||
expect(captured["edit-fields"]).toContain('"type":"radio"');
|
||||
});
|
||||
|
||||
test("create mode: a choice field auto-shows seeded options", async ({
|
||||
page,
|
||||
}) => {
|
||||
await stubFormEndpoints(page);
|
||||
await openFormTool(page);
|
||||
|
||||
await selectMode(page, "Create");
|
||||
await page.getByTestId("form-create-type-listbox").click();
|
||||
await drawField(page);
|
||||
|
||||
// The just-drawn field's property editor auto-expands and the Options
|
||||
// section is visible immediately, pre-seeded with two options — no manual
|
||||
// expand, no hunting at the bottom of the panel.
|
||||
await expect(page.getByText("Options", { exact: true })).toBeVisible();
|
||||
await expect(page.getByPlaceholder("Option 1")).toHaveValue("Option 1");
|
||||
await expect(page.getByPlaceholder("Option 2")).toHaveValue("Option 2");
|
||||
});
|
||||
|
||||
test("create mode: signature field explains it is a placeholder", async ({
|
||||
page,
|
||||
}) => {
|
||||
await stubFormEndpoints(page);
|
||||
await openFormTool(page);
|
||||
|
||||
await selectMode(page, "Create");
|
||||
await page.getByTestId("form-create-type-signature").click();
|
||||
await drawField(page);
|
||||
|
||||
// The editor makes clear you don't sign here - it's a placeholder a signer fills.
|
||||
await expect(page.getByText(/Placeholder only/i)).toBeVisible();
|
||||
});
|
||||
|
||||
test("modify mode: lists fields and deletes one via /edit-fields", async ({
|
||||
page,
|
||||
}) => {
|
||||
const captured = await stubFormEndpoints(page, STUB_FIELDS);
|
||||
await openFormTool(page);
|
||||
|
||||
await selectMode(page, "Modify");
|
||||
|
||||
// Both stubbed fields render as rows.
|
||||
await expect(page.getByTestId("form-modify-row-firstName")).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expect(page.getByTestId("form-modify-row-lastName")).toBeVisible();
|
||||
|
||||
// Mark one for deletion → commit count reflects it and button enables.
|
||||
await page.getByTestId("form-modify-delete-firstName").click();
|
||||
const commit = page.getByTestId("form-modify-commit");
|
||||
await expect(commit).toContainText("1");
|
||||
await expect(commit).toBeEnabled();
|
||||
|
||||
await commit.click();
|
||||
await expect.poll(() => captured["edit-fields"]).toBeTruthy();
|
||||
expect(captured["edit-fields"]).toContain('"delete"');
|
||||
expect(captured["edit-fields"]).toContain("firstName");
|
||||
});
|
||||
|
||||
test("modify mode: editing a property commits via /edit-fields", async ({
|
||||
page,
|
||||
}) => {
|
||||
const captured = await stubFormEndpoints(page, STUB_FIELDS);
|
||||
await openFormTool(page);
|
||||
|
||||
await selectMode(page, "Modify");
|
||||
await page.getByTestId("form-modify-row-firstName").click();
|
||||
|
||||
// The property editor reveals the label input; change it.
|
||||
const labelInput = page.getByLabel("Label").first();
|
||||
await expect(labelInput).toBeVisible();
|
||||
await labelInput.fill("Given name");
|
||||
|
||||
const commit = page.getByTestId("form-modify-commit");
|
||||
await expect(commit).toBeEnabled();
|
||||
await commit.click();
|
||||
|
||||
await expect.poll(() => captured["edit-fields"]).toBeTruthy();
|
||||
expect(captured["edit-fields"]).toContain('"modify"');
|
||||
expect(captured["edit-fields"]).toContain("firstName");
|
||||
expect(captured["edit-fields"]).toContain("Given name");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,233 @@
|
||||
/**
|
||||
* FormFieldCreatePanel — left-panel UI for "create" mode.
|
||||
*
|
||||
* Pick a field type to arm placement, draw fields on the page (handled by
|
||||
* FormFieldCreationOverlay), tweak each queued field's properties, then commit
|
||||
* them to the PDF in one request.
|
||||
*/
|
||||
import React, { useCallback, useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
Stack,
|
||||
Text,
|
||||
Button,
|
||||
Group,
|
||||
Alert,
|
||||
Collapse,
|
||||
ActionIcon,
|
||||
Paper,
|
||||
} from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutlineRounded";
|
||||
import EditIcon from "@mui/icons-material/Edit";
|
||||
import WarningAmberIcon from "@mui/icons-material/WarningAmber";
|
||||
import { useFormFill } from "@app/tools/formFill/FormFillContext";
|
||||
import {
|
||||
CREATABLE_FIELD_TYPES,
|
||||
type CreatableFieldType,
|
||||
type NewFieldDefinition,
|
||||
} from "@app/tools/formFill/types";
|
||||
import {
|
||||
FIELD_TYPE_ICON,
|
||||
FIELD_TYPE_COLOR,
|
||||
} from "@app/tools/formFill/fieldMeta";
|
||||
import { FormFieldPropertyEditor } from "@app/tools/formFill/FormFieldPropertyEditor";
|
||||
import { useFormCommit } from "@app/tools/formFill/useFormCommit";
|
||||
import styles from "@app/tools/formFill/FormFill.module.css";
|
||||
|
||||
interface FormFieldCreatePanelProps {
|
||||
currentFile: File | Blob | null;
|
||||
onApplied?: (blob: Blob) => void;
|
||||
}
|
||||
|
||||
const TYPE_LABEL: Record<CreatableFieldType, string> = {
|
||||
text: "Text",
|
||||
checkbox: "Checkbox",
|
||||
combobox: "Dropdown",
|
||||
listbox: "List box",
|
||||
radio: "Radio",
|
||||
button: "Button",
|
||||
signature: "Signature",
|
||||
};
|
||||
|
||||
export function FormFieldCreatePanel({
|
||||
currentFile,
|
||||
onApplied,
|
||||
}: FormFieldCreatePanelProps) {
|
||||
const { t } = useTranslation();
|
||||
const {
|
||||
creationType,
|
||||
setCreationType,
|
||||
pendingFields,
|
||||
updatePendingField,
|
||||
removePendingField,
|
||||
commitNewFields,
|
||||
} = useFormFill();
|
||||
|
||||
const [expandedId, setExpandedId] = useState<string | null>(null);
|
||||
const { committing, error, commit } = useFormCommit(onApplied);
|
||||
|
||||
// Auto-expand the property editor of a freshly-drawn field so its settings
|
||||
// (especially options for choice/radio) are visible immediately.
|
||||
const prevCountRef = useRef(0);
|
||||
useEffect(() => {
|
||||
if (pendingFields.length > prevCountRef.current) {
|
||||
setExpandedId(pendingFields[pendingFields.length - 1].id);
|
||||
}
|
||||
prevCountRef.current = pendingFields.length;
|
||||
}, [pendingFields]);
|
||||
|
||||
const handleCommit = useCallback(() => {
|
||||
if (!currentFile || pendingFields.length === 0) return;
|
||||
commit(
|
||||
() => commitNewFields(currentFile),
|
||||
"formFill.create.failed",
|
||||
"Failed to add fields",
|
||||
);
|
||||
}, [currentFile, pendingFields, commitNewFields, commit]);
|
||||
|
||||
return (
|
||||
<div className={styles.header}>
|
||||
<Stack gap="xs">
|
||||
<Text size="xs" c="dimmed">
|
||||
{t(
|
||||
"formFill.create.hint",
|
||||
"Pick a field type, then draw it on the page.",
|
||||
)}
|
||||
</Text>
|
||||
|
||||
{/* Type palette */}
|
||||
<Group gap={6} wrap="wrap">
|
||||
{CREATABLE_FIELD_TYPES.map((type) => {
|
||||
const armed = creationType === type;
|
||||
return (
|
||||
<Button
|
||||
key={type}
|
||||
size="xs"
|
||||
variant={armed ? "filled" : "default"}
|
||||
leftSection={FIELD_TYPE_ICON[type]}
|
||||
onClick={() => setCreationType(armed ? null : type)}
|
||||
data-testid={`form-create-type-${type}`}
|
||||
>
|
||||
{TYPE_LABEL[type]}
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</Group>
|
||||
|
||||
{creationType && (
|
||||
<Alert color="blue" variant="light" p="xs" radius="sm">
|
||||
<Text size="xs">
|
||||
{t(
|
||||
"formFill.create.placing",
|
||||
"Draw a {{type}} field on the page. Press Esc to stop.",
|
||||
{ type: TYPE_LABEL[creationType] },
|
||||
)}
|
||||
</Text>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert
|
||||
icon={<WarningAmberIcon sx={{ fontSize: 16 }} />}
|
||||
color="red"
|
||||
variant="light"
|
||||
p="xs"
|
||||
radius="sm"
|
||||
>
|
||||
<Text size="xs">{error}</Text>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Queued fields */}
|
||||
{pendingFields.length === 0 ? (
|
||||
<Text size="xs" c="dimmed" ta="center" py="md">
|
||||
{t("formFill.create.empty", "No fields drawn yet.")}
|
||||
</Text>
|
||||
) : (
|
||||
<Stack gap={6}>
|
||||
{pendingFields.map((pf) => {
|
||||
const expanded = expandedId === pf.id;
|
||||
return (
|
||||
<Paper key={pf.id} withBorder p={6} radius="sm">
|
||||
<Group gap={6} wrap="nowrap" justify="space-between">
|
||||
<Group gap={6} wrap="nowrap" style={{ minWidth: 0 }}>
|
||||
<span
|
||||
style={{
|
||||
color: `var(--mantine-color-${FIELD_TYPE_COLOR[pf.type]}-6)`,
|
||||
display: "flex",
|
||||
}}
|
||||
>
|
||||
{FIELD_TYPE_ICON[pf.type]}
|
||||
</span>
|
||||
<Text size="xs" truncate>
|
||||
{pf.name}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
p{pf.pageIndex + 1}
|
||||
</Text>
|
||||
</Group>
|
||||
<Group gap={2} wrap="nowrap">
|
||||
<ActionIcon
|
||||
size="sm"
|
||||
variant="subtle"
|
||||
aria-label={t(
|
||||
"formFill.create.editField",
|
||||
"Edit field",
|
||||
)}
|
||||
onClick={() => setExpandedId(expanded ? null : pf.id)}
|
||||
data-testid={`form-pending-edit-${pf.id}`}
|
||||
>
|
||||
<EditIcon sx={{ fontSize: 16 }} />
|
||||
</ActionIcon>
|
||||
<ActionIcon
|
||||
size="sm"
|
||||
variant="subtle"
|
||||
color="red"
|
||||
aria-label={t(
|
||||
"formFill.create.removeField",
|
||||
"Remove field",
|
||||
)}
|
||||
onClick={() => removePendingField(pf.id)}
|
||||
data-testid={`form-pending-remove-${pf.id}`}
|
||||
>
|
||||
<DeleteOutlineIcon sx={{ fontSize: 16 }} />
|
||||
</ActionIcon>
|
||||
</Group>
|
||||
</Group>
|
||||
<Collapse in={expanded}>
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<FormFieldPropertyEditor
|
||||
value={pf}
|
||||
onChange={(patch) =>
|
||||
updatePendingField(
|
||||
pf.id,
|
||||
patch as Partial<NewFieldDefinition>,
|
||||
)
|
||||
}
|
||||
showName
|
||||
/>
|
||||
</div>
|
||||
</Collapse>
|
||||
</Paper>
|
||||
);
|
||||
})}
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
<Button
|
||||
size="xs"
|
||||
onClick={handleCommit}
|
||||
loading={committing}
|
||||
disabled={!currentFile || pendingFields.length === 0}
|
||||
data-testid="form-create-commit"
|
||||
>
|
||||
{t("formFill.create.commit", "Add {{count}} field(s) to PDF", {
|
||||
count: pendingFields.length,
|
||||
})}
|
||||
</Button>
|
||||
</Stack>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default FormFieldCreatePanel;
|
||||
@@ -0,0 +1,319 @@
|
||||
/**
|
||||
* FormFieldCreationOverlay — drag-to-place layer for "create" mode.
|
||||
*
|
||||
* Mounted per page alongside FormFieldOverlay. When a field type is armed in
|
||||
* the create panel, dragging on the page draws a rectangle which becomes a
|
||||
* pending field. A plain click (no drag) drops a default-sized field. Pending
|
||||
* fields on this page are drawn as dashed outlines; alignment guides appear
|
||||
* while dragging.
|
||||
*
|
||||
* Coordinates use the exact same scale basis as FormFieldOverlay
|
||||
* (pageWidthPx / pdfPage.size.width), so a field placed at a pixel position
|
||||
* round-trips back to the same position after save/reload.
|
||||
*/
|
||||
import React, {
|
||||
useCallback,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
useEffect,
|
||||
} from "react";
|
||||
import { useFormFill } from "@app/tools/formFill/FormFillContext";
|
||||
import type { CreatableFieldType } from "@app/tools/formFill/types";
|
||||
import {
|
||||
pixelsToBackendRect,
|
||||
backendRectToPixels,
|
||||
clampPixelRect,
|
||||
roundPdfRect,
|
||||
type PixelRect,
|
||||
} from "@app/tools/formFill/formCoordinateUtils";
|
||||
import {
|
||||
collectSnapTargets,
|
||||
snapMove,
|
||||
type SnapGuide,
|
||||
} from "@app/tools/formFill/formSnapUtils";
|
||||
import { usePageScale, getLocalPoint } from "@app/tools/formFill/usePageScale";
|
||||
import { SnapGuides } from "@app/tools/formFill/SnapGuides";
|
||||
import { FORM_COLORS } from "@app/tools/formFill/formFieldColors";
|
||||
|
||||
interface FormFieldCreationOverlayProps {
|
||||
documentId: string;
|
||||
pageIndex: number;
|
||||
pageWidth: number;
|
||||
pageHeight: number;
|
||||
fileId?: string | null;
|
||||
}
|
||||
|
||||
/** Minimum drawn size (pixels) below which we treat the gesture as a click. */
|
||||
const MIN_DRAG_PX = 5;
|
||||
|
||||
/** Default field size in PDF points, used for click-to-place. */
|
||||
const DEFAULT_SIZE_PTS: Record<CreatableFieldType, { w: number; h: number }> = {
|
||||
text: { w: 150, h: 24 },
|
||||
checkbox: { w: 16, h: 16 },
|
||||
combobox: { w: 150, h: 24 },
|
||||
listbox: { w: 150, h: 64 },
|
||||
radio: { w: 16, h: 16 },
|
||||
button: { w: 120, h: 28 },
|
||||
signature: { w: 200, h: 60 },
|
||||
};
|
||||
|
||||
export function FormFieldCreationOverlay({
|
||||
documentId,
|
||||
pageIndex,
|
||||
pageWidth,
|
||||
pageHeight,
|
||||
fileId,
|
||||
}: FormFieldCreationOverlayProps) {
|
||||
const {
|
||||
mode,
|
||||
creationType,
|
||||
setCreationType,
|
||||
pendingFields,
|
||||
addPendingField,
|
||||
state,
|
||||
forFileId,
|
||||
} = useFormFill();
|
||||
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const [dragRect, setDragRect] = useState<PixelRect | null>(null);
|
||||
const [guides, setGuides] = useState<SnapGuide[]>([]);
|
||||
const dragStartRef = useRef<{ x: number; y: number } | null>(null);
|
||||
|
||||
const { scaleX, scaleY, pageHeightPts, pageWidthPts } = usePageScale(
|
||||
documentId,
|
||||
pageIndex,
|
||||
pageWidth,
|
||||
pageHeight,
|
||||
);
|
||||
|
||||
// Pixel rects of the OTHER fields on this page, used as snap targets.
|
||||
const snapRects = useMemo<PixelRect[]>(() => {
|
||||
const rects: PixelRect[] = [];
|
||||
for (const field of state.fields) {
|
||||
for (const w of field.widgets ?? []) {
|
||||
if (w.pageIndex !== pageIndex) continue;
|
||||
rects.push({
|
||||
left: w.x * scaleX,
|
||||
top: w.y * scaleY,
|
||||
width: w.width * scaleX,
|
||||
height: w.height * scaleY,
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const pf of pendingFields) {
|
||||
if (pf.pageIndex !== pageIndex) continue;
|
||||
rects.push(backendRectToPixels(pf, scaleX, scaleY, pageHeightPts));
|
||||
}
|
||||
return rects;
|
||||
}, [state.fields, pendingFields, pageIndex, scaleX, scaleY, pageHeightPts]);
|
||||
|
||||
// Precompute snap edges once (not on every pointermove).
|
||||
const snapTargets = useMemo(() => collectSnapTargets(snapRects), [snapRects]);
|
||||
|
||||
const active = mode === "create" && creationType != null;
|
||||
|
||||
// Stale-file guard: don't draw on a page whose fields belong to another file.
|
||||
const fileMismatch =
|
||||
fileId != null && forFileId != null && fileId !== forFileId;
|
||||
|
||||
const localPoint = useCallback(
|
||||
(e: React.PointerEvent) => getLocalPoint(e, rootRef.current),
|
||||
[],
|
||||
);
|
||||
|
||||
const handlePointerDown = useCallback(
|
||||
(e: React.PointerEvent) => {
|
||||
if (!active) return;
|
||||
// Only start a drag on the bare overlay, never on a pending outline.
|
||||
if (e.target !== rootRef.current) return;
|
||||
e.preventDefault();
|
||||
rootRef.current?.setPointerCapture(e.pointerId);
|
||||
const p = localPoint(e);
|
||||
dragStartRef.current = p;
|
||||
setDragRect({ left: p.x, top: p.y, width: 0, height: 0 });
|
||||
},
|
||||
[active, localPoint],
|
||||
);
|
||||
|
||||
const handlePointerMove = useCallback(
|
||||
(e: React.PointerEvent) => {
|
||||
if (!active || !dragStartRef.current) return;
|
||||
const p = localPoint(e);
|
||||
const start = dragStartRef.current;
|
||||
let rect: PixelRect = {
|
||||
left: Math.min(start.x, p.x),
|
||||
top: Math.min(start.y, p.y),
|
||||
width: Math.abs(p.x - start.x),
|
||||
height: Math.abs(p.y - start.y),
|
||||
};
|
||||
const snapped = snapMove(rect, snapTargets, 6);
|
||||
rect = { ...rect, left: snapped.left, top: snapped.top };
|
||||
setGuides(snapped.guides);
|
||||
setDragRect(rect);
|
||||
},
|
||||
[active, localPoint, snapTargets],
|
||||
);
|
||||
|
||||
const finishDrag = useCallback(
|
||||
(e: React.PointerEvent) => {
|
||||
if (!active || !dragStartRef.current || !creationType) return;
|
||||
const start = dragStartRef.current;
|
||||
dragStartRef.current = null;
|
||||
setGuides([]);
|
||||
try {
|
||||
rootRef.current?.releasePointerCapture(e.pointerId);
|
||||
} catch {
|
||||
/* pointer capture may already be released */
|
||||
}
|
||||
|
||||
const current = dragRect;
|
||||
setDragRect(null);
|
||||
if (!current) return;
|
||||
|
||||
const dragged =
|
||||
current.width >= MIN_DRAG_PX && current.height >= MIN_DRAG_PX;
|
||||
|
||||
let pixelRect: PixelRect;
|
||||
if (dragged) {
|
||||
pixelRect = current;
|
||||
} else {
|
||||
// Click-to-place: default size centred on the click point.
|
||||
const def = DEFAULT_SIZE_PTS[creationType];
|
||||
const wPx = def.w * scaleX;
|
||||
const hPx = def.h * scaleY;
|
||||
pixelRect = {
|
||||
left: start.x,
|
||||
top: start.y,
|
||||
width: wPx,
|
||||
height: hPx,
|
||||
};
|
||||
}
|
||||
|
||||
pixelRect = clampPixelRect(pixelRect, pageWidth, pageHeight);
|
||||
const pdf = roundPdfRect(
|
||||
pixelsToBackendRect(pixelRect, scaleX, scaleY, pageHeightPts),
|
||||
);
|
||||
|
||||
addPendingField({
|
||||
type: creationType,
|
||||
pageIndex,
|
||||
x: pdf.x,
|
||||
y: pdf.y,
|
||||
width: pdf.width,
|
||||
height: pdf.height,
|
||||
});
|
||||
},
|
||||
[
|
||||
active,
|
||||
creationType,
|
||||
dragRect,
|
||||
scaleX,
|
||||
scaleY,
|
||||
pageHeightPts,
|
||||
pageWidth,
|
||||
pageHeight,
|
||||
pageIndex,
|
||||
addPendingField,
|
||||
],
|
||||
);
|
||||
|
||||
// Escape disarms placement / cancels the in-progress drag.
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") {
|
||||
dragStartRef.current = null;
|
||||
setDragRect(null);
|
||||
setGuides([]);
|
||||
setCreationType(null);
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [active, setCreationType]);
|
||||
|
||||
if (mode !== "create" || fileMismatch || !pageWidthPts) return null;
|
||||
|
||||
const pendingOnPage = pendingFields.filter((p) => p.pageIndex === pageIndex);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={rootRef}
|
||||
data-testid={`form-create-overlay-${pageIndex}`}
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={finishDrag}
|
||||
style={{
|
||||
position: "absolute",
|
||||
inset: 0,
|
||||
pointerEvents: active ? "auto" : "none",
|
||||
cursor: active ? "crosshair" : "default",
|
||||
userSelect: "none",
|
||||
WebkitUserSelect: "none",
|
||||
zIndex: 5,
|
||||
}}
|
||||
>
|
||||
{/* Already-queued fields on this page */}
|
||||
{pendingOnPage.map((pf) => {
|
||||
const r = backendRectToPixels(pf, scaleX, scaleY, pageHeightPts);
|
||||
return (
|
||||
<div
|
||||
key={pf.id}
|
||||
style={{
|
||||
position: "absolute",
|
||||
left: r.left,
|
||||
top: r.top,
|
||||
width: r.width,
|
||||
height: r.height,
|
||||
border: `1.5px dashed ${FORM_COLORS.accent}`,
|
||||
background: FORM_COLORS.accentFill,
|
||||
borderRadius: 2,
|
||||
pointerEvents: "none",
|
||||
boxSizing: "border-box",
|
||||
}}
|
||||
>
|
||||
<span
|
||||
style={{
|
||||
position: "absolute",
|
||||
top: -16,
|
||||
left: 0,
|
||||
fontSize: 10,
|
||||
lineHeight: "14px",
|
||||
padding: "0 4px",
|
||||
background: FORM_COLORS.accent,
|
||||
color: "#fff",
|
||||
borderRadius: 2,
|
||||
whiteSpace: "nowrap",
|
||||
}}
|
||||
>
|
||||
{pf.name}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Live drag preview */}
|
||||
{dragRect && creationType && (
|
||||
<div
|
||||
style={{
|
||||
position: "absolute",
|
||||
left: dragRect.left,
|
||||
top: dragRect.top,
|
||||
width: dragRect.width,
|
||||
height: dragRect.height,
|
||||
border: `2px dashed ${FORM_COLORS.accent}`,
|
||||
background: FORM_COLORS.accentFill,
|
||||
pointerEvents: "none",
|
||||
boxSizing: "border-box",
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Alignment guides */}
|
||||
<SnapGuides guides={guides} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default FormFieldCreationOverlay;
|
||||
@@ -0,0 +1,535 @@
|
||||
/**
|
||||
* FormFieldEditOverlay — select / move / resize layer for "modify" mode.
|
||||
*
|
||||
* Mounted per page. Renders every field's widget(s) on the page as an outline.
|
||||
* Clicking selects a field (also reflected in the modify panel). The selected
|
||||
* field, when it has a single widget, gets drag-to-move and resize handles;
|
||||
* geometry changes are staged via stageModification() in CropBox-relative,
|
||||
* lower-left-origin points. Fields marked for deletion render struck-through.
|
||||
*
|
||||
* Uses the same scale basis as FormFieldOverlay so edits round-trip exactly.
|
||||
*/
|
||||
import React, {
|
||||
useCallback,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
useEffect,
|
||||
} from "react";
|
||||
import { useFormFill } from "@app/tools/formFill/FormFillContext";
|
||||
import type { FormField } from "@app/tools/formFill/types";
|
||||
import {
|
||||
pixelsToBackendRect,
|
||||
backendRectToPixels,
|
||||
widgetRectToPixels,
|
||||
clampPixelRect,
|
||||
roundPdfRect,
|
||||
type PixelRect,
|
||||
} from "@app/tools/formFill/formCoordinateUtils";
|
||||
import {
|
||||
collectSnapTargets,
|
||||
snapMove,
|
||||
snapResize,
|
||||
type SnapGuide,
|
||||
} from "@app/tools/formFill/formSnapUtils";
|
||||
import { usePageScale, getLocalPoint } from "@app/tools/formFill/usePageScale";
|
||||
import { SnapGuides } from "@app/tools/formFill/SnapGuides";
|
||||
import { FORM_COLORS } from "@app/tools/formFill/formFieldColors";
|
||||
|
||||
interface FormFieldEditOverlayProps {
|
||||
documentId: string;
|
||||
pageIndex: number;
|
||||
pageWidth: number;
|
||||
pageHeight: number;
|
||||
fileId?: string | null;
|
||||
}
|
||||
|
||||
type HandleId = "nw" | "n" | "ne" | "e" | "se" | "s" | "sw" | "w";
|
||||
|
||||
const HANDLES: { id: HandleId; cursor: string }[] = [
|
||||
{ id: "nw", cursor: "nwse-resize" },
|
||||
{ id: "n", cursor: "ns-resize" },
|
||||
{ id: "ne", cursor: "nesw-resize" },
|
||||
{ id: "e", cursor: "ew-resize" },
|
||||
{ id: "se", cursor: "nwse-resize" },
|
||||
{ id: "s", cursor: "ns-resize" },
|
||||
{ id: "sw", cursor: "nesw-resize" },
|
||||
{ id: "w", cursor: "ew-resize" },
|
||||
];
|
||||
|
||||
const MIN_PX = 8;
|
||||
const HANDLE_SIZE = 9;
|
||||
|
||||
interface Interaction {
|
||||
kind: "move" | "resize";
|
||||
handle?: HandleId;
|
||||
fieldName: string;
|
||||
startX: number;
|
||||
startY: number;
|
||||
startRect: PixelRect;
|
||||
}
|
||||
|
||||
function handleEdges(h: HandleId) {
|
||||
return {
|
||||
left: h === "nw" || h === "w" || h === "sw",
|
||||
right: h === "ne" || h === "e" || h === "se",
|
||||
top: h === "nw" || h === "n" || h === "ne",
|
||||
bottom: h === "sw" || h === "s" || h === "se",
|
||||
};
|
||||
}
|
||||
|
||||
function handlePosition(h: HandleId, rect: PixelRect) {
|
||||
const cx = rect.left + rect.width / 2;
|
||||
const cy = rect.top + rect.height / 2;
|
||||
const map: Record<HandleId, { x: number; y: number }> = {
|
||||
nw: { x: rect.left, y: rect.top },
|
||||
n: { x: cx, y: rect.top },
|
||||
ne: { x: rect.left + rect.width, y: rect.top },
|
||||
e: { x: rect.left + rect.width, y: cy },
|
||||
se: { x: rect.left + rect.width, y: rect.top + rect.height },
|
||||
s: { x: cx, y: rect.top + rect.height },
|
||||
sw: { x: rect.left, y: rect.top + rect.height },
|
||||
w: { x: rect.left, y: cy },
|
||||
};
|
||||
return map[h];
|
||||
}
|
||||
|
||||
export function FormFieldEditOverlay({
|
||||
documentId,
|
||||
pageIndex,
|
||||
pageWidth,
|
||||
pageHeight,
|
||||
fileId,
|
||||
}: FormFieldEditOverlayProps) {
|
||||
const {
|
||||
mode,
|
||||
state,
|
||||
selectedFieldName,
|
||||
setSelectedField,
|
||||
modifiedFields,
|
||||
stageModification,
|
||||
deletedFieldNames,
|
||||
forFileId,
|
||||
} = useFormFill();
|
||||
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const interactionRef = useRef<Interaction | null>(null);
|
||||
const [liveRect, setLiveRect] = useState<PixelRect | null>(null);
|
||||
const [guides, setGuides] = useState<SnapGuide[]>([]);
|
||||
|
||||
const { scaleX, scaleY, pageHeightPts, pageWidthPts } = usePageScale(
|
||||
documentId,
|
||||
pageIndex,
|
||||
pageWidth,
|
||||
pageHeight,
|
||||
);
|
||||
|
||||
/** First-widget pixel rect for a field on this page, honouring staged geometry. */
|
||||
const fieldRect = useCallback(
|
||||
(field: FormField): PixelRect | null => {
|
||||
const widget = field.widgets?.find((w) => w.pageIndex === pageIndex);
|
||||
if (!widget) return null;
|
||||
const staged = modifiedFields[field.name];
|
||||
if (
|
||||
staged &&
|
||||
staged.x != null &&
|
||||
staged.y != null &&
|
||||
staged.width != null &&
|
||||
staged.height != null
|
||||
) {
|
||||
return backendRectToPixels(
|
||||
{
|
||||
x: staged.x,
|
||||
y: staged.y,
|
||||
width: staged.width,
|
||||
height: staged.height,
|
||||
},
|
||||
scaleX,
|
||||
scaleY,
|
||||
pageHeightPts,
|
||||
);
|
||||
}
|
||||
return widgetRectToPixels(widget, scaleX, scaleY);
|
||||
},
|
||||
[modifiedFields, pageIndex, scaleX, scaleY, pageHeightPts],
|
||||
);
|
||||
|
||||
const fieldsOnPage = useMemo(
|
||||
() =>
|
||||
state.fields.filter((f) =>
|
||||
f.widgets?.some((w) => w.pageIndex === pageIndex),
|
||||
),
|
||||
[state.fields, pageIndex],
|
||||
);
|
||||
|
||||
const selectedField = useMemo(
|
||||
() => fieldsOnPage.find((f) => f.name === selectedFieldName) ?? null,
|
||||
[fieldsOnPage, selectedFieldName],
|
||||
);
|
||||
|
||||
const selectedSingleWidget =
|
||||
!!selectedField && (selectedField.widgets?.length ?? 0) === 1;
|
||||
|
||||
const snapRects = useMemo<PixelRect[]>(() => {
|
||||
const rects: PixelRect[] = [];
|
||||
for (const f of fieldsOnPage) {
|
||||
if (f.name === selectedFieldName) continue;
|
||||
const r = fieldRect(f);
|
||||
if (r) rects.push(r);
|
||||
}
|
||||
return rects;
|
||||
}, [fieldsOnPage, selectedFieldName, fieldRect]);
|
||||
|
||||
// Precompute snap edges once (not on every pointermove).
|
||||
const snapTargets = useMemo(() => collectSnapTargets(snapRects), [snapRects]);
|
||||
|
||||
const localPoint = useCallback(
|
||||
(e: React.PointerEvent) => getLocalPoint(e, rootRef.current),
|
||||
[],
|
||||
);
|
||||
|
||||
const beginInteraction = useCallback(
|
||||
(
|
||||
e: React.PointerEvent,
|
||||
field: FormField,
|
||||
kind: "move" | "resize",
|
||||
handle?: HandleId,
|
||||
) => {
|
||||
const rect = fieldRect(field);
|
||||
if (!rect) return;
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
rootRef.current?.setPointerCapture(e.pointerId);
|
||||
const p = localPoint(e);
|
||||
interactionRef.current = {
|
||||
kind,
|
||||
handle,
|
||||
fieldName: field.name,
|
||||
startX: p.x,
|
||||
startY: p.y,
|
||||
startRect: rect,
|
||||
};
|
||||
setLiveRect(rect);
|
||||
},
|
||||
[fieldRect, localPoint],
|
||||
);
|
||||
|
||||
const handlePointerMove = useCallback(
|
||||
(e: React.PointerEvent) => {
|
||||
const it = interactionRef.current;
|
||||
if (!it) return;
|
||||
const p = localPoint(e);
|
||||
const dx = p.x - it.startX;
|
||||
const dy = p.y - it.startY;
|
||||
const targets = snapTargets;
|
||||
|
||||
if (it.kind === "move") {
|
||||
let rect: PixelRect = {
|
||||
...it.startRect,
|
||||
left: it.startRect.left + dx,
|
||||
top: it.startRect.top + dy,
|
||||
};
|
||||
const snapped = snapMove(rect, targets, 6);
|
||||
rect = { ...rect, left: snapped.left, top: snapped.top };
|
||||
rect = clampPixelRect(rect, pageWidth, pageHeight);
|
||||
setGuides(snapped.guides);
|
||||
setLiveRect(rect);
|
||||
} else if (it.kind === "resize" && it.handle) {
|
||||
const edges = handleEdges(it.handle);
|
||||
let { left, top, width, height } = it.startRect;
|
||||
if (edges.left) {
|
||||
left = it.startRect.left + dx;
|
||||
width = it.startRect.width - dx;
|
||||
}
|
||||
if (edges.right) {
|
||||
width = it.startRect.width + dx;
|
||||
}
|
||||
if (edges.top) {
|
||||
top = it.startRect.top + dy;
|
||||
height = it.startRect.height - dy;
|
||||
}
|
||||
if (edges.bottom) {
|
||||
height = it.startRect.height + dy;
|
||||
}
|
||||
// Keep a positive minimum, anchoring the opposite edge.
|
||||
if (width < MIN_PX) {
|
||||
if (edges.left)
|
||||
left = it.startRect.left + it.startRect.width - MIN_PX;
|
||||
width = MIN_PX;
|
||||
}
|
||||
if (height < MIN_PX) {
|
||||
if (edges.top) top = it.startRect.top + it.startRect.height - MIN_PX;
|
||||
height = MIN_PX;
|
||||
}
|
||||
let rect: PixelRect = { left, top, width, height };
|
||||
const snapped = snapResize(rect, edges, targets, 6);
|
||||
rect = snapped.rect;
|
||||
setGuides(snapped.guides);
|
||||
setLiveRect(rect);
|
||||
}
|
||||
},
|
||||
[localPoint, snapTargets, pageWidth, pageHeight],
|
||||
);
|
||||
|
||||
const endInteraction = useCallback(
|
||||
(e: React.PointerEvent) => {
|
||||
const it = interactionRef.current;
|
||||
interactionRef.current = null;
|
||||
setGuides([]);
|
||||
try {
|
||||
rootRef.current?.releasePointerCapture(e.pointerId);
|
||||
} catch {
|
||||
/* already released */
|
||||
}
|
||||
const rect = liveRect;
|
||||
setLiveRect(null);
|
||||
if (!it || !rect) return;
|
||||
// A plain click (select) produces no movement — don't stage a no-op change
|
||||
// that would mark the field dirty.
|
||||
const moved =
|
||||
Math.abs(rect.left - it.startRect.left) > 0.5 ||
|
||||
Math.abs(rect.top - it.startRect.top) > 0.5 ||
|
||||
Math.abs(rect.width - it.startRect.width) > 0.5 ||
|
||||
Math.abs(rect.height - it.startRect.height) > 0.5;
|
||||
if (!moved) return;
|
||||
const clamped = clampPixelRect(rect, pageWidth, pageHeight);
|
||||
const pdf = roundPdfRect(
|
||||
pixelsToBackendRect(clamped, scaleX, scaleY, pageHeightPts),
|
||||
);
|
||||
stageModification(it.fieldName, {
|
||||
pageIndex,
|
||||
x: pdf.x,
|
||||
y: pdf.y,
|
||||
width: pdf.width,
|
||||
height: pdf.height,
|
||||
});
|
||||
},
|
||||
[
|
||||
liveRect,
|
||||
pageWidth,
|
||||
pageHeight,
|
||||
scaleX,
|
||||
scaleY,
|
||||
pageHeightPts,
|
||||
pageIndex,
|
||||
stageModification,
|
||||
],
|
||||
);
|
||||
|
||||
// Escape clears the selection; arrow keys nudge the selected field.
|
||||
// (Each visible page mounts this overlay, but only the page whose widget
|
||||
// matches selectedField resolves a rect, so a nudge applies exactly once.)
|
||||
useEffect(() => {
|
||||
if (mode !== "modify") return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") {
|
||||
interactionRef.current = null;
|
||||
setLiveRect(null);
|
||||
setGuides([]);
|
||||
setSelectedField(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
!selectedField ||
|
||||
!selectedSingleWidget ||
|
||||
deletedFieldNames.includes(selectedField.name)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const step = e.shiftKey ? 10 : 1;
|
||||
let dx = 0;
|
||||
let dy = 0;
|
||||
switch (e.key) {
|
||||
case "ArrowLeft":
|
||||
dx = -step;
|
||||
break;
|
||||
case "ArrowRight":
|
||||
dx = step;
|
||||
break;
|
||||
case "ArrowUp":
|
||||
dy = -step;
|
||||
break;
|
||||
case "ArrowDown":
|
||||
dy = step;
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
const base = fieldRect(selectedField);
|
||||
if (!base) return; // selected field's widget isn't on this page
|
||||
e.preventDefault();
|
||||
const moved = clampPixelRect(
|
||||
{ ...base, left: base.left + dx, top: base.top + dy },
|
||||
pageWidth,
|
||||
pageHeight,
|
||||
);
|
||||
const pdf = roundPdfRect(
|
||||
pixelsToBackendRect(moved, scaleX, scaleY, pageHeightPts),
|
||||
);
|
||||
stageModification(selectedField.name, {
|
||||
pageIndex,
|
||||
x: pdf.x,
|
||||
y: pdf.y,
|
||||
width: pdf.width,
|
||||
height: pdf.height,
|
||||
});
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [
|
||||
mode,
|
||||
setSelectedField,
|
||||
selectedField,
|
||||
selectedSingleWidget,
|
||||
deletedFieldNames,
|
||||
fieldRect,
|
||||
pageWidth,
|
||||
pageHeight,
|
||||
scaleX,
|
||||
scaleY,
|
||||
pageHeightPts,
|
||||
pageIndex,
|
||||
stageModification,
|
||||
]);
|
||||
|
||||
const fileMismatch =
|
||||
fileId != null && forFileId != null && fileId !== forFileId;
|
||||
if (mode !== "modify" || fileMismatch || !pageWidthPts) return null;
|
||||
|
||||
const selectedRect = selectedField
|
||||
? (liveRect ?? fieldRect(selectedField))
|
||||
: null;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={rootRef}
|
||||
data-testid={`form-edit-overlay-${pageIndex}`}
|
||||
onPointerDown={(e) => {
|
||||
// Clicking empty space deselects. preventDefault stops the underlying
|
||||
// PDF text layer from starting a text selection.
|
||||
e.preventDefault();
|
||||
setSelectedField(null);
|
||||
}}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={endInteraction}
|
||||
style={{
|
||||
position: "absolute",
|
||||
inset: 0,
|
||||
pointerEvents: "auto",
|
||||
userSelect: "none",
|
||||
WebkitUserSelect: "none",
|
||||
zIndex: 5,
|
||||
}}
|
||||
>
|
||||
{fieldsOnPage.map((field) => {
|
||||
const rect =
|
||||
field.name === selectedFieldName && selectedRect
|
||||
? selectedRect
|
||||
: fieldRect(field);
|
||||
if (!rect) return null;
|
||||
const isSelected = field.name === selectedFieldName;
|
||||
const isDeleted = deletedFieldNames.includes(field.name);
|
||||
return (
|
||||
<div
|
||||
key={field.name}
|
||||
data-testid={`form-edit-field-${field.name}`}
|
||||
onPointerDown={(e) => {
|
||||
if (isDeleted) return;
|
||||
e.stopPropagation();
|
||||
const singleWidget = (field.widgets?.length ?? 0) === 1;
|
||||
// Select and (for single-widget fields) start moving in one
|
||||
// gesture — no need to click first then drag. A click without
|
||||
// movement just selects (endInteraction ignores zero-delta).
|
||||
if (field.name !== selectedFieldName)
|
||||
setSelectedField(field.name);
|
||||
if (singleWidget) beginInteraction(e, field, "move");
|
||||
}}
|
||||
style={{
|
||||
position: "absolute",
|
||||
left: rect.left,
|
||||
top: rect.top,
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
border: isDeleted
|
||||
? `1.5px dashed ${FORM_COLORS.danger}`
|
||||
: isSelected
|
||||
? `2px solid ${FORM_COLORS.accent}`
|
||||
: `1.5px solid ${FORM_COLORS.neutralBorder}`,
|
||||
background: isDeleted
|
||||
? FORM_COLORS.dangerFill
|
||||
: isSelected
|
||||
? FORM_COLORS.accentFill
|
||||
: FORM_COLORS.neutralFill,
|
||||
borderRadius: 2,
|
||||
boxSizing: "border-box",
|
||||
cursor: isDeleted
|
||||
? "not-allowed"
|
||||
: (field.widgets?.length ?? 0) === 1
|
||||
? "move"
|
||||
: "pointer",
|
||||
textDecoration: isDeleted ? "line-through" : undefined,
|
||||
}}
|
||||
>
|
||||
<span
|
||||
style={{
|
||||
position: "absolute",
|
||||
top: -16,
|
||||
left: 0,
|
||||
fontSize: 10,
|
||||
lineHeight: "14px",
|
||||
padding: "0 4px",
|
||||
background: isDeleted
|
||||
? FORM_COLORS.danger
|
||||
: isSelected
|
||||
? FORM_COLORS.accent
|
||||
: FORM_COLORS.neutralChip,
|
||||
color: "#fff",
|
||||
borderRadius: 2,
|
||||
whiteSpace: "nowrap",
|
||||
opacity: isSelected || isDeleted ? 1 : 0.75,
|
||||
}}
|
||||
>
|
||||
{field.label || field.name}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Resize handles for the selected single-widget field */}
|
||||
{selectedRect &&
|
||||
selectedSingleWidget &&
|
||||
!deletedFieldNames.includes(selectedFieldName ?? "") &&
|
||||
HANDLES.map((h) => {
|
||||
const pos = handlePosition(h.id, selectedRect);
|
||||
return (
|
||||
<div
|
||||
key={h.id}
|
||||
data-testid={`form-edit-handle-${h.id}`}
|
||||
onPointerDown={(e) =>
|
||||
selectedField &&
|
||||
beginInteraction(e, selectedField, "resize", h.id)
|
||||
}
|
||||
style={{
|
||||
position: "absolute",
|
||||
left: pos.x - HANDLE_SIZE / 2,
|
||||
top: pos.y - HANDLE_SIZE / 2,
|
||||
width: HANDLE_SIZE,
|
||||
height: HANDLE_SIZE,
|
||||
background: "#fff",
|
||||
border: `1.5px solid ${FORM_COLORS.accent}`,
|
||||
borderRadius: 2,
|
||||
cursor: h.cursor,
|
||||
boxSizing: "border-box",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Alignment guides */}
|
||||
<SnapGuides guides={guides} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default FormFieldEditOverlay;
|
||||
@@ -0,0 +1,373 @@
|
||||
/**
|
||||
* FormFieldModifyPanel — left-panel UI for "modify" mode.
|
||||
*
|
||||
* Lists existing fields grouped by page. Selecting one highlights it on the
|
||||
* page (via FormFieldEditOverlay) and reveals a property editor plus precise
|
||||
* X/Y/W/H inputs. Fields can be marked for deletion. All staged changes commit
|
||||
* in one round-trip.
|
||||
*/
|
||||
import React, { useCallback, useEffect, useMemo, useRef } from "react";
|
||||
import {
|
||||
Text,
|
||||
Button,
|
||||
Group,
|
||||
Alert,
|
||||
Collapse,
|
||||
ActionIcon,
|
||||
Paper,
|
||||
NumberInput,
|
||||
ScrollArea,
|
||||
Tooltip,
|
||||
} from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutlineRounded";
|
||||
import RestoreIcon from "@mui/icons-material/Restore";
|
||||
import WarningAmberIcon from "@mui/icons-material/WarningAmber";
|
||||
import { useFormFill } from "@app/tools/formFill/FormFillContext";
|
||||
import type {
|
||||
FormField,
|
||||
ModifyFieldDefinition,
|
||||
} from "@app/tools/formFill/types";
|
||||
import {
|
||||
FIELD_TYPE_ICON,
|
||||
FIELD_TYPE_COLOR,
|
||||
} from "@app/tools/formFill/fieldMeta";
|
||||
import {
|
||||
FormFieldPropertyEditor,
|
||||
type EditableFieldProps,
|
||||
} from "@app/tools/formFill/FormFieldPropertyEditor";
|
||||
import { useFormCommit } from "@app/tools/formFill/useFormCommit";
|
||||
import styles from "@app/tools/formFill/FormFill.module.css";
|
||||
|
||||
interface FormFieldModifyPanelProps {
|
||||
currentFile: File | Blob | null;
|
||||
onApplied?: (blob: Blob) => void;
|
||||
}
|
||||
|
||||
/** Current backend (lower-left origin) coords for a field's first widget. */
|
||||
function currentCoords(field: FormField, staged?: ModifyFieldDefinition) {
|
||||
const w = field.widgets?.[0];
|
||||
if (!w) return null;
|
||||
if (
|
||||
staged &&
|
||||
staged.x != null &&
|
||||
staged.y != null &&
|
||||
staged.width != null &&
|
||||
staged.height != null
|
||||
) {
|
||||
return {
|
||||
x: staged.x,
|
||||
y: staged.y,
|
||||
width: staged.width,
|
||||
height: staged.height,
|
||||
};
|
||||
}
|
||||
const cropH = w.cropBoxHeight ?? 0;
|
||||
return {
|
||||
x: w.x,
|
||||
y: cropH ? cropH - w.y - w.height : w.y,
|
||||
width: w.width,
|
||||
height: w.height,
|
||||
};
|
||||
}
|
||||
|
||||
export function FormFieldModifyPanel({
|
||||
currentFile,
|
||||
onApplied,
|
||||
}: FormFieldModifyPanelProps) {
|
||||
const { t } = useTranslation();
|
||||
const {
|
||||
state,
|
||||
selectedFieldName,
|
||||
setSelectedField,
|
||||
modifiedFields,
|
||||
stageModification,
|
||||
deletedFieldNames,
|
||||
toggleFieldDeleted,
|
||||
commitModifications,
|
||||
hasUncommittedChanges,
|
||||
} = useFormFill();
|
||||
|
||||
const { committing, error, commit } = useFormCommit(onApplied);
|
||||
const selectedRowRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Group fields by their first widget's page.
|
||||
const { sortedPages, fieldsByPage } = useMemo(() => {
|
||||
const byPage = new Map<number, FormField[]>();
|
||||
for (const field of state.fields) {
|
||||
const pageIndex = field.widgets?.[0]?.pageIndex ?? 0;
|
||||
if (!byPage.has(pageIndex)) byPage.set(pageIndex, []);
|
||||
byPage.get(pageIndex)!.push(field);
|
||||
}
|
||||
return {
|
||||
sortedPages: Array.from(byPage.keys()).sort((a, b) => a - b),
|
||||
fieldsByPage: byPage,
|
||||
};
|
||||
}, [state.fields]);
|
||||
|
||||
// Auto-scroll the list to the selected field (e.g. selected via the overlay).
|
||||
useEffect(() => {
|
||||
if (selectedFieldName && selectedRowRef.current) {
|
||||
selectedRowRef.current.scrollIntoView({
|
||||
behavior: "smooth",
|
||||
block: "nearest",
|
||||
});
|
||||
}
|
||||
}, [selectedFieldName]);
|
||||
|
||||
const changeCount =
|
||||
Object.keys(modifiedFields).length + deletedFieldNames.length;
|
||||
|
||||
const handleCommit = useCallback(() => {
|
||||
if (!currentFile || !hasUncommittedChanges) return;
|
||||
commit(
|
||||
() => commitModifications(currentFile),
|
||||
"formFill.modify.failed",
|
||||
"Failed to save changes",
|
||||
);
|
||||
}, [currentFile, hasUncommittedChanges, commitModifications, commit]);
|
||||
|
||||
const editorValue = useCallback(
|
||||
(field: FormField): EditableFieldProps => {
|
||||
const staged = modifiedFields[field.name];
|
||||
return {
|
||||
name: staged?.name ?? field.name,
|
||||
label: staged?.label ?? field.label,
|
||||
type: staged?.type ?? field.type,
|
||||
defaultValue: staged?.defaultValue ?? field.value,
|
||||
tooltip: staged?.tooltip ?? field.tooltip ?? "",
|
||||
fontSize: staged?.fontSize ?? field.widgets?.[0]?.fontSize,
|
||||
required: staged?.required ?? field.required,
|
||||
readOnly: staged?.readOnly ?? field.readOnly,
|
||||
multiline: staged?.multiline ?? field.multiline,
|
||||
multiSelect: staged?.multiSelect ?? field.multiSelect,
|
||||
options: staged?.options ?? field.options ?? [],
|
||||
};
|
||||
},
|
||||
[modifiedFields],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<div className={styles.header}>
|
||||
<Text size="xs" c="dimmed">
|
||||
{t(
|
||||
"formFill.modify.hint",
|
||||
"Select a field to edit its properties, drag it on the page, or delete it.",
|
||||
)}
|
||||
</Text>
|
||||
|
||||
{error && (
|
||||
<Alert
|
||||
icon={<WarningAmberIcon sx={{ fontSize: 16 }} />}
|
||||
color="red"
|
||||
variant="light"
|
||||
p="xs"
|
||||
radius="sm"
|
||||
>
|
||||
<Text size="xs">{error}</Text>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Button
|
||||
size="xs"
|
||||
onClick={handleCommit}
|
||||
loading={committing}
|
||||
disabled={!currentFile || !hasUncommittedChanges}
|
||||
data-testid="form-modify-commit"
|
||||
>
|
||||
{t("formFill.modify.commit", "Save {{count}} change(s)", {
|
||||
count: changeCount,
|
||||
})}
|
||||
</Button>
|
||||
|
||||
{state.fields.length === 0 && !state.loading && (
|
||||
<Text size="xs" c="dimmed" ta="center" py="md">
|
||||
{t("formFill.modify.empty", "This PDF has no form fields yet.")}
|
||||
</Text>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ScrollArea className={styles.fieldList}>
|
||||
<div className={styles.fieldListInner}>
|
||||
{sortedPages.map((pageIdx, i) => (
|
||||
<React.Fragment key={pageIdx}>
|
||||
<div
|
||||
className={styles.pageDivider}
|
||||
style={i === 0 ? { marginTop: 0 } : undefined}
|
||||
>
|
||||
<Text className={styles.pageDividerLabel}>
|
||||
{t("formFill.page", "Page")} {pageIdx + 1}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
{fieldsByPage.get(pageIdx)!.map((field) => {
|
||||
const selected = selectedFieldName === field.name;
|
||||
const deleted = deletedFieldNames.includes(field.name);
|
||||
const coords = currentCoords(field, modifiedFields[field.name]);
|
||||
return (
|
||||
<Paper
|
||||
key={field.name}
|
||||
ref={selected ? selectedRowRef : undefined}
|
||||
withBorder
|
||||
p={6}
|
||||
radius="sm"
|
||||
style={{
|
||||
cursor: "pointer",
|
||||
borderColor: selected
|
||||
? "var(--mantine-color-blue-5)"
|
||||
: undefined,
|
||||
opacity: deleted ? 0.55 : 1,
|
||||
}}
|
||||
onClick={() =>
|
||||
setSelectedField(selected ? null : field.name)
|
||||
}
|
||||
data-testid={`form-modify-row-${field.name}`}
|
||||
>
|
||||
<Group gap={6} wrap="nowrap" justify="space-between">
|
||||
<Group gap={6} wrap="nowrap" style={{ minWidth: 0 }}>
|
||||
<span
|
||||
style={{
|
||||
color: `var(--mantine-color-${FIELD_TYPE_COLOR[field.type]}-6)`,
|
||||
display: "flex",
|
||||
}}
|
||||
>
|
||||
{FIELD_TYPE_ICON[field.type]}
|
||||
</span>
|
||||
<Text
|
||||
size="xs"
|
||||
truncate
|
||||
td={deleted ? "line-through" : undefined}
|
||||
>
|
||||
{field.label || field.name}
|
||||
</Text>
|
||||
</Group>
|
||||
<Tooltip
|
||||
label={
|
||||
deleted
|
||||
? t("formFill.modify.restore", "Restore")
|
||||
: t("formFill.modify.delete", "Delete")
|
||||
}
|
||||
withArrow
|
||||
>
|
||||
<ActionIcon
|
||||
size="sm"
|
||||
variant="subtle"
|
||||
color={deleted ? "blue" : "red"}
|
||||
aria-label={
|
||||
deleted
|
||||
? t("formFill.modify.restore", "Restore")
|
||||
: t("formFill.modify.delete", "Delete")
|
||||
}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
toggleFieldDeleted(field.name);
|
||||
}}
|
||||
data-testid={`form-modify-delete-${field.name}`}
|
||||
>
|
||||
{deleted ? (
|
||||
<RestoreIcon sx={{ fontSize: 16 }} />
|
||||
) : (
|
||||
<DeleteOutlineIcon sx={{ fontSize: 16 }} />
|
||||
)}
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
|
||||
<Collapse in={selected && !deleted}>
|
||||
<div
|
||||
style={{ marginTop: 8 }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<FormFieldPropertyEditor
|
||||
value={editorValue(field)}
|
||||
onChange={(patch) =>
|
||||
stageModification(
|
||||
field.name,
|
||||
patch as Partial<ModifyFieldDefinition>,
|
||||
)
|
||||
}
|
||||
showName
|
||||
allowTypeChange
|
||||
/>
|
||||
|
||||
{coords && (
|
||||
<Group gap={6} mt="xs" grow>
|
||||
<NumberInput
|
||||
size="xs"
|
||||
label="X"
|
||||
value={Math.round(coords.x)}
|
||||
onChange={(v) =>
|
||||
typeof v === "number" &&
|
||||
stageModification(field.name, {
|
||||
pageIndex: pageIdx,
|
||||
x: v,
|
||||
y: coords.y,
|
||||
width: coords.width,
|
||||
height: coords.height,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<NumberInput
|
||||
size="xs"
|
||||
label="Y"
|
||||
value={Math.round(coords.y)}
|
||||
onChange={(v) =>
|
||||
typeof v === "number" &&
|
||||
stageModification(field.name, {
|
||||
pageIndex: pageIdx,
|
||||
x: coords.x,
|
||||
y: v,
|
||||
width: coords.width,
|
||||
height: coords.height,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<NumberInput
|
||||
size="xs"
|
||||
label="W"
|
||||
value={Math.round(coords.width)}
|
||||
min={1}
|
||||
onChange={(v) =>
|
||||
typeof v === "number" &&
|
||||
stageModification(field.name, {
|
||||
pageIndex: pageIdx,
|
||||
x: coords.x,
|
||||
y: coords.y,
|
||||
width: v,
|
||||
height: coords.height,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<NumberInput
|
||||
size="xs"
|
||||
label="H"
|
||||
value={Math.round(coords.height)}
|
||||
min={1}
|
||||
onChange={(v) =>
|
||||
typeof v === "number" &&
|
||||
stageModification(field.name, {
|
||||
pageIndex: pageIdx,
|
||||
x: coords.x,
|
||||
y: coords.y,
|
||||
width: coords.width,
|
||||
height: v,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</Group>
|
||||
)}
|
||||
</div>
|
||||
</Collapse>
|
||||
</Paper>
|
||||
);
|
||||
})}
|
||||
</React.Fragment>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default FormFieldModifyPanel;
|
||||
@@ -0,0 +1,356 @@
|
||||
/**
|
||||
* FormFieldPropertyEditor — shared property form used by both the create and
|
||||
* modify panels. It edits the subset of attributes common to new and existing
|
||||
* fields and reports changes as partial patches via onChange.
|
||||
*/
|
||||
import React from "react";
|
||||
import {
|
||||
Stack,
|
||||
TextInput,
|
||||
NumberInput,
|
||||
Select,
|
||||
Switch,
|
||||
Group,
|
||||
ActionIcon,
|
||||
Button,
|
||||
Text,
|
||||
Alert,
|
||||
} from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import AddIcon from "@mui/icons-material/Add";
|
||||
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutlineRounded";
|
||||
import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
|
||||
|
||||
export interface EditableFieldProps {
|
||||
name?: string;
|
||||
label?: string;
|
||||
type: string;
|
||||
defaultValue?: string;
|
||||
tooltip?: string;
|
||||
fontSize?: number;
|
||||
required?: boolean;
|
||||
readOnly?: boolean;
|
||||
multiline?: boolean;
|
||||
multiSelect?: boolean;
|
||||
options?: string[];
|
||||
maxLength?: number;
|
||||
buttonAction?: string;
|
||||
}
|
||||
|
||||
interface FormFieldPropertyEditorProps {
|
||||
value: EditableFieldProps;
|
||||
onChange: (patch: Partial<EditableFieldProps>) => void;
|
||||
/** Show the field-name input (create mode). */
|
||||
showName?: boolean;
|
||||
/** Allow changing the field type (modify mode). */
|
||||
allowTypeChange?: boolean;
|
||||
}
|
||||
|
||||
const TYPE_LABEL: Record<string, string> = {
|
||||
text: "Text",
|
||||
checkbox: "Checkbox",
|
||||
combobox: "Dropdown",
|
||||
listbox: "List box",
|
||||
radio: "Radio group",
|
||||
button: "Button",
|
||||
signature: "Signature",
|
||||
};
|
||||
|
||||
// Type-change is only safe between the "simple" single-widget types; retyping
|
||||
// into radio/button/signature needs dedicated creation, so it's create-only.
|
||||
const TYPE_CHANGE_OPTIONS = ["text", "checkbox", "combobox", "listbox"];
|
||||
|
||||
/** Split a stored buttonAction string into a kind + optional url. */
|
||||
function parseButtonAction(action: string | undefined): {
|
||||
kind: string;
|
||||
url: string;
|
||||
} {
|
||||
if (!action) return { kind: "none", url: "" };
|
||||
if (action === "reset") return { kind: "reset", url: "" };
|
||||
if (action === "print") return { kind: "print", url: "" };
|
||||
if (action.startsWith("uri:")) return { kind: "uri", url: action.slice(4) };
|
||||
if (action.startsWith("submit:"))
|
||||
return { kind: "submit", url: action.slice(7) };
|
||||
return { kind: "none", url: "" };
|
||||
}
|
||||
|
||||
function buildButtonAction(kind: string, url: string): string {
|
||||
switch (kind) {
|
||||
case "reset":
|
||||
return "reset";
|
||||
case "print":
|
||||
return "print";
|
||||
case "uri":
|
||||
return `uri:${url}`;
|
||||
case "submit":
|
||||
return `submit:${url}`;
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
export function FormFieldPropertyEditor({
|
||||
value,
|
||||
onChange,
|
||||
showName = true,
|
||||
allowTypeChange = false,
|
||||
}: FormFieldPropertyEditorProps) {
|
||||
const { t } = useTranslation();
|
||||
const hasOptions =
|
||||
value.type === "combobox" ||
|
||||
value.type === "listbox" ||
|
||||
value.type === "radio";
|
||||
const isVariableText =
|
||||
value.type === "text" ||
|
||||
value.type === "combobox" ||
|
||||
value.type === "listbox";
|
||||
const isText = value.type === "text";
|
||||
const isButton = value.type === "button";
|
||||
const isSignature = value.type === "signature";
|
||||
const isFillable = !isButton && !isSignature;
|
||||
const canRetype = TYPE_CHANGE_OPTIONS.includes(value.type);
|
||||
|
||||
const updateOption = (index: number, next: string) => {
|
||||
const options = [...(value.options ?? [])];
|
||||
options[index] = next;
|
||||
onChange({ options });
|
||||
};
|
||||
const addOption = () => onChange({ options: [...(value.options ?? []), ""] });
|
||||
const removeOption = (index: number) =>
|
||||
onChange({ options: (value.options ?? []).filter((_, i) => i !== index) });
|
||||
|
||||
const action = parseButtonAction(value.buttonAction);
|
||||
|
||||
return (
|
||||
<Stack gap="xs">
|
||||
{isSignature && (
|
||||
<Alert
|
||||
color="blue"
|
||||
variant="light"
|
||||
p="xs"
|
||||
radius="sm"
|
||||
icon={<InfoOutlinedIcon sx={{ fontSize: 16 }} />}
|
||||
>
|
||||
<Text size="xs">
|
||||
{t(
|
||||
"formFill.editor.signatureNote",
|
||||
"Placeholder only - you don't sign here. It marks where a signature belongs so a PDF signer (Adobe Acrobat, a signing service, etc.) places the signature in this spot when the document is signed.",
|
||||
)}
|
||||
</Text>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{showName && (
|
||||
<TextInput
|
||||
size="xs"
|
||||
label={t("formFill.editor.name", "Field name")}
|
||||
value={value.name ?? ""}
|
||||
onChange={(e) => onChange({ name: e.currentTarget.value })}
|
||||
/>
|
||||
)}
|
||||
|
||||
<TextInput
|
||||
size="xs"
|
||||
label={
|
||||
isButton
|
||||
? t("formFill.editor.caption", "Button caption")
|
||||
: t("formFill.editor.label", "Label")
|
||||
}
|
||||
value={value.label ?? ""}
|
||||
onChange={(e) => onChange({ label: e.currentTarget.value })}
|
||||
/>
|
||||
|
||||
{allowTypeChange && (
|
||||
<Select
|
||||
size="xs"
|
||||
label={t("formFill.editor.type", "Type")}
|
||||
value={canRetype ? value.type : null}
|
||||
data={TYPE_CHANGE_OPTIONS.map((tp) => ({
|
||||
value: tp,
|
||||
label: TYPE_LABEL[tp],
|
||||
}))}
|
||||
disabled={!canRetype}
|
||||
placeholder={canRetype ? undefined : TYPE_LABEL[value.type]}
|
||||
onChange={(v) => v && onChange({ type: v })}
|
||||
comboboxProps={{ withinPortal: true }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{hasOptions && (
|
||||
<Stack gap={4}>
|
||||
<Text size="xs" fw={600}>
|
||||
{t("formFill.editor.options", "Options")}
|
||||
</Text>
|
||||
{(value.options ?? []).length === 0 && (
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("formFill.editor.optionsEmpty", "Add at least one option.")}
|
||||
</Text>
|
||||
)}
|
||||
{(value.options ?? []).map((opt, i) => (
|
||||
<Group key={i} gap={4} wrap="nowrap">
|
||||
<TextInput
|
||||
size="xs"
|
||||
style={{ flex: 1 }}
|
||||
value={opt}
|
||||
placeholder={t(
|
||||
"formFill.editor.optionPlaceholder",
|
||||
"Option {{n}}",
|
||||
{
|
||||
n: i + 1,
|
||||
},
|
||||
)}
|
||||
onChange={(e) => updateOption(i, e.currentTarget.value)}
|
||||
/>
|
||||
<ActionIcon
|
||||
size="sm"
|
||||
variant="subtle"
|
||||
color="red"
|
||||
aria-label={t("formFill.editor.removeOption", "Remove option")}
|
||||
onClick={() => removeOption(i)}
|
||||
>
|
||||
<DeleteOutlineIcon sx={{ fontSize: 16 }} />
|
||||
</ActionIcon>
|
||||
</Group>
|
||||
))}
|
||||
<Button
|
||||
size="compact-xs"
|
||||
variant="light"
|
||||
leftSection={<AddIcon sx={{ fontSize: 14 }} />}
|
||||
onClick={addOption}
|
||||
>
|
||||
{t("formFill.editor.addOption", "Add option")}
|
||||
</Button>
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
{isFillable && (
|
||||
<TextInput
|
||||
size="xs"
|
||||
label={t("formFill.editor.defaultValue", "Default value")}
|
||||
value={value.defaultValue ?? ""}
|
||||
onChange={(e) => onChange({ defaultValue: e.currentTarget.value })}
|
||||
/>
|
||||
)}
|
||||
|
||||
<TextInput
|
||||
size="xs"
|
||||
label={t("formFill.editor.tooltip", "Tooltip")}
|
||||
value={value.tooltip ?? ""}
|
||||
onChange={(e) => onChange({ tooltip: e.currentTarget.value })}
|
||||
/>
|
||||
|
||||
{isButton && (
|
||||
<>
|
||||
<Select
|
||||
size="xs"
|
||||
label={t("formFill.editor.action", "Button action")}
|
||||
value={action.kind}
|
||||
data={[
|
||||
{ value: "none", label: t("formFill.editor.actionNone", "None") },
|
||||
{
|
||||
value: "reset",
|
||||
label: t("formFill.editor.actionReset", "Reset form"),
|
||||
},
|
||||
{
|
||||
value: "print",
|
||||
label: t("formFill.editor.actionPrint", "Print"),
|
||||
},
|
||||
{
|
||||
value: "uri",
|
||||
label: t("formFill.editor.actionUri", "Open URL"),
|
||||
},
|
||||
{
|
||||
value: "submit",
|
||||
label: t("formFill.editor.actionSubmit", "Submit to URL"),
|
||||
},
|
||||
]}
|
||||
onChange={(v) =>
|
||||
onChange({
|
||||
buttonAction: buildButtonAction(v ?? "none", action.url),
|
||||
})
|
||||
}
|
||||
comboboxProps={{ withinPortal: true }}
|
||||
/>
|
||||
{(action.kind === "uri" || action.kind === "submit") && (
|
||||
<TextInput
|
||||
size="xs"
|
||||
label={t("formFill.editor.actionUrl", "URL")}
|
||||
value={action.url}
|
||||
onChange={(e) =>
|
||||
onChange({
|
||||
buttonAction: buildButtonAction(
|
||||
action.kind,
|
||||
e.currentTarget.value,
|
||||
),
|
||||
})
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{isVariableText && (
|
||||
<NumberInput
|
||||
size="xs"
|
||||
label={t("formFill.editor.fontSize", "Font size")}
|
||||
value={value.fontSize ?? ""}
|
||||
min={1}
|
||||
max={144}
|
||||
onChange={(v) =>
|
||||
onChange({ fontSize: typeof v === "number" ? v : undefined })
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isText && (
|
||||
<>
|
||||
<Switch
|
||||
size="xs"
|
||||
label={t("formFill.editor.multiline", "Multi-line")}
|
||||
checked={!!value.multiline}
|
||||
onChange={(e) => onChange({ multiline: e.currentTarget.checked })}
|
||||
/>
|
||||
<NumberInput
|
||||
size="xs"
|
||||
label={t("formFill.editor.maxLength", "Max length (comb)")}
|
||||
value={value.maxLength ?? ""}
|
||||
min={0}
|
||||
max={500}
|
||||
onChange={(v) =>
|
||||
onChange({ maxLength: typeof v === "number" ? v : undefined })
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{value.type === "listbox" && (
|
||||
<Switch
|
||||
size="xs"
|
||||
label={t("formFill.editor.multiSelect", "Allow multiple selection")}
|
||||
checked={!!value.multiSelect}
|
||||
onChange={(e) => onChange({ multiSelect: e.currentTarget.checked })}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isFillable && (
|
||||
<Switch
|
||||
size="xs"
|
||||
label={t("formFill.editor.required", "Required")}
|
||||
checked={!!value.required}
|
||||
onChange={(e) => onChange({ required: e.currentTarget.checked })}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isFillable && (
|
||||
<Switch
|
||||
size="xs"
|
||||
label={t("formFill.editor.readOnly", "Read-only")}
|
||||
checked={!!value.readOnly}
|
||||
onChange={(e) => onChange({ readOnly: e.currentTarget.checked })}
|
||||
/>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
export default FormFieldPropertyEditor;
|
||||
@@ -49,12 +49,23 @@
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
/* Selected tab: the indicator is a saturated blue in both colour schemes, so the
|
||||
label and its icon must flip to white for legible contrast. Without this the
|
||||
muted-grey text sat on the blue and read poorly, especially in dark mode. */
|
||||
.segmentedInnerLabel[data-active] {
|
||||
color: var(--mantine-color-white);
|
||||
}
|
||||
|
||||
.modeTabIcon {
|
||||
font-size: 1rem !important;
|
||||
margin-bottom: 0.125rem;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.segmentedInnerLabel[data-active] .modeTabIcon {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.header {
|
||||
flex-shrink: 0;
|
||||
padding: 0.75rem 1rem;
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
/**
|
||||
* FormFill: The tool component that renders in the left ToolPanel
|
||||
* when the "Fill Form" tool is selected.
|
||||
* FormFill: The "Form Editor" tool component that renders in the left ToolPanel
|
||||
* when the formFill tool is selected.
|
||||
*
|
||||
* Redesigned with:
|
||||
* - Mode tabs for future extensibility (Fill / Make / Batch / Modify)
|
||||
* - Clean visual hierarchy with proper spacing
|
||||
* - Shared FieldInput component (eliminates duplication)
|
||||
* - CSS module for theme-consistent styling
|
||||
* - Status bar at bottom for contextual info
|
||||
* Modes:
|
||||
* - Fill: enter values into existing fields
|
||||
* - Create: draw new fields (text/checkbox/dropdown/list/radio/button/signature)
|
||||
* - Modify: select, move/resize, edit properties, and delete existing fields
|
||||
*/
|
||||
import React, {
|
||||
useEffect,
|
||||
@@ -24,6 +22,7 @@ import {
|
||||
ScrollArea,
|
||||
Progress,
|
||||
Tooltip,
|
||||
SegmentedControl,
|
||||
} from "@mantine/core";
|
||||
import { Button } from "@app/ui/Button";
|
||||
import { ActionIcon } from "@app/ui/ActionIcon";
|
||||
@@ -50,7 +49,6 @@ import RefreshIcon from "@mui/icons-material/Refresh";
|
||||
import WarningAmberIcon from "@mui/icons-material/WarningAmber";
|
||||
import EditNoteIcon from "@mui/icons-material/EditNote";
|
||||
import PostAddIcon from "@mui/icons-material/PostAdd";
|
||||
import FileCopyIcon from "@mui/icons-material/FileCopy";
|
||||
import BuildCircleIcon from "@mui/icons-material/BuildCircle";
|
||||
import DescriptionIcon from "@mui/icons-material/Description";
|
||||
import FileDownloadIcon from "@mui/icons-material/FileDownload";
|
||||
@@ -58,65 +56,22 @@ import {
|
||||
extractFormFieldsCsv,
|
||||
extractFormFieldsXlsx,
|
||||
} from "@app/tools/formFill/formApi";
|
||||
import type { FormMode } from "@app/tools/formFill/types";
|
||||
import { FormFieldCreatePanel } from "@app/tools/formFill/FormFieldCreatePanel";
|
||||
import { FormFieldModifyPanel } from "@app/tools/formFill/FormFieldModifyPanel";
|
||||
import { dispatchFormApply } from "@app/tools/formFill/formFillEvents";
|
||||
import styles from "@app/tools/formFill/FormFill.module.css";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mode tabs — extensible for future form tools
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type FormMode = "fill" | "make" | "batch" | "modify";
|
||||
|
||||
interface ModeTabDef {
|
||||
id: FormMode;
|
||||
label: string;
|
||||
icon: React.ReactNode;
|
||||
ready: boolean;
|
||||
}
|
||||
|
||||
const _MODE_TABS: ModeTabDef[] = [
|
||||
{
|
||||
id: "fill",
|
||||
label: "Fill",
|
||||
icon: <EditNoteIcon className={styles.modeTabIcon} />,
|
||||
ready: true,
|
||||
},
|
||||
{
|
||||
id: "make",
|
||||
label: "Create",
|
||||
icon: <PostAddIcon className={styles.modeTabIcon} />,
|
||||
ready: false,
|
||||
},
|
||||
{
|
||||
id: "batch",
|
||||
label: "Batch",
|
||||
icon: <FileCopyIcon className={styles.modeTabIcon} />,
|
||||
ready: false,
|
||||
},
|
||||
{
|
||||
id: "modify",
|
||||
label: "Modify",
|
||||
icon: <BuildCircleIcon className={styles.modeTabIcon} />,
|
||||
ready: false,
|
||||
},
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Coming-soon placeholder for unimplemented tabs
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// ComingSoonPlaceholder — re-enable when mode tabs are exposed
|
||||
// function ComingSoonPlaceholder({ mode }: { mode: ModeTabDef }) {
|
||||
// return (
|
||||
// <div className={styles.comingSoon}>
|
||||
// <DescriptionIcon className={styles.comingSoonIcon} />
|
||||
// <div className={styles.comingSoonTitle}>{mode.label} Forms</div>
|
||||
// <div className={styles.comingSoonDesc}>
|
||||
// This feature is coming soon. Stay tuned!
|
||||
// </div>
|
||||
// </div>
|
||||
// );
|
||||
// }
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Main FormFill component
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -133,18 +88,36 @@ const FormFill = (_props: BaseToolProps) => {
|
||||
setValue,
|
||||
setActiveField,
|
||||
validateForm,
|
||||
mode,
|
||||
setMode,
|
||||
} = useFormFill();
|
||||
|
||||
const MODE_TABS: ModeTabDef[] = useMemo(
|
||||
() => [
|
||||
{
|
||||
id: "fill",
|
||||
label: t("formFill.mode.fill", "Fill"),
|
||||
icon: <EditNoteIcon className={styles.modeTabIcon} />,
|
||||
},
|
||||
{
|
||||
id: "create",
|
||||
label: t("formFill.mode.create", "Create"),
|
||||
icon: <PostAddIcon className={styles.modeTabIcon} />,
|
||||
},
|
||||
{
|
||||
id: "modify",
|
||||
label: t("formFill.mode.modify", "Modify"),
|
||||
icon: <BuildCircleIcon className={styles.modeTabIcon} />,
|
||||
},
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
const allValues = useAllFormValues();
|
||||
const { validationErrors } = formState;
|
||||
|
||||
const { scrollActions } = useViewer();
|
||||
|
||||
// Mode system is temporarily restricted to 'fill' only.
|
||||
// Other modes (make, batch, modify) are defined above but not yet exposed in the UI.
|
||||
// When ready, uncomment the SegmentedControl and mode state below.
|
||||
// const [mode, setMode] = useState<FormMode>('fill');
|
||||
const mode: FormMode = "fill";
|
||||
const [flatten, setFlatten] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [extracting, setExtracting] = useState(false);
|
||||
@@ -262,14 +235,11 @@ const FormFill = (_props: BaseToolProps) => {
|
||||
// Track the flatten value at save so toggling it later re-enables Save
|
||||
setLastSavedFlatten(flatten);
|
||||
|
||||
// Dispatch to the viewer's handleFormApply via custom event.
|
||||
// This ensures the viewer tracks the new file ID, preserves
|
||||
// scroll position and rotation — instead of our own consumeFiles
|
||||
// call which would lose the viewer's file tracking context.
|
||||
const event = new CustomEvent("formfill:apply", {
|
||||
detail: { blob: filledBlob },
|
||||
});
|
||||
window.dispatchEvent(event);
|
||||
// Hand the filled PDF to the viewer's handleFormApply via custom event.
|
||||
// This ensures the viewer tracks the new file ID and preserves scroll
|
||||
// position and rotation, instead of our own consumeFiles call which
|
||||
// would lose the viewer's file tracking context.
|
||||
dispatchFormApply(filledBlob);
|
||||
} catch (err) {
|
||||
const status = isAxiosError(err) ? err.response?.status : undefined;
|
||||
const message =
|
||||
@@ -389,7 +359,7 @@ const FormFill = (_props: BaseToolProps) => {
|
||||
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
{/* ---- Mode selection (commented out until additional modes are implemented) ----
|
||||
{/* ---- Mode selection ---- */}
|
||||
<div className={styles.modeTabs}>
|
||||
<SegmentedControl
|
||||
value={mode}
|
||||
@@ -414,10 +384,16 @@ const FormFill = (_props: BaseToolProps) => {
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
---- */}
|
||||
|
||||
{/* ---- Coming-soon for non-ready tabs (hidden while mode tabs are disabled) ---- */}
|
||||
{/* !currentModeDef.ready && <ComingSoonPlaceholder mode={currentModeDef} /> */}
|
||||
{/* ---- Create mode ---- */}
|
||||
{mode === "create" && (
|
||||
<FormFieldCreatePanel currentFile={currentFile as File | Blob | null} />
|
||||
)}
|
||||
|
||||
{/* ---- Modify mode ---- */}
|
||||
{mode === "modify" && (
|
||||
<FormFieldModifyPanel currentFile={currentFile as File | Blob | null} />
|
||||
)}
|
||||
|
||||
{/* ---- Fill Form content ---- */}
|
||||
{mode === "fill" && (
|
||||
|
||||
@@ -35,11 +35,22 @@ import type {
|
||||
FormField,
|
||||
FormFillState,
|
||||
WidgetCoordinates,
|
||||
FormMode,
|
||||
CreatableFieldType,
|
||||
NewFieldDefinition,
|
||||
ModifyFieldDefinition,
|
||||
} from "@app/tools/formFill/types";
|
||||
import type { IFormDataProvider } from "@app/tools/formFill/providers/types";
|
||||
import { PdfBoxFormProvider } from "@app/tools/formFill/providers/PdfBoxFormProvider";
|
||||
import { PdfiumFormProvider } from "@app/tools/formFill/providers/PdfiumFormProvider";
|
||||
import { fetchSignatureFieldsWithAppearances } from "@app/services/pdfiumService";
|
||||
import { applyFieldEdits } from "@app/tools/formFill/formApi";
|
||||
import { mergeSignatureAppearances } from "@app/tools/formFill/formFieldMerge";
|
||||
|
||||
/** A field queued for creation, with a client-side id for list keys. */
|
||||
export interface PendingField extends NewFieldDefinition {
|
||||
id: string;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// FormValuesStore — external store for field values (outside React state)
|
||||
@@ -206,6 +217,56 @@ export interface FormFillContextValue {
|
||||
setProviderMode: (mode: "pdflib" | "pdfbox") => void;
|
||||
/** The file ID that the current form fields belong to (null if no fields loaded) */
|
||||
forFileId: string | null;
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Structural editing (create / modify modes)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/** Current tool mode. */
|
||||
mode: FormMode;
|
||||
/** Switch mode. Switching clears the other mode's uncommitted working state. */
|
||||
setMode: (mode: FormMode) => void;
|
||||
|
||||
// --- Create mode ---
|
||||
/** Field type currently armed for placement (null = not placing). */
|
||||
creationType: CreatableFieldType | null;
|
||||
setCreationType: (type: CreatableFieldType | null) => void;
|
||||
/** Fields drawn but not yet committed to the PDF. */
|
||||
pendingFields: PendingField[];
|
||||
/** Queue a new field (id + default name auto-assigned). Returns the new id. */
|
||||
addPendingField: (
|
||||
field: Omit<NewFieldDefinition, "name"> & { name?: string },
|
||||
) => string;
|
||||
updatePendingField: (id: string, patch: Partial<NewFieldDefinition>) => void;
|
||||
removePendingField: (id: string) => void;
|
||||
clearPendingFields: () => void;
|
||||
/** POST queued fields to the backend; resolves to the updated PDF blob. */
|
||||
commitNewFields: (file: File | Blob) => Promise<Blob>;
|
||||
|
||||
// --- Modify mode ---
|
||||
/** Field currently selected for editing in modify mode. */
|
||||
selectedFieldName: string | null;
|
||||
setSelectedField: (name: string | null) => void;
|
||||
/** Staged (uncommitted) property/geometry changes, keyed by original field name. */
|
||||
modifiedFields: Record<string, ModifyFieldDefinition>;
|
||||
/** Merge a partial change for a field into the staged set. */
|
||||
stageModification: (
|
||||
targetName: string,
|
||||
patch: Partial<ModifyFieldDefinition>,
|
||||
) => void;
|
||||
/** Discard staged changes for a single field. */
|
||||
clearModification: (targetName: string) => void;
|
||||
/** Field names marked for deletion. */
|
||||
deletedFieldNames: string[];
|
||||
/** Toggle a field's deletion mark. */
|
||||
toggleFieldDeleted: (name: string) => void;
|
||||
/** Discard all staged modifications and deletions. */
|
||||
clearModifications: () => void;
|
||||
/** POST staged modifications + deletions; resolves to the updated PDF blob. */
|
||||
commitModifications: (file: File | Blob) => Promise<Blob>;
|
||||
|
||||
/** True when create or modify mode has uncommitted work. */
|
||||
hasUncommittedChanges: boolean;
|
||||
}
|
||||
|
||||
const FormFillContext = createContext<FormFillContextValue | null>(null);
|
||||
@@ -307,6 +368,28 @@ export function FormFillProvider({
|
||||
// This prevents full context re-renders on every keystroke.
|
||||
const [valuesStore] = useState(() => new FormValuesStore());
|
||||
|
||||
// --- Structural editing state (create / modify modes) ---
|
||||
const [mode, setModeState] = useState<FormMode>("fill");
|
||||
const [creationType, setCreationType] = useState<CreatableFieldType | null>(
|
||||
null,
|
||||
);
|
||||
const [pendingFields, setPendingFields] = useState<PendingField[]>([]);
|
||||
const [selectedFieldName, setSelectedField] = useState<string | null>(null);
|
||||
const [modifiedFields, setModifiedFields] = useState<
|
||||
Record<string, ModifyFieldDefinition>
|
||||
>({});
|
||||
const [deletedFieldNames, setDeletedFieldNames] = useState<string[]>([]);
|
||||
// Monotonic counter for client-side pending-field ids and default names.
|
||||
const pendingCounterRef = useRef(0);
|
||||
|
||||
const clearEditingState = useCallback(() => {
|
||||
setCreationType(null);
|
||||
setPendingFields([]);
|
||||
setSelectedField(null);
|
||||
setModifiedFields({});
|
||||
setDeletedFieldNames([]);
|
||||
}, []);
|
||||
|
||||
const fetchFields = useCallback(
|
||||
async (file: File | Blob, fileId?: string) => {
|
||||
// Increment version so any in-flight fetch for a previous file is discarded.
|
||||
@@ -322,6 +405,11 @@ export function FormFillProvider({
|
||||
setForFileId(null);
|
||||
valuesStore.reset({});
|
||||
dispatch({ type: "RESET" });
|
||||
// NOTE: deliberately do NOT clear create/modify editing state here.
|
||||
// EmbedPdfViewer re-fetches fields on provider switch and file load, and
|
||||
// those background fetches must not wipe a user's in-progress drawn
|
||||
// fields or staged edits. Editing state is cleared on explicit mode
|
||||
// switch (setMode) and reset() instead.
|
||||
dispatch({ type: "FETCH_START" });
|
||||
try {
|
||||
let fields = await providerRef.current.fetchFields(file);
|
||||
@@ -333,8 +421,10 @@ export function FormFillProvider({
|
||||
return;
|
||||
}
|
||||
|
||||
// When the pdfbox provider is active the backend doesn't return signature fields
|
||||
// (they're not fillable). Fetch them via pdflib so their appearances still render.
|
||||
// The pdfbox backend returns signature fields, but without a rendered
|
||||
// appearance. Fetch the rendered signature appearances via pdfium and
|
||||
// MERGE them by name — enrich an existing backend entry rather than
|
||||
// appending a duplicate (otherwise a signature shows up twice).
|
||||
if (providerModeRef.current === "pdfbox") {
|
||||
try {
|
||||
// Convert File/Blob to ArrayBuffer for pdfiumService
|
||||
@@ -342,9 +432,7 @@ export function FormFillProvider({
|
||||
const sigFields =
|
||||
await fetchSignatureFieldsWithAppearances(arrayBuffer);
|
||||
if (fetchVersionRef.current !== version) return; // stale check after async
|
||||
if (sigFields.length > 0) {
|
||||
fields = [...fields, ...sigFields];
|
||||
}
|
||||
fields = mergeSignatureAppearances(fields, sigFields);
|
||||
} catch (e) {
|
||||
console.warn(
|
||||
"[FormFill] Failed to extract signature appearances for pdfbox mode:",
|
||||
@@ -481,7 +569,145 @@ export function FormFillProvider({
|
||||
setForFileId(null);
|
||||
valuesStore.reset({});
|
||||
dispatch({ type: "RESET" });
|
||||
}, [valuesStore]);
|
||||
clearEditingState();
|
||||
}, [valuesStore, clearEditingState]);
|
||||
|
||||
// --- Mode switching ---
|
||||
const setMode = useCallback(
|
||||
(next: FormMode) => {
|
||||
setModeState((prev) => {
|
||||
if (prev === next) return prev;
|
||||
// Leaving a mode discards its uncommitted working state so the user
|
||||
// doesn't carry half-drawn fields or staged edits between modes.
|
||||
clearEditingState();
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[clearEditingState],
|
||||
);
|
||||
|
||||
// --- Create mode ---
|
||||
const addPendingField = useCallback(
|
||||
(field: Omit<NewFieldDefinition, "name"> & { name?: string }): string => {
|
||||
const seq = ++pendingCounterRef.current;
|
||||
const id = `pending-${seq}`;
|
||||
// Friendly, readable default names that match how the viewer labels
|
||||
// fields, instead of cryptic "Field_5".
|
||||
const TYPE_DEFAULT_NAME: Record<string, string> = {
|
||||
text: "Text field",
|
||||
checkbox: "Checkbox",
|
||||
combobox: "Dropdown",
|
||||
listbox: "List",
|
||||
radio: "Radio group",
|
||||
button: "Button",
|
||||
signature: "Signature",
|
||||
};
|
||||
const defaultName =
|
||||
field.name?.trim() ||
|
||||
`${TYPE_DEFAULT_NAME[field.type] ?? "Field"} ${seq}`;
|
||||
// Choice/radio fields need options to be useful — seed a sensible default
|
||||
// so the field isn't empty and the options editor has something to show.
|
||||
const needsOptions =
|
||||
field.type === "combobox" ||
|
||||
field.type === "listbox" ||
|
||||
field.type === "radio";
|
||||
const options =
|
||||
field.options ?? (needsOptions ? ["Option 1", "Option 2"] : undefined);
|
||||
setPendingFields((prev) => [
|
||||
...prev,
|
||||
{ ...field, name: defaultName, options, id } as PendingField,
|
||||
]);
|
||||
return id;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const updatePendingField = useCallback(
|
||||
(id: string, patch: Partial<NewFieldDefinition>) => {
|
||||
setPendingFields((prev) =>
|
||||
prev.map((f) => (f.id === id ? { ...f, ...patch } : f)),
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const removePendingField = useCallback((id: string) => {
|
||||
setPendingFields((prev) => prev.filter((f) => f.id !== id));
|
||||
}, []);
|
||||
|
||||
const clearPendingFields = useCallback(() => {
|
||||
setPendingFields([]);
|
||||
setCreationType(null);
|
||||
}, []);
|
||||
|
||||
const commitNewFields = useCallback(
|
||||
async (file: File | Blob): Promise<Blob> => {
|
||||
// Strip the client-side id before sending to the backend.
|
||||
const definitions: NewFieldDefinition[] = pendingFields.map(
|
||||
({ id: _id, ...rest }) => rest,
|
||||
);
|
||||
const blob = await applyFieldEdits(file, { add: definitions });
|
||||
setPendingFields([]);
|
||||
setCreationType(null);
|
||||
return blob;
|
||||
},
|
||||
[pendingFields],
|
||||
);
|
||||
|
||||
// --- Modify mode ---
|
||||
const stageModification = useCallback(
|
||||
(targetName: string, patch: Partial<ModifyFieldDefinition>) => {
|
||||
setModifiedFields((prev) => ({
|
||||
...prev,
|
||||
[targetName]: { ...prev[targetName], targetName, ...patch },
|
||||
}));
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const clearModification = useCallback((targetName: string) => {
|
||||
setModifiedFields((prev) => {
|
||||
if (!(targetName in prev)) return prev;
|
||||
const { [targetName]: _removed, ...rest } = prev;
|
||||
return rest;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const toggleFieldDeleted = useCallback((name: string) => {
|
||||
setDeletedFieldNames((prev) =>
|
||||
prev.includes(name) ? prev.filter((n) => n !== name) : [...prev, name],
|
||||
);
|
||||
}, []);
|
||||
|
||||
const clearModifications = useCallback(() => {
|
||||
setModifiedFields({});
|
||||
setDeletedFieldNames([]);
|
||||
setSelectedField(null);
|
||||
}, []);
|
||||
|
||||
const commitModifications = useCallback(
|
||||
async (file: File | Blob): Promise<Blob> => {
|
||||
// Apply property/geometry changes (for fields not being deleted) and the
|
||||
// deletions in a single backend round-trip.
|
||||
const updates = Object.values(modifiedFields).filter(
|
||||
(m) => !deletedFieldNames.includes(m.targetName),
|
||||
);
|
||||
const blob = await applyFieldEdits(file, {
|
||||
modify: updates,
|
||||
delete: deletedFieldNames,
|
||||
});
|
||||
setModifiedFields({});
|
||||
setDeletedFieldNames([]);
|
||||
setSelectedField(null);
|
||||
return blob;
|
||||
},
|
||||
[modifiedFields, deletedFieldNames],
|
||||
);
|
||||
|
||||
const hasUncommittedChanges =
|
||||
pendingFields.length > 0 ||
|
||||
Object.keys(modifiedFields).length > 0 ||
|
||||
deletedFieldNames.length > 0;
|
||||
|
||||
const fieldsByPage = useMemo(() => {
|
||||
const map = new Map<number, FormField[]>();
|
||||
@@ -511,6 +737,27 @@ export function FormFillProvider({
|
||||
activeProviderName: providerRef.current.name,
|
||||
setProviderMode,
|
||||
forFileId,
|
||||
// editing
|
||||
mode,
|
||||
setMode,
|
||||
creationType,
|
||||
setCreationType,
|
||||
pendingFields,
|
||||
addPendingField,
|
||||
updatePendingField,
|
||||
removePendingField,
|
||||
clearPendingFields,
|
||||
commitNewFields,
|
||||
selectedFieldName,
|
||||
setSelectedField,
|
||||
modifiedFields,
|
||||
stageModification,
|
||||
clearModification,
|
||||
deletedFieldNames,
|
||||
toggleFieldDeleted,
|
||||
clearModifications,
|
||||
commitModifications,
|
||||
hasUncommittedChanges,
|
||||
}),
|
||||
[
|
||||
state,
|
||||
@@ -527,6 +774,24 @@ export function FormFillProvider({
|
||||
providerMode,
|
||||
setProviderMode,
|
||||
forFileId,
|
||||
mode,
|
||||
setMode,
|
||||
creationType,
|
||||
pendingFields,
|
||||
addPendingField,
|
||||
updatePendingField,
|
||||
removePendingField,
|
||||
clearPendingFields,
|
||||
commitNewFields,
|
||||
selectedFieldName,
|
||||
modifiedFields,
|
||||
stageModification,
|
||||
clearModification,
|
||||
deletedFieldNames,
|
||||
toggleFieldDeleted,
|
||||
clearModifications,
|
||||
commitModifications,
|
||||
hasUncommittedChanges,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* SnapGuides — renders the pink alignment guide lines shared by the create and
|
||||
* edit overlays. Absolutely positioned within the page overlay.
|
||||
*/
|
||||
import React from "react";
|
||||
import type { SnapGuide } from "@app/tools/formFill/formSnapUtils";
|
||||
import { FORM_COLORS } from "@app/tools/formFill/formFieldColors";
|
||||
|
||||
const GUIDE_COLOR = FORM_COLORS.guide;
|
||||
|
||||
export function SnapGuides({ guides }: { guides: SnapGuide[] }) {
|
||||
return (
|
||||
<>
|
||||
{guides.map((g, i) => (
|
||||
<div
|
||||
key={i}
|
||||
style={
|
||||
g.orientation === "v"
|
||||
? {
|
||||
position: "absolute",
|
||||
left: g.position,
|
||||
top: 0,
|
||||
width: 1,
|
||||
height: "100%",
|
||||
background: GUIDE_COLOR,
|
||||
pointerEvents: "none",
|
||||
}
|
||||
: {
|
||||
position: "absolute",
|
||||
top: g.position,
|
||||
left: 0,
|
||||
height: 1,
|
||||
width: "100%",
|
||||
background: GUIDE_COLOR,
|
||||
pointerEvents: "none",
|
||||
}
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default SnapGuides;
|
||||
@@ -2,7 +2,12 @@
|
||||
* API service for form-related backend calls.
|
||||
*/
|
||||
import apiClient from "@app/services/apiClient";
|
||||
import type { FormField } from "@app/tools/formFill/types";
|
||||
import type {
|
||||
FormField,
|
||||
NewFieldDefinition,
|
||||
ModifyFieldDefinition,
|
||||
FieldEditBatch,
|
||||
} from "@app/tools/formFill/types";
|
||||
|
||||
/**
|
||||
* Fetch form fields with coordinates from the backend.
|
||||
@@ -89,3 +94,93 @@ export async function extractFormFieldsXlsx(
|
||||
});
|
||||
return response.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new form fields and get back the updated PDF blob.
|
||||
* Calls POST /api/v1/form/add-fields
|
||||
*/
|
||||
export async function addFormFields(
|
||||
file: File | Blob,
|
||||
fields: NewFieldDefinition[],
|
||||
): Promise<Blob> {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
formData.append(
|
||||
"fields",
|
||||
new Blob([JSON.stringify(fields)], { type: "application/json" }),
|
||||
);
|
||||
|
||||
const response = await apiClient.post("/api/v1/form/add-fields", formData, {
|
||||
responseType: "blob",
|
||||
});
|
||||
return response.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Modify existing form fields (rename, retype, reposition, resize, flags…)
|
||||
* and get back the updated PDF blob.
|
||||
* Calls POST /api/v1/form/modify-fields
|
||||
*/
|
||||
export async function modifyFormFields(
|
||||
file: File | Blob,
|
||||
updates: ModifyFieldDefinition[],
|
||||
): Promise<Blob> {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
formData.append(
|
||||
"updates",
|
||||
new Blob([JSON.stringify(updates)], { type: "application/json" }),
|
||||
);
|
||||
|
||||
const response = await apiClient.post(
|
||||
"/api/v1/form/modify-fields",
|
||||
formData,
|
||||
{ responseType: "blob" },
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a combined batch of field edits (add + modify + delete) in a single
|
||||
* request, returning the updated PDF blob.
|
||||
* Calls POST /api/v1/form/edit-fields
|
||||
*/
|
||||
export async function applyFieldEdits(
|
||||
file: File | Blob,
|
||||
batch: FieldEditBatch,
|
||||
): Promise<Blob> {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
formData.append(
|
||||
"edits",
|
||||
new Blob([JSON.stringify(batch)], { type: "application/json" }),
|
||||
);
|
||||
|
||||
const response = await apiClient.post("/api/v1/form/edit-fields", formData, {
|
||||
responseType: "blob",
|
||||
});
|
||||
return response.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete form fields by name and get back the updated PDF blob.
|
||||
* Calls POST /api/v1/form/delete-fields
|
||||
*/
|
||||
export async function deleteFormFields(
|
||||
file: File | Blob,
|
||||
names: string[],
|
||||
): Promise<Blob> {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
formData.append(
|
||||
"names",
|
||||
new Blob([JSON.stringify(names)], { type: "application/json" }),
|
||||
);
|
||||
|
||||
const response = await apiClient.post(
|
||||
"/api/v1/form/delete-fields",
|
||||
formData,
|
||||
{ responseType: "blob" },
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Coordinate helpers for the form field editor.
|
||||
*
|
||||
* Three coordinate spaces are in play:
|
||||
*
|
||||
* - Pixel space: rendered <div> pixels inside a PDF page container, top-left
|
||||
* origin, Y growing downward. This is what pointer events give us.
|
||||
* - PDF point space (top-left origin): the space the backend already emits in
|
||||
* WidgetCoordinates (CropBox-relative, Y already flipped). FormFieldOverlay
|
||||
* renders these directly as `x * scaleX`, `y * scaleY`.
|
||||
* - PDF point space (lower-left origin): native PDF user space, CropBox-relative.
|
||||
* This is what /add-fields and /modify-fields expect; the backend adds the
|
||||
* CropBox offset to recover absolute coordinates.
|
||||
*
|
||||
* `scaleX = pageWidthPx / pageWidthPts` and `scaleY = pageHeightPx / pageHeightPts`,
|
||||
* computed exactly as FormFieldOverlay does, so a field placed at pixel (px, py)
|
||||
* round-trips back to the same pixel after a save/reload cycle. `pageHeightPts`
|
||||
* is the CropBox height in PDF points (EmbedPDF's `page.size.height`).
|
||||
*/
|
||||
|
||||
export interface PixelRect {
|
||||
left: number;
|
||||
top: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** CropBox-relative, lower-left-origin PDF points (backend create/modify space). */
|
||||
export interface PdfRect {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** Top-left-origin PDF points, as stored on a WidgetCoordinates. */
|
||||
export interface WidgetRect {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** Convert a widget's top-left-origin point rect to pixel space for rendering. */
|
||||
export function widgetRectToPixels(
|
||||
widget: WidgetRect,
|
||||
scaleX: number,
|
||||
scaleY: number,
|
||||
): PixelRect {
|
||||
return {
|
||||
left: widget.x * scaleX,
|
||||
top: widget.y * scaleY,
|
||||
width: widget.width * scaleX,
|
||||
height: widget.height * scaleY,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a pixel rect (top-left origin) to backend PDF coordinates
|
||||
* (lower-left origin, CropBox-relative points). Inverse of
|
||||
* {@link backendRectToPixels}.
|
||||
*/
|
||||
export function pixelsToBackendRect(
|
||||
rect: PixelRect,
|
||||
scaleX: number,
|
||||
scaleY: number,
|
||||
pageHeightPts: number,
|
||||
): PdfRect {
|
||||
const xPts = rect.left / scaleX;
|
||||
const widthPts = rect.width / scaleX;
|
||||
const heightPts = rect.height / scaleY;
|
||||
const topPts = rect.top / scaleY; // distance from page top, in points
|
||||
// Flip to lower-left origin: y is the distance from the page bottom to the
|
||||
// field's bottom edge.
|
||||
const yPts = pageHeightPts - topPts - heightPts;
|
||||
return { x: xPts, y: yPts, width: widthPts, height: heightPts };
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert backend PDF coordinates (lower-left origin, CropBox-relative points)
|
||||
* to a pixel rect (top-left origin). Inverse of {@link pixelsToBackendRect}.
|
||||
*/
|
||||
export function backendRectToPixels(
|
||||
rect: PdfRect,
|
||||
scaleX: number,
|
||||
scaleY: number,
|
||||
pageHeightPts: number,
|
||||
): PixelRect {
|
||||
const topPts = pageHeightPts - rect.y - rect.height;
|
||||
return {
|
||||
left: rect.x * scaleX,
|
||||
top: topPts * scaleY,
|
||||
width: rect.width * scaleX,
|
||||
height: rect.height * scaleY,
|
||||
};
|
||||
}
|
||||
|
||||
/** Clamp a pixel rect so it stays within the page bounds. */
|
||||
export function clampPixelRect(
|
||||
rect: PixelRect,
|
||||
pageWidthPx: number,
|
||||
pageHeightPx: number,
|
||||
): PixelRect {
|
||||
const width = Math.min(rect.width, pageWidthPx);
|
||||
const height = Math.min(rect.height, pageHeightPx);
|
||||
const left = Math.max(0, Math.min(rect.left, pageWidthPx - width));
|
||||
const top = Math.max(0, Math.min(rect.top, pageHeightPx - height));
|
||||
return { left, top, width, height };
|
||||
}
|
||||
|
||||
/** Round a PdfRect's components to a sane precision before sending to the API. */
|
||||
export function roundPdfRect(rect: PdfRect): PdfRect {
|
||||
const r = (n: number) => Math.round(n * 100) / 100;
|
||||
return {
|
||||
x: r(rect.x),
|
||||
y: r(rect.y),
|
||||
width: r(rect.width),
|
||||
height: r(rect.height),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Restrained, professional palette for the form overlays.
|
||||
*
|
||||
* Deliberately NOT a per-type rainbow: existing fields read as neutral slate,
|
||||
* the active/selected field and newly-drawn fields use a single blue accent,
|
||||
* deletions are red. The field TYPE is conveyed by the small icon in the side
|
||||
* panel, not by a saturated fill colour on the page.
|
||||
*/
|
||||
export const FORM_COLORS = {
|
||||
/** Selected / active / newly-drawn fields. */
|
||||
accent: "#2563eb",
|
||||
accentFillSoft: "rgba(37, 99, 235, 0.06)",
|
||||
accentFill: "rgba(37, 99, 235, 0.10)",
|
||||
|
||||
/** Existing (unselected) fields — quiet slate so the page stays readable. */
|
||||
neutralBorder: "rgba(71, 85, 105, 0.55)",
|
||||
neutralFill: "rgba(71, 85, 105, 0.05)",
|
||||
neutralChip: "#475569",
|
||||
|
||||
/** Fields marked for deletion. */
|
||||
danger: "#dc2626",
|
||||
dangerFill: "rgba(220, 38, 38, 0.08)",
|
||||
|
||||
/** Alignment guides (thin lines, shown only while dragging). */
|
||||
guide: "#2563eb",
|
||||
} as const;
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { mergeSignatureAppearances } from "@app/tools/formFill/formFieldMerge";
|
||||
import type { FormField } from "@app/tools/formFill/types";
|
||||
|
||||
function field(name: string, type: FormField["type"]): FormField {
|
||||
return {
|
||||
name,
|
||||
label: name,
|
||||
type,
|
||||
value: "",
|
||||
options: null,
|
||||
displayOptions: null,
|
||||
required: false,
|
||||
readOnly: false,
|
||||
multiSelect: false,
|
||||
multiline: false,
|
||||
tooltip: null,
|
||||
widgets: [{ pageIndex: 0, x: 0, y: 0, width: 10, height: 10 }],
|
||||
};
|
||||
}
|
||||
|
||||
describe("mergeSignatureAppearances", () => {
|
||||
it("does not duplicate a signature the backend already returned", () => {
|
||||
// The backend now returns signature fields; the pdfium pass returns the
|
||||
// same field with a rendered appearance. They must merge to ONE entry.
|
||||
const backend = [field("FullName", "text"), field("Sign", "signature")];
|
||||
const sig = {
|
||||
...field("Sign", "signature"),
|
||||
appearanceDataUrl: "data:img",
|
||||
};
|
||||
|
||||
const merged = mergeSignatureAppearances(backend, [sig]);
|
||||
|
||||
expect(merged).toHaveLength(2);
|
||||
expect(merged.filter((f) => f.name === "Sign")).toHaveLength(1);
|
||||
// …and the surviving entry is enriched with the rendered appearance.
|
||||
expect(merged.find((f) => f.name === "Sign")?.appearanceDataUrl).toBe(
|
||||
"data:img",
|
||||
);
|
||||
});
|
||||
|
||||
it("appends a signature the backend did not return", () => {
|
||||
const backend = [field("FullName", "text")];
|
||||
const sig = { ...field("Ghost", "signature"), appearanceDataUrl: "data:x" };
|
||||
|
||||
const merged = mergeSignatureAppearances(backend, [sig]);
|
||||
|
||||
expect(merged).toHaveLength(2);
|
||||
expect(merged.map((f) => f.name)).toEqual(["FullName", "Ghost"]);
|
||||
});
|
||||
|
||||
it("returns the backend list unchanged when there are no signatures", () => {
|
||||
const backend = [field("A", "text"), field("B", "checkbox")];
|
||||
expect(mergeSignatureAppearances(backend, [])).toBe(backend);
|
||||
});
|
||||
|
||||
it("does not overwrite an existing appearance", () => {
|
||||
const backend = [
|
||||
{ ...field("Sign", "signature"), appearanceDataUrl: "keep" },
|
||||
];
|
||||
const sig = { ...field("Sign", "signature"), appearanceDataUrl: "new" };
|
||||
const merged = mergeSignatureAppearances(backend, [sig]);
|
||||
expect(merged.find((f) => f.name === "Sign")?.appearanceDataUrl).toBe(
|
||||
"keep",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Merge helpers for assembling the form field list shown to the user.
|
||||
*
|
||||
* In pdfbox mode the backend already returns every field (including signature
|
||||
* fields), but it cannot render a signature's visual appearance. The frontend
|
||||
* separately rasterises signature appearances via PDFium. These must be merged
|
||||
* BY NAME — enriching the existing backend entry with the rendered appearance —
|
||||
* rather than concatenated, otherwise a signature appears twice in the list.
|
||||
*/
|
||||
import type { FormField } from "@app/tools/formFill/types";
|
||||
|
||||
/**
|
||||
* Returns a new array where each pdfium-rendered signature field either enriches
|
||||
* the matching backend field (by name) with its `appearanceDataUrl`, or is
|
||||
* appended if the backend didn't return it. Never produces duplicates by name.
|
||||
*/
|
||||
export function mergeSignatureAppearances(
|
||||
backendFields: FormField[],
|
||||
signatureFields: FormField[],
|
||||
): FormField[] {
|
||||
if (signatureFields.length === 0) return backendFields;
|
||||
|
||||
const merged = backendFields.map((f) => ({ ...f }));
|
||||
const byName = new Map(merged.map((f) => [f.name, f]));
|
||||
|
||||
for (const sig of signatureFields) {
|
||||
const existing = byName.get(sig.name);
|
||||
if (existing) {
|
||||
if (sig.appearanceDataUrl && !existing.appearanceDataUrl) {
|
||||
existing.appearanceDataUrl = sig.appearanceDataUrl;
|
||||
}
|
||||
} else {
|
||||
merged.push({ ...sig });
|
||||
byName.set(sig.name, merged[merged.length - 1]);
|
||||
}
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* The custom event the form tools use to hand a freshly-produced PDF blob to
|
||||
* the viewer (EmbedPdfViewer listens for it and reloads the file, preserving
|
||||
* scroll/rotation). Centralised so the event name isn't duplicated as a string
|
||||
* across the fill/create/modify flows.
|
||||
*/
|
||||
export const FORM_APPLY_EVENT = "formfill:apply";
|
||||
|
||||
export interface FormApplyDetail {
|
||||
blob: Blob;
|
||||
}
|
||||
|
||||
/** Dispatch a produced PDF blob to the viewer for reload + refresh. */
|
||||
export function dispatchFormApply(blob: Blob): void {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent<FormApplyDetail>(FORM_APPLY_EVENT, { detail: { blob } }),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* Lightweight alignment snapping for the form field editor.
|
||||
*
|
||||
* Everything here works in page pixel space (top-left origin), the same space
|
||||
* the creation/edit overlays operate in. A dragged rectangle's edges and centre
|
||||
* snap to the edges and centres of the other fields on the page when they come
|
||||
* within a small threshold, and the matched lines are returned as guides for
|
||||
* visual feedback.
|
||||
*/
|
||||
import type { PixelRect } from "@app/tools/formFill/formCoordinateUtils";
|
||||
|
||||
export const DEFAULT_SNAP_THRESHOLD = 6;
|
||||
|
||||
export interface SnapGuide {
|
||||
/** "v" = vertical line at x; "h" = horizontal line at y. */
|
||||
orientation: "v" | "h";
|
||||
/** Pixel offset of the line within the page. */
|
||||
position: number;
|
||||
}
|
||||
|
||||
export interface SnapTargets {
|
||||
/** Candidate vertical lines (left/right/centre of other fields). */
|
||||
xs: number[];
|
||||
/** Candidate horizontal lines (top/bottom/middle of other fields). */
|
||||
ys: number[];
|
||||
}
|
||||
|
||||
/** Build snap targets from the pixel rects of the other fields on a page. */
|
||||
export function collectSnapTargets(rects: PixelRect[]): SnapTargets {
|
||||
const xs: number[] = [];
|
||||
const ys: number[] = [];
|
||||
for (const r of rects) {
|
||||
xs.push(r.left, r.left + r.width, r.left + r.width / 2);
|
||||
ys.push(r.top, r.top + r.height, r.top + r.height / 2);
|
||||
}
|
||||
return { xs, ys };
|
||||
}
|
||||
|
||||
function nearest(
|
||||
value: number,
|
||||
targets: number[],
|
||||
threshold: number,
|
||||
): { snapped: number; delta: number } | null {
|
||||
let best: { snapped: number; delta: number } | null = null;
|
||||
for (const t of targets) {
|
||||
const delta = t - value;
|
||||
if (
|
||||
Math.abs(delta) <= threshold &&
|
||||
(!best || Math.abs(delta) < Math.abs(best.delta))
|
||||
) {
|
||||
best = { snapped: t, delta };
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/**
|
||||
* Snap a moving rectangle (size fixed). Returns the adjusted top-left plus the
|
||||
* guide lines that were matched.
|
||||
*/
|
||||
export function snapMove(
|
||||
rect: PixelRect,
|
||||
targets: SnapTargets,
|
||||
threshold = DEFAULT_SNAP_THRESHOLD,
|
||||
): { left: number; top: number; guides: SnapGuide[] } {
|
||||
const guides: SnapGuide[] = [];
|
||||
let { left, top } = rect;
|
||||
|
||||
// X axis: try left edge, right edge, then centre.
|
||||
const xCandidates = [left, left + rect.width, left + rect.width / 2];
|
||||
let xSnap: { snapped: number; delta: number } | null = null;
|
||||
for (const c of xCandidates) {
|
||||
const hit = nearest(c, targets.xs, threshold);
|
||||
if (hit && (!xSnap || Math.abs(hit.delta) < Math.abs(xSnap.delta)))
|
||||
xSnap = hit;
|
||||
}
|
||||
if (xSnap) {
|
||||
left += xSnap.delta;
|
||||
guides.push({ orientation: "v", position: xSnap.snapped });
|
||||
}
|
||||
|
||||
const yCandidates = [top, top + rect.height, top + rect.height / 2];
|
||||
let ySnap: { snapped: number; delta: number } | null = null;
|
||||
for (const c of yCandidates) {
|
||||
const hit = nearest(c, targets.ys, threshold);
|
||||
if (hit && (!ySnap || Math.abs(hit.delta) < Math.abs(ySnap.delta)))
|
||||
ySnap = hit;
|
||||
}
|
||||
if (ySnap) {
|
||||
top += ySnap.delta;
|
||||
guides.push({ orientation: "h", position: ySnap.snapped });
|
||||
}
|
||||
|
||||
return { left, top, guides };
|
||||
}
|
||||
|
||||
/**
|
||||
* Snap a rectangle being resized. `edges` flags which sides are moving; only
|
||||
* those edges snap, the opposite edges stay put.
|
||||
*/
|
||||
export function snapResize(
|
||||
rect: PixelRect,
|
||||
edges: { left?: boolean; right?: boolean; top?: boolean; bottom?: boolean },
|
||||
targets: SnapTargets,
|
||||
threshold = DEFAULT_SNAP_THRESHOLD,
|
||||
): { rect: PixelRect; guides: SnapGuide[] } {
|
||||
const guides: SnapGuide[] = [];
|
||||
let { left, top, width, height } = rect;
|
||||
const right = left + width;
|
||||
const bottom = top + height;
|
||||
|
||||
if (edges.left) {
|
||||
const hit = nearest(left, targets.xs, threshold);
|
||||
if (hit) {
|
||||
left = hit.snapped;
|
||||
width = right - left;
|
||||
guides.push({ orientation: "v", position: hit.snapped });
|
||||
}
|
||||
}
|
||||
if (edges.right) {
|
||||
const hit = nearest(right, targets.xs, threshold);
|
||||
if (hit) {
|
||||
width = hit.snapped - left;
|
||||
guides.push({ orientation: "v", position: hit.snapped });
|
||||
}
|
||||
}
|
||||
if (edges.top) {
|
||||
const hit = nearest(top, targets.ys, threshold);
|
||||
if (hit) {
|
||||
top = hit.snapped;
|
||||
height = bottom - top;
|
||||
guides.push({ orientation: "h", position: hit.snapped });
|
||||
}
|
||||
}
|
||||
if (edges.bottom) {
|
||||
const hit = nearest(bottom, targets.ys, threshold);
|
||||
if (hit) {
|
||||
height = hit.snapped - top;
|
||||
guides.push({ orientation: "h", position: hit.snapped });
|
||||
}
|
||||
}
|
||||
|
||||
return { rect: { left, top, width, height }, guides };
|
||||
}
|
||||
@@ -13,6 +13,12 @@ export interface WidgetCoordinates {
|
||||
exportValue?: string;
|
||||
/** Font size in PDF points */
|
||||
fontSize?: number;
|
||||
/**
|
||||
* CropBox height in PDF points for the page this widget sits on. Lets the
|
||||
* editor reverse the backend's Y-flip when sending new/changed coordinates
|
||||
* back for create/modify operations.
|
||||
*/
|
||||
cropBoxHeight?: number;
|
||||
}
|
||||
|
||||
export interface FormField {
|
||||
@@ -67,6 +73,90 @@ export interface ButtonAction {
|
||||
submitFlags?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Field types that can be created/edited structurally through the editor.
|
||||
*/
|
||||
export type CreatableFieldType =
|
||||
| "text"
|
||||
| "checkbox"
|
||||
| "combobox"
|
||||
| "listbox"
|
||||
| "radio"
|
||||
| "button"
|
||||
| "signature";
|
||||
|
||||
export const CREATABLE_FIELD_TYPES: CreatableFieldType[] = [
|
||||
"text",
|
||||
"checkbox",
|
||||
"combobox",
|
||||
"listbox",
|
||||
"radio",
|
||||
"button",
|
||||
"signature",
|
||||
];
|
||||
|
||||
/**
|
||||
* A new field queued for creation. Coordinates are CropBox-relative,
|
||||
* lower-left-origin PDF points — the reverse of what the backend emits in
|
||||
* WidgetCoordinates, ready to POST to /api/v1/form/add-fields.
|
||||
*/
|
||||
export interface NewFieldDefinition {
|
||||
name: string;
|
||||
label?: string;
|
||||
type: CreatableFieldType;
|
||||
pageIndex: number;
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
required?: boolean;
|
||||
multiSelect?: boolean;
|
||||
options?: string[];
|
||||
defaultValue?: string;
|
||||
tooltip?: string;
|
||||
fontSize?: number;
|
||||
readOnly?: boolean;
|
||||
multiline?: boolean;
|
||||
maxLength?: number; // text only; >0 also makes it a comb field
|
||||
/** Push-button activation action: "reset" | "print" | "uri:<url>" | "submit:<url>" */
|
||||
buttonAction?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A change to an existing field. Only non-undefined properties are applied.
|
||||
* Coordinates (when present) are CropBox-relative, lower-left-origin PDF points.
|
||||
*/
|
||||
export interface ModifyFieldDefinition {
|
||||
targetName: string;
|
||||
name?: string;
|
||||
label?: string;
|
||||
type?: FormFieldType;
|
||||
pageIndex?: number;
|
||||
x?: number;
|
||||
y?: number;
|
||||
width?: number;
|
||||
height?: number;
|
||||
required?: boolean;
|
||||
multiSelect?: boolean;
|
||||
options?: string[];
|
||||
defaultValue?: string;
|
||||
tooltip?: string;
|
||||
fontSize?: number;
|
||||
readOnly?: boolean;
|
||||
multiline?: boolean;
|
||||
maxLength?: number; // text only; >0 also makes it a comb field
|
||||
}
|
||||
|
||||
/** A batch of field edits committed in one request via /api/v1/form/edit-fields. */
|
||||
export interface FieldEditBatch {
|
||||
add?: NewFieldDefinition[];
|
||||
modify?: ModifyFieldDefinition[];
|
||||
delete?: string[];
|
||||
}
|
||||
|
||||
/** The form tool's working mode. */
|
||||
export type FormMode = "fill" | "create" | "modify";
|
||||
|
||||
export interface FormFillState {
|
||||
/** Fields fetched from backend with coordinates */
|
||||
fields: FormField[];
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Shared commit boilerplate for the create and modify panels: run an async
|
||||
* action that produces the edited PDF blob, hand it to the viewer, and track
|
||||
* committing/error state. Keeps both panels from repeating the same
|
||||
* try/catch/dispatch dance.
|
||||
*/
|
||||
import { useState, useCallback } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { dispatchFormApply } from "@app/tools/formFill/formFillEvents";
|
||||
|
||||
export function useFormCommit(onApplied?: (blob: Blob) => void) {
|
||||
const { t } = useTranslation();
|
||||
const [committing, setCommitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const commit = useCallback(
|
||||
async (
|
||||
run: () => Promise<Blob>,
|
||||
errorKey: string,
|
||||
errorFallback: string,
|
||||
) => {
|
||||
setCommitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
const blob = await run();
|
||||
dispatchFormApply(blob);
|
||||
onApplied?.(blob);
|
||||
} catch (err) {
|
||||
setError(
|
||||
(err instanceof Error ? err.message : undefined) ||
|
||||
t(errorKey, errorFallback),
|
||||
);
|
||||
console.error("[FormFill] commit failed:", err);
|
||||
} finally {
|
||||
setCommitting(false);
|
||||
}
|
||||
},
|
||||
[onApplied, t],
|
||||
);
|
||||
|
||||
return { committing, error, setError, commit };
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Shared page-scale helpers for the form overlays.
|
||||
*
|
||||
* Both the creation and edit overlays need the pixel<->PDF-point scale for a
|
||||
* rendered page (and a pointer-to-local-pixel conversion). This centralises
|
||||
* that so they stay in sync with FormFieldOverlay's basis and don't duplicate
|
||||
* the documentState math.
|
||||
*/
|
||||
import { useMemo } from "react";
|
||||
import { useDocumentState } from "@embedpdf/core/react";
|
||||
|
||||
export interface PageScale {
|
||||
scaleX: number;
|
||||
scaleY: number;
|
||||
/** CropBox height in PDF points; 0 until the page has rendered. */
|
||||
pageHeightPts: number;
|
||||
/** CropBox width in PDF points; 0 until the page has rendered. */
|
||||
pageWidthPts: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pixel<->point scale for a page, derived from EmbedPDF's document state.
|
||||
* `scaleX = pageWidthPx / pageWidthPts`. `pageWidthPts` is 0 until the page has
|
||||
* rendered, so callers should guard on it before drawing.
|
||||
*/
|
||||
export function usePageScale(
|
||||
documentId: string,
|
||||
pageIndex: number,
|
||||
pageWidth: number,
|
||||
pageHeight: number,
|
||||
): PageScale {
|
||||
const documentState = useDocumentState(documentId);
|
||||
return useMemo(() => {
|
||||
const pdfPage = documentState?.document?.pages?.[pageIndex];
|
||||
if (!pdfPage?.size || !pageWidth || !pageHeight) {
|
||||
const s = documentState?.scale ?? 1;
|
||||
return { scaleX: s, scaleY: s, pageHeightPts: 0, pageWidthPts: 0 };
|
||||
}
|
||||
return {
|
||||
scaleX: pageWidth / pdfPage.size.width,
|
||||
scaleY: pageHeight / pdfPage.size.height,
|
||||
pageHeightPts: pdfPage.size.height,
|
||||
pageWidthPts: pdfPage.size.width,
|
||||
};
|
||||
}, [documentState, pageIndex, pageWidth, pageHeight]);
|
||||
}
|
||||
|
||||
/** Pointer position relative to an element's top-left, in CSS pixels. */
|
||||
export function getLocalPoint(
|
||||
e: { clientX: number; clientY: number },
|
||||
el: HTMLElement | null,
|
||||
): { x: number; y: number } {
|
||||
const rect = el?.getBoundingClientRect();
|
||||
if (!rect) return { x: 0, y: 0 };
|
||||
return { x: e.clientX - rect.left, y: e.clientY - rect.top };
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
/* Shared classification-label pill (team labels editor + sidebar category manager). */
|
||||
|
||||
.sui-labelchip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
padding: 0.2rem 0.3rem 0.2rem 0.25rem;
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: var(--radius-lg);
|
||||
background: var(--color-surface);
|
||||
max-width: 16rem;
|
||||
}
|
||||
|
||||
.sui-labelchip-icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 1.5rem;
|
||||
height: 1.5rem;
|
||||
color: var(--color-text-2);
|
||||
}
|
||||
|
||||
.sui-labelchip-name {
|
||||
font-size: 0.8125rem;
|
||||
color: var(--color-text-1);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.sui-labelchip-count {
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 500;
|
||||
color: var(--color-text-3);
|
||||
padding-left: 0.1rem;
|
||||
}
|
||||
|
||||
.sui-labelchip-remove {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
border: none;
|
||||
border-radius: 999px;
|
||||
background: transparent;
|
||||
color: var(--color-text-3);
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background var(--motion-fast),
|
||||
color var(--motion-fast);
|
||||
}
|
||||
|
||||
.sui-labelchip-remove:hover {
|
||||
background: var(--color-bg-hover);
|
||||
color: var(--color-red);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { LabelChip } from "@app/ui/LabelChip";
|
||||
|
||||
const meta: Meta<typeof LabelChip> = {
|
||||
title: "Primitives/LabelChip",
|
||||
component: LabelChip,
|
||||
tags: ["autodocs"],
|
||||
parameters: { layout: "centered" },
|
||||
args: { label: "Invoice", icon: "receipt-long" },
|
||||
argTypes: {
|
||||
label: { control: "text" },
|
||||
icon: { control: "text" },
|
||||
count: { control: "number" },
|
||||
onRemove: { action: "removed" },
|
||||
},
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof LabelChip>;
|
||||
|
||||
/** The classification-label pill shared by the labels editor and the sidebar category manager. */
|
||||
export const Playground: Story = {};
|
||||
|
||||
/** With a file count, as shown in the sidebar category manager. */
|
||||
export const WithCount: Story = {
|
||||
args: { label: "Contract", icon: "handshake", count: 12 },
|
||||
};
|
||||
|
||||
/** Removable — the trailing × appears when `onRemove` is set. */
|
||||
export const Removable: Story = {
|
||||
args: { label: "NDA", icon: "lock", onRemove: () => {} },
|
||||
};
|
||||
|
||||
/** Falls back to the default "sell" icon when none is given. */
|
||||
export const DefaultIcon: Story = {
|
||||
args: { label: "Uncategorised label", icon: undefined },
|
||||
};
|
||||
|
||||
/** Long names truncate rather than overflow the pill. */
|
||||
export const LongName: Story = {
|
||||
args: { label: "Memorandum of understanding and mutual agreement", count: 3 },
|
||||
};
|
||||
|
||||
export const Row: Story = {
|
||||
render: () => (
|
||||
<div style={{ display: "flex", gap: 8, flexWrap: "wrap", maxWidth: 420 }}>
|
||||
<LabelChip label="Invoice" icon="receipt-long" count={12} />
|
||||
<LabelChip label="Contract" icon="handshake" onRemove={() => {}} />
|
||||
<LabelChip label="Lab report" icon="science" count={2} />
|
||||
<LabelChip label="Payslip" icon="payments" />
|
||||
</div>
|
||||
),
|
||||
};
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { ReactNode } from "react";
|
||||
import CloseIcon from "@mui/icons-material/Close";
|
||||
import { LocalIcon } from "@app/components/shared/LocalIcon";
|
||||
import "@app/ui/LabelChip.css";
|
||||
|
||||
export interface LabelChipProps {
|
||||
/** The label text. */
|
||||
label: string;
|
||||
/** Material Symbols key for a leading icon; ignored when `leading` is given. */
|
||||
icon?: string;
|
||||
/** Custom leading node (e.g. an icon picker), overriding `icon`. */
|
||||
leading?: ReactNode;
|
||||
/** Optional trailing count (e.g. how many files carry this label). */
|
||||
count?: number;
|
||||
/** Show a trailing `×`; called on click. */
|
||||
onRemove?: () => void;
|
||||
/** Accessible name for the remove button. */
|
||||
removeAriaLabel?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A classification-label pill: leading icon (or a custom control like an icon
|
||||
* picker) + name, with an optional count and remove button. The shared look for
|
||||
* every place labels are shown as chips — the team labels editor and the
|
||||
* sidebar category manager both render this so they stay visually identical.
|
||||
*/
|
||||
export function LabelChip({
|
||||
label,
|
||||
icon,
|
||||
leading,
|
||||
count,
|
||||
onRemove,
|
||||
removeAriaLabel,
|
||||
}: LabelChipProps) {
|
||||
return (
|
||||
<span className="sui-labelchip" role="listitem">
|
||||
{leading ?? (
|
||||
<span className="sui-labelchip-icon">
|
||||
<LocalIcon icon={icon || "sell"} width="1rem" />
|
||||
</span>
|
||||
)}
|
||||
<span className="sui-labelchip-name" title={label}>
|
||||
{label}
|
||||
</span>
|
||||
{count != null && count > 0 && (
|
||||
<span className="sui-labelchip-count">{count}</span>
|
||||
)}
|
||||
{onRemove && (
|
||||
<button
|
||||
type="button"
|
||||
className="sui-labelchip-remove"
|
||||
onClick={onRemove}
|
||||
aria-label={removeAriaLabel ?? `Remove ${label}`}
|
||||
>
|
||||
<CloseIcon sx={{ fontSize: "0.85rem" }} />
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -56,11 +56,11 @@ export interface PolicyField {
|
||||
export interface PolicyCategory {
|
||||
id: string;
|
||||
label: string;
|
||||
icon: string;
|
||||
tone: "neutral" | "blue" | "purple" | "green" | "amber" | "red";
|
||||
desc: string;
|
||||
providesClassification?: boolean;
|
||||
comingSoon?: boolean;
|
||||
requiresAiEngine?: boolean;
|
||||
}
|
||||
|
||||
export interface PolicyConfigDef {
|
||||
@@ -133,21 +133,14 @@ export interface CatalogueEntry {
|
||||
/* Endpoint display labels */
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
/**
|
||||
* i18n keys keyed by endpoint; labels stored steps in the detail view. Mostly
|
||||
* {@link ToolEndpoint}s, plus the AI classify endpoint, which isn't part of the generated union.
|
||||
*/
|
||||
export const ENDPOINT_LABELS: Partial<
|
||||
Record<ToolEndpoint | "/api/v1/ai/tools/classify-and-label", string>
|
||||
> = {
|
||||
/** i18n keys keyed by {@link ToolEndpoint}; labels stored steps in the detail view. */
|
||||
export const ENDPOINT_LABELS: Partial<Record<ToolEndpoint, string>> = {
|
||||
"/api/v1/security/auto-redact": "portal.policies.endpoints.autoRedact",
|
||||
"/api/v1/security/sanitize-pdf": "portal.policies.endpoints.sanitizePdf",
|
||||
"/api/v1/security/add-watermark": "portal.policies.endpoints.addWatermark",
|
||||
"/api/v1/misc/ocr-pdf": "portal.policies.endpoints.ocrPdf",
|
||||
"/api/v1/misc/flatten": "portal.policies.endpoints.flatten",
|
||||
"/api/v1/misc/compress-pdf": "portal.policies.endpoints.compressPdf",
|
||||
"/api/v1/ai/tools/classify-and-label":
|
||||
"portal.policies.endpoints.classifyAndLabel",
|
||||
};
|
||||
|
||||
export function humanizeEndpoint(
|
||||
@@ -177,6 +170,7 @@ export const POLICY_CATEGORIES: PolicyCategory[] = [
|
||||
{
|
||||
id: "ingestion",
|
||||
label: "portal.policies.categories.ingestion.label",
|
||||
icon: "layers",
|
||||
tone: "blue",
|
||||
desc: "portal.policies.categories.ingestion.desc",
|
||||
providesClassification: true,
|
||||
@@ -185,20 +179,14 @@ export const POLICY_CATEGORIES: PolicyCategory[] = [
|
||||
{
|
||||
id: "security",
|
||||
label: "portal.policies.categories.security.label",
|
||||
icon: "shield",
|
||||
tone: "purple",
|
||||
desc: "portal.policies.categories.security.desc",
|
||||
},
|
||||
{
|
||||
id: "classification",
|
||||
label: "portal.policies.categories.classification.label",
|
||||
tone: "blue",
|
||||
desc: "portal.policies.categories.classification.desc",
|
||||
providesClassification: true,
|
||||
requiresAiEngine: true,
|
||||
},
|
||||
{
|
||||
id: "compliance",
|
||||
label: "portal.policies.categories.compliance.label",
|
||||
icon: "check",
|
||||
tone: "amber",
|
||||
desc: "portal.policies.categories.compliance.desc",
|
||||
comingSoon: true,
|
||||
@@ -206,6 +194,7 @@ export const POLICY_CATEGORIES: PolicyCategory[] = [
|
||||
{
|
||||
id: "routing",
|
||||
label: "portal.policies.categories.routing.label",
|
||||
icon: "route",
|
||||
tone: "green",
|
||||
desc: "portal.policies.categories.routing.desc",
|
||||
comingSoon: true,
|
||||
@@ -213,6 +202,7 @@ export const POLICY_CATEGORIES: PolicyCategory[] = [
|
||||
{
|
||||
id: "retention",
|
||||
label: "portal.policies.categories.retention.label",
|
||||
icon: "schedule",
|
||||
tone: "neutral",
|
||||
desc: "portal.policies.categories.retention.desc",
|
||||
comingSoon: true,
|
||||
@@ -274,16 +264,6 @@ export const POLICY_CONFIG: Record<string, PolicyConfigDef> = {
|
||||
],
|
||||
fields: [],
|
||||
},
|
||||
classification: {
|
||||
summary: "portal.policies.config.classification.summary",
|
||||
rules: [
|
||||
"portal.policies.config.classification.rules.0",
|
||||
"portal.policies.config.classification.rules.1",
|
||||
],
|
||||
scopeLabel: "portal.policies.config.scopeAll",
|
||||
defaultOperations: [policyStep("classify")],
|
||||
fields: [],
|
||||
},
|
||||
compliance: {
|
||||
summary: "portal.policies.config.compliance.summary",
|
||||
rules: [
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
type CatalogueEntry,
|
||||
type PoliciesResponse,
|
||||
} from "@portal/api/policies";
|
||||
import { policyCategoryIcon } from "@app/components/policies/policyCategoryIcon";
|
||||
import { policyIcon } from "@portal/components/policies/policyIcons";
|
||||
import "@portal/components/PolicySummary.css";
|
||||
|
||||
/**
|
||||
@@ -64,7 +64,7 @@ export function PolicySummary() {
|
||||
render: ({ entry }) => (
|
||||
<div className="portal-policysum__cat">
|
||||
<span className="portal-policysum__icon" aria-hidden>
|
||||
{policyCategoryIcon(entry.category.id)}
|
||||
{policyIcon(entry.category.icon)}
|
||||
</span>
|
||||
<div className="portal-policysum__cat-text">
|
||||
<strong>{t(entry.category.label)}</strong>
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
/* Read-only classification-vocabulary viewer in the policy wizard. */
|
||||
.classification-summary {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
.classification-summary-stats {
|
||||
display: flex;
|
||||
gap: var(--space-3);
|
||||
font-size: 0.8125rem;
|
||||
color: var(--color-text-2);
|
||||
}
|
||||
.classification-summary-note {
|
||||
font-size: 0.75rem;
|
||||
color: var(--color-text-3);
|
||||
}
|
||||
|
||||
/* Expandable category → labels list. */
|
||||
.classification-categories {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.classification-category {
|
||||
border-top: 1px solid var(--border-default);
|
||||
}
|
||||
.classification-category:last-child {
|
||||
border-bottom: 1px solid var(--border-default);
|
||||
}
|
||||
.classification-category-header {
|
||||
min-height: 2.5rem;
|
||||
}
|
||||
.classification-category-lead {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
.classification-category-name {
|
||||
font-weight: 600;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
.classification-category-count {
|
||||
font-size: 0.75rem;
|
||||
color: var(--color-text-3);
|
||||
}
|
||||
.classification-category-labels {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1_5);
|
||||
padding: 0 var(--space-2) var(--space-2) 2rem;
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
// Read-only view of the classification vocabulary shown in the policy wizard. The labels and their
|
||||
// categories are a fixed, built-in set shared across the whole team — there's nothing to edit, but
|
||||
// the full vocabulary is browsable: expand a category to see the labels it groups.
|
||||
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
|
||||
import KeyboardArrowRightIcon from "@mui/icons-material/KeyboardArrowRight";
|
||||
import { Button, Card, Chip } from "@app/ui";
|
||||
import { LocalIcon } from "@app/components/shared/LocalIcon";
|
||||
import {
|
||||
DEFAULT_CLASSIFICATION_LABELS,
|
||||
LABEL_FAMILIES,
|
||||
} from "@app/data/classificationLabels";
|
||||
import "@portal/components/policies/ClassificationLabelsSection.css";
|
||||
|
||||
export function ClassificationLabelsSection() {
|
||||
const { t } = useTranslation();
|
||||
const [expanded, setExpanded] = useState<ReadonlySet<string>>(new Set());
|
||||
|
||||
const toggle = (id: string) =>
|
||||
setExpanded((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
return next;
|
||||
});
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<div className="classification-summary">
|
||||
<div className="classification-summary-stats">
|
||||
<span>
|
||||
<strong>{DEFAULT_CLASSIFICATION_LABELS.length}</strong>{" "}
|
||||
{t("policies.labels.labelCount", "labels")}
|
||||
</span>
|
||||
<span>
|
||||
<strong>{LABEL_FAMILIES.length}</strong>{" "}
|
||||
{t("policies.labels.categoryCount", "categories")}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<ul className="classification-categories">
|
||||
{LABEL_FAMILIES.map((family) => {
|
||||
const open = expanded.has(family.id);
|
||||
return (
|
||||
<li key={family.id} className="classification-category">
|
||||
<Button
|
||||
variant="quiet"
|
||||
fullWidth
|
||||
justify="between"
|
||||
className="classification-category-header"
|
||||
aria-expanded={open}
|
||||
onClick={() => toggle(family.id)}
|
||||
leftSection={
|
||||
<span className="classification-category-lead">
|
||||
{open ? (
|
||||
<KeyboardArrowDownIcon sx={{ fontSize: "1.1rem" }} />
|
||||
) : (
|
||||
<KeyboardArrowRightIcon sx={{ fontSize: "1.1rem" }} />
|
||||
)}
|
||||
<LocalIcon icon={family.icon} width="1.1rem" />
|
||||
<span className="classification-category-name">
|
||||
{family.name}
|
||||
</span>
|
||||
</span>
|
||||
}
|
||||
rightSection={
|
||||
<span className="classification-category-count">
|
||||
{family.labels.length}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
{open && (
|
||||
<div className="classification-category-labels">
|
||||
{family.labels.map((label) => (
|
||||
<Chip key={label.id} accent="neutral" size="sm">
|
||||
{t(`classification.labels.${label.id}`, label.name)}
|
||||
</Chip>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
|
||||
<span className="classification-summary-note">
|
||||
{t(
|
||||
"policies.labels.sharedNote",
|
||||
"These labels are built in and shared across your whole team.",
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,28 +1,19 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Card, Chip, StatusBadge } from "@app/ui";
|
||||
import type { CatalogueEntry } from "@portal/api/policies";
|
||||
import { policyCategoryIcon } from "@app/components/policies/policyCategoryIcon";
|
||||
import { policyIcon } from "@portal/components/policies/policyIcons";
|
||||
import "@portal/views/Policies.css";
|
||||
|
||||
interface PolicyCategoryCardProps {
|
||||
entry: CatalogueEntry;
|
||||
onOpen: (entry: CatalogueEntry) => void;
|
||||
/** Setup is unavailable (e.g. the AI engine is off): shown, but not openable. */
|
||||
locked?: boolean;
|
||||
/** Chip text explaining why setup is locked (e.g. "Requires AI engine"). */
|
||||
lockedLabel?: string;
|
||||
}
|
||||
|
||||
export function PolicyCategoryCard({
|
||||
entry,
|
||||
onOpen,
|
||||
locked = false,
|
||||
lockedLabel,
|
||||
}: PolicyCategoryCardProps) {
|
||||
export function PolicyCategoryCard({ entry, onOpen }: PolicyCategoryCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const { category, config, policy } = entry;
|
||||
const comingSoon = category.comingSoon === true;
|
||||
const openable = !comingSoon && !locked;
|
||||
const openable = !comingSoon;
|
||||
const status = policy?.state.status;
|
||||
const enforces = config.rules.map((r) => t(r)).join(" · ");
|
||||
|
||||
@@ -30,7 +21,7 @@ export function PolicyCategoryCard({
|
||||
<Card
|
||||
className={
|
||||
"portal-policies__card" +
|
||||
(comingSoon || locked ? " portal-policies__card--locked" : "")
|
||||
(comingSoon ? " portal-policies__card--locked" : "")
|
||||
}
|
||||
interactive={openable}
|
||||
onClick={openable ? () => onOpen(entry) : undefined}
|
||||
@@ -48,7 +39,7 @@ export function PolicyCategoryCard({
|
||||
}
|
||||
>
|
||||
<span className="portal-policies__cat-icon" aria-hidden>
|
||||
{policyCategoryIcon(category.id)}
|
||||
{policyIcon(category.icon)}
|
||||
</span>
|
||||
|
||||
<div className="portal-policies__card-identity">
|
||||
@@ -62,10 +53,6 @@ export function PolicyCategoryCard({
|
||||
<Chip accent="neutral" size="sm">
|
||||
{t("portal.policies.card.comingSoon")}
|
||||
</Chip>
|
||||
) : locked ? (
|
||||
<Chip accent="neutral" size="sm">
|
||||
{lockedLabel ?? t("portal.policies.card.requiresAiEngine")}
|
||||
</Chip>
|
||||
) : policy ? (
|
||||
<div className="portal-policies__card-meta">
|
||||
<span className="portal-policies__card-statpair">
|
||||
|
||||
@@ -8,9 +8,6 @@ import {
|
||||
import { PolicySetupWizard } from "@portal/components/policies/PolicySetupWizard";
|
||||
|
||||
const security = POLICY_CATEGORIES.find((c) => c.id === "security")!;
|
||||
const classification = POLICY_CATEGORIES.find(
|
||||
(c) => c.id === "classification",
|
||||
)!;
|
||||
|
||||
const meta: Meta<typeof PolicySetupWizard> = {
|
||||
title: "Portal/Policies/PolicySetupWizard",
|
||||
@@ -50,14 +47,3 @@ export const Edit: Story = {
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/** Classification: the workflow step shows the team label editor, not tool toggles. */
|
||||
export const Classification: Story = {
|
||||
args: {
|
||||
entry: {
|
||||
category: classification,
|
||||
config: POLICY_CONFIG.classification,
|
||||
policy: null,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
import { useMemo, useState, type ReactNode } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import CheckIcon from "@mui/icons-material/Check";
|
||||
import EditOutlinedIcon from "@mui/icons-material/EditOutlined";
|
||||
import FolderOutlinedIcon from "@mui/icons-material/FolderOutlined";
|
||||
import CloudOutlinedIcon from "@mui/icons-material/CloudOutlined";
|
||||
import StorageOutlinedIcon from "@mui/icons-material/StorageOutlined";
|
||||
import {
|
||||
Banner,
|
||||
Button,
|
||||
@@ -34,27 +29,12 @@ import {
|
||||
import { fetchSources } from "@portal/api/sources";
|
||||
import { useAsync } from "@portal/hooks/useAsync";
|
||||
import { PolicyFieldRow } from "@portal/components/policies/PolicyFieldRow";
|
||||
import { policyCategoryIcon } from "@app/components/policies/policyCategoryIcon";
|
||||
import { policyIcon } from "@portal/components/policies/policyIcons";
|
||||
import { sourceTypeMeta } from "@portal/components/sources/sourceTypes";
|
||||
import { PolicyRedactConfig } from "@app/components/policies/PolicyRedactConfig";
|
||||
import { PolicyWatermarkConfig } from "@app/components/policies/PolicyWatermarkConfig";
|
||||
import { ClassificationLabelsSection } from "@portal/components/policies/ClassificationLabelsSection";
|
||||
import "@portal/views/Policies.css";
|
||||
|
||||
/** Outline icon for a source tile, keyed by the backend source `type`. */
|
||||
function sourceIcon(type: string): ReactNode {
|
||||
const sx = { fontSize: "1.1rem" } as const;
|
||||
switch (type) {
|
||||
case "editor":
|
||||
return <EditOutlinedIcon sx={sx} />;
|
||||
case "folder":
|
||||
return <FolderOutlinedIcon sx={sx} />;
|
||||
case "s3":
|
||||
return <CloudOutlinedIcon sx={sx} />;
|
||||
default:
|
||||
return <StorageOutlinedIcon sx={sx} />;
|
||||
}
|
||||
}
|
||||
|
||||
interface PolicySetupWizardProps {
|
||||
/** The category being configured, or null when closed. */
|
||||
entry: CatalogueEntry | null;
|
||||
@@ -139,13 +119,6 @@ const CAPABILITY_META: Record<
|
||||
descKey: "portal.policies.wizard.capability.compress.desc",
|
||||
descEn: "Compresses the document to a smaller file size.",
|
||||
},
|
||||
classify: {
|
||||
labelKey: "portal.policies.wizard.capability.classify.label",
|
||||
labelEn: "Classify the document",
|
||||
descKey: "portal.policies.wizard.capability.classify.desc",
|
||||
descEn:
|
||||
"Identifies the document's type from your team's labels and tags it, so it files and searches by category.",
|
||||
},
|
||||
};
|
||||
|
||||
function seedTools(entry: CatalogueEntry): ToolState[] {
|
||||
@@ -206,18 +179,9 @@ function PolicySetupWizardBody({
|
||||
|
||||
const { category, config, policy } = entry;
|
||||
const isEdit = policy != null;
|
||||
const isClassification = category.id === "classification";
|
||||
|
||||
const [step, setStep] = useState<Step>("workflow");
|
||||
const [tools, setTools] = useState<ToolState[]>(() => {
|
||||
const seeded = seedTools(entry);
|
||||
// Classification's single tool has no toggle in the workflow step, so keep it
|
||||
// enabled unconditionally — otherwise editing a policy whose saved steps
|
||||
// somehow lack it would strand submit with no way to re-enable it.
|
||||
return isClassification
|
||||
? seeded.map((t) => ({ ...t, enabled: true }))
|
||||
: seeded;
|
||||
});
|
||||
const [tools, setTools] = useState<ToolState[]>(() => seedTools(entry));
|
||||
const [fieldValues, setFieldValues] = useState(() =>
|
||||
resolveFieldValues(entry),
|
||||
);
|
||||
@@ -226,25 +190,11 @@ function PolicySetupWizardBody({
|
||||
);
|
||||
|
||||
const sourcesAsync = useAsync(() => fetchSources(), []);
|
||||
const availableSources = useMemo(() => {
|
||||
const backendSources = (sourcesAsync.data?.sources ?? []).filter(
|
||||
(s) => s.status !== "disabled",
|
||||
);
|
||||
// The editor is always an available source. The backend now returns it as a
|
||||
// virtual source too, so take that when present (avoids a duplicate tile) and
|
||||
// otherwise fall back to a synthetic one; keep it first, selected by default.
|
||||
const editorSource = backendSources.find((s) => s.id === "editor") ?? {
|
||||
id: "editor",
|
||||
name: t("portal.sources.types.editor.label"),
|
||||
type: "editor",
|
||||
status: "active" as const,
|
||||
referenceCount: 0,
|
||||
referencingPolicies: [],
|
||||
config: [],
|
||||
docsTotal: null,
|
||||
};
|
||||
return [editorSource, ...backendSources.filter((s) => s.id !== "editor")];
|
||||
}, [sourcesAsync.data, t]);
|
||||
const availableSources = useMemo(
|
||||
() =>
|
||||
(sourcesAsync.data?.sources ?? []).filter((s) => s.status !== "disabled"),
|
||||
[sourcesAsync.data],
|
||||
);
|
||||
// Document-type scoping has no UI; preserve any saved scope on edit and
|
||||
// default new policies to all document types.
|
||||
const [scopeTypes] = useState<string[]>(policy?.state.scopeTypes ?? []);
|
||||
@@ -335,7 +285,7 @@ function PolicySetupWizardBody({
|
||||
title={
|
||||
<span className="portal-policies__wizard-title">
|
||||
<span className="portal-policies__cat-icon" aria-hidden>
|
||||
{policyCategoryIcon(category.id)}
|
||||
{policyIcon(category.icon)}
|
||||
</span>
|
||||
{isEdit
|
||||
? t("portal.policies.wizard.title.edit", {
|
||||
@@ -399,25 +349,7 @@ function PolicySetupWizardBody({
|
||||
/>
|
||||
)}
|
||||
|
||||
{step === "workflow" && isClassification && (
|
||||
<div className="portal-policies__wizard-section">
|
||||
<p className="portal-policies__wizard-desc">
|
||||
{t(
|
||||
"portal.policies.wizard.classification.description",
|
||||
"Every uploaded document is classified against the built-in labels and tagged with the types that fit. The label set is shared across your whole team.",
|
||||
)}
|
||||
</p>
|
||||
<h3 className="portal-policies__wizard-heading">
|
||||
{t(
|
||||
"portal.policies.wizard.classification.labelsHeading",
|
||||
"Classification labels",
|
||||
)}
|
||||
</h3>
|
||||
<ClassificationLabelsSection />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === "workflow" && !isClassification && (
|
||||
{step === "workflow" && (
|
||||
<div className="portal-policies__wizard-section">
|
||||
<p className="portal-policies__wizard-desc">
|
||||
{t(
|
||||
@@ -516,38 +448,35 @@ function PolicySetupWizardBody({
|
||||
// The backend always returns the editor as a virtual source, so the
|
||||
// loaded list is never empty - no "no sources" state exists.
|
||||
<div className="portal-policies__sources">
|
||||
{availableSources.map((src) => {
|
||||
const on = sources.includes(src.id);
|
||||
return (
|
||||
<Button
|
||||
key={src.id}
|
||||
variant={on ? "secondary" : "quiet"}
|
||||
justify="between"
|
||||
fullWidth
|
||||
className={
|
||||
"portal-policies__source" +
|
||||
(on ? " portal-policies__source--on" : "")
|
||||
}
|
||||
// The check keeps its slot when unselected (hidden) so the
|
||||
// icon + name stay put whether or not the tile is selected.
|
||||
rightSection={
|
||||
<CheckIcon
|
||||
sx={{
|
||||
fontSize: "1.1rem",
|
||||
visibility: on ? "visible" : "hidden",
|
||||
}}
|
||||
/>
|
||||
}
|
||||
onClick={() => toggleSource(src.id)}
|
||||
aria-pressed={on}
|
||||
>
|
||||
{availableSources.map((src) => (
|
||||
// A selectable multi-line tile (icon + name + type + check).
|
||||
// Uses the shared Button (raw <button> is lint-banned); the tile
|
||||
// CSS overrides the Button's fixed height for the two-line layout.
|
||||
<Button
|
||||
key={src.id}
|
||||
variant="quiet"
|
||||
justify="start"
|
||||
className={
|
||||
"portal-policies__source" +
|
||||
(sources.includes(src.id)
|
||||
? " portal-policies__source--on"
|
||||
: "")
|
||||
}
|
||||
onClick={() => toggleSource(src.id)}
|
||||
>
|
||||
<span className="portal-policies__source-icon" aria-hidden>
|
||||
{sourceTypeMeta(src.type).icon}
|
||||
</span>
|
||||
<span className="portal-policies__source-text">
|
||||
<span className="portal-policies__source-label">
|
||||
{sourceIcon(src.type)}
|
||||
{src.name}
|
||||
</span>
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
<span className="portal-policies__source-desc">
|
||||
{src.type}
|
||||
</span>
|
||||
</span>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Glyphs for the policy catalogue's string icon keys. The catalogue model
|
||||
* carries semantic keys (e.g. "shield", "layers") rather than React nodes so
|
||||
* the data stays portable; the portal owns the rendering and maps each key to a
|
||||
* glyph here.
|
||||
*/
|
||||
export const POLICY_ICON_GLYPHS: Record<string, string> = {
|
||||
layers: "▤",
|
||||
shield: "🛡",
|
||||
check: "✓",
|
||||
route: "⇉",
|
||||
clock: "⏲",
|
||||
// Source icons.
|
||||
file: "▢",
|
||||
device: "▣",
|
||||
globe: "◍",
|
||||
cloud: "☁",
|
||||
mail: "✉",
|
||||
folder: "▤",
|
||||
};
|
||||
|
||||
/** Resolve an icon key to its glyph, falling back to a neutral dot. */
|
||||
export function policyIcon(key: string): string {
|
||||
return POLICY_ICON_GLYPHS[key] ?? "•";
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
// AI-engine flag from the backend's public app-config. Gates Classification
|
||||
// setup: the card always shows but can't be enabled until the engine is on.
|
||||
// `loading` lets callers hold the decision rather than flash a locked card.
|
||||
|
||||
import { apiClient } from "@portal/api/http";
|
||||
import { useAsync } from "@portal/hooks/useAsync";
|
||||
|
||||
interface AppConfigShape {
|
||||
aiEngineEnabled?: boolean;
|
||||
}
|
||||
|
||||
export interface AiEngineState {
|
||||
enabled: boolean;
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
export function useAiEngineEnabled(): AiEngineState {
|
||||
const state = useAsync<AppConfigShape>(
|
||||
() => apiClient.local.json<AppConfigShape>("/api/v1/config/app-config"),
|
||||
[],
|
||||
);
|
||||
return {
|
||||
enabled: Boolean(state.data?.aiEngineEnabled),
|
||||
loading: state.loading && state.data === null,
|
||||
};
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import { http, HttpResponse } from "msw";
|
||||
|
||||
// The Classification policy only needs the app-config `aiEngineEnabled` flag to be
|
||||
// on; its label vocabulary is a fixed built-in set (no team endpoint anymore).
|
||||
|
||||
export const classificationHandlers = [
|
||||
http.get("/api/v1/config/app-config", () =>
|
||||
HttpResponse.json({ aiEngineEnabled: true }),
|
||||
),
|
||||
];
|
||||
@@ -12,7 +12,6 @@ import { usersHandlers } from "@portal/mocks/handlers/users";
|
||||
import { teamSaasHandlers } from "@portal/mocks/handlers/teamSaas";
|
||||
import { agentsHandlers } from "@portal/mocks/handlers/agents";
|
||||
import { policiesHandlers } from "@portal/mocks/handlers/policies";
|
||||
import { classificationHandlers } from "@portal/mocks/handlers/classification";
|
||||
import { documentsHandlers } from "@portal/mocks/handlers/documents";
|
||||
import { sdkComponentsHandlers } from "@portal/mocks/handlers/sdkComponents";
|
||||
import { editorDeployHandlers } from "@portal/mocks/handlers/editorDeploy";
|
||||
@@ -33,7 +32,6 @@ export const handlers = [
|
||||
...teamSaasHandlers,
|
||||
...agentsHandlers,
|
||||
...policiesHandlers,
|
||||
...classificationHandlers,
|
||||
...documentsHandlers,
|
||||
...sdkComponentsHandlers,
|
||||
...editorDeployHandlers,
|
||||
|
||||
@@ -266,23 +266,116 @@
|
||||
}
|
||||
|
||||
/* Sources picker */
|
||||
/* Selectable source tiles: a vertical stack of full-width shared Buttons
|
||||
(icon · name · check). Layout is the Button's own leftSection/label/
|
||||
rightSection — only the selected border/tint is added here. */
|
||||
.portal-policies__sources {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
@media (max-width: 40rem) {
|
||||
.portal-policies__sources {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.portal-policies__source {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.625rem;
|
||||
text-align: left;
|
||||
background: var(--color-surface);
|
||||
border: 1.5px solid var(--color-border);
|
||||
border-radius: var(--radius-md);
|
||||
cursor: pointer;
|
||||
/* Shared Button pins a fixed control height and natural width; this tile is a
|
||||
full-width, two-line card, so fill the grid cell and grow to fit content. */
|
||||
width: 100%;
|
||||
height: auto;
|
||||
font-weight: inherit;
|
||||
transition:
|
||||
border-color var(--motion-fast),
|
||||
background var(--motion-fast);
|
||||
}
|
||||
|
||||
/* The shared Button wraps children in an inner/label node. Let the inner grow
|
||||
(so the ::after check sits at the far right) and the label carry the
|
||||
icon + two-line-text row. */
|
||||
.portal-policies__source .mantine-Button-inner {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.portal-policies__source .mantine-Button-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
width: 100%;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.portal-policies__source::after {
|
||||
content: "";
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
margin-left: auto;
|
||||
width: 1rem;
|
||||
height: 1rem;
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1.5px solid var(--color-border-strong);
|
||||
transition:
|
||||
border-color var(--motion-fast),
|
||||
background var(--motion-fast);
|
||||
}
|
||||
|
||||
.portal-policies__source:hover {
|
||||
background: var(--color-bg-hover);
|
||||
}
|
||||
|
||||
.portal-policies__source--on {
|
||||
border-color: var(--color-blue);
|
||||
background: var(--color-blue-light);
|
||||
}
|
||||
|
||||
.portal-policies__source--on::after {
|
||||
content: "✓";
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
border-color: var(--color-blue);
|
||||
background: var(--color-blue);
|
||||
}
|
||||
|
||||
.portal-policies__source-icon {
|
||||
font-size: 1rem;
|
||||
line-height: 1.2;
|
||||
flex-shrink: 0;
|
||||
color: var(--color-text-3);
|
||||
}
|
||||
|
||||
.portal-policies__source--on .portal-policies__source-icon {
|
||||
color: var(--color-blue);
|
||||
}
|
||||
|
||||
.portal-policies__source-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.0625rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.portal-policies__source-label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
|
||||
.portal-policies__source-desc {
|
||||
font-size: 0.6875rem;
|
||||
color: var(--color-text-4);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.portal-policies__link {
|
||||
|
||||
@@ -20,7 +20,6 @@ import { CatalogueSummary } from "@portal/components/policies/CatalogueSummary";
|
||||
import { PolicyCategoryCard } from "@portal/components/policies/PolicyCategoryCard";
|
||||
import { PolicyDetailPanel } from "@portal/components/policies/PolicyDetailPanel";
|
||||
import { PolicySetupWizard } from "@portal/components/policies/PolicySetupWizard";
|
||||
import { useAiEngineEnabled } from "@portal/hooks/useAiEngineEnabled";
|
||||
import "@portal/views/Policies.css";
|
||||
|
||||
export function Policies() {
|
||||
@@ -35,18 +34,6 @@ export function Policies() {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [pageError, setPageError] = useState<string | null>(null);
|
||||
|
||||
const { enabled: aiEngineEnabled, loading: aiEngineLoading } =
|
||||
useAiEngineEnabled();
|
||||
|
||||
function isLocked(entry: CatalogueEntry): boolean {
|
||||
return (
|
||||
entry.category.requiresAiEngine === true &&
|
||||
!aiEngineEnabled &&
|
||||
!aiEngineLoading &&
|
||||
!entry.policy
|
||||
);
|
||||
}
|
||||
|
||||
const catalogue = data?.catalogue ?? [];
|
||||
const refetch = useCallback(() => setVersion((v) => v + 1), []);
|
||||
// The catalogue cards are always shown (they're the "configure a policy" CTAs),
|
||||
@@ -70,11 +57,6 @@ export function Policies() {
|
||||
}));
|
||||
|
||||
function openEntry(entry: CatalogueEntry) {
|
||||
// Block setup of an AI-required policy until the engine is confirmed on (so a
|
||||
// click during the app-config load can't open a wizard for a disabled
|
||||
// feature); a configured policy stays openable so it can be paused/deleted.
|
||||
if (entry.category.requiresAiEngine && !aiEngineEnabled && !entry.policy)
|
||||
return;
|
||||
if (entry.policy) setDetail(entry);
|
||||
else setWizard(entry);
|
||||
}
|
||||
@@ -175,8 +157,6 @@ export function Policies() {
|
||||
key={entry.category.id}
|
||||
entry={entry}
|
||||
onOpen={openEntry}
|
||||
locked={isLocked(entry)}
|
||||
lockedLabel={t("portal.policies.card.requiresAiEngine")}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
/* Category show/hide list (Files-sidebar visibility picker). */
|
||||
.category-visibility {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.category-visibility-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
min-height: 2.25rem;
|
||||
padding: 0 var(--space-1);
|
||||
}
|
||||
.category-visibility-icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex: none;
|
||||
color: var(--color-text-2);
|
||||
}
|
||||
.category-visibility-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: 0.875rem;
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
.category-visibility-count {
|
||||
font-size: 0.75rem;
|
||||
color: var(--color-text-3);
|
||||
}
|
||||
/* Hidden categories read as dimmed until re-shown. */
|
||||
.category-visibility-row--hidden .category-visibility-icon,
|
||||
.category-visibility-row--hidden .category-visibility-name,
|
||||
.category-visibility-row--hidden .category-visibility-count {
|
||||
opacity: 0.5;
|
||||
}
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { ClassificationCategoryManager } from "@app/components/policies/ClassificationCategoryManager";
|
||||
import type { SidebarCategory } from "@app/services/fileSidebarCategories";
|
||||
|
||||
const CATEGORIES: SidebarCategory[] = [
|
||||
{ id: "finance", name: "Financial", icon: "payments", labelKeys: [] },
|
||||
{ id: "legal", name: "Legal", icon: "gavel", labelKeys: [] },
|
||||
{ id: "hr", name: "HR", icon: "badge", labelKeys: [] },
|
||||
{ id: "reports", name: "Reports", icon: "monitoring", labelKeys: [] },
|
||||
];
|
||||
|
||||
const COUNTS = new Map<string, number>([
|
||||
["finance", 12],
|
||||
["legal", 4],
|
||||
["reports", 7],
|
||||
]);
|
||||
|
||||
// The store is device-local; the story holds the hidden state so the toggle is live.
|
||||
function Harness() {
|
||||
const [categories, setCategories] = useState(CATEGORIES);
|
||||
return (
|
||||
<div style={{ maxWidth: 420 }}>
|
||||
<ClassificationCategoryManager
|
||||
categories={categories}
|
||||
counts={COUNTS}
|
||||
onToggleHidden={(id, hidden) =>
|
||||
setCategories((prev) =>
|
||||
prev.map((c) => (c.id === id ? { ...c, hidden } : c)),
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const meta: Meta<typeof Harness> = {
|
||||
title: "Policies/ClassificationCategoryManager",
|
||||
component: Harness,
|
||||
parameters: { layout: "padded" },
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof Harness>;
|
||||
|
||||
/** Show/hide the fixed, shared categories in the Files sidebar. */
|
||||
export const Default: Story = {};
|
||||
@@ -1,68 +0,0 @@
|
||||
// Uber-simple category visibility list for the Files sidebar. Categories are the fixed, shared set
|
||||
// (the built-in label families) — they can't be created, renamed, re-grouped, or have their labels
|
||||
// edited. The only choice is showing or hiding each one in this device's sidebar; a hidden category
|
||||
// forms no group, so its files fall to "Other".
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import VisibilityIcon from "@mui/icons-material/Visibility";
|
||||
import VisibilityOffIcon from "@mui/icons-material/VisibilityOff";
|
||||
import { ActionIcon } from "@app/ui/ActionIcon";
|
||||
import { LocalIcon } from "@app/components/shared/LocalIcon";
|
||||
import type { SidebarCategory } from "@app/services/fileSidebarCategories";
|
||||
import "@app/components/policies/ClassificationCategoryManager.css";
|
||||
|
||||
interface ClassificationCategoryManagerProps {
|
||||
categories: SidebarCategory[];
|
||||
onToggleHidden: (id: string, hidden: boolean) => void;
|
||||
/** Optional per-category file counts. */
|
||||
counts?: Map<string, number>;
|
||||
}
|
||||
|
||||
export function ClassificationCategoryManager({
|
||||
categories,
|
||||
onToggleHidden,
|
||||
counts,
|
||||
}: ClassificationCategoryManagerProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<ul className="category-visibility">
|
||||
{categories.map((category) => {
|
||||
const count = counts?.get(category.id);
|
||||
return (
|
||||
<li
|
||||
key={category.id}
|
||||
className={
|
||||
category.hidden
|
||||
? "category-visibility-row category-visibility-row--hidden"
|
||||
: "category-visibility-row"
|
||||
}
|
||||
>
|
||||
<span className="category-visibility-icon">
|
||||
<LocalIcon icon={category.icon} width="1.1rem" />
|
||||
</span>
|
||||
<span className="category-visibility-name">{category.name}</span>
|
||||
{count !== undefined && (
|
||||
<span className="category-visibility-count">{count}</span>
|
||||
)}
|
||||
<ActionIcon
|
||||
variant="quiet"
|
||||
aria-pressed={!category.hidden}
|
||||
aria-label={
|
||||
category.hidden
|
||||
? t("policies.labels.showCategory", "Show category")
|
||||
: t("policies.labels.hideCategory", "Hide category")
|
||||
}
|
||||
onClick={() => onToggleHidden(category.id, !category.hidden)}
|
||||
>
|
||||
{category.hidden ? (
|
||||
<VisibilityOffIcon sx={{ fontSize: "1.1rem" }} />
|
||||
) : (
|
||||
<VisibilityIcon sx={{ fontSize: "1.1rem" }} />
|
||||
)}
|
||||
</ActionIcon>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* The Classification policy's team-labels control, shown in its Edit-Settings
|
||||
* view: a compact summary (count + chips) with an Expand button that opens the
|
||||
* fat {@link LabelsEditorModal}. Team-shared; only users who can configure
|
||||
* policies may edit it. Owns the editable draft and the load/save/import/export
|
||||
* wiring via {@link useClassificationLabels}.
|
||||
*/
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import OpenInFullIcon from "@mui/icons-material/OpenInFull";
|
||||
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
|
||||
import { Card } from "@app/ui/Card";
|
||||
import { Button } from "@app/ui/Button";
|
||||
import { Chip } from "@app/ui/Chip";
|
||||
import { Banner } from "@app/ui/Banner";
|
||||
import { useClassificationLabels } from "@app/hooks/useClassificationLabels";
|
||||
import { LabelsEditorModal } from "@app/components/policies/LabelsEditorModal";
|
||||
import {
|
||||
downloadLabels,
|
||||
parseLabelsFile,
|
||||
validateLabels,
|
||||
} from "@app/services/labelsFile";
|
||||
import {
|
||||
DEFAULT_CLASSIFICATION_LABELS,
|
||||
type ClassificationLabel,
|
||||
} from "@app/data/classificationLabels";
|
||||
import "@app/components/policies/LabelsEditor.css";
|
||||
|
||||
/** Chips shown in the collapsed team summary before it gets noisy. */
|
||||
const SUMMARY_CHIP_COUNT = 12;
|
||||
|
||||
interface ClassificationLabelsSectionProps {
|
||||
canConfigure: boolean;
|
||||
}
|
||||
|
||||
export function ClassificationLabelsSection({
|
||||
canConfigure,
|
||||
}: ClassificationLabelsSectionProps) {
|
||||
const { t } = useTranslation();
|
||||
const { teamLabels, isCustom, loading, saving, error, saveTeam } =
|
||||
useClassificationLabels(true);
|
||||
|
||||
const [draft, setDraft] = useState<ClassificationLabel[]>(teamLabels);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [localError, setLocalError] = useState<string | null>(null);
|
||||
|
||||
// Sync the draft to server truth whenever it changes (load / save / reset).
|
||||
// Local edits don't change `teamLabels`, so this never clobbers them mid-edit.
|
||||
useEffect(() => setDraft(teamLabels), [teamLabels]);
|
||||
|
||||
const dirty = useMemo(
|
||||
() => JSON.stringify(draft) !== JSON.stringify(teamLabels),
|
||||
[draft, teamLabels],
|
||||
);
|
||||
|
||||
const close = () => {
|
||||
setDraft(teamLabels);
|
||||
setLocalError(null);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const onImportFile = (file: File) => {
|
||||
setLocalError(null);
|
||||
void parseLabelsFile(file)
|
||||
.then(setDraft)
|
||||
.catch((e: unknown) =>
|
||||
setLocalError(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: t("policies.labels.importError", "Couldn't import that file."),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const onSave = () => {
|
||||
const errors = validateLabels({ labels: draft });
|
||||
if (errors.length > 0) {
|
||||
setLocalError(errors[0]);
|
||||
return;
|
||||
}
|
||||
setLocalError(null);
|
||||
void saveTeam(draft).then(() => setOpen(false));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="labels-summary">
|
||||
<p className="pol-section-label">
|
||||
{t("policies.labels.sectionLabel", "Classification labels")}
|
||||
</p>
|
||||
<Card>
|
||||
{loading ? (
|
||||
<span className="labels-empty">{t("loading", "Loading…")}</span>
|
||||
) : (
|
||||
<div className="labels-summary">
|
||||
<div className="labels-summary-stats">
|
||||
<span>
|
||||
<strong>{teamLabels.length}</strong>{" "}
|
||||
{t("policies.labels.teamCount", "team labels")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="labels-chips">
|
||||
{teamLabels.slice(0, SUMMARY_CHIP_COUNT).map((label) => (
|
||||
<Chip key={label.id} accent="neutral" size="sm">
|
||||
{label.name}
|
||||
</Chip>
|
||||
))}
|
||||
{teamLabels.length > SUMMARY_CHIP_COUNT && (
|
||||
<Chip accent="neutral" size="sm">
|
||||
+{teamLabels.length - SUMMARY_CHIP_COUNT}
|
||||
</Chip>
|
||||
)}
|
||||
</div>
|
||||
<span className="labels-summary-note">
|
||||
{isCustom
|
||||
? t("policies.labels.customNote", "Customized for your team.")
|
||||
: t(
|
||||
"policies.labels.defaultNote",
|
||||
"Using the built-in default, shared with your team.",
|
||||
)}
|
||||
</span>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
leftSection={<OpenInFullIcon sx={{ fontSize: "1rem" }} />}
|
||||
onClick={() => setOpen(true)}
|
||||
style={{ alignSelf: "flex-start" }}
|
||||
>
|
||||
{canConfigure
|
||||
? t("policies.labels.edit", "Edit labels")
|
||||
: t("policies.labels.view", "View labels")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{!canConfigure && (
|
||||
<Banner
|
||||
tone="neutral"
|
||||
icon={<LockOutlinedIcon sx={{ fontSize: "1rem" }} />}
|
||||
description={t(
|
||||
"policies.labels.managedNote",
|
||||
"Team labels are managed by your team leader.",
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{error && !open && <Banner tone="danger" description={error} />}
|
||||
|
||||
<LabelsEditorModal
|
||||
open={open}
|
||||
onClose={close}
|
||||
draft={draft}
|
||||
onDraftChange={setDraft}
|
||||
onImportFile={onImportFile}
|
||||
onExport={() => downloadLabels(draft)}
|
||||
onReset={() => {
|
||||
// Stage the built-in default into the draft — reversible via Cancel,
|
||||
// only persisted on Save (no immediate destructive server delete).
|
||||
setLocalError(null);
|
||||
setDraft(DEFAULT_CLASSIFICATION_LABELS);
|
||||
}}
|
||||
onClear={() => {
|
||||
// Stage an empty list to build from scratch — also reversible until Save.
|
||||
setLocalError(null);
|
||||
setDraft([]);
|
||||
}}
|
||||
onSave={onSave}
|
||||
dirty={dirty}
|
||||
saving={saving}
|
||||
readOnly={!canConfigure}
|
||||
error={localError ?? error}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* Small popover picker for a classification label's icon: a trigger button
|
||||
* showing the current icon, opening a grid of the curated
|
||||
* {@link LABEL_ICON_OPTIONS}. Icons render via {@link LocalIcon} (Material
|
||||
* Symbols). No search yet — the palette is small enough to scan.
|
||||
*/
|
||||
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Popover, SimpleGrid, Tooltip } from "@mantine/core";
|
||||
import { ActionIcon } from "@app/ui/ActionIcon";
|
||||
import { LocalIcon } from "@app/components/shared/LocalIcon";
|
||||
import { Z_INDEX_AUTOMATE_DROPDOWN } from "@app/styles/zIndex";
|
||||
import { LABEL_ICON_OPTIONS, DEFAULT_LABEL_ICON } from "@app/data/labelIcons";
|
||||
|
||||
interface LabelIconPickerProps {
|
||||
/** Current icon key, or undefined to show the default placeholder. */
|
||||
value?: string;
|
||||
onChange: (icon: string) => void;
|
||||
ariaLabel: string;
|
||||
}
|
||||
|
||||
export function LabelIconPicker({
|
||||
value,
|
||||
onChange,
|
||||
ariaLabel,
|
||||
}: LabelIconPickerProps) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<Popover
|
||||
opened={open}
|
||||
onChange={setOpen}
|
||||
onDismiss={() => setOpen(false)}
|
||||
position="bottom-start"
|
||||
withArrow
|
||||
trapFocus
|
||||
withinPortal
|
||||
zIndex={Z_INDEX_AUTOMATE_DROPDOWN}
|
||||
>
|
||||
<Popover.Target>
|
||||
<ActionIcon
|
||||
variant="quiet"
|
||||
className="labels-icon-pick"
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
aria-label={ariaLabel}
|
||||
aria-haspopup="true"
|
||||
>
|
||||
<LocalIcon icon={value || DEFAULT_LABEL_ICON} width="1.15rem" />
|
||||
</ActionIcon>
|
||||
</Popover.Target>
|
||||
<Popover.Dropdown p="xs" style={{ maxHeight: 280, overflowY: "auto" }}>
|
||||
<SimpleGrid cols={10} spacing={4} verticalSpacing={4}>
|
||||
{LABEL_ICON_OPTIONS.map((option) => {
|
||||
const iconLabel = t(
|
||||
`policies.labels.iconName.${option.icon}`,
|
||||
option.label,
|
||||
);
|
||||
return (
|
||||
<Tooltip
|
||||
key={option.icon}
|
||||
label={iconLabel}
|
||||
withArrow
|
||||
openDelay={300}
|
||||
>
|
||||
<ActionIcon
|
||||
variant="quiet"
|
||||
className={`labels-icon-option${option.icon === value ? " is-selected" : ""}`}
|
||||
onClick={() => {
|
||||
onChange(option.icon);
|
||||
setOpen(false);
|
||||
}}
|
||||
aria-label={t(
|
||||
"policies.labels.pickIcon",
|
||||
"Use {{label}} icon",
|
||||
{
|
||||
label: iconLabel,
|
||||
},
|
||||
)}
|
||||
aria-pressed={option.icon === value}
|
||||
>
|
||||
<LocalIcon icon={option.icon} width="1.25rem" />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
</SimpleGrid>
|
||||
</Popover.Dropdown>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
/* Classification-labels editor: add box, chip grid, icon picker, and the
|
||||
summary/modal chrome around them. */
|
||||
|
||||
.labels-editor {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
/* ---- Add box ---- */
|
||||
.labels-add {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
.labels-add-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 0.4rem 0.6rem;
|
||||
font-size: 0.8125rem;
|
||||
font-family: inherit;
|
||||
color: var(--color-text-1);
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: var(--radius-md);
|
||||
outline: none;
|
||||
transition: border-color var(--motion-fast);
|
||||
}
|
||||
.labels-add-input:focus {
|
||||
border-color: var(--color-blue);
|
||||
}
|
||||
.labels-add-error {
|
||||
margin: 0;
|
||||
font-size: 0.75rem;
|
||||
color: var(--color-red);
|
||||
}
|
||||
.labels-empty {
|
||||
margin: 0;
|
||||
font-size: 0.8125rem;
|
||||
color: var(--color-text-3);
|
||||
}
|
||||
|
||||
/* ---- Chip grid (chips themselves are the shared @app/ui/LabelChip) ---- */
|
||||
.labels-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1_5);
|
||||
overflow-y: auto;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
/* ---- Icon picker (trigger + popover options) ---- */
|
||||
.labels-icon-pick {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: none;
|
||||
width: 1.5rem;
|
||||
height: 1.5rem;
|
||||
border: none;
|
||||
border-radius: var(--radius-md);
|
||||
background: transparent;
|
||||
color: var(--color-text-2);
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background var(--motion-fast),
|
||||
color var(--motion-fast);
|
||||
}
|
||||
.labels-icon-pick:hover {
|
||||
background: var(--color-bg-hover);
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
.labels-icon-option {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
border: none;
|
||||
background: transparent;
|
||||
border-radius: var(--radius-md);
|
||||
color: var(--color-text-2);
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background var(--motion-fast),
|
||||
color var(--motion-fast);
|
||||
}
|
||||
.labels-icon-option:hover {
|
||||
background: var(--color-bg-hover);
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
.labels-icon-option.is-selected {
|
||||
background: var(--color-blue-light);
|
||||
color: var(--color-blue);
|
||||
}
|
||||
|
||||
/* ---- Section summary (Edit-Settings card) ---- */
|
||||
.labels-summary {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
.labels-summary-stats {
|
||||
display: flex;
|
||||
gap: var(--space-3);
|
||||
font-size: 0.8125rem;
|
||||
color: var(--color-text-2);
|
||||
}
|
||||
.labels-summary-note {
|
||||
font-size: 0.75rem;
|
||||
color: var(--color-text-3);
|
||||
}
|
||||
|
||||
/* ---- Fat modal ---- */
|
||||
.labels-modal {
|
||||
width: min(1100px, 94vw);
|
||||
max-width: min(1100px, 94vw);
|
||||
}
|
||||
.labels-modal-body {
|
||||
max-height: min(70vh, 640px);
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
min-height: 0;
|
||||
}
|
||||
.labels-toolbar {
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
.labels-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
width: 100%;
|
||||
}
|
||||
.labels-footer-left,
|
||||
.labels-footer-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
/* ---- Grouped mode: chips under collapsible parent categories ---- */
|
||||
.labels-groups {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
.labels-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
.labels-group-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-1, inherit);
|
||||
}
|
||||
.labels-group-name {
|
||||
flex: 1;
|
||||
text-align: left;
|
||||
}
|
||||
.labels-group-count {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 500;
|
||||
color: var(--color-text-3, rgba(128, 128, 128, 0.9));
|
||||
}
|
||||
.labels-group-ungrouped {
|
||||
margin: 0;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-2, inherit);
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
// Editor for a classification-label list: an add box on top, then the labels as chips (icon picker + remove), duplicate names rejected case-insensitively (optionally also against `reservedNames`). In `grouped` mode the chips are organised under collapsible parent categories (the device-local sidebar categories), matching the sidebar's category picker; labels in no category fall under "Ungrouped". Grouping is presentational — editing still mutates the flat list.
|
||||
|
||||
import { useMemo, useState, useSyncExternalStore, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import AddIcon from "@mui/icons-material/Add";
|
||||
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
|
||||
import KeyboardArrowRightIcon from "@mui/icons-material/KeyboardArrowRight";
|
||||
import { Button } from "@app/ui/Button";
|
||||
import { LabelChip } from "@app/ui/LabelChip";
|
||||
import { LocalIcon } from "@app/components/shared/LocalIcon";
|
||||
import { LabelIconPicker } from "@app/components/policies/LabelIconPicker";
|
||||
import { DEFAULT_LABEL_ICON } from "@app/data/labelIcons";
|
||||
import {
|
||||
getSidebarCategories,
|
||||
subscribeSidebarCategories,
|
||||
} from "@app/services/fileSidebarCategories";
|
||||
import {
|
||||
labelId,
|
||||
type ClassificationLabel,
|
||||
} from "@app/data/classificationLabels";
|
||||
|
||||
const MAX_TEXT_LENGTH = 128;
|
||||
|
||||
interface LabelsEditorProps {
|
||||
value: ClassificationLabel[];
|
||||
onChange: (next: ClassificationLabel[]) => void;
|
||||
readOnly?: boolean;
|
||||
/** Names that can't be added here because another set already owns them. */
|
||||
reservedNames?: string[];
|
||||
addPlaceholder?: string;
|
||||
emptyText?: string;
|
||||
/** Render chips under collapsible parent categories (like the sidebar picker). */
|
||||
grouped?: boolean;
|
||||
}
|
||||
|
||||
export function LabelsEditor({
|
||||
value,
|
||||
onChange,
|
||||
readOnly = false,
|
||||
reservedNames,
|
||||
addPlaceholder,
|
||||
emptyText,
|
||||
grouped = false,
|
||||
}: LabelsEditorProps) {
|
||||
const { t } = useTranslation();
|
||||
const [pending, setPending] = useState("");
|
||||
const [addError, setAddError] = useState<string | null>(null);
|
||||
|
||||
const add = () => {
|
||||
const name = pending.trim();
|
||||
if (!name) return;
|
||||
if (name.length > MAX_TEXT_LENGTH) {
|
||||
setAddError(
|
||||
t(
|
||||
"policies.labels.tooLong",
|
||||
"Labels can be at most {{max}} characters.",
|
||||
{ max: MAX_TEXT_LENGTH },
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const key = name.toLowerCase();
|
||||
const taken =
|
||||
value.some((label) => label.name.toLowerCase() === key) ||
|
||||
(reservedNames ?? []).some((reserved) => reserved.toLowerCase() === key);
|
||||
if (taken) {
|
||||
setAddError(
|
||||
t("policies.labels.duplicate", '"{{name}}" already exists.', { name }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
setAddError(null);
|
||||
setPending("");
|
||||
onChange([...value, { id: labelId(name), name }]);
|
||||
};
|
||||
|
||||
const removeById = (id: string) =>
|
||||
onChange(value.filter((label) => label.id !== id));
|
||||
|
||||
const setIconById = (id: string, icon: string) =>
|
||||
onChange(
|
||||
value.map((label) => (label.id === id ? { ...label, icon } : label)),
|
||||
);
|
||||
|
||||
const renderChip = (label: ClassificationLabel) => {
|
||||
const key = label.id;
|
||||
return (
|
||||
<LabelChip
|
||||
key={key}
|
||||
label={label.name}
|
||||
leading={
|
||||
readOnly ? (
|
||||
<span className="sui-labelchip-icon">
|
||||
<LocalIcon icon={label.icon || DEFAULT_LABEL_ICON} width="1rem" />
|
||||
</span>
|
||||
) : (
|
||||
<LabelIconPicker
|
||||
value={label.icon}
|
||||
onChange={(icon) => setIconById(key, icon)}
|
||||
ariaLabel={t(
|
||||
"policies.labels.iconAria",
|
||||
"Choose an icon for {{name}}",
|
||||
{ name: label.name },
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
onRemove={readOnly ? undefined : () => removeById(key)}
|
||||
removeAriaLabel={t("policies.labels.removeAria", "Remove {{name}}", {
|
||||
name: label.name,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="labels-editor">
|
||||
{!readOnly && (
|
||||
<div className="labels-add">
|
||||
<input
|
||||
className="labels-add-input"
|
||||
value={pending}
|
||||
maxLength={MAX_TEXT_LENGTH + 1}
|
||||
placeholder={
|
||||
addPlaceholder ??
|
||||
t("policies.labels.addPlaceholder", "Add a label…")
|
||||
}
|
||||
onChange={(e) => {
|
||||
setPending(e.target.value);
|
||||
if (addError) setAddError(null);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
add();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
leftSection={<AddIcon sx={{ fontSize: "1rem" }} />}
|
||||
onClick={add}
|
||||
disabled={!pending.trim()}
|
||||
>
|
||||
{t("policies.labels.add", "Add")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{addError && <p className="labels-add-error">{addError}</p>}
|
||||
|
||||
{value.length === 0 ? (
|
||||
<p className="labels-empty">
|
||||
{emptyText ?? t("policies.labels.empty", "No labels yet.")}
|
||||
</p>
|
||||
) : grouped ? (
|
||||
<GroupedLabels value={value} renderChip={renderChip} />
|
||||
) : (
|
||||
<div className="labels-chips" role="list">
|
||||
{value.map(renderChip)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface GroupedLabelsProps {
|
||||
value: ClassificationLabel[];
|
||||
renderChip: (label: ClassificationLabel) => ReactNode;
|
||||
}
|
||||
|
||||
/** Chips laid out under collapsible parent categories (device-local structure). */
|
||||
function GroupedLabels({ value, renderChip }: GroupedLabelsProps) {
|
||||
const { t } = useTranslation();
|
||||
const categories = useSyncExternalStore(
|
||||
subscribeSidebarCategories,
|
||||
getSidebarCategories,
|
||||
);
|
||||
|
||||
// Category sections that actually contain labels from `value`, plus the leftovers.
|
||||
const { sections, ungrouped } = useMemo(() => {
|
||||
const byId = new Map(value.map((l) => [l.id, l]));
|
||||
const claimed = new Set<string>();
|
||||
const sections = categories
|
||||
.map((category) => {
|
||||
const members = category.labelKeys
|
||||
.map((id) => byId.get(id))
|
||||
.filter((l): l is ClassificationLabel => !!l);
|
||||
members.forEach((m) => claimed.add(m.id));
|
||||
return { category, members };
|
||||
})
|
||||
.filter((s) => s.members.length > 0);
|
||||
const ungrouped = value.filter((l) => !claimed.has(l.id));
|
||||
return { sections, ungrouped };
|
||||
}, [value, categories]);
|
||||
|
||||
// Only the first section starts expanded — a scannable overview.
|
||||
const [expanded, setExpanded] = useState<ReadonlySet<string>>(
|
||||
() => new Set(sections.length > 0 ? [sections[0].category.id] : []),
|
||||
);
|
||||
const toggle = (id: string) =>
|
||||
setExpanded((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
return next;
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="labels-groups">
|
||||
{sections.map(({ category, members }) => {
|
||||
const isOpen = expanded.has(category.id);
|
||||
return (
|
||||
<section key={category.id} className="labels-group">
|
||||
<Button
|
||||
variant="quiet"
|
||||
fullWidth
|
||||
justify="between"
|
||||
className="labels-group-header"
|
||||
aria-expanded={isOpen}
|
||||
onClick={() => toggle(category.id)}
|
||||
leftSection={
|
||||
<>
|
||||
{isOpen ? (
|
||||
<KeyboardArrowDownIcon sx={{ fontSize: "1.1rem" }} />
|
||||
) : (
|
||||
<KeyboardArrowRightIcon sx={{ fontSize: "1.1rem" }} />
|
||||
)}
|
||||
<LocalIcon icon={category.icon} width="1.05rem" />
|
||||
</>
|
||||
}
|
||||
rightSection={
|
||||
<span className="labels-group-count">{members.length}</span>
|
||||
}
|
||||
>
|
||||
<span className="labels-group-name">{category.name}</span>
|
||||
</Button>
|
||||
{isOpen && (
|
||||
<div className="labels-chips" role="list">
|
||||
{members.map(renderChip)}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
{ungrouped.length > 0 && (
|
||||
<section className="labels-group">
|
||||
<p className="labels-group-ungrouped">
|
||||
{t("policies.labels.ungrouped", "Ungrouped")}
|
||||
</p>
|
||||
<div className="labels-chips" role="list">
|
||||
{ungrouped.map(renderChip)}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* Full-screen ("fat") editor for the team's classification labels — the roomy
|
||||
* view the settings summary's Edit button opens. Hosts the {@link LabelsEditor}
|
||||
* chip grid plus an Import/Export toolbar and a footer holding the destructive
|
||||
* actions (reset / start-from-scratch) and the Save/Cancel buttons. Editing is
|
||||
* staged: nothing is persisted until Save, which stays disabled until the draft
|
||||
* actually changes. The draft is owned by the caller so the settings summary
|
||||
* reflects saved changes.
|
||||
*/
|
||||
|
||||
import { useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import FileDownloadOutlinedIcon from "@mui/icons-material/FileDownloadOutlined";
|
||||
import FileUploadOutlinedIcon from "@mui/icons-material/FileUploadOutlined";
|
||||
import RestartAltIcon from "@mui/icons-material/RestartAlt";
|
||||
import DeleteSweepOutlinedIcon from "@mui/icons-material/DeleteSweepOutlined";
|
||||
import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
|
||||
import { Modal } from "@app/ui/Modal";
|
||||
import { Button } from "@app/ui/Button";
|
||||
import { Banner } from "@app/ui/Banner";
|
||||
import { LabelsEditor } from "@app/components/policies/LabelsEditor";
|
||||
import type { ClassificationLabel } from "@app/data/classificationLabels";
|
||||
|
||||
interface LabelsEditorModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
draft: ClassificationLabel[];
|
||||
onDraftChange: (next: ClassificationLabel[]) => void;
|
||||
onImportFile: (file: File) => void;
|
||||
onExport: () => void;
|
||||
/** Stage the built-in default into the draft. */
|
||||
onReset: () => void;
|
||||
/** Stage an empty list into the draft (build from scratch). */
|
||||
onClear: () => void;
|
||||
onSave: () => void;
|
||||
dirty: boolean;
|
||||
saving: boolean;
|
||||
readOnly: boolean;
|
||||
/** Save (server) or import (file) failure to surface, if any. */
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export function LabelsEditorModal({
|
||||
open,
|
||||
onClose,
|
||||
draft,
|
||||
onDraftChange,
|
||||
onImportFile,
|
||||
onExport,
|
||||
onReset,
|
||||
onClear,
|
||||
onSave,
|
||||
dirty,
|
||||
saving,
|
||||
readOnly,
|
||||
error,
|
||||
}: LabelsEditorModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleFile = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
// Reset the input so picking the same file twice still fires onChange.
|
||||
e.target.value = "";
|
||||
if (file) onImportFile(file);
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
width="xl"
|
||||
className="labels-modal"
|
||||
title={t("policies.labels.modalTitle", "Classification labels")}
|
||||
subtitle={t(
|
||||
"policies.labels.modalSubtitle",
|
||||
"Shared with your whole team. The classifier picks the labels that fit each document.",
|
||||
)}
|
||||
footer={
|
||||
<div className="labels-footer">
|
||||
<div className="labels-footer-left">
|
||||
{!readOnly && (
|
||||
<>
|
||||
<Button
|
||||
variant="tertiary"
|
||||
accent="danger"
|
||||
size="sm"
|
||||
leftSection={
|
||||
<DeleteSweepOutlinedIcon sx={{ fontSize: "1rem" }} />
|
||||
}
|
||||
onClick={onClear}
|
||||
disabled={saving}
|
||||
>
|
||||
{t("policies.labels.startFromScratch", "Start from scratch")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="tertiary"
|
||||
accent="danger"
|
||||
size="sm"
|
||||
leftSection={<RestartAltIcon sx={{ fontSize: "1rem" }} />}
|
||||
onClick={onReset}
|
||||
disabled={saving}
|
||||
>
|
||||
{t("policies.labels.resetToDefault", "Reset to default")}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="labels-footer-right">
|
||||
<Button variant="tertiary" size="sm" onClick={onClose}>
|
||||
{readOnly ? t("close", "Close") : t("cancel", "Cancel")}
|
||||
</Button>
|
||||
{!readOnly && (
|
||||
<Button
|
||||
variant="primary"
|
||||
size="sm"
|
||||
onClick={onSave}
|
||||
disabled={!dirty || saving}
|
||||
>
|
||||
{saving
|
||||
? t("policies.labels.saving", "Saving…")
|
||||
: t("policies.labels.saveForTeam", "Save for team")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="labels-modal-body">
|
||||
{error && (
|
||||
<Banner
|
||||
tone="danger"
|
||||
icon={<InfoOutlinedIcon sx={{ fontSize: "1rem" }} />}
|
||||
description={error}
|
||||
/>
|
||||
)}
|
||||
{!readOnly && (
|
||||
<div className="labels-toolbar">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
leftSection={<FileUploadOutlinedIcon sx={{ fontSize: "1rem" }} />}
|
||||
onClick={() => fileInput.current?.click()}
|
||||
>
|
||||
{t("policies.labels.import", "Import JSON")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
leftSection={
|
||||
<FileDownloadOutlinedIcon sx={{ fontSize: "1rem" }} />
|
||||
}
|
||||
onClick={onExport}
|
||||
>
|
||||
{t("policies.labels.export", "Export JSON")}
|
||||
</Button>
|
||||
<input
|
||||
ref={fileInput}
|
||||
type="file"
|
||||
accept="application/json,.json"
|
||||
hidden
|
||||
onChange={handleFile}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<LabelsEditor
|
||||
value={draft}
|
||||
onChange={onDraftChange}
|
||||
readOnly={readOnly}
|
||||
grouped
|
||||
/>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* The fixed, configurable tool chain per policy category — the locked set the
|
||||
* config page shows (one section per tool). Tools can be configured + toggled
|
||||
* on/off, but not added or removed. Each id is a frontend tool-registry key (and
|
||||
* maps to that tool's backend endpoint via the registry's operationConfig).
|
||||
*/
|
||||
export const POLICY_TOOL_CHAINS: Record<string, string[]> = {
|
||||
// Security: redact PII + watermark + sanitize (strips JS). Which are enabled
|
||||
// by default comes from the preset's defaultOperations, not this list.
|
||||
security: ["redact", "watermark", "sanitize"],
|
||||
// Classification: a single backend step that classifies the document and
|
||||
// writes the result into its metadata.
|
||||
classification: ["classify"],
|
||||
};
|
||||
|
||||
/** The configurable tool chain for a category, or null if it has none yet. */
|
||||
export function getPolicyToolChain(categoryId: string): string[] | null {
|
||||
return POLICY_TOOL_CHAINS[categoryId] ?? null;
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { DEFAULT_CLASSIFICATION_LABELS } from "@app/data/classificationLabels";
|
||||
|
||||
// The classifier vocabulary is bundled in TWO places that must not drift:
|
||||
// - this frontend JSON (source of truth for sidebar categories + display names)
|
||||
// - a backend copy the classify tool sends to the AI engine per request
|
||||
// (app/proprietary/src/main/resources/classification/classification-labels.json).
|
||||
// The backend sends label IDS the engine stores on the document and the frontend
|
||||
// then displays, so a divergence means the classifier picks a label the UI can't
|
||||
// render (or the UI advertises labels the classifier never uses). This guards it.
|
||||
|
||||
const REPO_ROOT = path.resolve(__dirname, "../../../../..");
|
||||
const BACKEND_LABELS_FILE = path.join(
|
||||
REPO_ROOT,
|
||||
"app/proprietary/src/main/resources/classification/classification-labels.json",
|
||||
);
|
||||
|
||||
interface Label {
|
||||
id: string;
|
||||
name: string;
|
||||
icon?: string | null;
|
||||
}
|
||||
|
||||
function readBackendLabels(): Label[] {
|
||||
const raw = JSON.parse(fs.readFileSync(BACKEND_LABELS_FILE, "utf8")) as {
|
||||
labels: Label[];
|
||||
};
|
||||
return raw.labels;
|
||||
}
|
||||
|
||||
describe("classification label vocabulary (frontend ↔ backend)", () => {
|
||||
const frontend = DEFAULT_CLASSIFICATION_LABELS;
|
||||
const backend = readBackendLabels();
|
||||
|
||||
it("has the identical set of label ids on both sides", () => {
|
||||
const frontendIds = [...new Set(frontend.map((l) => l.id))].sort();
|
||||
const backendIds = [...new Set(backend.map((l) => l.id))].sort();
|
||||
expect(backendIds).toEqual(frontendIds);
|
||||
});
|
||||
|
||||
it("has matching name and icon per id on both sides", () => {
|
||||
const backendById = new Map(backend.map((l) => [l.id, l]));
|
||||
for (const label of frontend) {
|
||||
const other = backendById.get(label.id);
|
||||
expect(other, `backend missing label "${label.id}"`).toBeDefined();
|
||||
expect({ name: other!.name, icon: other!.icon ?? null }).toEqual({
|
||||
name: label.name,
|
||||
icon: label.icon ?? null,
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,14 @@
|
||||
// Classification labels. The SOURCE OF TRUTH is the co-located static JSON
|
||||
// (`classificationLabels.json`), imported here and shaped into typed objects —
|
||||
// edit THAT file, not this one. It's a fixed, built-in vocabulary shared by
|
||||
// everyone (no per-team customization); it drives the sidebar's grouping, icons,
|
||||
// and display names.
|
||||
// Default classification labels. The SOURCE OF TRUTH is the co-located static
|
||||
// JSON (`classificationLabels.json`), imported here and shaped into typed
|
||||
// objects — edit THAT file, not this one. This is the ONLY copy of the label
|
||||
// data: it seeds a team's editable set and drives the sidebar's grouping,
|
||||
// icons, and display names. Neither the backend nor the engine keeps a copy.
|
||||
//
|
||||
// The backend keeps a SECOND copy of this list
|
||||
// (`app/proprietary/src/main/resources/classification/classification-labels.json`)
|
||||
// which it sends to the engine per classify request (the engine holds no
|
||||
// vocabulary of its own). The two copies must not drift — `classificationLabels.drift.test.ts`
|
||||
// guards that. When you edit the labels here, update the backend copy too.
|
||||
// NOTE: this is only the built-in default vocabulary. A team's own
|
||||
// (admin-editable) labels live in the backend store and are what the backend
|
||||
// sends to the engine per classify request — the engine holds no vocabulary of
|
||||
// its own. Edits to a team's set reach Python on the next run, independent of
|
||||
// this file.
|
||||
//
|
||||
// `labels` is the flat set: each has a stable `id` (slug — the value on the wire,
|
||||
// in storage and keyed on) and a human `name` (display, translatable via
|
||||
|
||||
@@ -1,21 +1,22 @@
|
||||
/**
|
||||
* Curated palette of icons the classification labels use, rendered in the file
|
||||
* sidebar's label/category groups. Keys are Material Symbols names rendered via
|
||||
* {@link LocalIcon}.
|
||||
* Curated palette of icons a classification label can use, shown in the label
|
||||
* icon picker and rendered in the file sidebar's label groups. Keys are
|
||||
* Material Symbols names rendered via {@link LocalIcon}.
|
||||
*
|
||||
* IMPORTANT — this list is also the icon BUNDLING MANIFEST for classification.
|
||||
* The label/family icons live in `classificationLabels.json`, but the bundler
|
||||
* (`scripts/generate-icons.js`) only regex-scans `.ts/.tsx` for `icon: "…"`
|
||||
* literals, not JSON — so every icon those labels use must appear here as a
|
||||
* literal or it falls back to the CDN and renders blank offline. Do NOT delete
|
||||
* `LABEL_ICON_OPTIONS` as "unused": nothing imports it, but it's load-bearing
|
||||
* for offline icons. After editing, run `task frontend:prepare:icons`.
|
||||
* IMPORTANT: each entry is written as an `icon: "…"` literal so the icon-bundler
|
||||
* (`scripts/generate-icons.js`, which regex-scans for icon literals) picks every
|
||||
* one up and bundles it — otherwise a picked icon would fall back to the CDN and
|
||||
* render blank offline. After adding/removing entries run `task frontend:prepare:icons`.
|
||||
*
|
||||
* Search is intentionally omitted for now (no synonyms to maintain); the palette
|
||||
* is small enough to eyeball.
|
||||
*/
|
||||
|
||||
export interface LabelIconOption {
|
||||
/** Material Symbols key (no `material-symbols:` prefix). */
|
||||
icon: string;
|
||||
/** Short English name for the icon (documentation only). */
|
||||
/** Short English name — the en-US default for the icon's tooltip/aria; the
|
||||
* picker translates it via `policies.labels.iconName.<icon>`. */
|
||||
label: string;
|
||||
}
|
||||
|
||||
@@ -187,3 +188,8 @@ export const LABEL_ICON_OPTIONS: LabelIconOption[] = [
|
||||
{ icon: "recycling", label: "Recycling" },
|
||||
{ icon: "agriculture", label: "Agriculture" },
|
||||
];
|
||||
|
||||
/** Set of valid palette keys, for validating a stored/imported icon. */
|
||||
export const LABEL_ICON_KEYS: ReadonlySet<string> = new Set(
|
||||
LABEL_ICON_OPTIONS.map((option) => option.icon),
|
||||
);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user