Introduce new TreeView UI component

Key highlights:

- Written from scratch to cater specifically to privacy.sexy's
  needs and requirements.
- The visual look mimics the previous component with minimal changes,
  but its internal code is completely rewritten.
- Lays groundwork for future functionalities like the "expand all"
  button a flat view mode as discussed in #158.
- Facilitates the transition to Vue 3 by omitting the Vue 2.0 dependent
  `liquour-tree` as part of #230.

Improvements and features:

- Caching for quicker node queries.
- Gradual rendering of nodes that introduces a noticable boost in
  performance, particularly during search/filtering.
  - `TreeView` solely governs the check states of branch nodes.

Changes:

- Keyboard interactions now alter the background color to highlight the
  focused item. Previously, it was changing the color of the text.
- Better state management with clear separation of concerns:
  - `TreeView` exclusively manages indeterminate states.
  - `TreeView` solely governs the check states of branch nodes.
  - Introduce transaction pattern to update state in batches to minimize
    amount of events handled.
- Improve keyboard focus, style background instead of foreground. Use
  hover/touch color on keyboard focus.
- `SelectableTree` has been removed. Instead, `TreeView` is now directly
  integrated with `ScriptsTree`.
- `ScriptsTree` has been refactored to incorporate hooks for clearer
  code and separation of duties.
- Adopt Vue-idiomatic bindings instead of keeping a reference of the
  tree component.
- Simplify and change filter event management.
- Abandon global styles in favor of class-scoped styles.
- Use global mixins with descriptive names to clarify indended
  functionality.
This commit is contained in:
undergroundwires
2023-09-09 22:26:21 +02:00
parent 821cc62c4c
commit 65f121c451
120 changed files with 4537 additions and 1203 deletions

View File

@@ -0,0 +1,104 @@
import { describe, it, expect } from 'vitest';
import { createRenderer } from '@/presentation/components/Scripts/View/Tree/NodeContent/Documentation/MarkdownRenderer';
describe('MarkdownRenderer', () => {
describe('createRenderer', () => {
it('can create', () => {
// arrange & act
const renderer = createRenderer();
// assert
expect(renderer !== undefined);
});
describe('sets expected anchor attributes', () => {
const attributes: ReadonlyArray<{
readonly name: string,
readonly expectedValue: string,
readonly invalidMarkdown: string
}> = [
{
name: 'target',
expectedValue: '_blank',
invalidMarkdown: '<a href="https://undergroundwires.dev" target="_self">example</a>',
},
{
name: 'rel',
expectedValue: 'noopener noreferrer',
invalidMarkdown: '<a href="https://undergroundwires.dev" rel="nooverride">example</a>',
},
];
for (const attribute of attributes) {
const { name, expectedValue, invalidMarkdown } = attribute;
it(`adds "${name}" attribute to anchor elements`, () => {
// arrange
const renderer = createRenderer();
const markdown = '[undergroundwires.dev](https://undergroundwires.dev)';
// act
const htmlString = renderer.render(markdown);
// assert
const html = parseHtml(htmlString);
const aElement = html.getElementsByTagName('a')[0];
expect(aElement.getAttribute(name)).to.equal(expectedValue);
});
it(`overrides existing "${name}" attribute`, () => {
// arrange
const renderer = createRenderer();
// act
const htmlString = renderer.render(invalidMarkdown);
// assert
const html = parseHtml(htmlString);
const aElement = html.getElementsByTagName('a')[0];
expect(aElement.getAttribute(name)).to.equal(expectedValue);
});
}
});
it('does not convert single linebreak to <br>', () => {
// arrange
const renderer = createRenderer();
const markdown = 'Text with\nSingle\nLinebreaks';
// act
const htmlString = renderer.render(markdown);
// assert
const html = parseHtml(htmlString);
const totalBrElements = html.getElementsByTagName('br').length;
expect(totalBrElements).to.equal(0);
});
it('creates links for plain URL', () => {
// arrange
const renderer = createRenderer();
const expectedUrl = 'https://privacy.sexy/';
const markdown = `Visit ${expectedUrl} now!`;
// act
const htmlString = renderer.render(markdown);
// assert
const html = parseHtml(htmlString);
const aElement = html.getElementsByTagName('a')[0];
const href = aElement.getAttribute('href');
expect(href).to.equal(expectedUrl);
});
it('it generates beautiful labels for auto-linkified URL', () => {
// arrange
const renderer = createRenderer();
const url = 'https://privacy.sexy';
const expectedText = 'privacy.sexy';
const markdown = `Visit ${url} now!`;
// act
const htmlString = renderer.render(markdown);
// assert
const html = parseHtml(htmlString);
const aElement = html.getElementsByTagName('a')[0];
expect(aElement.text).to.equal(expectedText);
});
});
});
function parseHtml(htmlString: string): Document {
const parser = new window.DOMParser();
const htmlDoc = parser.parseFromString(htmlString, 'text/html');
return htmlDoc;
}

View File

@@ -0,0 +1,106 @@
import { describe, it, expect } from 'vitest';
import { CategoryReverter } from '@/presentation/components/Scripts/View/Tree/NodeContent/Reverter/CategoryReverter';
import { SelectedScript } from '@/application/Context/State/Selection/SelectedScript';
import { UserSelection } from '@/application/Context/State/Selection/UserSelection';
import { CategoryStub } from '@tests/unit/shared/Stubs/CategoryStub';
import { CategoryCollectionStub } from '@tests/unit/shared/Stubs/CategoryCollectionStub';
import { ScriptStub } from '@tests/unit/shared/Stubs/ScriptStub';
import { getCategoryNodeId } from '@/presentation/components/Scripts/View/Tree/TreeViewAdapter/CategoryNodeMetadataConverter';
describe('CategoryReverter', () => {
describe('getState', () => {
// arrange
const scripts = [
new ScriptStub('revertable').withRevertCode('REM revert me'),
new ScriptStub('revertable2').withRevertCode('REM revert me 2'),
];
const category = new CategoryStub(1).withScripts(...scripts);
const nodeId = getCategoryNodeId(category);
const collection = new CategoryCollectionStub().withAction(category);
const sut = new CategoryReverter(nodeId, collection);
const testCases = [
{
name: 'false when subscripts are not reverted',
state: scripts.map((script) => new SelectedScript(script, false)),
expected: false,
},
{
name: 'false when some subscripts are reverted',
state: [new SelectedScript(scripts[0], false), new SelectedScript(scripts[0], true)],
expected: false,
},
{
name: 'false when subscripts are not reverted',
state: scripts.map((script) => new SelectedScript(script, true)),
expected: true,
},
];
for (const testCase of testCases) {
it(testCase.name, () => {
// act
const actual = sut.getState(testCase.state);
// assert
expect(actual).to.equal(testCase.expected);
});
}
});
describe('selectWithRevertState', () => {
// arrange
const scripts = [
new ScriptStub('revertable').withRevertCode('REM revert me'),
new ScriptStub('revertable2').withRevertCode('REM revert me 2'),
];
const category = new CategoryStub(1).withScripts(...scripts);
const collection = new CategoryCollectionStub().withAction(category);
/* eslint-disable object-property-newline */
const testCases = [
{
name: 'selects with revert state when not selected',
selection: [],
revert: true, expectRevert: true,
},
{
name: 'selects with non-revert state when not selected',
selection: [],
revert: false, expectRevert: false,
},
{
name: 'switches when already selected with revert state',
selection: scripts.map((script) => new SelectedScript(script, true)),
revert: false, expectRevert: false,
},
{
name: 'switches when already selected with not revert state',
selection: scripts.map((script) => new SelectedScript(script, false)),
revert: true, expectRevert: true,
},
{
name: 'keeps revert state when already selected with revert state',
selection: scripts.map((script) => new SelectedScript(script, true)),
revert: true, expectRevert: true,
},
{
name: 'keeps revert state deselected when already selected wtih non revert state',
selection: scripts.map((script) => new SelectedScript(script, false)),
revert: false, expectRevert: false,
},
];
/* eslint-enable object-property-newline */
const nodeId = getCategoryNodeId(category);
for (const testCase of testCases) {
it(testCase.name, () => {
const selection = new UserSelection(collection, testCase.selection);
const sut = new CategoryReverter(nodeId, collection);
// act
sut.selectWithRevertState(testCase.revert, selection);
// assert
expect(sut.getState(selection.selectedScripts)).to.equal(testCase.expectRevert);
expect(selection.selectedScripts).has.lengthOf(2);
expect(selection.selectedScripts[0].id).equal(scripts[0].id);
expect(selection.selectedScripts[1].id).equal(scripts[1].id);
expect(selection.selectedScripts[0].revert).equal(testCase.expectRevert);
expect(selection.selectedScripts[1].revert).equal(testCase.expectRevert);
});
}
});
});

View File

@@ -0,0 +1,47 @@
import { describe, it, expect } from 'vitest';
import { getReverter } from '@/presentation/components/Scripts/View/Tree/NodeContent/Reverter/ReverterFactory';
import { ScriptReverter } from '@/presentation/components/Scripts/View/Tree/NodeContent/Reverter/ScriptReverter';
import { CategoryReverter } from '@/presentation/components/Scripts/View/Tree/NodeContent/Reverter/CategoryReverter';
import { CategoryCollectionStub } from '@tests/unit/shared/Stubs/CategoryCollectionStub';
import { CategoryStub } from '@tests/unit/shared/Stubs/CategoryStub';
import { ScriptStub } from '@tests/unit/shared/Stubs/ScriptStub';
import { getCategoryNodeId, getScriptNodeId } from '@/presentation/components/Scripts/View/Tree/TreeViewAdapter/CategoryNodeMetadataConverter';
import { NodeType } from '@/application/Parser/NodeValidation/NodeType';
import { NodeMetadata } from '@/presentation/components/Scripts/View/Tree/NodeContent/NodeMetadata';
describe('ReverterFactory', () => {
describe('getReverter', () => {
it('gets CategoryReverter for category node', () => {
// arrange
const category = new CategoryStub(0).withScriptIds('55');
const node = getNodeContentStub(getCategoryNodeId(category), NodeType.Category);
const collection = new CategoryCollectionStub()
.withAction(category);
// act
const result = getReverter(node, collection);
// assert
expect(result instanceof CategoryReverter).to.equal(true);
});
it('gets ScriptReverter for script node', () => {
// arrange
const script = new ScriptStub('test');
const node = getNodeContentStub(getScriptNodeId(script), NodeType.Script);
const collection = new CategoryCollectionStub()
.withAction(new CategoryStub(0).withScript(script));
// act
const result = getReverter(node, collection);
// assert
expect(result instanceof ScriptReverter).to.equal(true);
});
});
function getNodeContentStub(nodeId: string, type: NodeType): NodeMetadata {
return {
id: nodeId,
text: 'text',
isReversible: false,
docs: [],
children: [],
type,
};
}
});

View File

@@ -0,0 +1,90 @@
import { describe, it, expect } from 'vitest';
import { ScriptReverter } from '@/presentation/components/Scripts/View/Tree/NodeContent/Reverter/ScriptReverter';
import { UserSelection } from '@/application/Context/State/Selection/UserSelection';
import { SelectedScript } from '@/application/Context/State/Selection/SelectedScript';
import { CategoryCollectionStub } from '@tests/unit/shared/Stubs/CategoryCollectionStub';
import { CategoryStub } from '@tests/unit/shared/Stubs/CategoryStub';
import { ScriptStub } from '@tests/unit/shared/Stubs/ScriptStub';
import { SelectedScriptStub } from '@tests/unit/shared/Stubs/SelectedScriptStub';
import { getScriptNodeId } from '@/presentation/components/Scripts/View/Tree/TreeViewAdapter/CategoryNodeMetadataConverter';
describe('ScriptReverter', () => {
describe('getState', () => {
it('false when script is not selected', () => {
// arrange
const script = new ScriptStub('id');
const nodeId = getScriptNodeId(script);
const sut = new ScriptReverter(nodeId);
// act
const actual = sut.getState([]);
// assert
expect(actual).to.equal(false);
});
it('false when script is selected but not reverted', () => {
// arrange
const scripts = [new SelectedScriptStub('id'), new SelectedScriptStub('dummy')];
const nodeId = getScriptNodeId(scripts[0].script);
const sut = new ScriptReverter(nodeId);
// act
const actual = sut.getState(scripts);
// assert
expect(actual).to.equal(false);
});
it('true when script is selected and reverted', () => {
// arrange
const scripts = [new SelectedScriptStub('id', true), new SelectedScriptStub('dummy')];
const nodeId = getScriptNodeId(scripts[0].script);
const sut = new ScriptReverter(nodeId);
// act
const actual = sut.getState(scripts);
// assert
expect(actual).to.equal(true);
});
});
describe('selectWithRevertState', () => {
// arrange
const script = new ScriptStub('id');
const collection = new CategoryCollectionStub()
.withAction(new CategoryStub(5).withScript(script));
/* eslint-disable object-property-newline */
const testCases = [
{
name: 'selects with revert state when not selected',
selection: [], revert: true, expectRevert: true,
},
{
name: 'selects with non-revert state when not selected',
selection: [], revert: false, expectRevert: false,
},
{
name: 'switches when already selected with revert state',
selection: [new SelectedScript(script, true)], revert: false, expectRevert: false,
},
{
name: 'switches when already selected with not revert state',
selection: [new SelectedScript(script, false)], revert: true, expectRevert: true,
},
{
name: 'keeps revert state when already selected with revert state',
selection: [new SelectedScript(script, true)], revert: true, expectRevert: true,
},
{
name: 'keeps revert state deselected when already selected with non revert state',
selection: [new SelectedScript(script, false)], revert: false, expectRevert: false,
},
];
/* eslint-enable object-property-newline */
const nodeId = getScriptNodeId(script);
for (const testCase of testCases) {
it(testCase.name, () => {
const selection = new UserSelection(collection, testCase.selection);
const sut = new ScriptReverter(nodeId);
// act
sut.selectWithRevertState(testCase.revert, selection);
// assert
expect(selection.isSelected(script.id)).to.equal(true);
expect(selection.selectedScripts[0].revert).equal(testCase.expectRevert);
});
}
});
});

View File

@@ -0,0 +1,237 @@
import { describe, it, expect } from 'vitest';
import {
Wrapper, shallowMount,
mount,
} from '@vue/test-utils';
import { nextTick, defineComponent } from 'vue';
import ToggleSwitch from '@/presentation/components/Scripts/View/Tree/NodeContent/ToggleSwitch.vue';
const DOM_INPUT_TOGGLE_CHECKBOX_SELECTOR = 'input.toggle-input';
const DOM_INPUT_TOGGLE_LABEL_OFF_SELECTOR = 'span.label-off';
const DOM_INPUT_TOGGLE_LABEL_ON_SELECTOR = 'span.label-on';
describe('ToggleSwitch.vue', () => {
describe('initial state', () => {
const testCases = [
{
initialValue: false,
description: 'unchecked for false',
},
{
initialValue: true,
description: 'checked for true',
},
];
testCases.forEach(({ initialValue, description }) => {
it(`renders as ${description}`, () => {
// arrange
const expectedState = initialValue;
// act
const wrapper = mountComponent({
properties: {
modelValue: initialValue,
},
});
const { checkboxElement } = getCheckboxElement(wrapper);
// assert
expect(checkboxElement.checked).to.equal(expectedState);
});
});
});
describe('label rendering', () => {
const testCases = [
{
description: 'off label',
selector: DOM_INPUT_TOGGLE_LABEL_OFF_SELECTOR,
},
{
description: 'on label',
selector: DOM_INPUT_TOGGLE_LABEL_ON_SELECTOR,
},
];
testCases.forEach(({ selector, description }) => {
it(description, () => {
// arrange
const expectedLabel = 'expected-test-label';
// act
const wrapper = mountComponent({
properties: {
label: expectedLabel,
},
});
// assert
const element = wrapper.find(selector);
expect(element.text()).to.equal(expectedLabel);
});
});
});
describe('model updates', () => {
describe('emission on change', () => {
const testCases = [
{
initialValue: true,
newCheckValue: false,
},
{
initialValue: false,
newCheckValue: true,
},
];
testCases.forEach(({ initialValue, newCheckValue }) => {
it(`emits ${newCheckValue} when initial value is ${initialValue} and checkbox value changes`, async () => {
// arrange
const wrapper = mountComponent({
properties: {
modelValue: initialValue,
},
});
const { checkboxWrapper } = getCheckboxElement(wrapper);
// act
await checkboxWrapper.setChecked(newCheckValue);
await nextTick();
// assert
expect(wrapper.emitted().input).to.deep.equal([[newCheckValue]]);
});
});
});
describe('no emission on identical value', () => {
const testCases = [
{
value: true,
description: 'true',
},
{
value: false,
description: 'false',
},
];
testCases.forEach(({ value, description }) => {
it(`does not emit for an unchanged value of ${description}`, async () => {
// arrange
const wrapper = mountComponent({
properties: {
modelValue: value,
},
});
const { checkboxWrapper } = getCheckboxElement(wrapper);
// act
await checkboxWrapper.setChecked(value);
await nextTick();
// assert
expect(wrapper.emitted().input).to.equal(undefined);
});
});
});
});
describe('click propagation', () => {
it('stops propagation `stopClickPropagation` is true', async () => {
// arrange
const { wrapper: parentWrapper, parentClickEventName } = mountToggleSwitchParent(
{ stopClickPropagation: true },
);
const switchWrapper = parentWrapper.getComponent(ToggleSwitch);
// act
switchWrapper.trigger('click');
await nextTick();
// assert
expect(switchWrapper.exists());
const receivedEvents = parentWrapper.emitted(parentClickEventName);
expect(receivedEvents).to.equal(undefined);
});
it('allows propagation `stopClickPropagation` is false', async () => {
// arrange
const { wrapper: parentWrapper, parentClickEventName } = mountToggleSwitchParent(
{ stopClickPropagation: false },
);
const switchWrapper = parentWrapper.getComponent(ToggleSwitch);
// act
switchWrapper.trigger('click');
await nextTick();
// assert
expect(switchWrapper.exists());
const receivedEvents = parentWrapper.emitted(parentClickEventName);
expect(receivedEvents).to.have.lengthOf(1);
});
});
});
function getCheckboxElement(wrapper: Wrapper<Vue>) {
const checkboxWrapper = wrapper.find(DOM_INPUT_TOGGLE_CHECKBOX_SELECTOR);
const checkboxElement = checkboxWrapper.element as HTMLInputElement;
return {
checkboxWrapper,
checkboxElement,
};
}
function mountComponent(options?: {
readonly properties?: {
readonly modelValue?: boolean,
readonly label?: string,
readonly stopClickPropagation?: boolean,
}
}) {
const wrapper = shallowMount(ToggleSwitch as unknown, {
propsData: {
value: options?.properties?.modelValue,
label: options?.properties?.label ?? 'test-label',
stopClickPropagation: options?.properties?.stopClickPropagation,
},
});
return wrapper;
}
function mountToggleSwitchParent(options?: {
readonly stopClickPropagation?: boolean,
}) {
const parentClickEventName = 'parent-clicked';
const parentComponent = defineComponent({
components: {
ToggleSwitch,
},
emits: [parentClickEventName],
template: `
<div @click="handleParentClick">
<ToggleSwitch
:stopClickPropagation="stopClickPropagation"
:label="'test-label'"
/>
</div>
`,
setup(_, { emit }) {
const stopClickPropagation = options?.stopClickPropagation;
function handleParentClick() {
emit(parentClickEventName);
}
return {
handleParentClick,
stopClickPropagation,
};
},
});
const wrapper = mount(
parentComponent as unknown,
{
stubs: { ToggleSwitch: false },
},
);
return {
wrapper,
parentClickEventName,
};
}