0
# Display and Formatting
1
2
Utilities for converting values to display strings, formatting data for user presentation, and generating error-friendly code frames for debugging.
3
4
## Capabilities
5
6
### Display String Conversion
7
8
Functions for converting any JavaScript value to a user-friendly string representation.
9
10
```typescript { .api }
11
/**
12
* Convert any value to a display string for template interpolation
13
* Handles refs, objects, arrays, and primitive types intelligently
14
* @param val - Value to convert to display string
15
* @returns String representation suitable for display
16
*/
17
function toDisplayString(val: unknown): string;
18
```
19
20
### Code Frame Generation
21
22
Functions for generating formatted code frames that highlight specific regions of source code.
23
24
```typescript { .api }
25
/**
26
* Generate a formatted code frame showing source code with line numbers
27
* Highlights a specific range and provides context lines around it
28
* @param source - Source code string to generate frame from
29
* @param start - Start position to highlight (default: 0)
30
* @param end - End position to highlight (default: source.length)
31
* @returns Formatted code frame with line numbers and highlighting
32
*/
33
function generateCodeFrame(
34
source: string,
35
start?: number,
36
end?: number
37
): string;
38
```
39
40
**Usage Examples:**
41
42
```typescript
43
import { toDisplayString, generateCodeFrame } from "@vue/shared";
44
45
// Basic value conversion
46
console.log(toDisplayString("hello")); // "hello"
47
console.log(toDisplayString(42)); // "42"
48
console.log(toDisplayString(true)); // "true"
49
console.log(toDisplayString(null)); // ""
50
console.log(toDisplayString(undefined)); // ""
51
52
// Array conversion
53
const arr = [1, 2, { name: "test" }];
54
console.log(toDisplayString(arr));
55
// Formatted JSON with proper indentation:
56
// [
57
// 1,
58
// 2,
59
// {
60
// "name": "test"
61
// }
62
// ]
63
64
// Object conversion
65
const obj = {
66
name: "John",
67
age: 30,
68
active: true,
69
toString: () => "Custom toString" // Ignored - uses JSON.stringify
70
};
71
console.log(toDisplayString(obj));
72
// {
73
// "name": "John",
74
// "age": 30,
75
// "active": true
76
// }
77
78
// Special object handling
79
const specialObj = {
80
name: "test",
81
toString: Object.prototype.toString // Uses JSON.stringify
82
};
83
console.log(toDisplayString(specialObj)); // JSON formatted
84
85
const customToString = {
86
name: "test",
87
toString: () => "Custom representation"
88
};
89
console.log(toDisplayString(customToString)); // "Custom representation"
90
91
// Map and Set handling
92
const map = new Map([
93
["key1", "value1"],
94
[Symbol("sym"), "symbolValue"],
95
[123, "numberKey"]
96
]);
97
console.log(toDisplayString(map));
98
// {
99
// "Map(3)": {
100
// "key1 =>": "value1",
101
// "Symbol(sym) =>": "symbolValue",
102
// "123 =>": "numberKey"
103
// }
104
// }
105
106
const set = new Set([1, "hello", Symbol("test")]);
107
console.log(toDisplayString(set));
108
// {
109
// "Set(3)": [
110
// 1,
111
// "hello",
112
// "Symbol(test)"
113
// ]
114
// }
115
116
// Symbol handling
117
const sym = Symbol("description");
118
console.log(toDisplayString(sym)); // "Symbol(description)"
119
120
const anonSym = Symbol();
121
console.log(toDisplayString(anonSym)); // "Symbol()"
122
123
// Code frame generation
124
const sourceCode = `function hello() {
125
const message = "Hello World";
126
console.log(message);
127
return message;
128
}`;
129
130
// Highlight specific range
131
const frame = generateCodeFrame(sourceCode, 25, 45);
132
console.log(frame);
133
// Output:
134
// 1 | function hello() {
135
// 2 | const message = "Hello World";
136
// | ^^^^^^^^^^^^^
137
// 3 | console.log(message);
138
// 4 | return message;
139
// 5 | }
140
141
// Highlight entire line
142
const lineFrame = generateCodeFrame(sourceCode, 20, 50);
143
console.log(lineFrame);
144
145
// Error position highlighting
146
const errorCode = `const x = 1 +;
147
const y = 2;`;
148
149
const errorFrame = generateCodeFrame(errorCode, 12, 13);
150
console.log(errorFrame);
151
// Output:
152
// 1 | const x = 1 +;
153
// | ^
154
// 2 | const y = 2;
155
```
156
157
### Display String Conversion Rules
158
159
**toDisplayString** follows these conversion rules:
160
161
1. **Strings**: Return as-is
162
2. **null/undefined**: Return empty string `""`
163
3. **Arrays**: Use `JSON.stringify` with 2-space indentation
164
4. **Objects**:
165
- If has custom `toString` (not Object.prototype.toString): Use it
166
- Otherwise: Use `JSON.stringify` with 2-space indentation
167
5. **Maps**: Convert to object notation showing entries
168
6. **Sets**: Convert to array notation showing values
169
7. **Symbols**: Show with description `Symbol(description)`
170
8. **Refs**: Recursively convert the `.value` property
171
9. **Other**: Use `String()` conversion
172
173
### Code Frame Features
174
175
**Line Numbering**: Automatic line number generation with consistent padding
176
**Context Lines**: Shows 2 lines before and after the highlighted region
177
**Range Highlighting**: Uses `^` characters to mark the specific range
178
**Multi-line Support**: Handles ranges spanning multiple lines
179
**Edge Cases**: Safely handles out-of-bounds positions
180
181
### Advanced Usage Examples
182
183
```typescript
184
// Vue ref handling (when available)
185
import { ref } from 'vue';
186
const reactiveValue = ref({ count: 5 });
187
console.log(toDisplayString(reactiveValue));
188
// Shows the value, not the ref wrapper:
189
// {
190
// "count": 5
191
// }
192
193
// Nested ref handling
194
const nestedRef = ref(ref("nested"));
195
console.log(toDisplayString(nestedRef)); // "nested"
196
197
// Complex nested structures
198
const complex = {
199
users: new Map([
200
["john", { age: 30, roles: new Set(["admin", "user"]) }]
201
]),
202
settings: [
203
{ key: "theme", value: "dark" },
204
{ key: "lang", value: "en" }
205
]
206
};
207
208
console.log(toDisplayString(complex));
209
// Properly formatted with Map and Set representations
210
211
// Code frame for syntax errors
212
const syntaxError = `import { computed } from 'vue'
213
214
const value = computed(( => {
215
return state.count * 2
216
})`;
217
218
const frame = generateCodeFrame(syntaxError, 45, 46);
219
// Points to the syntax error position
220
```
221
222
### Integration with Vue
223
224
These utilities are integral to Vue's template system:
225
226
- **Template Interpolation**: `toDisplayString` formats `{{ }}` expressions
227
- **Error Reporting**: `generateCodeFrame` shows exact error locations in templates
228
- **Development Tools**: Better debugging experience with formatted output
229
- **SSR**: Consistent string conversion across server and client rendering