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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 133 additions & 0 deletions src/components/PatronAuthServiceEditForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import * as React from "react";
import { PatronAuthServicesData } from "../interfaces";
import {
LibraryWithSettingsData,
PatronBlockingRule,
ProtocolData,
} from "../interfaces";
Comment on lines +2 to +7
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion - combine these two into a single import.

import ServiceEditForm from "./ServiceEditForm";
import PatronBlockingRulesEditor, {
PatronBlockingRulesEditorHandle,
} from "./PatronBlockingRulesEditor";
import { supportsPatronBlockingRules } from "../utils/patronBlockingRules";

/** Extends ServiceEditForm with patron-blocking-rules support for protocols that
* support it. The editor is injected via the hook methods added
* to ServiceEditForm; editLibrary and addLibrary are overridden to collect the
* rules from the editor ref and persist them in library state. */
export default class PatronAuthServiceEditForm extends ServiceEditForm<
PatronAuthServicesData
> {
private newLibraryRulesRef = React.createRef<
PatronBlockingRulesEditorHandle
>();
private libraryRulesRefs = new Map<
string,
React.RefObject<PatronBlockingRulesEditorHandle>
>();

private getOrCreateLibraryRef(
shortName: string
): React.RefObject<PatronBlockingRulesEditorHandle> {
if (!this.libraryRulesRefs.has(shortName)) {
this.libraryRulesRefs.set(
shortName,
React.createRef<PatronBlockingRulesEditorHandle>()
);
}
return this.libraryRulesRefs.get(shortName);
}

protocolHasLibrarySettings(protocol: ProtocolData): boolean {
return (
super.protocolHasLibrarySettings(protocol) ||
supportsPatronBlockingRules(protocol && protocol.name)
);
}

renderExtraExpandedLibrarySettings(
library: LibraryWithSettingsData,
protocol: ProtocolData,
disabled: boolean
): React.ReactNode {
if (!supportsPatronBlockingRules(protocol && protocol.name)) {
return null;
}
return (
<PatronBlockingRulesEditor
ref={this.getOrCreateLibraryRef(library.short_name)}
value={(library.patron_blocking_rules as PatronBlockingRule[]) || []}
disabled={disabled}
error={this.props.error}
/>
);
}

renderExtraNewLibrarySettings(
protocol: ProtocolData,
disabled: boolean
): React.ReactNode {
if (!supportsPatronBlockingRules(protocol && protocol.name)) {
return null;
}
return (
<PatronBlockingRulesEditor
ref={this.newLibraryRulesRef}
value={[]}
disabled={disabled}
error={this.props.error}
/>
);
}

editLibrary(library: LibraryWithSettingsData, protocol: ProtocolData) {
const libraries = this.state.libraries.filter(
(stateLibrary) => stateLibrary.short_name !== library.short_name
);
const expandedLibraries = this.state.expandedLibraries.filter(
(shortName) => shortName !== library.short_name
);
const newLibrary: LibraryWithSettingsData = {
short_name: library.short_name,
};
for (const setting of this.protocolLibrarySettings(protocol)) {
const value = (this.refs[
`${library.short_name}_${setting.key}`
] as any).getValue();
if (value) {
newLibrary[setting.key] = value;
}
}
if (supportsPatronBlockingRules(protocol && protocol.name)) {
const editorRef = this.libraryRulesRefs.get(library.short_name);
if (editorRef?.current) {
newLibrary.patron_blocking_rules = editorRef.current.getValue();
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to check for support here? Won't editorRef be undefined, since the editor wasn't rendered?

Suggested change
}
const editorRef = this.libraryRulesRefs.get(library.short_name);
if (editorRef?.current) {
newLibrary.patron_blocking_rules = editorRef.current.getValue();
}

libraries.push(newLibrary);
this.setState(
Object.assign({}, this.state, { libraries, expandedLibraries })
);
}

addLibrary(protocol: ProtocolData) {
const name = this.state.selectedLibrary;
const newLibrary: LibraryWithSettingsData = { short_name: name };
for (const setting of this.protocolLibrarySettings(protocol)) {
const value = (this.refs[setting.key] as any).getValue();
if (value) {
newLibrary[setting.key] = value;
}
(this.refs[setting.key] as any).clear();
}
if (supportsPatronBlockingRules(protocol && protocol.name)) {
if (this.newLibraryRulesRef.current) {
newLibrary.patron_blocking_rules = this.newLibraryRulesRef.current.getValue();
}
}
Comment on lines +123 to +127
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar comment here...

Suggested change
if (supportsPatronBlockingRules(protocol && protocol.name)) {
if (this.newLibraryRulesRef.current) {
newLibrary.patron_blocking_rules = this.newLibraryRulesRef.current.getValue();
}
}
if (this.newLibraryRulesRef.current) {
newLibrary.patron_blocking_rules = this.newLibraryRulesRef.current.getValue();
}

const libraries = this.state.libraries.concat(newLibrary);
this.setState(
Object.assign({}, this.state, { libraries, selectedLibrary: null })
);
}
}
4 changes: 2 additions & 2 deletions src/components/PatronAuthServices.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import EditableConfigList, {
import { connect } from "react-redux";
import ActionCreator from "../actions";
import { PatronAuthServicesData, PatronAuthServiceData } from "../interfaces";
import ServiceEditForm from "./ServiceEditForm";
import PatronAuthServiceEditForm from "./PatronAuthServiceEditForm";
import NeighborhoodAnalyticsForm from "./NeighborhoodAnalyticsForm";

/** Right panel for patron authentication services on the system
Expand All @@ -18,7 +18,7 @@ export class PatronAuthServices extends EditableConfigList<
PatronAuthServicesData,
PatronAuthServiceData
> {
EditForm = ServiceEditForm;
EditForm = PatronAuthServiceEditForm;
ExtraFormSection = NeighborhoodAnalyticsForm;
extraFormKey = "neighborhood_mode";
listDataKey = "patron_auth_services";
Expand Down
193 changes: 193 additions & 0 deletions src/components/PatronBlockingRulesEditor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
import * as React from "react";
import { Button } from "library-simplified-reusable-components";
import { FetchErrorData } from "@thepalaceproject/web-opds-client/lib/interfaces";
import { PatronBlockingRule } from "../interfaces";
import EditableInput from "./EditableInput";
import WithRemoveButton from "./WithRemoveButton";

function extractErrorMessage(error: FetchErrorData): string | null {
if (!error || error.status < 400) return null;
const resp = error.response as string;
if (!resp) return null;
try {
return JSON.parse(resp).detail || resp;
} catch {
return resp;
}
}

export interface PatronBlockingRulesEditorProps {
value?: PatronBlockingRule[];
disabled?: boolean;
error?: FetchErrorData;
}

export interface PatronBlockingRulesEditorHandle {
getValue: () => PatronBlockingRule[];
validateAndGetValue: () => PatronBlockingRule[] | null;
}

type ClientErrors = { [index: number]: { name?: boolean; rule?: boolean } };

/** Protocol-agnostic editor for a list of patron blocking rules stored in library settings. */
const PatronBlockingRulesEditor = React.forwardRef<
PatronBlockingRulesEditorHandle,
PatronBlockingRulesEditorProps
>(({ value = [], disabled = false, error }, ref) => {
const [rules, setRules] = React.useState<PatronBlockingRule[]>(() =>
(value || []).map((r) => ({ ...r }))
);
const [clientErrors, setClientErrors] = React.useState<ClientErrors>({});

const serverErrorMessage = extractErrorMessage(error);

React.useImperativeHandle(
ref,
() => ({
getValue: () => rules,
validateAndGetValue: () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see validateAndGetValue being called anywhere. Seems like the validation should happen no later than saving (add / edit in PatronAuthServiceEditForm.tsx). Ideally, it would happen as each rule is added, but that is difficult with the current architecture.

Also, it doesn't look like this is tested.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm going to revisit this to see if there is a way for us to validate a rule based on the current state of the Patron Auth Provider settings.

const errors: ClientErrors = {};
let valid = true;
rules.forEach((r, i) => {
const rowErrors: { name?: boolean; rule?: boolean } = {};
if (!r.name) {
rowErrors.name = true;
valid = false;
}
if (!r.rule) {
rowErrors.rule = true;
valid = false;
}
if (Object.keys(rowErrors).length > 0) {
errors[i] = rowErrors;
}
});
setClientErrors(errors);
return valid ? rules : null;
},
}),
[rules]
);

const addRule = () => {
setRules((prev) => [...prev, { name: "", rule: "", message: "" }]);
};

const removeRule = (index: number) => {
setRules((prev) => prev.filter((_, i) => i !== index));
setClientErrors((prev) => {
const next = { ...prev };
delete next[index];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like the rule and errors indices could get out of sync here. We're deleting something possibly from the middle of the error entries, but not re-keying the index for positions after the deletion.

Adding a general test for sync between rules and errors after deletion would clear this up one way or the other.

return next;
});
};

const updateRule = (
index: number,
field: keyof PatronBlockingRule,
value: string
) => {
setRules((prev) =>
prev.map((r, i) => (i === index ? { ...r, [field]: value } : r))
);
if (field === "name" || field === "rule") {
setClientErrors((prev) => {
if (!prev[index]) return prev;
return { ...prev, [index]: { ...prev[index], [field]: !value } };
});
}
};

return (
<div className="patron-blocking-rules-editor">
<div className="patron-blocking-rules-header">
<label className="control-label">Patron Blocking Rules</label>
<Button
type="button"
className="add-patron-blocking-rule"
disabled={disabled}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion - This button should also be disabled whenever there is an incomplete rule (missing any required field) in the form. Otherwise, a user can just create a bunch of incomplete rules.

Currently, this is disabled with just the prop that is passed when the this component is mounted.

callback={addRule}
content="Add Rule"
/>
</div>
{serverErrorMessage && rules.length > 0 && (
<p className="patron-blocking-rule-field-error text-danger">
{serverErrorMessage}
</p>
)}
Comment on lines +113 to +117
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want to suppress a server error message just because there are no rules? Would that message be displayed somewhere else or just hidden entirely?

{rules.length === 0 && (
<p className="no-rules-message">No patron blocking rules defined.</p>
)}
<ul className="patron-blocking-rules-list list-unstyled">
{rules.map((rule, index) => {
const rowErrors = clientErrors[index] || {};
const nameClientError = !!rowErrors.name;
const ruleClientError = !!rowErrors.rule;

return (
<li key={index} className="patron-blocking-rule-row">
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using index for the key here is potentially problematic because it is not unique for a given rule. So, it is possible that the wrong data could be display because the DOM is confused. For example, if we have more than one rule and we delete the first one, then the second one will end up with the index that used to belong to the first one. When that happens, the DOM may not understand that it needs to update that <li>.

<WithRemoveButton
disabled={disabled}
onRemove={() => removeRule(index)}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because of the way removeRule works, it looks like removing a rule from the list could lead to errors being out of sync with the errors, since the latter is not sync'd when a rule is removed.

>
<div className="patron-blocking-rule-fields">
{nameClientError && (
<p className="patron-blocking-rule-field-error text-danger">
Rule Name is required.
</p>
)}
<EditableInput
elementType="input"
type="text"
label="Rule Name"
name={`patron_blocking_rule_name_${index}`}
value={rule.name}
required={true}
disabled={disabled}
readOnly={disabled}
optionalText={false}
clientError={rowErrors.name}
error={error}
onChange={(value) => updateRule(index, "name", value)}
/>
{ruleClientError && (
<p className="patron-blocking-rule-field-error text-danger">
Rule Expression is required.
</p>
)}
<EditableInput
elementType="textarea"
label="Rule Expression"
name={`patron_blocking_rule_rule_${index}`}
value={rule.rule}
required={true}
disabled={disabled}
readOnly={disabled}
optionalText={false}
clientError={rowErrors.rule}
error={error}
onChange={(value) => updateRule(index, "rule", value)}
/>
<EditableInput
elementType="textarea"
label="Message (optional)"
name={`patron_blocking_rule_message_${index}`}
value={rule.message || ""}
disabled={disabled}
readOnly={disabled}
optionalText={false}
onChange={(value) => updateRule(index, "message", value)}
/>
</div>
</WithRemoveButton>
</li>
Comment on lines +127 to +183
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion - Factor this out into its own little RuleFormListItem (or similarly named) component. This is really a lot to pack into the middle of some JSX and makes it difficult to reason over the function of this code.

);
})}
</ul>
</div>
);
});

PatronBlockingRulesEditor.displayName = "PatronBlockingRulesEditor";

export default PatronBlockingRulesEditor;
Loading