@instructure/ui-truncate-text 10.11.0 → 10.11.1-snapshot-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/es/TruncateText/__new-tests__/TruncateText.test.js +75 -0
  3. package/es/TruncateText/utils/__new-tests__/cleanData.test.js +108 -0
  4. package/es/TruncateText/utils/__new-tests__/cleanString.test.js +49 -0
  5. package/es/TruncateText/utils/__new-tests__/measureText.test.js +148 -0
  6. package/lib/TruncateText/__new-tests__/TruncateText.test.js +77 -0
  7. package/lib/TruncateText/utils/__new-tests__/cleanData.test.js +112 -0
  8. package/lib/TruncateText/utils/__new-tests__/cleanString.test.js +52 -0
  9. package/lib/TruncateText/utils/__new-tests__/measureText.test.js +150 -0
  10. package/package.json +19 -15
  11. package/src/TruncateText/__new-tests__/TruncateText.test.tsx +99 -0
  12. package/src/TruncateText/utils/__new-tests__/cleanData.test.tsx +131 -0
  13. package/src/TruncateText/utils/__new-tests__/cleanString.test.tsx +57 -0
  14. package/src/TruncateText/utils/__new-tests__/measureText.test.tsx +173 -0
  15. package/tsconfig.build.json +1 -0
  16. package/tsconfig.build.tsbuildinfo +1 -1
  17. package/types/TruncateText/__new-tests__/TruncateText.test.d.ts +2 -0
  18. package/types/TruncateText/__new-tests__/TruncateText.test.d.ts.map +1 -0
  19. package/types/TruncateText/utils/__new-tests__/cleanData.test.d.ts +2 -0
  20. package/types/TruncateText/utils/__new-tests__/cleanData.test.d.ts.map +1 -0
  21. package/types/TruncateText/utils/__new-tests__/cleanString.test.d.ts +2 -0
  22. package/types/TruncateText/utils/__new-tests__/cleanString.test.d.ts.map +1 -0
  23. package/types/TruncateText/utils/__new-tests__/measureText.test.d.ts +2 -0
  24. package/types/TruncateText/utils/__new-tests__/measureText.test.d.ts.map +1 -0
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
+ var _react = _interopRequireDefault(require("react"));
5
+ var _react2 = require("@testing-library/react");
6
+ var _vitest = require("vitest");
7
+ require("@testing-library/jest-dom");
8
+ var _measureText = _interopRequireDefault(require("../measureText"));
9
+ var _div, _div2, _div3, _div4;
10
+ /*
11
+ * The MIT License (MIT)
12
+ *
13
+ * Copyright (c) 2015 - present Instructure, Inc.
14
+ *
15
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
16
+ * of this software and associated documentation files (the "Software"), to deal
17
+ * in the Software without restriction, including without limitation the rights
18
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
19
+ * copies of the Software, and to permit persons to whom the Software is
20
+ * furnished to do so, subject to the following conditions:
21
+ *
22
+ * The above copyright notice and this permission notice shall be included in all
23
+ * copies or substantial portions of the Software.
24
+ *
25
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31
+ * SOFTWARE.
32
+ */
33
+ const baseStyle = {
34
+ fontSize: '16px',
35
+ fontFamily: 'Arial',
36
+ fontWeight: 'normal',
37
+ fontStyle: 'normal',
38
+ letterSpacing: 'normal'
39
+ };
40
+ const getNodes = root => Array.from(root.childNodes).filter(node => node.nodeType === Node.ELEMENT_NODE || node.nodeType === Node.TEXT_NODE);
41
+ describe('measureText', () => {
42
+ beforeEach(() => {
43
+ _vitest.vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(() => {
44
+ return {
45
+ font: '',
46
+ measureText: _vitest.vi.fn(text => {
47
+ return {
48
+ width: text.length * 10
49
+ };
50
+ })
51
+ };
52
+ });
53
+ });
54
+ afterEach(() => {
55
+ _vitest.vi.restoreAllMocks();
56
+ });
57
+ it('should calculate the width of a single text node correctly', () => {
58
+ const node = document.createElement('div');
59
+ Object.assign(node.style, baseStyle);
60
+ node.textContent = 'Hello';
61
+ const width = (0, _measureText.default)([node]);
62
+ (0, _vitest.expect)(width).toBe(50); // 5 characters * 10 (mocked width per character)
63
+ });
64
+ it('should return zero for empty nodes', () => {
65
+ const node = document.createElement('div');
66
+ Object.assign(node.style, baseStyle);
67
+ node.textContent = '';
68
+ const width = (0, _measureText.default)([node]);
69
+ (0, _vitest.expect)(width).toBe(0);
70
+ });
71
+ it('should calculate text width correctly', () => {
72
+ (0, _react2.render)(_div || (_div = /*#__PURE__*/_react.default.createElement("div", {
73
+ "data-testid": "stage",
74
+ style: baseStyle
75
+ }, "Lorem ipsum ", /*#__PURE__*/_react.default.createElement("span", {
76
+ style: baseStyle
77
+ }, "DOLOR SIT AMET."))));
78
+ const stage = _react2.screen.getByTestId('stage');
79
+ const nodes = getNodes(stage);
80
+ const width = (0, _measureText.default)(nodes, stage);
81
+ (0, _vitest.expect)(width).toBe(270);
82
+ });
83
+ it('should account for different nodes', async () => {
84
+ const _render = (0, _react2.render)(_div2 || (_div2 = /*#__PURE__*/_react.default.createElement("div", {
85
+ "data-testid": "stage",
86
+ style: baseStyle
87
+ }, "Lorem ipsum ", /*#__PURE__*/_react.default.createElement("span", {
88
+ style: baseStyle
89
+ }, "DOLOR SIT AMET.")))),
90
+ rerender = _render.rerender;
91
+ const stage = _react2.screen.getByTestId('stage');
92
+ const nodes = getNodes(stage);
93
+ const width = (0, _measureText.default)(nodes, stage);
94
+
95
+ // Set child
96
+ rerender(_div3 || (_div3 = /*#__PURE__*/_react.default.createElement("div", {
97
+ "data-testid": "stage",
98
+ style: baseStyle
99
+ }, "Lorem ipsum DOLOR SIT AMET.")));
100
+ const stage2 = _react2.screen.getByTestId('stage');
101
+ const nodes2 = getNodes(stage2);
102
+ const width2 = (0, _measureText.default)(nodes2, stage2);
103
+ (0, _vitest.expect)(width).toEqual(width2);
104
+ });
105
+ it('should call measureText on a properly configured canvas 2d context', () => {
106
+ const mockedStyle = {
107
+ fontSize: '20px',
108
+ fontWeight: 'bold',
109
+ fontStyle: 'italic',
110
+ fontFamily: 'Arial'
111
+ };
112
+ (0, _react2.render)(/*#__PURE__*/_react.default.createElement("div", {
113
+ "data-testid": "stage",
114
+ style: mockedStyle
115
+ }, "Lorem ipsum"));
116
+ const stage = _react2.screen.getByTestId('stage');
117
+ const nodes = getNodes(stage);
118
+ (0, _measureText.default)(nodes, stage);
119
+
120
+ // The width calculation depends on the modified canvas context
121
+ const getContextSpy = HTMLCanvasElement.prototype.getContext;
122
+ const context = getContextSpy.mock.results[0].value;
123
+ (0, _vitest.expect)(context.measureText).toHaveBeenCalledTimes(1);
124
+ (0, _vitest.expect)(context.font).toBe('bold italic 20px Arial');
125
+ });
126
+ it('should account for letter spacing styles', async () => {
127
+ const _render2 = (0, _react2.render)(_div4 || (_div4 = /*#__PURE__*/_react.default.createElement("div", {
128
+ "data-testid": "stage",
129
+ style: baseStyle
130
+ }, "Lorem ipsum"))),
131
+ rerender = _render2.rerender;
132
+ const stage = _react2.screen.getByTestId('stage');
133
+ const nodes = getNodes(stage);
134
+ const width = (0, _measureText.default)(nodes, stage);
135
+ (0, _vitest.expect)(width).toBe(110); // default mocked width (text.length * 10)
136
+
137
+ // Set letterSpacing
138
+ rerender(/*#__PURE__*/_react.default.createElement("div", {
139
+ "data-testid": "stage2",
140
+ style: {
141
+ ...baseStyle,
142
+ letterSpacing: '5px'
143
+ }
144
+ }, "Lorem ipsum"));
145
+ const stage2 = _react2.screen.getByTestId('stage2');
146
+ const nodes2 = getNodes(stage2);
147
+ const width2 = (0, _measureText.default)(nodes2, stage2);
148
+ (0, _vitest.expect)(width2).toBe(165); // default mocked width + letterOffset (text.length * letterSpacing)
149
+ });
150
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@instructure/ui-truncate-text",
3
- "version": "10.11.0",
3
+ "version": "10.11.1-snapshot-2",
4
4
  "description": "A TruncateText component made by Instructure Inc.",
5
5
  "author": "Instructure, Inc. Engineering and Product Design",
6
6
  "module": "./es/index.js",
@@ -24,24 +24,28 @@
24
24
  "license": "MIT",
25
25
  "dependencies": {
26
26
  "@babel/runtime": "^7.26.0",
27
- "@instructure/console": "10.11.0",
28
- "@instructure/debounce": "10.11.0",
29
- "@instructure/emotion": "10.11.0",
30
- "@instructure/shared-types": "10.11.0",
31
- "@instructure/ui-dom-utils": "10.11.0",
32
- "@instructure/ui-react-utils": "10.11.0",
33
- "@instructure/ui-testable": "10.11.0",
34
- "@instructure/ui-utils": "10.11.0",
27
+ "@instructure/console": "10.11.1-snapshot-2",
28
+ "@instructure/debounce": "10.11.1-snapshot-2",
29
+ "@instructure/emotion": "10.11.1-snapshot-2",
30
+ "@instructure/shared-types": "10.11.1-snapshot-2",
31
+ "@instructure/ui-dom-utils": "10.11.1-snapshot-2",
32
+ "@instructure/ui-react-utils": "10.11.1-snapshot-2",
33
+ "@instructure/ui-testable": "10.11.1-snapshot-2",
34
+ "@instructure/ui-utils": "10.11.1-snapshot-2",
35
35
  "escape-html": "^1.0.3",
36
36
  "prop-types": "^15.8.1"
37
37
  },
38
38
  "devDependencies": {
39
- "@instructure/ui-babel-preset": "10.11.0",
40
- "@instructure/ui-color-utils": "10.11.0",
41
- "@instructure/ui-test-utils": "10.11.0",
42
- "@instructure/ui-text": "10.11.0",
43
- "@instructure/ui-themes": "10.11.0",
44
- "@types/escape-html": "^1.0.4"
39
+ "@instructure/ui-axe-check": "10.11.1-snapshot-2",
40
+ "@instructure/ui-babel-preset": "10.11.1-snapshot-2",
41
+ "@instructure/ui-color-utils": "10.11.1-snapshot-2",
42
+ "@instructure/ui-test-utils": "10.11.1-snapshot-2",
43
+ "@instructure/ui-text": "10.11.1-snapshot-2",
44
+ "@instructure/ui-themes": "10.11.1-snapshot-2",
45
+ "@testing-library/jest-dom": "^6.6.3",
46
+ "@testing-library/react": "^16.0.1",
47
+ "@types/escape-html": "^1.0.4",
48
+ "vitest": "^2.1.8"
45
49
  },
46
50
  "peerDependencies": {
47
51
  "react": ">=16.14 <=18"
@@ -0,0 +1,99 @@
1
+ /*
2
+ * The MIT License (MIT)
3
+ *
4
+ * Copyright (c) 2015 - present Instructure, Inc.
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ import React from 'react'
26
+ import { render, waitFor } from '@testing-library/react'
27
+ import { vi, expect } from 'vitest'
28
+ import type { MockInstance } from 'vitest'
29
+
30
+ import '@testing-library/jest-dom'
31
+ import { runAxeCheck } from '@instructure/ui-axe-check'
32
+ import { TruncateText } from '../index'
33
+
34
+ const defaultText = 'Hello world! This is a long string that should truncate'
35
+
36
+ describe('<TruncateText />', () => {
37
+ let consoleErrorMock: ReturnType<typeof vi.spyOn>
38
+
39
+ beforeEach(() => {
40
+ // Mocking console to prevent test output pollution and expect for messages
41
+ consoleErrorMock = vi
42
+ .spyOn(console, 'error')
43
+ .mockImplementation(() => {}) as MockInstance
44
+ })
45
+
46
+ afterEach(() => {
47
+ consoleErrorMock.mockRestore()
48
+ })
49
+
50
+ it('should warn if children prop receives too deep of a node tree', async () => {
51
+ render(
52
+ <div style={{ width: '200px' }}>
53
+ <TruncateText>
54
+ Hello world!{' '}
55
+ <strong>
56
+ <span>This is a</span>
57
+ </strong>{' '}
58
+ long string that should truncate
59
+ </TruncateText>
60
+ </div>
61
+ )
62
+
63
+ const expectedErrorMessage =
64
+ 'Some children are too deep in the node tree and will not render.'
65
+
66
+ await waitFor(() => {
67
+ expect(consoleErrorMock).toHaveBeenCalledWith(
68
+ expect.stringContaining(expectedErrorMessage),
69
+ expect.any(String)
70
+ )
71
+ })
72
+ })
73
+
74
+ it('should handle the empty string as a child', async () => {
75
+ let error = false
76
+
77
+ try {
78
+ const { rerender } = render(<TruncateText>{''}</TruncateText>)
79
+
80
+ rerender(<TruncateText>{'hello world'}</TruncateText>)
81
+ rerender(<TruncateText>{''}</TruncateText>)
82
+ } catch (_e) {
83
+ error = true
84
+ }
85
+
86
+ expect(error).toBe(false)
87
+ })
88
+
89
+ it('should meet a11y standards', async () => {
90
+ const { container } = render(
91
+ <div style={{ width: '200px' }}>
92
+ <TruncateText>{defaultText}</TruncateText>
93
+ </div>
94
+ )
95
+ const axeCheck = await runAxeCheck(container)
96
+
97
+ expect(axeCheck).toBe(true)
98
+ })
99
+ })
@@ -0,0 +1,131 @@
1
+ /*
2
+ * The MIT License (MIT)
3
+ *
4
+ * Copyright (c) 2015 - present Instructure, Inc.
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+ import { expect } from 'chai'
25
+ import '@testing-library/jest-dom'
26
+ import cleanData from '../cleanData'
27
+ import { CleanDataOptions } from '../../props'
28
+
29
+ describe('cleanData', () => {
30
+ it('should remove spaces from the end of character data', async () => {
31
+ const data = [['T', 'e', 's', 't', ' ', '...']]
32
+ const options: Required<CleanDataOptions> = {
33
+ truncate: 'character',
34
+ ellipsis: '...',
35
+ ignore: [' ']
36
+ }
37
+ const newData = cleanData(data, options)
38
+ expect(newData[0].join('')).to.equal('Test...')
39
+ })
40
+
41
+ it('should remove spaces from the end of word data', async () => {
42
+ const data = [['Test ', '...']]
43
+ const options: Required<CleanDataOptions> = {
44
+ truncate: 'word',
45
+ ellipsis: '...',
46
+ ignore: [' ']
47
+ }
48
+
49
+ const newData = cleanData(data, options)
50
+ expect(newData[0].join('')).to.equal('Test...')
51
+ })
52
+
53
+ it('should remove spaces from the middle of character data', async () => {
54
+ const data = [
55
+ ['H', 'e', 'l', 'l', 'o', ' ', '...', ' ', 'w', 'o', 'r', 'l', 'd']
56
+ ]
57
+ const options: Required<CleanDataOptions> = {
58
+ truncate: 'character',
59
+ ellipsis: '...',
60
+ ignore: [' ']
61
+ }
62
+
63
+ const newData = cleanData(data, options)
64
+ expect(newData[0].join('')).to.equal('Hello...world')
65
+ })
66
+
67
+ it('should remove spaces from the middle of word data', async () => {
68
+ const data = [['Hello ', '...', 'world']]
69
+ const options: Required<CleanDataOptions> = {
70
+ truncate: 'word',
71
+ ellipsis: '...',
72
+ ignore: [' ']
73
+ }
74
+
75
+ const newData = cleanData(data, options)
76
+ expect(newData[0].join('')).to.equal('Hello...world')
77
+ })
78
+
79
+ it('should do a thorough cleaning', async () => {
80
+ const data = [['T', 'e', 's', 't', '.', ' ', '...']]
81
+ const options: Required<CleanDataOptions> = {
82
+ truncate: 'character',
83
+ ellipsis: '...',
84
+ ignore: [' ', '.']
85
+ }
86
+
87
+ const newData = cleanData(data, options, true)
88
+ expect(newData[0].join('')).to.equal('Test...')
89
+ })
90
+
91
+ it('should remove spaces from the end of complex character data', async () => {
92
+ let data = [['H', 'e', 'l', 'l', 'o', ' '], ['...']]
93
+ const options: Required<CleanDataOptions> = {
94
+ truncate: 'character',
95
+ ellipsis: '...',
96
+ ignore: [' ']
97
+ }
98
+
99
+ let newData = cleanData(data, options)
100
+ const text = newData[0].join('') + newData[1].join('')
101
+
102
+ data = [
103
+ ['H', 'e', 'l', 'l', 'o', ' '],
104
+ ['w', 'o', 'r', 'l', 'd', ' ', '...']
105
+ ]
106
+ newData = cleanData(data, options)
107
+ const text2 = newData[0].join('') + newData[1].join('')
108
+
109
+ expect(text).to.equal('Hello...')
110
+ expect(text2).to.equal('Hello world...')
111
+ })
112
+
113
+ it('should remove spaces from the middle of complex word data', async () => {
114
+ let data = [['Hello ', '...'], ['world']]
115
+ const options: Required<CleanDataOptions> = {
116
+ truncate: 'word',
117
+ ellipsis: '...',
118
+ ignore: [' ']
119
+ }
120
+
121
+ let newData = cleanData(data, options)
122
+ const text = newData[0].join('') + newData[1].join('')
123
+
124
+ data = [['Hello '], ['...', 'world']]
125
+ newData = cleanData(data, options)
126
+ const text2 = newData[0].join('') + newData[1].join('')
127
+
128
+ expect(text).to.equal('Hello...world')
129
+ expect(text2).to.equal('Hello...world')
130
+ })
131
+ })
@@ -0,0 +1,57 @@
1
+ /*
2
+ * The MIT License (MIT)
3
+ *
4
+ * Copyright (c) 2015 - present Instructure, Inc.
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ import { expect } from 'chai'
26
+ import '@testing-library/jest-dom'
27
+ import cleanString from '../cleanString'
28
+
29
+ describe('cleanSring', () => {
30
+ it('should remove spaces from start and end of string', async () => {
31
+ const string = ' Hello world '
32
+
33
+ const newString = cleanString(string, [' '])
34
+ expect(newString).to.equal('Hello world')
35
+ })
36
+
37
+ it('should remove spaces from only the end of string', async () => {
38
+ const string = ' Hello world '
39
+
40
+ const newString = cleanString(string, [' '], false)
41
+ expect(newString).to.equal(' Hello world')
42
+ })
43
+
44
+ it('should remove spaces and commas', async () => {
45
+ const string = ' Hello world,'
46
+
47
+ const newString = cleanString(string, [' ', ','])
48
+ expect(newString).to.equal('Hello world')
49
+ })
50
+
51
+ it('should do a thorough cleaning', async () => {
52
+ const string = 'Hello world. '
53
+
54
+ const newString = cleanString(string, [' ', '.'], false, true, true)
55
+ expect(newString).to.equal('Hello world')
56
+ })
57
+ })
@@ -0,0 +1,173 @@
1
+ /*
2
+ * The MIT License (MIT)
3
+ *
4
+ * Copyright (c) 2015 - present Instructure, Inc.
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ import React from 'react'
26
+ import { render, screen } from '@testing-library/react'
27
+ import { vi, expect } from 'vitest'
28
+
29
+ import '@testing-library/jest-dom'
30
+ import measureText from '../measureText'
31
+
32
+ const baseStyle = {
33
+ fontSize: '16px',
34
+ fontFamily: 'Arial',
35
+ fontWeight: 'normal',
36
+ fontStyle: 'normal',
37
+ letterSpacing: 'normal'
38
+ }
39
+
40
+ const getNodes = (root: Element) =>
41
+ Array.from(root.childNodes).filter(
42
+ (node) =>
43
+ node.nodeType === Node.ELEMENT_NODE || node.nodeType === Node.TEXT_NODE
44
+ )
45
+
46
+ describe('measureText', () => {
47
+ beforeEach(() => {
48
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(
49
+ () => {
50
+ return {
51
+ font: '',
52
+ measureText: vi.fn((text: string) => {
53
+ return { width: text.length * 10 }
54
+ })
55
+ } as unknown as CanvasRenderingContext2D
56
+ }
57
+ )
58
+ })
59
+
60
+ afterEach(() => {
61
+ vi.restoreAllMocks()
62
+ })
63
+
64
+ it('should calculate the width of a single text node correctly', () => {
65
+ const node = document.createElement('div')
66
+ Object.assign(node.style, baseStyle)
67
+ node.textContent = 'Hello'
68
+
69
+ const width = measureText([node])
70
+
71
+ expect(width).toBe(50) // 5 characters * 10 (mocked width per character)
72
+ })
73
+
74
+ it('should return zero for empty nodes', () => {
75
+ const node = document.createElement('div')
76
+ Object.assign(node.style, baseStyle)
77
+ node.textContent = ''
78
+
79
+ const width = measureText([node])
80
+
81
+ expect(width).toBe(0)
82
+ })
83
+
84
+ it('should calculate text width correctly', () => {
85
+ render(
86
+ <div data-testid="stage" style={baseStyle}>
87
+ Lorem ipsum <span style={baseStyle}>DOLOR SIT AMET.</span>
88
+ </div>
89
+ )
90
+ const stage = screen.getByTestId('stage')
91
+ const nodes = getNodes(stage)
92
+
93
+ const width = measureText(nodes, stage)
94
+
95
+ expect(width).toBe(270)
96
+ })
97
+
98
+ it('should account for different nodes', async () => {
99
+ const { rerender } = render(
100
+ <div data-testid="stage" style={baseStyle}>
101
+ Lorem ipsum <span style={baseStyle}>DOLOR SIT AMET.</span>
102
+ </div>
103
+ )
104
+ const stage = screen.getByTestId('stage')
105
+ const nodes = getNodes(stage)
106
+
107
+ const width = measureText(nodes, stage)
108
+
109
+ // Set child
110
+ rerender(
111
+ <div data-testid="stage" style={baseStyle}>
112
+ Lorem ipsum DOLOR SIT AMET.
113
+ </div>
114
+ )
115
+ const stage2 = screen.getByTestId('stage')
116
+ const nodes2 = getNodes(stage2)
117
+
118
+ const width2 = measureText(nodes2, stage2)
119
+
120
+ expect(width).toEqual(width2)
121
+ })
122
+
123
+ it('should call measureText on a properly configured canvas 2d context', () => {
124
+ const mockedStyle = {
125
+ fontSize: '20px',
126
+ fontWeight: 'bold',
127
+ fontStyle: 'italic',
128
+ fontFamily: 'Arial'
129
+ }
130
+
131
+ render(
132
+ <div data-testid="stage" style={mockedStyle}>
133
+ Lorem ipsum
134
+ </div>
135
+ )
136
+ const stage = screen.getByTestId('stage')
137
+ const nodes = getNodes(stage)
138
+
139
+ measureText(nodes, stage)
140
+
141
+ // The width calculation depends on the modified canvas context
142
+ const getContextSpy = HTMLCanvasElement.prototype.getContext as any
143
+ const context = getContextSpy.mock.results[0].value
144
+
145
+ expect(context.measureText).toHaveBeenCalledTimes(1)
146
+ expect(context.font).toBe('bold italic 20px Arial')
147
+ })
148
+
149
+ it('should account for letter spacing styles', async () => {
150
+ const { rerender } = render(
151
+ <div data-testid="stage" style={baseStyle}>
152
+ Lorem ipsum
153
+ </div>
154
+ )
155
+ const stage = screen.getByTestId('stage')
156
+ const nodes = getNodes(stage)
157
+ const width = measureText(nodes, stage)
158
+
159
+ expect(width).toBe(110) // default mocked width (text.length * 10)
160
+
161
+ // Set letterSpacing
162
+ rerender(
163
+ <div data-testid="stage2" style={{ ...baseStyle, letterSpacing: '5px' }}>
164
+ Lorem ipsum
165
+ </div>
166
+ )
167
+ const stage2 = screen.getByTestId('stage2')
168
+ const nodes2 = getNodes(stage2)
169
+ const width2 = measureText(nodes2, stage2)
170
+
171
+ expect(width2).toBe(165) // default mocked width + letterOffset (text.length * letterSpacing)
172
+ })
173
+ })
@@ -7,6 +7,7 @@
7
7
  },
8
8
  "include": ["./src"],
9
9
  "references": [
10
+ { "path": "../ui-axe-check/tsconfig.build.json" },
10
11
  { "path": "../console/tsconfig.build.json" },
11
12
  { "path": "../debounce/tsconfig.build.json" },
12
13
  { "path": "../emotion/tsconfig.build.json" },