• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Styled String (System API)
2
3Styled strings are string objects that facilitate the flexible use of text styles. They can be bound to the **Text** component using the [setStyledString](./ts-basic-components-text.md#setstyledstring12) API in **TextController**, and to the **RichEditor** component using the [setStyledString](ts-basic-components-richeditor.md#setstyledstring12) API in **RichEditorStyledStringController**.
4
5>  **NOTE**
6>
7>  This component is supported since API version 13. Updates will be marked with a superscript to indicate their earliest API version.
8>
9>  This topic describes only system APIs provided by the module. For details about its public APIs, see [Styled String](ts-universal-styled-string.md).
10
11## StyledString
12
13### marshalling
14
15static marshalling(styledString: StyledString): ArrayBuffer
16
17Marshals a styled string.
18
19**System API**: This is a system API.
20
21**Atomic service API**: This API can be used in atomic services since API version 13.
22
23**System capability**: SystemCapability.ArkUI.ArkUI.Full
24
25**Parameters**
26
27| Name| Type| Mandatory| Description|
28| ----- | ----- | ---- | ---- |
29| styledString | [StyledString](ts-universal-styled-string.md) | Yes | Styled string to marshal.|
30
31**Return value**
32
33| Type             |Description      |
34| ------- | --------------------------------- |
35| ArrayBuffer | Buffer information after marshalling.<br>**NOTE**<br>Currently, text and images are supported.|
36
37### marshalling<sup>18+</sup>
38
39static marshalling(styledString: StyledString, callback: StyledStringMarshallCallback): ArrayBuffer
40
41Marshals a styled string by defining a callback to marshal [StyledStringMarshallingValue](#styledstringmarshallingvalue18).
42
43**System API**: This is a system API.
44
45**Atomic service API**: This API can be used in atomic services since API version 18.
46
47**System capability**: SystemCapability.ArkUI.ArkUI.Full
48
49**Parameters**
50
51| Name| Type| Mandatory| Description|
52| ----- | ----- | ---- | ---- |
53| styledString | [StyledString](ts-universal-styled-string.md) | Yes | Styled string to marshal.|
54| callback | [StyledStringMarshallCallback](#styledstringmarshallcallback18) | Yes| Callback defining how to marshal [StyledStringMarshallingValue](#styledstringmarshallingvalue18).|
55
56**Return value**
57
58| Type             |Description      |
59| ------- | --------------------------------- |
60| ArrayBuffer | Buffer information after marshalling.<br>**NOTE**<br>Currently, text and images are supported.|
61
62### unmarshalling
63
64static unmarshalling(buffer: ArrayBuffer): Promise\<StyledString>
65
66Unarshals a buffer to obtain a styled string.
67
68**System API**: This is a system API.
69
70**Atomic service API**: This API can be used in atomic services since API version 13.
71
72**System capability**: SystemCapability.ArkUI.ArkUI.Full
73
74**Parameters**
75
76| Name| Type| Mandatory| Description|
77| ----- | ----- | ---- | ---- |
78| buffer | ArrayBuffer | Yes | Data marshaled from a styled string.|
79
80**Return value**
81
82| Type                            | Description                 |
83| -------------------------------- | --------------------- |
84| Promise\<[StyledString](ts-universal-styled-string.md)> |Promise used to return the result.|
85
86
87### unmarshalling<sup>18+</sup>
88
89static unmarshalling(buffer: ArrayBuffer, callback: StyledStringUnmarshallCallback): Promise\<StyledString>
90
91Unmarshals a styled string by defining a callback to [StyledStringMarshallingValue](#styledstringmarshallingvalue18).
92
93**System API**: This is a system API.
94
95**Atomic service API**: This API can be used in atomic services since API version 18.
96
97**System capability**: SystemCapability.ArkUI.ArkUI.Full
98
99**Parameters**
100
101| Name| Type| Mandatory| Description|
102| ----- | ----- | ---- | ---- |
103| buffer | ArrayBuffer | Yes | Data marshaled from a styled string.|
104| callback | [StyledStringUnmarshallCallback](#styledstringunmarshallcallback18) | Yes| Callback defining how to marshal **ArrayBuffer**.|
105
106**Return value**
107
108| Type                            | Description                 |
109| -------------------------------- | --------------------- |
110| Promise\<[StyledString](ts-universal-styled-string.md)> |Promise used to return the result.|
111
112**Error codes**
113
114For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md).
115
116| ID| Error Message|
117| ------- | -------- |
118| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
119
120## StyledStringMarshallingValue<sup>18+</sup>
121
122type StyledStringMarshallingValue = UserDataSpan
123
124Defines a custom marshalling object for styled strings, which you need to define marshalling and unmarshalling methods.
125
126**System API**: This is a system API.
127
128**Atomic service API**: This API can be used in atomic services since API version 18.
129
130**System capability**: SystemCapability.ArkUI.ArkUI.Full
131
132| Type | Description  |
133| ------ | ---------- |
134| [UserDataSpan](ts-universal-styled-string.md#userdataspan) | User data span style.|
135
136## StyledStringMarshallCallback<sup>18+</sup>
137
138type StyledStringMarshallCallback = (marshallableVal: StyledStringMarshallingValue) => ArrayBuffer
139
140Defines a callback for marshalling [StyledStringMarshallingValue](#styledstringmarshallingvalue18).
141
142**System API**: This is a system API.
143
144**Atomic service API**: This API can be used in atomic services since API version 18.
145
146**System capability**: SystemCapability.ArkUI.ArkUI.Full
147
148**Parameters**
149
150| Name | Type  | Mandatory| Description                         |
151| ------- | ------ | ---- | --------------------------- |
152| marshallableVal | [StyledStringMarshallingValue](#styledstringmarshallingvalue18)| Yes| Object to be marshaled.|
153
154**Return value**
155
156| Type                            | Description                 |
157| -------------------------------- | --------------------- |
158| ArrayBuffer | Marshaled data of [StyledStringMarshallingValue](#styledstringmarshallingvalue18).|
159
160## StyledStringUnmarshallCallback<sup>18+</sup>
161
162type StyledStringUnmarshallCallback = (buf: ArrayBuffer) => StyledStringMarshallingValue
163
164Defines a callback for unmarshalling an ArrayBuffer to obtain [StyledStringMarshallingValue](#styledstringmarshallingvalue18).
165
166**System API**: This is a system API.
167
168**Atomic service API**: This API can be used in atomic services since API version 18.
169
170**System capability**: SystemCapability.ArkUI.ArkUI.Full
171
172**Parameters**
173
174| Name | Type  | Mandatory| Description                         |
175| ------- | ------ | ---- | --------------------------- |
176| buf | ArrayBuffer | Yes| Marshaled data of [StyledStringMarshallingValue](#styledstringmarshallingvalue18).|
177
178**Return value**
179
180| Type                            | Description                 |
181| -------------------------------- | --------------------- |
182| [StyledStringMarshallingValue](#styledstringmarshallingvalue18) | [StyledStringMarshallingValue](#styledstringmarshallingvalue18) obtained after unmarshalling.|
183
184## Example
185
186### Example 1: Marshalling and Unmarshalling Styled Strings
187
188This example demonstrates the marshalling and unmarshalling of styled strings using the **marshalling** and **unmarshalling** APIs.
189
190```ts
191// xxx.ets
192import { LengthMetrics } from '@kit.ArkUI'
193
194@Entry
195@Component
196struct Index {
197  @State textTitle: string = "Marshalling and unmarshalling APIs"
198  @State textResult: string = "Hello world"
199  @State serializeStr: string = "Marshalling"
200  @State flag: boolean = false
201  private textAreaController: TextAreaController = new TextAreaController()
202  private buff: Uint8Array = new Uint8Array()
203
204  fontStyle: TextStyle = new TextStyle({
205    fontWeight: FontWeight.Lighter,
206    fontFamily: 'HarmonyOS Sans',
207    fontColor: Color.Green,
208    fontSize: LengthMetrics.vp(30),
209    fontStyle: FontStyle.Normal
210  })
211  // Create a styled string object.
212  styledString: StyledString = new StyledString("Hello world",
213    [{ start: 0, length: 11, styledKey: StyledStringKey.FONT, styledValue: this.fontStyle }]);
214
215  @Builder
216  controllableBuild() {
217    Column(){
218      TextArea({
219        text: this.textResult,
220        controller: this.textAreaController
221      }).width('95%').height('40%').enableKeyboardOnFocus(false)
222
223      Button(this.serializeStr)
224        .margin(5)
225        .onClick(async ()=>{
226          this.flag = !this.flag
227          if (!this.flag) {
228            console.info("Debug: Unmarshalling")
229            let styles: StyledString = await StyledString.unmarshalling(this.buff.buffer)
230            this.textTitle = "After calling decodeTlv, the result of unmarshalling is: "
231            if (styles == undefined) {
232              console.error("Debug: Failed to obtain the styled string.")
233              return
234            }
235            this.textResult =  styles.getString()
236            console.info("Debug: this.textResult = " + this.textResult)
237            let stylesArr = styles.getStyles(0, this.textResult.length, StyledStringKey.FONT)
238            console.info("Debug: stylesArr.length = " + stylesArr.length)
239            for (let i = 0; i < stylesArr.length; ++i) {
240              console.info("Debug: style.start = " + stylesArr[i].start)
241              console.info("Debug: style.length = " + stylesArr[i].length)
242              console.info("Debug: style.styledKey = " + stylesArr[i].styledKey)
243              let font = stylesArr[i].styledValue as TextStyle
244              console.info("Debug: style.fontColor = " + font.fontColor)
245              console.info("Debug: style.fontSize = " + font.fontSize)
246              console.info("Debug: style.fontFamily = " + font.fontFamily)
247              console.info("Debug: style.fontStyle = " + font.fontStyle)
248            }
249            let subStr = styles.subStyledString(0, 2)
250            console.info("Debug: subStr = " + subStr.getString())
251            this.serializeStr = "Marshalling"
252          } else {
253            console.info("Debug: Marshalling")
254            let resultBuffer = StyledString.marshalling(this.styledString)
255            this.buff = new Uint8Array(resultBuffer)
256            this.textTitle = "After calling encodeTlv, the result of marshalling is: "
257            this.textResult = this.buff.toString()
258            console.info("Debug: buff = " + this.buff.toString())
259            this.serializeStr = "Unmarshalling"
260          }
261        })
262    }.margin(10)
263  }
264
265  build() {
266    Column() {
267      Blank().margin(30)
268      Text(this.textTitle)
269      this.controllableBuild()
270    }
271  }
272}
273```
274
275### Example 2: Marshalling and Unmarshalling Styled Strings with UserDataSpan
276
277This example demonstrates the marshalling and unmarshalling of styled strings that include custom user data spans using the **marshalling** and **unmarshalling** APIs.
278
279```ts
280enum MyUserDataType {
281  TYPE1 = 0,
282  TYPE2
283}
284
285class MyUserData extends UserDataSpan {
286  constructor(){
287    super()
288  }
289  marshalling() {
290    console.log("MyUserData marshalling...")
291    const text = "MyUserData1";
292    const buffer = new ArrayBuffer(text.length + 1);
293    const uint8View = new Uint8Array(buffer);
294    // Write the type.
295    uint8View[0] = MyUserDataType.TYPE1;
296    for (let i = 1; i < text.length; i++) {
297      uint8View[i] = text.charCodeAt(i);
298    }
299    return uint8View.buffer;
300  }
301  unmarshalling()
302  {
303    console.log("MyUserData unmarshalling...")
304    return new MyUserData()
305  }
306}
307
308class MyUserData2 extends UserDataSpan {
309  marshalling() {
310    console.log("MyUserData2 marshalling...")
311    const text = "MyUserData2";
312    const buffer = new ArrayBuffer(text.length + 1);
313    const uint8View = new Uint8Array(buffer);
314    uint8View[0] = MyUserDataType.TYPE2;
315    for (let i = 1; i < text.length; i++) {
316      uint8View[i] = text.charCodeAt(i);
317    }
318    return uint8View.buffer;
319  }
320  unmarshalling()
321  {
322    console.log("MyUserData2 unmarshalling...")
323    return new MyUserData2()
324  }
325}
326
327@Entry
328@Component
329struct MarshallExample1 {
330
331  controller : TextController = new TextController()
332
333  build() {
334    Column() {
335      Text(undefined, {controller: this.controller})
336      Button("Marshall&UnMarshall")
337        .onClick(async () => {
338          let myData = new MyUserData();
339          let myData2 = new MyUserData2();
340          let myStyledString = new MutableStyledString("12345", [{
341            start: 0,
342            length: 3,
343            styledKey: StyledStringKey.USER_DATA,
344            styledValue: myData
345          }, {
346            start: 3,
347            length: 1,
348            styledKey: StyledStringKey.USER_DATA,
349            styledValue: myData2
350          }])
351
352          let buffer = StyledString.marshalling(myStyledString, (marshallingValue: StyledStringMarshallingValue)=> {
353            // Perform marshalling based on the type.
354            if (marshallingValue instanceof MyUserData) {
355              console.log("StyledString.marshalling MyUserData")
356              let value = marshallingValue as MyUserData;
357              return value.marshalling()
358            } else if (marshallingValue instanceof MyUserData2) {
359              console.log("StyledString.marshalling MyUserData2")
360              let value = marshallingValue as MyUserData2;
361              return value.marshalling()
362            }
363            console.log("StyledString.marshalling default")
364            return new ArrayBuffer(10)
365          })
366
367          let newStyledString = await StyledString.unmarshalling(buffer, (value: ArrayBuffer) => {
368            // 1. Read the type from the buffer.
369            // 2. Based on the type, choose the appropriate API to parse the buffer.
370            const uint8View  = new Uint8Array(value);
371            let type = uint8View[0];
372            console.log("unmarshalling length:" + uint8View.length)
373            if (type == MyUserDataType.TYPE1) {
374              console.log("unmarshalling type1:" + type)
375              let myUserData = new MyUserData()
376              return myUserData.unmarshalling()
377            } else if (type == MyUserDataType.TYPE2) {
378              console.log("unmarshalling type2:" + type)
379              let myUserData = new MyUserData2()
380              return myUserData.unmarshalling()
381            }
382            return new ArrayBuffer(0)
383          })
384
385          this.controller.setStyledString(newStyledString)
386        })
387        .fontSize(20)
388        .margin(10)
389    }
390    .justifyContent(FlexAlign.Center)
391    .width('100%')
392    .height('100%')
393  }
394}
395```
396