recogito / recogito-js

A JavaScript library for text annotation
BSD 3-Clause "New" or "Revised" License
349 stars 38 forks source link

Using custom formatters #103

Closed hbast closed 2 months ago

hbast commented 3 months ago

I'm having trouble understanding how to add my own formatting to annotations. I used the demo code [1] from the wiki and added the line formatter: 'formatter' to the init function.

However, when I run it, I get the error message TypeError: r.formatter is not a function. I am probably doing something wrong.

I would be very grateful for a hint.

[1] - https://github.com/recogito/recogito-js/wiki/API-Reference#formatters

rsimon commented 3 months ago

You need to supply the formatter function as the argument (not a string). E.g:

// E.g. to give a different background color to annotations with multiple bodies
var myFormatterFunction = function(annotation) {
  return (annotation.bodies.length > 1) ? "has-multiple-bodies" : "";
}

// ...
var r = Recogito.init({
  //...
  formatter: myFormatterFunction
});
hbast commented 3 months ago

Ah, my bad. Thanks for helping.

Actually, I am looking for a way to set the annotation color based on the author information. The W3C annotations support style information, but I'm not sure if recogito supports that. Otherwise I could add this information in the backend and use the formatter function to customize the rendering.

https://www.w3.org/TR/annotation-model/#styles Like in example 34 or 35.

How would you solve this?

rsimon commented 3 months ago

That's right. RecogitoJS doesn't support the W3C style props out of the box. (TBH, I always considered style to be more of an application concern, rather than a data model concern.) But, anyways: the formatter function receives the full annotation as the argument. So you can build the style using whatever annotation properties you want! E.g. if you want to style based on the author, you could simply do something like this:

var creatorFormatter = function(annotation) {
  if (annotation.creator === 'http://example.org/user1' {
    return { style: 'backgroundColor: red' };
  } else if (annotation.creator === 'http://example.org/user1' {
    return { style: 'backgroundColor: green' };
  } else {
    return { style: 'backgroundColor: green' };
  }
}

Obviously, you'd be a bit smarter & more efficient in reality, but you get the idea :-)

hbast commented 2 months ago

Obviously, you'd be a bit smarter & more efficient in reality, but you get the idea :-)

I wouldn't be so sure about that ;-)

I set the color code as a JSON value when creating the annotation and then send it to the backend. On reload, the customformatter function grabs the code and renders the annotation in the appropriate color.