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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions e2e/schemer-embedded.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1361,6 +1361,40 @@ test('embedded Schemer destroys rich text editors after save, cancel and Escape'
}
});

test('embedded Schemer preserves pasted list numbering and styles after save and reopen', async ({ page }) => {
const frame = await loadEmbeddedSchemer(page);
await expect(frame.locator('.var-list-entry')).toHaveCount(2);
await frame.locator('var-coding .manual-instruction button').first().click();
const editor = frame.locator('.ProseMirror');
await editor.focus();
await editor.evaluate(element => {
const clipboardData = new DataTransfer();
clipboardData.setData('text/html', '<ol start="3" type="a"><li>Third'
+ '<ol start="4" type="I"><li>Nested</li></ol></li><li>Fourth</li></ol>');
clipboardData.setData('text/plain', 'Third\nNested\nFourth');
element.dispatchEvent(new ClipboardEvent('paste', { clipboardData, bubbles: true, cancelable: true }));
});
await expect(editor.locator('ol').first()).toHaveAttribute('start', '3');
await expect(editor.locator('ol').nth(1)).toHaveAttribute('start', '4');
await frame.getByRole('button', { name: 'Speichern', exact: true }).click();
await expect(frame.getByRole('dialog')).toHaveCount(0);

const storedLists = await page.evaluate(() => {
const changed = window.received.filter(message => message.type === 'vosSchemeChangedNotification').at(-1);
const html = JSON.parse(changed.codingScheme).variableCodings[0].manualInstruction;
return Array.from(new DOMParser().parseFromString(html, 'text/html').querySelectorAll('ol'))
.map(list => ({ start: list.start, style: list.style.listStyleType }));
});
expect(storedLists).toEqual([{ start: 3, style: 'lower-latin' }, { start: 4, style: 'upper-roman' }]);

await frame.locator('var-coding .manual-instruction button').first().click();
await expect(editor.locator('ol').first()).toHaveAttribute('start', '3');
await expect(editor.locator('ol').nth(1)).toHaveAttribute('start', '4');
expect(await editor.locator('ol').evaluateAll(lists => lists.map(list => list.style.listStyleType)))
.toEqual(['lower-latin', 'upper-roman']);
await frame.getByRole('button', { name: 'Abbrechen', exact: true }).click();
});

test('embedded Schemer saves rich text and an asynchronous image and discards cancelled edits', async ({ page }) => {
const frame = await loadEmbeddedSchemer(page);
await expect(frame.locator('.var-list-entry')).toHaveCount(2);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@
@Output() cancel = new EventEmitter<void>();
@ViewChild(MatSort) sort!: MatSort;

dataSource = new MatTableDataSource<UnitSelectionItem>([]);
dataSource: MatTableDataSource<UnitSelectionItem> = new MatTableDataSource<UnitSelectionItem>([]);
columns = ['select', 'key', 'name', 'group'];
selection: number[] = [];
filter = '';
Expand All @@ -77,9 +77,9 @@
if (changes['availableUnits']) {
this.unitsLoaded ||= this.availableUnits.length > 0 || !changes['availableUnits'].firstChange;
this.dataSource.data = this.availableUnits;
this.dataSource.filterPredicate = (unit, filter) => [unit.key, unit.unitName, this.showGroupColumn ? unit.groupName || '' : '']

Check warning on line 80 in projects/ngx-coding-components/codebook-export/codebook-export.component.ts

View workflow job for this annotation

GitHub Actions / lint-and-test

This line has a length of 133. Maximum allowed is 120

Check warning on line 80 in projects/ngx-coding-components/codebook-export/codebook-export.component.ts

View workflow job for this annotation

GitHub Actions / lint-and-test

This line has a length of 133. Maximum allowed is 120
.some(value => value.toLowerCase().includes(filter));
this.dataSource.sortingDataAccessor = (unit, column) => ({ key: unit.key, name: unit.unitName, group: unit.groupName || '' }[column] || '');

Check warning on line 82 in projects/ngx-coding-components/codebook-export/codebook-export.component.ts

View workflow job for this annotation

GitHub Actions / lint-and-test

This line has a length of 146. Maximum allowed is 120

Check warning on line 82 in projects/ngx-coding-components/codebook-export/codebook-export.component.ts

View workflow job for this annotation

GitHub Actions / lint-and-test

This line has a length of 146. Maximum allowed is 120
}
if (changes['missingsProfiles']) {
this.profilesLoaded ||= this.missingsProfiles.length > 0 || !changes['missingsProfiles'].firstChange;
Expand Down Expand Up @@ -122,13 +122,13 @@

toggle(unit: UnitSelectionItem): void {
if (unit.disabled || this.loading || this.busy) return;
this.selection = this.selection.includes(unit.unitId) ? this.selection.filter(id => id !== unit.unitId) : [...this.selection, unit.unitId];

Check warning on line 125 in projects/ngx-coding-components/codebook-export/codebook-export.component.ts

View workflow job for this annotation

GitHub Actions / lint-and-test

This line has a length of 143. Maximum allowed is 120

Check warning on line 125 in projects/ngx-coding-components/codebook-export/codebook-export.component.ts

View workflow job for this annotation

GitHub Actions / lint-and-test

This line has a length of 143. Maximum allowed is 120
this.selectionChanged.emit([...this.selection]);
}

toggleAll(): void {
if (this.loading || this.busy) return;
this.selection = this.allSelected ? [] : this.availableUnits.filter(unit => !unit.disabled).map(unit => unit.unitId);

Check warning on line 131 in projects/ngx-coding-components/codebook-export/codebook-export.component.ts

View workflow job for this annotation

GitHub Actions / lint-and-test

This line has a length of 121. Maximum allowed is 120

Check warning on line 131 in projects/ngx-coding-components/codebook-export/codebook-export.component.ts

View workflow job for this annotation

GitHub Actions / lint-and-test

This line has a length of 121. Maximum allowed is 120
this.selectionChanged.emit([...this.selection]);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,90 @@ describe('Instruction list paste compatibility', () => {
expect(editor.getHTML()).not.toContain('<ol');
});
});

const expectStableRoundtrips = () => {
const content = editor.getJSON();
const html = editor.getHTML();
editor.commands.setContent(html, { emitUpdate: false });
expect(editor.getHTML()).toBe(html);
editor.commands.setContent(content, { emitUpdate: false });
expect(editor.getJSON()).toEqual(content);
expect(editor.getHTML()).toBe(html);
};

[3, 0, -2].forEach(start => {
it(`preserves the HTML clipboard numbering start ${start}`, () => {
expect(editor.view.pasteHTML(`<ol start="${start}"><li>First</li><li>Second</li></ol>`)).toBeTrue();

expect(editor.view.dom.querySelector('ol')?.start).toBe(start);
expectStableRoundtrips();
});
});

[
['a', 'lower-latin'], ['A', 'upper-latin'], ['i', 'lower-roman'], ['I', 'upper-roman'], ['1', 'decimal']
].forEach(([type, listStyle]) => {
it(`preserves HTML clipboard type ${type} and maps it to the editor list style`, () => {
editor.view.pasteHTML(`<ol start="3" type="${type}"><li>First</li><li>Second</li></ol>`);

expect(editor.view.dom.querySelector('ol')?.start).toBe(3);
expect(editor.getJSON().content?.[0].attrs?.['listStyle']).toBe(listStyle);
expect(editor.view.dom.querySelector('ol')?.style.listStyleType).toBe(listStyle);
expectStableRoundtrips();
});
});

it('keeps CSS list styles and font sizes ahead of a conflicting HTML type', () => {
editor.view.pasteHTML('<ol start="3" type="a" style="list-style-type: upper-roman; font-size: 18px">' +
'<li>First</li><li>Second</li></ol>');

expect(editor.getJSON().content?.[0].attrs).toEqual(jasmine.objectContaining({
start: 3, listStyle: 'upper-roman', fontSize: '18px'
}));
expectStableRoundtrips();
});

it('imports the list style from a first list item, as supplied by Google Docs', () => {
editor.view.pasteHTML('<ol start="3"><li style="list-style-type: lower-alpha">First</li><li>Second</li></ol>');

expect(editor.getJSON().content?.[0].attrs).toEqual(jasmine.objectContaining({
start: 3, listStyle: 'lower-alpha'
}));
expectStableRoundtrips();
});

it('preserves independent starts and styles in nested lists', () => {
editor.view.pasteHTML('<ol start="3" type="a"><li>Outer' +
'<ol start="4" type="I"><li>Inner</li></ol></li><li>Next</li></ol>');

const lists = Array.from(editor.view.dom.querySelectorAll('ol'));
expect(lists.map(list => list.start)).toEqual([3, 4]);
expect(lists.map(list => list.style.listStyleType)).toEqual(['lower-latin', 'upper-roman']);
expectStableRoundtrips();
});

it('keeps a user-selected custom style when a typed list is saved and reopened', () => {
editor.view.pasteHTML('<ol start="3" type="a"><li>First</li><li>Second</li></ol>');
editor.commands.selectAll();
editor.commands.setOrderedListStyle('lower-greek');

expect(editor.view.dom.querySelector('ol')?.style.listStyleType).toBe('lower-greek');
expectStableRoundtrips();
expect(editor.view.dom.querySelector('ol')?.start).toBe(3);
});

it('reopens legacy JSON lists without changing their custom style', () => {
editor.commands.setContent({
type: 'doc',
content: [{
type: 'orderedList',
attrs: { listStyle: 'lower-greek', fontSize: '18px' },
content: [{ type: 'listItem', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Legacy' }] }] }]
}]
});

expect(editor.view.dom.querySelector('ol')?.start).toBe(1);
expect(editor.view.dom.querySelector('ol')?.style.listStyleType).toBe('lower-greek');
expectStableRoundtrips();
});
});
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { OrderedList } from '@tiptap/extension-ordered-list';

const listStyleByType = new Map([
['1', 'decimal'], ['a', 'lower-latin'], ['A', 'upper-latin'], ['i', 'lower-roman'], ['I', 'upper-roman']
]);

declare module '@tiptap/core' {
interface Commands<ReturnType> {
orderedListExtension: {
Expand All @@ -12,9 +16,12 @@ declare module '@tiptap/core' {
export const OrderedListExtension = OrderedList.extend({
addAttributes() {
return {
...this.parent?.(),
listStyle: {
default: 'upper-roman',
parseHTML: element => element.style.listStyleType,
parseHTML: element => element.style.listStyleType ||
element.querySelector('li')?.style.listStyleType ||
listStyleByType.get(element.getAttribute('type') || '') || '',
renderHTML: attributes => ({ style: `list-style: ${attributes['listStyle']}` })
},
fontSize: {
Expand Down
77 changes: 62 additions & 15 deletions scripts/codebook-type-resolution.test.mjs
Original file line number Diff line number Diff line change
@@ -1,10 +1,36 @@
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { test } from 'node:test';
import { mkdtemp, mkdir, rm, symlink, writeFile } from 'node:fs/promises';
import { mkdtemp, mkdir, readFile, rm, symlink, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import ts from 'typescript';

const expectTypeChecks = (source, consumer, resolution) => {
const program = ts.createProgram([source], {
noEmit: true,
strict: true,
skipLibCheck: false,
target: ts.ScriptTarget.ES2022,
module: resolution === 'NodeNext' ? ts.ModuleKind.NodeNext : ts.ModuleKind.ESNext,
moduleResolution: ts.ModuleResolutionKind[resolution]
});
const errors = ts.getPreEmitDiagnostics(program)
.filter(diagnostic => diagnostic.category === ts.DiagnosticCategory.Error);
assert.equal(errors.length, 0, ts.formatDiagnosticsWithColorAndContext(errors, {
getCanonicalFileName: file => file,
getCurrentDirectory: () => consumer,
getNewLine: () => '\n'
}));
};

const npm = (args, cwd) => {
const result = spawnSync('npm', args, { cwd, encoding: 'utf8', timeout: 120000 });
assert.equal(result.error, undefined, result.error?.message);
assert.equal(result.status, 0, result.stderr || result.stdout);
return result.stdout;
};

for (const resolution of ['Bundler', 'NodeNext']) {
test(`public codebook types support ${resolution} consumers`, async () => {
const consumer = await mkdtemp(join(tmpdir(), 'codebook-type-consumer-'));
Expand All @@ -27,22 +53,43 @@ for (const resolution of ['Bundler', 'NodeNext']) {
const output: Promise<Blob> = CodebookGenerator.generateCodebook(units, options, []);
void output;
`);
const program = ts.createProgram([source], {
noEmit: true,
strict: true,
target: ts.ScriptTarget.ES2022,
module: resolution === 'NodeNext' ? ts.ModuleKind.NodeNext : ts.ModuleKind.ESNext,
moduleResolution: ts.ModuleResolutionKind[resolution]
});
const errors = ts.getPreEmitDiagnostics(program)
.filter(diagnostic => diagnostic.category === ts.DiagnosticCategory.Error);
assert.equal(errors.length, 0, ts.formatDiagnosticsWithColorAndContext(errors, {
getCanonicalFileName: file => file,
getCurrentDirectory: () => consumer,
getNewLine: () => '\n'
}));
expectTypeChecks(source, consumer, resolution);
} finally {
await rm(consumer, { recursive: true, force: true });
}
});
}

test('packed public Angular entry points support strict Bundler consumers', async () => {
const consumer = await mkdtemp(join(tmpdir(), 'packed-ui-type-consumer-'));
try {
const library = JSON.parse(await readFile('dist/ngx-coding-components/package.json', 'utf8'));
const lock = JSON.parse(await readFile('package-lock.json', 'utf8'));
const [tarball] = JSON.parse(npm(['pack', '--ignore-scripts', '--json', '--pack-destination', consumer],
resolve('dist/ngx-coding-components')));
// Use the host versions tested by this checkout, including one consistent Angular major.
const peers = Object.fromEntries(Object.keys(library.peerDependencies).map(name => (
[name, lock.packages[`node_modules/${name}`].version]
)));
await writeFile(join(consumer, 'package.json'), JSON.stringify({
name: 'packed-ui-type-consumer', private: true, type: 'module',
dependencies: { ...peers, [library.name]: `file:${join(consumer, tarball.filename)}` }
}));
npm(['install', '--ignore-scripts', '--no-audit', '--no-fund'], consumer);
const source = join(consumer, 'consumer.mts');
await writeFile(source, `
import { SchemerComponent } from '@iqb/ngx-coding-components';
import { CodebookExportComponent } from '@iqb/ngx-coding-components/codebook-export';
import { CodebookGenerator } from '@iqb/ngx-coding-components/codebook-generator';
import type { UnitSelectionItem } from '@iqb/ngx-coding-components/codebook-models';
import * as translations from '@iqb/ngx-coding-components/translations';
import type { MatTableDataSource } from '@angular/material/table';
const exportForm = null! as CodebookExportComponent;
const dataSource: MatTableDataSource<UnitSelectionItem> = exportForm.dataSource;
void [SchemerComponent, CodebookGenerator, translations, dataSource];
`);
expectTypeChecks(source, consumer, 'Bundler');
} finally {
await rm(consumer, { recursive: true, force: true });
}
});
Loading