text:
How get latitudeDelta and longitudeDelta from any region?

Hello, how can i get this requirements ? because without them, my initial marker (when map runs) is in full zoom possible in map, so i need that when the map runs, it have a zoom for 10 or something, is this possible?
UPDATE:
is there any easy way to make zoom when map runs? 😕
Thanks!

I  also like to know this too, in the example the latitudeDelta has a value but I don't know how that value was calculated.
Thanks

I didn't figure out how the latitudeDelta and longitudeDelta are calculated.
However, I logged the region value with the event onRegionChangeComplete to have a basic understanding of what kind of values I need to use to zoom on the markers the way I want.
If you want to zoom programmatically on anything, you can use the method animateToRegion and pass the coords, and the deltas you got from logging. You just have to find your desired "zoom" by pinching the map, and note down these values.
Here's my sample of code to center / zoom the map on one of my markers :
    onPressMarker (markerData) {
        this.setState({ openedMarker: markerData });
        this.refs.map.animateToRegion({
            latitude: parseFloat(markerData.latitude),
            longitude: parseFloat(markerData.longitude),
            latitudeDelta: 0.0043,
            longitudeDelta: 0.0034
        });
    }

This gives me exactly the zoom I want.

Given an array of coordinates coords this function returns the region (lat, lng and deltas) to contain those coordinates.
export function getRegionForCoordinates(coords) {
  // coords should be an array of { latitude: X, longitude: Y }
  let minX, maxX, minY, maxY;

  // init first point
  ((point) => {
    minX = point.latitude;
    maxX = point.latitude;
    minY = point.longitude;
    maxY = point.longitude;
  })(points[0]);

  // calculate rect
  points.map((point) => {
    minX = Math.min(minX, point.latitude);
    maxX = Math.max(maxX, point.latitude);
    minY = Math.min(minY, point.longitude);
    maxY = Math.max(maxY, point.longitude);
  });

  const midX = (minX + maxX) / 2;
  const midY = (minY + maxY) / 2;
  const midPoint = [midX, midY];

  const deltaX = (maxX - minX);
  const deltaY = (maxY - minY);

  return {
    latitude: midX,
    longitude: midY,
    latitudeDelta: deltaX,
    longitudeDelta: deltaY
  };
}

HI needed to pass in an object, not an array and fix a few other variables but latitude is undefined so I am not sure why. do you have any idea? I passed both latitude and longitude.

Given a point x,y your region is effectively a box around that pint, right?  A GPS location has an accuracy field expressed in meters.  But a region is expressed in degrees latitude and longitude, so I you need to convert meters to degrees.  And because the earth is a sphere the maths (I think) is as follows:
regionFrom(lat, lon, accuracy) {
    const oneDegreeOfLongitudeInMeters = 111.32 * 1000;
    const circumference = (40075 / 360) * 1000;

    const latDelta = accuracy * (1 / (Math.cos(lat) * circumference));
    const lonDelta = (accuracy / oneDegreeOfLongitudeInMeters);

    return {
      latitude: lat,
      longitude: lon,
      latitudeDelta: Math.max(0, latDelta),
      longitudeDelta: Math.max(0, lonDelta)
    };
  }

@uriklar your formula just return 0 for longtitudeDelta and latitudeDelta.
@npomfret your formula crashes...

Yeah, i thin k there's a divide by zero error that happens at 0 degrees

+1 on any updates for this as my team is struggling with the same issue.

  static regionFrom(lat, lon, accuracy) {
    const oneDegreeOfLongitudeInMeters = 111.32 * 1000;
    const circumference = (40075 / 360) * 1000;

    const latDelta = accuracy * (1 / (Math.cos(lat) * circumference));
    const lonDelta = (accuracy / oneDegreeOfLongitudeInMeters);

    return {
      latitude: lat,
      longitude: lon,
      latitudeDelta: Math.max(0, latDelta),
      longitudeDelta: Math.max(0, lonDelta)
    };
  }

@npomfret Thank you for this, but I experience that it returns 0 quite often, do you know any way to redeem this?

Returns 0?  I don't understand, this function returns an object, not a number.

thanks to all!

@cinder92 Why is there no "official" example on how to calculate delta? I'd never heard of it before this plugin, I'm sure I'm not alone

@npomfret long/lat-delta algorithm did not work for me an I have my doubts about it's correctness.
One degree of latitude in meters is independent of longitude and can be assumed a constant. One degree of longitude in meters however depends on the latitude. My code is based on the following formular:

(Source: http://www.movable-type.co.uk/scripts/latlong.html#destPoint)
I set the bearing to 90 degrees because I only need it to calculate the longitude delta. The latitude delta can be determined from the oneDegreeOfLatitudeInMeters constant.
This is working for me:
regionFrom(lat, lon, distance) {
        distance = distance/2
        const circumference = 40075
        const oneDegreeOfLatitudeInMeters = 111.32 * 1000
        const angularDistance = distance/circumference

        const latitudeDelta = distance / oneDegreeOfLatitudeInMeters
        const longitudeDelta = Math.abs(Math.atan2(
                Math.sin(angularDistance)*Math.cos(lat),
                Math.cos(angularDistance) - Math.sin(lat) * Math.sin(lat)))

        return result = {
            latitude: lat,
            longitude: lon,
            latitudeDelta,
            longitudeDelta,
        }
    }

@cgrossde thanks for the info.  Can you give an example of where mine didn't work? It looks ok in my map.  I'm using it to draw a circle based on accuracy - the circle is exactly the same size as the one drawn by the native map code it you turn on user tracking.

Hi @uriklar , can you give the complete example. Here is my code.
import React from 'react';
import { StyleSheet,Text,View }  from 'react-native';
import MapView from 'react-native-maps';
export default class ReactMap extends React.Component {
constructor(props){
super(props);
this.state={
markers:[{
coordinates:{
latitude: 18.5204,
longitude: 73.8567,
},
},
{
coordinates:{
latitude: 25.2744,
longitude: 133.7751,
},
},
{
coordinates:{
latitude: 37.0902,
longitude: 72.8777,
            },
        },
        {
            coordinates:{
                latitude: 46.2276,
                longitude: 2.2137,

            },
        }]
    }

}

  getRegionForCoordinates(points) {
    // points should be an array of { latitude: X, longitude: Y }
    let minX, maxX, minY, maxY;
    console.log("Points",points)
    // init first point
    ((point) => {
      minX = point.latitude;
      maxX = point.latitude;
      minY = point.longitude;
      maxY = point.longitude;
    })(points[0]);

    // calculate rect
    points.map((point) => {
      minX = Math.min(minX, point.latitude);
      maxX = Math.max(maxX, point.latitude);
      minY = Math.min(minY, point.longitude);
      maxY = Math.max(maxY, point.longitude);
    });

    const midX = (minX + maxX) / 2;
    const midY = (minY + maxY) / 2;
    const deltaX = (maxX - minX);
    const deltaY = (maxY - minY);

    return {
      latitude: midX,
      longitude: midY,
      latitudeDelta: deltaX,
      longitudeDelta: deltaY
    };
  }

render() {

    return (

                <MapView style={styles.map}
                region={this.state.getRegionForCoordinates(this.state.markers)}
         /*       ref={(ref)=>{this.mapRef=ref}}
                showsTraffic={true}
             //   onLayout = {(ref) => this.mapRef.fitToCoordinates(this.state.markers, { edgePadding: { top: 10, right: 10, bottom: 10, left: 10 }, animated: false })}
                onRegionChangeComplete={(region) => {
                    console.log(" region", region)
              }}    */
              >

                {this.state.markers.map(marker =>   (
                    <MapView.Marker key={marker.title}
                    coordinate={marker.coordinates}
                    title={marker.title}
                    >
                    <View style={styles.radius}>
                    <View style={styles.markerStyle}/>
                    </View>
                   </MapView.Marker>
                ))}

                </MapView>

    );
}

}
const styles=StyleSheet.create({
container:{
position:'absolute',
top:0,
bottom:0,
left:0,
right:0,
justifyContent:'flex-end',
alignItems:'center'
},
map:{
position:'absolute',
top:0,
bottom:0,
left:0,
right:0,
},
radius:{
height:15,
width:15,
backgroundColor:'#81BD26',
overflow:'hidden',
borderRadius:50/2,
borderWidth:1,
alignItems:'center',
justifyContent:'center'
},
markerStyle:{
height:14,
width:14,
backgroundColor:'#81BD26',
alignItems:'center',
justifyContent:'center'
}
});

The other functions didn't work for me. @cgrossde's worked partially but I was getting some weird zoom levels when using coordinates in Bogotá, Colombia (it worked with other cities).
So I found this simplified version that seems to work everywhere:
static getDelta(lat, lon, distance): Coordinates {
       const latitudeDelta =distance / oneDegreeOfLatitudeInMeters;
       const longitudeDelta = distance / (oneDegreeOfLatitudeInMeters * Math.cos(lat * (Math.PI / 180)));

       return result = {
           latitude: lat,
           longitude: lon,
           latitudeDelta,
           longitudeDelta,
       }
   }

@cgrossde what does the "distance" refer to?

@hugoh1995 If I remember correctly it should be meters.

how do I pass the longitude and latitude received from  a firebase database to be rendered in the google map with markers.
please I need help

what is this stupid distance, god this delta thing is so frustrating!!

so, having one {lag,lng} which is center of the map, how could I get (determine) any other {lat,lng} by specify x,y of View of the map?

what is distance?

So many magic calculations..

I think distance is 'accuracy' here.

Here is the solution for latitudeDelta and longitudeDelta =>
calDelta(lat,long,accuracy){
const oneDegreeOfLatitudeInMeters = 111.32 * 1000;
const latDelta =accuracy / oneDegreeOfLatitudeInMeters;
const longDelta = accuracy / (oneDegreeOfLatitudeInMeters * Math.cos(lat * (Math.PI / 180)));
    this.setState({
        region:{
          latitude:lat,
          longitude:long,
          latitudeDelta:latDelta,
          longitudeDelta:longDelta,
          accuracy:accuracy,
          },
        });
}

Here is the complete example to view marker with zoom level=>
import React, {Component} from 'react';
import {View,Text,StyleSheet,Dimensions} from 'react-native';
import MapView, { PROVIDER_GOOGLE, Marker } from 'react-native-maps';
const {width,height} = Dimensions.get('window')
class CurrentPosition extends Component{
constructor() {
super();
this.state = {
region: {
latitude: "",
longitude: "",
latitudeDelta:"",
longitudeDelta:"",
accuracy:"",
}
}
}
calDelta(lat,long,accuracy){
   const oneDegreeOfLatitudeInMeters = 111.32 * 1000;
   const latDelta =accuracy / oneDegreeOfLatitudeInMeters;
   const longDelta = accuracy / (oneDegreeOfLatitudeInMeters * Math.cos(lat * (Math.PI / 180)));

    this.setState({
        region:{
          latitude:lat,
          longitude:long,
          latitudeDelta:latDelta,
          longitudeDelta:longDelta,
          accuracy:accuracy,
          },
        });
}

componentWillMount(){

this.watchID = navigator.geolocation.watchPosition((position)=>
       {
        const lat = position.coords.latitude;
        const long = position.coords.longitude;
        const accuracy = position.coords.accuracy;

        this.calDelta(lat,long,accuracy)
    },

    (error)=>{
          console.log(error.message)
    },
    {enableHighAccuracy:true,timeout:20000,maximumAge:1000,}
  )

}
componentWillUnmount(){
navigator.geolocation.clearWatch(this.watchID)
}
marker(){
return {
latitude:this.state.region.latitude,
longitude:this.state.region.longitude
}
}
render(){
    console.log(this.state.region)
    return(
          <View style={styles.container}>
            {this.state.region.latitude ?
            <MapView
            provider={PROVIDER_GOOGLE}
             style={styles.map}
             initialRegion={this.state.region}
              >
             <MapView.Marker
                coordinate={this.marker()}
                title="You"
                description="You are here!"
                pinColor='green'
             />

            </MapView>
            : <Text>cordinates not found</Text> }

          </View>

       )

}

}
const styles = StyleSheet.create({
container:{
flex:1,
justifyContent:'center'
},
map: {
width:width,
height:height,
flex: 1
}
});
export default CurrentPosition;
I hope this will solve your problem.

Given an array of coordinates coords this function returns the region (lat, lng and deltas) to contain those coordinates.
export function getRegionForCoordinates(points) {
  // points should be an array of { latitude: X, longitude: Y }
  let minX, maxX, minY, maxY;

  // init first point
  ((point) => {
    minX = point.latitude;
    maxX = point.latitude;
    minY = point.longitude;
    maxY = point.longitude;
  })(points[0]);

  // calculate rect
  points.map((point) => {
    minX = Math.min(minX, point.latitude);
    maxX = Math.max(maxX, point.latitude);
    minY = Math.min(minY, point.longitude);
    maxY = Math.max(maxY, point.longitude);
  });

  const midX = (minX + maxX) / 2;
  const midY = (minY + maxY) / 2;
  const deltaX = (maxX - minX);
  const deltaY = (maxY - minY);

  return {
    latitude: midX,
    longitude: midY,
    latitudeDelta: deltaX,
    longitudeDelta: deltaY
  };
}

returning longitudeDelta:0 0

If it's still actual for someone then you can find my solution here, don't know it is super stable or not , but can be useful https://github.com/react-native-community/react-native-maps/issues/705#issuecomment-557790428

Given an array of coordinates coords this function returns the region (lat, lng and deltas) to contain those coordinates.
export function getRegionForCoordinates(points) {
  // points should be an array of { latitude: X, longitude: Y }
  let minX, maxX, minY, maxY;

  // init first point
  ((point) => {
    minX = point.latitude;
    maxX = point.latitude;
    minY = point.longitude;
    maxY = point.longitude;
  })(points[0]);

  // calculate rect
  points.map((point) => {
    minX = Math.min(minX, point.latitude);
    maxX = Math.max(maxX, point.latitude);
    minY = Math.min(minY, point.longitude);
    maxY = Math.max(maxY, point.longitude);
  });

  const midX = (minX + maxX) / 2;
  const midY = (minY + maxY) / 2;
  const deltaX = (maxX - minX);
  const deltaY = (maxY - minY);

  return {
    latitude: midX,
    longitude: midY,
    latitudeDelta: deltaX,
    longitudeDelta: deltaY
  };
}

This solution doesn't work when having location with negative longitude value and another with positive longitude value.

@npomfret long/lat-delta algorithm did not work for me an I have my doubts about it's correctness.
One degree of latitude in meters is independent of longitude and can be assumed a constant. One degree of longitude in meters however depends on the latitude. My code is based on the following formular:

(Source: http://www.movable-type.co.uk/scripts/latlong.html#destPoint)
I set the bearing to 90 degrees because I only need it to calculate the longitude delta. The latitude delta can be determined from the oneDegreeOfLatitudeInMeters constant.
This is working for me:
regionFrom(lat, lon, distance) {
        distance = distance/2
        const circumference = 40075
        const oneDegreeOfLatitudeInMeters = 111.32 * 1000
        const angularDistance = distance/circumference

        const latitudeDelta = distance / oneDegreeOfLatitudeInMeters
        const longitudeDelta = Math.abs(Math.atan2(
                Math.sin(angularDistance)*Math.cos(lat),
                Math.cos(angularDistance) - Math.sin(lat) * Math.sin(lat)))

        return result = {
            latitude: lat,
            longitude: lon,
            latitudeDelta,
            longitudeDelta,
        }
    }

How i get "distance" ?

Try following this, worked for me: https://github.com/react-native-community/react-native-maps/issues/356#issuecomment-515694070

my simple solution working for me:
const getRegionFromBounds = (bounds) => { // from Directions API
    const northeastLat = bounds.northeast.lat, southwestLat = bounds.southwest.lat;
    const northeastLng = bounds.northeast.lng, southwestLng = bounds.southwest.lng;
    return {
        latitude: (northeastLat + southwestLat) / 2, // 2D middle point
        longitude: (northeastLng + southwestLng) / 2, // 2D middle point
        latitudeDelta: Math.max(northeastLat, southwestLat) - Math.min(northeastLat, southwestLat),
        longitudeDelta: (Math.max(northeastLng, southwestLng) - Math.min(northeastLng, southwestLng)) * height / width,
    };// height and width are the dimensions of the screen
}

I am not quite sure what the distance/accuracy is from in the previous answers, for me I have google location details, thus I tried with the following answer, seems to work:
https://stackoverflow.com/a/51118004/13529635
But I don't know why in the example code such as https://github.com/react-native-maps/react-native-maps/blob/master/example/examples/AnimatedMarkers.js , the const LATITUDE_DELTA is 0.0922? How is it calculated? Is it the same by details.geometry.viewport.northeast.lat - details.geometry.viewport.southwest.lat?

`
import { getCenterOfBounds, getBounds } from 'geolib';
...
// Polygon calculations
const center = getCenterOfBounds(polygonCoordinates);
const bounds = getBounds(polygonCoordinates);
// Map size
const { width, height: sHeight } = Dimensions.get('screen');
const height = sHeight / 3;
const aspectRatio = width / height;
// Delta calculations
const zoomOutValue = 0.8;
const deltaMultiplier = (maxCoord, minCoord) => (maxCoord - minCoord) * aspectRatio * zoomOutValue;
const latitudeDelta = deltaMultiplier(bounds.maxLat, bounds.minLat);
const longitudeDelta = deltaMultiplier(bounds.maxLng, bounds.minLng);
const initialRegion = {
...center,
latitudeDelta,
longitudeDelta,
};
return (
<MapView
style={{ width, height }}
initialRegion={initialRegion}

<Polygon
  coordinates={polygonCoordinates}
  fillColor="#ff000052"
  strokeColor="red"
  strokeWidth={2}
/>

`

I created the following based on the mercator math in https://github.com/tuupola/php_google_maps
The key function is mercatorDegreeDeltas(latitude, longitude, width, height, zoom) which returns { latitudeDelta, longitudeDelta } for the specified latitude/longitude center point, map dimensions, and zoom level (1-20).
import React from 'react';
import { useWindowDimensions } from 'react-native';
import MapView from 'react-native-maps';
import { useBottomTabBarHeight } from '@react-navigation/bottom-tabs';
import { useHeaderHeight } from '@react-navigation/elements';

const MERCATOR_OFFSET = Math.pow(2, 28);
const MERCATOR_RADIUS = MERCATOR_OFFSET / Math.PI;

function mercatorLatitudeToY(latitude) {
  return Math.round(
    MERCATOR_OFFSET -
    (
      (
        MERCATOR_RADIUS *
          Math.log(
            (1 + Math.sin(latitude * (Math.PI / 180))) /
            (1 - Math.sin(latitude * (Math.PI / 180)))
          )
      ) / 2
    )
  );
}

function mercatorLongitudeToX(longitude) {
  return Math.round(
    MERCATOR_OFFSET +
      (
        (
          (MERCATOR_RADIUS * longitude) * Math.PI
        ) / 180
      )
  );
}

function mercatorXToLongitude(x) {
  return (
    (
      (x - MERCATOR_OFFSET) / MERCATOR_RADIUS
    ) * 180
  ) / Math.PI;
}

function mercatorYToLatitude(y) {
  return (
    (
      (
        Math.PI / 2
      ) -
        (2 * Math.atan(
              Math.exp(
                (
                  y - MERCATOR_OFFSET
                ) / MERCATOR_RADIUS
              )
            )
        )
    ) * 180
  ) / Math.PI;
}

function mercatorAdjustLatitudeByOffsetAndZoom(latitude, offset, zoom) {
  return mercatorYToLatitude(mercatorLatitudeToY(latitude) + (offset << (21 - zoom)));
}

function mercatorAdjustLongitudeByOffsetAndZoom(longitude, offset, zoom) {
  return mercatorXToLongitude(mercatorLongitudeToX(longitude) + (offset << (21 - zoom)));
}

function mercatorDegreeDeltas(latitude, longitude, width, height, zoom) {

  if (!zoom) {
    zoom = 20;
  }

  const deltaX = width / 2;
  const deltaY = height / 2;

  const northLatitude = mercatorAdjustLatitudeByOffsetAndZoom(latitude, deltaY * -1, zoom);
  const westLongitude = mercatorAdjustLongitudeByOffsetAndZoom(longitude, deltaX * -1, zoom);
  const southLatitude = mercatorAdjustLatitudeByOffsetAndZoom(latitude, deltaY, zoom);
  const eastLongitude = mercatorAdjustLongitudeByOffsetAndZoom(longitude, deltaY, zoom);

  const latitudeDelta = Math.abs(northLatitude - southLatitude);
  const longitudeDelta = Math.abs(eastLongitude - westLongitude);

  return { latitudeDelta, longitudeDelta };
}

const CENTER_UNITED_STATES = {
  latitude: 37.68001896458841,
  longitude: -97.29625353645876,
};

export default function MapViewWrapper() {
  const { width, height } = useWindowDimensions();
  const tabBarHeight = useBottomTabBarHeight();
  const headerHeight = useHeaderHeight();
  const initialRegion = React.useRef(null);
  const availableHeight = height - tabBarHeight - headerHeight;

  // Only calculate initial region once
  if (!initialRegion.current) {
    const { latitudeDelta, longitudeDelta } = mercatorDegreeDeltas(
      CENTER_UNITED_STATES.latitude,
      CENTER_UNITED_STATES.longitude,
      width,
      availableHeight,
      4,
    );

    initialRegion.current = {
      latitude: CENTER_UNITED_STATES.latitude,
      longitude: CENTER_UNITED_STATES.longitude,
      latitudeDelta: latitudeDelta,
      longitudeDelta: longitudeDelta,
    };
  }

  return (
    <MapView
      initialRegion={initialRegion.current}
      style={{ width: width, height: availableHeight }}
    />
  );
}

There is at least one issue: if you change the zoom from 4 to 3, it isn't centered properly, but larger zoom values work. I don't need the lower zoom values right now, so I haven't investigated the math any further (maybe some sort of overflow?).

  static regionFrom(lat, lon, accuracy) {
    const oneDegreeOfLongitudeInMeters = 111.32 * 1000;
    const circumference = (40075 / 360) * 1000;

    const latDelta = accuracy * (1 / (Math.cos(lat) * circumference));
    const lonDelta = (accuracy / oneDegreeOfLongitudeInMeters);

    return {
      latitude: lat,
      longitude: lon,
      latitudeDelta: Math.max(0, latDelta),
      longitudeDelta: Math.max(0, lonDelta)
    };
  }

This worked for me. Thanks

authors: Cammoy EgorKazachenko Exilz Larney11 ShaikhKabeer VaporFoxLash benjick calinbuzatu cgrossde cinder92 code-by findhumane flora8984461 hugoh1995 jereztech jnrepo karamat manojkumawat003 nateeither npomfret patilrevansidh sisiguo supercamilo theHinneh uriklar yasora099 yassern yeomann


text:
[V6-alpha] Why has GoogleAds been added to the dependencies?

Hello,
I've just upgraded the package to the latest 6.0.0-alpha.5 and noticed that a new GoogleAds dependency was added both to the Android and Ios native dependencies.
I mean, I understand that adding support for CSAI could be useful for some projects, but making it a mandatory dependency for the whole library seems to take us away from the main purpose of this library.
Maybe I haven't notice something so feel free to correct me 😅

this block iOS publishing for me getting "non-public selector..." referencing the ads GoogleAds as blocker
I'm  NOT using the ads feature, so I expect this to be an optional deps like many others
pls help, thx

Ok I did the job on Android, someone also need to do it also on ios.
I will not have time to do this week (not sure for the week after). Quick solution is to downgrade on previous version.

This will help https://www.youtube.com/watch?v=vVI7ZAZq5e0

source: gharchive/issue

authors: BraveEvidence freeboub hatem-72 samihabuawadSL

repo: react-native-video/react-native-video

license: MIT

license_type: permissive

license_source: github-api


text:
Revert "fix: remove pausePlayback when audio focus loss event (#3496)"

This reverts commit b1ab0f24a3efbcc3be49005060f50b34a117664e.
It causes regression in case of incoming call.
initial PR: https://github.com/react-native-video/react-native-video/pull/3496
New Pr to be created

ping @YangJonghun

source: gharchive/pull-request


text:
Getting ERR_CLEARTEXT_NOT_PERMITTED in WebView

Bug description:
Given unsecured links in html
When user click on those links
Then I get an error page with ERR_CLEARTEXT_NOT_PERMITTED
To Reproduce:
Load an html page that include unsecured http links
Expected behavior:
Allow redirect to http links
Screenshots/Videos:

Environment:

react-native version: 0.61.2

Note that my AndroidManifest.xml includes:
<application android:usesCleartextTraffic="true" />
Related links:

https://stackoverflow.com/questions/54752716/why-am-i-seeing-neterr-cleartext-not-permitted-errors-after-upgrading-to-cordo

Add the below line in your application tag:
android:usesCleartextTraffic="true"

As shown below:
<application
    ....
    android:usesCleartextTraffic="true"
    ....>

Hope it helps.
https://stackoverflow.com/questions/52707918/webview-showing-err-cleartext-not-permitted-although-site-is-https

I am also faceing same issue

@HellzAngel got the same problem, did you solve this?

Adding
android:usesCleartextTraffic="true"

doesn't help. Any other suggestions?

Hi!
I get the same error, but this solution working!
Thanks!

y other s

how did u solve it?

Hi Oscar.
I fix it adding android:usesCleartextTraffic="true" in my AndroidManifest:

Regards!

Adding
android:usesCleartextTraffic="true"

doesn't help. Any other suggestions?

Please note that this file (AndroidManifest.xml) is in main folder not in debug folder

hey is there anyway to allow cleartext text traffic in android only for the webview ?
like in iOS we do have NSAllowsArbitraryLoadsInWebContent key

https://github.com/rajguptaH/ReactNativeWebView you can take reference from here you just have to add
android:usesCleartextTraffic="true"

in AndroidManifest.xml file
and if your expo there is no android folder so you have to use normal template of react native as their official documents have

add this lines of code in AndroidMainfest.xml file =>>>>>  android:usesCleartextTraffic="true"

How to do this in an Expo managed project since there is no android folder present?

How to do this in an Expo managed project since there is no android folder present? @rajguptaH

You could execute the npx expo prebuild command in root of your expo project which will create the android folder.

How to do this in an Expo managed project since there is no android folder present? @rajguptaH

As per https://stackoverflow.com/a/76708333/2987737

You'll need to use the expo-build-properties plugin
npx expo install expo-build-properties and then add the config in app.json

{
  "expo":
  {
  ...
    "plugins": [
      ["expo-build-properties", {
        "android": {
          "usesCleartextTraffic": true
        },
        "ios": {
          ...
        }
      }]
  }
}

I encountered the same issue and was using android:usesCleartextTraffic="true", but it didn't resolve the problem.
To fix it, I had to add android:networkSecurityConfig="@xml/network_security_config" as well.
e.g.
<application
      …
      android:usesCleartextTraffic="true"
      android:networkSecurityConfig="@xml/network_security_config">

My network_security_config.xml located at {reactNativeAppPath}/android/app/src/main/res/xml/network_security_config.xml:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">{allowedDomain}</domain>
        <domain includeSubdomains="true">localhost</domain>
    </domain-config>
</network-security-config>

authors: ErickMaeda FanShiDe HellzAngel JohnTechAU Josnic LYevhen MdIntezarAlam Oscarz90 Sumansourabh14 chenop harveyconnor oldo rajguptaH skizzo vaishnav-197


text:
[Question] Loading injectedJavascript content from a file

Hi,
This is more of a question rather than a bug or feature request.
My injectedJavascript prop is receiving a value that is getting too big and I would like to extract it to a different JS file. How can I load a stringified version of the JS file as-is so that I can then pass it to the webview prop?
Thanks!

OK, I wrote this experimental code, not sure if it will work everywhere but it is a start:
jsSerializer.js
export default (theModule) => {
  if (!theModule || !theModule.main) {
    throw new Error(
      "The module must be defined and have a function called 'main'",
    );
  }
  const serialized = Object.keys(theModule)
    .filter((fnName) => typeof theModule[fnName] === 'function')
    .reduce((acc, fnName) => `${acc}${theModule[fnName]}\n`, '');

  return `${serialized}main();true;`;
};

fileToBeInjected.js
export function aux() {
   return 'this is an aux function';
}
export function main() {
  window.ReactNativeWebView.postMessage(aux());
}

App.js
import React from 'react';
import {WebView} from 'react-native-webview';
import * as fileToBeInjected from './fileToBeInjected';
import jsSerializer from './jsSerializer';

const App = () => {
  return (
    <WebView
        source={{uri: 'https://google.com'}}
        javaScriptEnabled={true}
        injectedJavaScript={jsSerializer(fileToBeInjected)}
        onMessage={console.log}
      />
  );
};

export default App;

OK, I wrote this experimental code, not sure if it will work everywhere but it is a start:
jsSerializer.js
export default (theModule) => {
  if (!theModule || !theModule.main) {
    throw new Error(
      "The module must be defined and have a function called 'main'",
    );
  }
  const serialized = Object.keys(theModule)
    .filter((fnName) => typeof theModule[fnName] === 'function')
    .reduce((acc, fnName) => `${acc}${theModule[fnName]}\n`, '');

  return `${serialized}main();true;`;
};

fileToBeInjected.js
export function aux() {
   return 'this is an aux function';
}
export function main() {
  window.ReactNativeWebView.postMessage(aux());
}

App.js
import React from 'react';
import {WebView} from 'react-native-webview';
import * as fileToBeInjected from './fileToBeInjected';
import jsSerializer from './jsSerializer';

const App = () => {
  return (
    <WebView
        source={{uri: 'https://google.com'}}
        javaScriptEnabled={true}
        injectedJavaScript={jsSerializer(fileToBeInjected)}
        onMessage={console.log}
      />
  );
};

export default App;


text:
useTransition notification-hub example doesn't work with v9.0rc3

I have upgraded react-spring to v9rc3 in the MessageHub example https://codesandbox.io/s/messagehub-lrxrb and it stopped working with the error:
Cannot read property 'life' of undefined

The v9-compatible version of that example is found here:
https://github.com/react-spring/react-spring-examples/blob/v9/demos/hooks/notification-hub/index.js

authors: aleclarson gvocale

repo: react-spring/react-spring


text:
Update Storybook addon metadata

Hey react-theming! We've created a catalog of Storybook addons and yours is included: https://storybook.js.org/addons/@react-theming/storybook-addon
To make your addon more discoverable in the catalog, we've curated some of its metadata, and I've included those edits in this PR.
To learn more about the catalog metadata, check out our documentation: https://storybook.js.org/docs/react/addons/addon-catalog

Hey @coderkevin thanks.... looks it's an auto created PR as it tries to change existing metadata 😄

Hi @UsulPro, yeah I'm running a script to help me get these PRs out and they're based on human-curated data we've added for the catalog. If you've made any recent changes to your metadata since we added some of our own, it may be incompatible. It looks like all you really. need here are the extra 2 keywords. Would you like me to modify this PR to reflect that?

Thanks @coderkevin
do I need to publish updates to NPM to them take affect?

Thanks! Yes, the changes will be reflected after the next NPM release.

authors: UsulPro coderkevin

repo: react-theming/storybook-addon


text:
Rerender table on data change, is it through shouldComponentUpdate?

Hi,
my data changes, comes from external json, stored in redux store and changes as actions are dispatched. I am trying to get the table to rerender upon data change, which is passed as props and is used in row composition.
I saw some examples about shouldComponentUpdate as body/row wrapper, also tried through componentWillReceiveProps(), but I just can't seem to get the table to refresh.
What would be the standard way to refresh the table on data change?
Thank you

I think you may have to override the default SCU. See here. It should pick up row level changes by default but maybe there's something else going on and you have to account for that.

Yes, that's the example I looked at and tried to reproduce, but I did not see that it was picking up props changes. Will it detect custom props changes? Also, for body wrapper it was clear, but for row wrapper, I tried but I was not sure how to combine it with dnd.Rows.
Also, the initial use of my props is in the constructor, where it sets the version of state variable rows, if there a way to create that relationship between rows and my data (through props) at rendering level, I guess it would pick up automatically. Also I tried to reset state in componenWillReceiveProps, replicating the code from constructor, but it was giving me error about missing column. Are we supposed to be able to redefine rows? I know for columns I don't have issues, I resize them dynamically and it reflects in table.
Is any of what I am mentioning supposed to work and I am just doing it wrong?
Thanks

Now I can clearly see it is not seeing my component level props, and if I try to explicitly put my prop in Table.Body it gets rejected. For sure I am not doing this the right way, trying to understand how I can achieve that (associating my table json data to the table in such a way that it will refresh the table when data changes).

Hi,
I would need a small example to run to tell what's going on. You could disable SCU behavior temporarily entirely as that's one possible source of the problem. You will also want to validate that the table gets the right data when the JSON changes. Maybe it has something to do with the column definition too?

Hi,
I can confirm that state properly gets updated at page level, and issue is how to get the table to react to it. I feel the way I made it does not create a strong enough connection between that external data and the row, since my external data is only used in constructor, and constructor would be called only once, so rerendering does not update the table data.
Basically, I am very confident that if relationship between row and my data is enforced in render method, it would be very easy to get the table to update. However, doing that requires a much deeper understanding of how ReactTabular works internally than I currently do, hopefully you know a proper way to do this.
Here is a simplified version of my code to better illustrate what I am doing (which is directly based on your examples and I adapt to my needs):
// constructor
//...
    const columns = this.getColumns();
    const rows = resolve.resolve({ columns })(
      this.props.myTableData);

    this.state = {
      searchColumn: 'all',
      query: {},
      sortingColumns: null,
      rows,
      columns
}
//...
// getColumns
  getColumns() {
    return [
      {
        property: 'firstColumn',
        props: {
          style: { minWidth: columnBaseWidthFirstColumn, width: columnBaseWidthFirstColumn }
        },
        header: {
          label: 'First Column'
        },
        cell: {
          formatters: [
            tree.toggleChildren({
              getRows: () => this.state.rows,
              getShowingChildren: ({ rowData }) => rowData.showingChildren,
              toggleShowingChildren: rowIndex => {
                const rows = cloneDeep(this.state.rows);

                rows[rowIndex].showingChildren = !rows[rowIndex].showingChildren;

                this.setState({ rows });
              },
              // Inject custom class name per row here etc.
              props: {}
            })
          ]
        },
        visible: true
      },
      {
        property: 'secondColumn',
        props: {
          style: { minWidth: columnBaseWidthSecondColumn, width: columnBaseWidthSecondColumn }
        },
        header: {
          label: 'SecondColumn'
        },
        visible: true
      }
    ];
  }
  //render()
  //...
      const {
      searchColumn, columns, sortingColumns, query
    } = this.state;
    const visibleColumns = columns.filter(column => column.visible);

    const rows = compose(
      tree.filter({ fieldName: 'showingChildren' }),
      tree.wrap({
        operations: [
          sort.sorter({
            columns,
            sortingColumns,
            sort: orderBy
          })
        ]
      }),
      tree.search({
        operation: search.multipleColumns({ columns, query })
      })
    )(this.state.rows);

    const components = {
      body: {
        //wrapper: BodyWrapper,
        row: dnd.Row // how am I supposed to combine this with a row wrapper?
      }
    };
//...
return (
//...
          <Table.Provider
            className="pure-table pure-table-striped"
            style={{ 'fontSize': this.state.tableTextFontSize }}
            components={components}
            columns={this.state.columns}//{visibleColumns}
          >
            <Table.Header />
            <Table.Body rows={rows} rowKey="id" onRow={this.onRow} />
          </Table.Provider>

)

Also to provide some background information on what I am doing, I am basically building a table that uses the tree structure and the drag and drop, but I am only taking advantage of the fact id is exposed, then I drop to a custom drop zone and go from that. That part is working fine so far.
Thanks

Can you show where/how you fetch the external data?

Data is passed as props by the parent of the component in which the table is rendered. Data itself is initially fetched from a json file by a redux middleware, and after that the other changes are internal, events from within the page trigger redux actions that modify the data.
I don't have any doubt that the page is receiving the updated state from the redux store. For example, I am checking in componentWillReceiveProps and I clearly see the new state being sent to the component.
I can show code if necessary, but from my point of view issue is that my external data is only explicitly used in constructor, so I tried to reset the state when props change, but I get "Error: resolve - Missing columns!" (I am doing the same thing I am doing in constructor for rows), tried inside of componentWillReceiveProps and componentDidUpdate, but both giving the same error.

Hi,
I understand now. It's good to remember the constructor gets called only when a component is mounting. You should see React lifecycle methods and do a resolve pass when rows change. Otherwise you'll miss that and the table won't work as you expect.

About the error, validate that const columns = this.getColumns(); returns something sensible. One option would be to push resolve to render just to get it working before optimizing.

Oh boy, it seems I had not wrapped columns in {} when updating rows and calling resolve.resolve in componentDidUpdate, it's now refreshing the table. Sorry about that, really is my bad. The other solutions you proposed, I am not sure I understand how to achieve those.
Now I realise the way it refreshes the data is not what I am looking for. No Data gets deleted or added, only some column values change in existing rows, and I need to persist the state, like scrolling position, tree status, etc., so back to the drawing board. If I copy current rows and update the rows manually and then set the state to that, without doing a new resolve, will my table refresh without resetting all trees and positions?
Thanks again.

If I copy current rows and update the rows manually and then set the state to that, without doing a new resolve, will my table refresh without resetting all trees and positions?

You need resolve to inject _index to the data. The underlying logic (dnd) relies on that.
Please note that this library is not under active maintenance and I'm thinking of dropping support entirely as there's no commercial demand whatsoever (doing this support work is losing money/time). So it may be a good idea to explore better supported alternatives.

I use your drag, but not your drop, I don't drop in same table, I drop in other components elsewhere in the page, so I don't think resolve is needed but I'll have to try it out (to see if I can update a few columns and that state, tree, scrolling) will persist).
A few weeks back I did ask about that (if using this for new projects was a good idea) and your answer was that you were in minimal support mode, that PRs are welcome and that you could recommend that I fork your project and start from there.
I like your project, but what I find the hardest with it is the documentation. I am not saying documentation is bad, it provides enough examples to get started, but the way it is built does not make learning easy, at least for me. So to sum up the situation, if I stick with this, there is a big possibility I will be on my own?
My next steps would be heavy customization (inserting links, using left/right click, custom style based on dynamic flags that change as actions get triggered, etc.), so there is a big chance I'd have more questions for you, so maybe your timing is right :). If this loses you time and money and there is no benefit at all for you, then I'd feel bad keeping this up and harassing you with questions.
In any case, whatever your decision is, thanks again for the help and support and I hope I was not too annoying with my questions.

I use your drag, but not your drop, I don't drop in same table, I drop in other components elsewhere in the page, so I don't think resolve is needed but I'll have to try it out (to see if I can update a few columns and that state (tree, scrolling) will persist).

Alright.

I like your project, but what I find the hardest with it is the documentation. I am not saying documentation is bad, it provides enough examples to get started, but the way it is built does not make learning easy, at least for me. So to sum up the situation, if I stick with this, there is a big possibility I will be on my own?

Basically I can provide an answer every now and then but to truly help I would need some code to run. Otherwise it's guesswork.
To truly understand what's going under the hood it's likely a good idea to spend some time with the code. There's not much of it despite the amount of packages. That will help you understand how it all goes together. Every part of the design is there for some specific reason.

My next steps would be heavy customization (inserting links, using left/right click, custom style based on dynamic flags that change as actions get triggered, etc.), so there is a big chance I'd have more questions for you, so maybe your timing is right :). If this loses you time and money and there is no benefit at all for you, then I'd feel bad keeping this up and harassing you with questions.

If it's something business-related, maybe you could look into getting your company to sponsor some of this work. But yeah, now the project is literally losing money as I don't have an employer and time I use is my own.
It's that customization part where reactabular begins to shine assuming you get the other problems tackled first. It's not the easiest to pick up but I tried to design it so that it doesn't get in your way when a weird requirement comes your way.

Time to close. Please open separate issues for further questions.

authors: bebraw zelanter

repo: reactabular/reactabular

license: mit

license_source: bigquery


text:
update build script

The Unicast tests are now included in the test run and the nuspec file is used as a workaround for the TCK nuget package.

looks good


text:
[Bug]: Putting RoutedViewHost inside a TabControl on Avalonia causes an app crash after navigating the second time

Describe the bug 🐞
I have the following scenario

A TabControl with 2 tabs - Companies and Employees
Each tab has a RoutedViewHost
When the app is launched everything is rendered correctly
When you go from companies tab to the employees and come back to companies tab the application crashes with the following error

Unhandled exception. System.InvalidOperationException: The control already has a visual parent.
   at Avalonia.Visual.ValidateVisualChild(Visual c)
   at Avalonia.Collections.AvaloniaList`1.Add(T item)
   at Avalonia.Controls.Presenters.ContentPresenter.UpdateChild(Object content)
   at Avalonia.Controls.Presenters.ContentPresenter.ContentChanged(AvaloniaPropertyChangedEventArgs e)
   at Avalonia.Animation.Animatable.OnPropertyChangedCore(AvaloniaPropertyChangedEventArgs change)
   at Avalonia.AvaloniaObject.RaisePropertyChanged[T](AvaloniaProperty`1 property, Optional`1 oldValue, BindingValue`1 newValue, BindingPriority priority, Boolean isEffectiveValue)
   at Avalonia.PropertyStore.EffectiveValue`1.SetAndRaiseCore(ValueStore owner, StyledProperty`1 property, T value, BindingPriority priority, Boolean isOverriddenCurrentValue, Boolean isCoercedDefaultValue)
   at Avalonia.PropertyStore.ValueStore.SetLocalValue[T](StyledProperty`1 property, T value)
   at Avalonia.PropertyStore.ValueStore.SetValue[T](StyledProperty`1 property, T value, BindingPriority priority)
   at Avalonia.Controls.Presenters.ContentPresenter.set_Content(Object value)
   at Avalonia.Controls.TransitioningContentControl.UpdateContent(Boolean withTransition)
   at Avalonia.Controls.TransitioningContentControl.OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
   at Avalonia.Visual.OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs e)
   at Avalonia.Layout.Layoutable.OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs e)
   at Avalonia.Controls.Control.OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs e)
   at Avalonia.Visual.SetVisualParent(Visual value)
   at Avalonia.Visual.SetVisualParent(IList children, Visual parent)
   at Avalonia.Collections.AvaloniaList`1.NotifyAdd(T item, Int32 index)
   at Avalonia.Controls.Presenters.ContentPresenter.UpdateChild(Object content)
   at Avalonia.Controls.Presenters.ContentPresenter.ContentChanged(AvaloniaPropertyChangedEventArgs e)
   at Avalonia.Animation.Animatable.OnPropertyChangedCore(AvaloniaPropertyChangedEventArgs change)
   at Avalonia.AvaloniaObject.RaisePropertyChanged[T](AvaloniaProperty`1 property, Optional`1 oldValue, BindingValue`1 newValue, BindingPriority priority, Boolean isEffectiveValue)
   at Avalonia.PropertyStore.EffectiveValue`1.SetAndRaiseCore(ValueStore owner, StyledProperty`1 property, T value, BindingPriority priority, Boolean isOverriddenCurrentValue, Boolean isCoercedDefaultValue)
   at Avalonia.PropertyStore.EffectiveValue`1.SetAndRaise(ValueStore owner, IValueEntry value, BindingPriority priority)
   at Avalonia.PropertyStore.ValueStore.ReevaluateEffectiveValue(AvaloniaProperty property, EffectiveValue current, IValueEntry changedValueEntry, Boolean ignoreLocalValue)
   at Avalonia.PropertyStore.ValueStore.OnBindingValueChanged(IValueEntry entry, BindingPriority priority)
   at Avalonia.PropertyStore.BindingEntryBase`2.<SetValue>g__Execute|38_0(BindingEntryBase`2 instance, BindingValue`1 value)
   at Avalonia.PropertyStore.BindingEntryBase`2.SetValue(BindingValue`1 value)
   at Avalonia.PropertyStore.BindingEntryBase`2.OnNext(TSource value)
   at Avalonia.Data.TemplateBinding.PublishValue()
   at Avalonia.AvaloniaObject.RaisePropertyChanged[T](AvaloniaProperty`1 property, Optional`1 oldValue, BindingValue`1 newValue, BindingPriority priority, Boolean isEffectiveValue)
   at Avalonia.AvaloniaObject.SetAndRaise[T](DirectPropertyBase`1 property, T& field, T value)
   at Avalonia.Controls.TabControl.set_SelectedContent(Object value)
   at Avalonia.Controls.TabControl.<UpdateSelectedContent>b__45_0(Object v)
   at Avalonia.Reactive.LightweightObservableBase`1.Subscribe(IObserver`1 observer)
   at Avalonia.Controls.TabControl.UpdateSelectedContent(Control container)
   at Avalonia.Controls.TabControl.<>c.<.cctor>b__10_0(TabControl x, AvaloniaPropertyChangedEventArgs e)
   at Avalonia.Reactive.LightweightObservableBase`1.PublishNext(T value)
   at Avalonia.AvaloniaObject.RaisePropertyChanged[T](AvaloniaProperty`1 property, Optional`1 oldValue, BindingValue`1 newValue, BindingPriority priority, Boolean isEffectiveValue)
   at Avalonia.AvaloniaObject.RaisePropertyChanged[T](DirectPropertyBase`1 property, T oldValue, T newValue)
   at Avalonia.Controls.Primitives.SelectingItemsControl.OnSelectionModelPropertyChanged(Object sender, PropertyChangedEventArgs e)
   at Avalonia.Controls.Selection.SelectionModel`1.RaisePropertyChanged(String propertyName)
   at Avalonia.Controls.Selection.SelectionModel`1.CommitOperation(Operation operation, Boolean raisePropertyChanged)
   at Avalonia.Controls.Selection.SelectionModel`1.EndBatchUpdate()
   at Avalonia.Controls.Selection.SelectionModelExtensions.BatchUpdateOperation.Dispose()
   at Avalonia.Controls.Primitives.SelectingItemsControl.UpdateSelection(Int32 index, Boolean select, Boolean rangeModifier, Boolean toggleModifier, Boolean rightButton, Boolean fromFocus)
   at Avalonia.Controls.Primitives.SelectingItemsControl.UpdateSelection(Control container, Boolean select, Boolean rangeModifier, Boolean toggleModifier, Boolean rightButton, Boolean fromFocus)
   at Avalonia.Controls.Primitives.SelectingItemsControl.UpdateSelectionFromEventSource(Object eventSource, Boolean select, Boolean rangeModifier, Boolean toggleModifier, Boolean rightButton, Boolean fromFocus)
   at Avalonia.Controls.TabControl.OnPointerPressed(PointerPressedEventArgs e)
   at Avalonia.Input.InputElement.<>c.<.cctor>b__32_8(InputElement x, PointerPressedEventArgs e)
   at Avalonia.Reactive.LightweightObservableBase`1.PublishNext(T value)
   at Avalonia.Interactivity.EventRoute.RaiseEventImpl(RoutedEventArgs e)
   at Avalonia.Interactivity.EventRoute.RaiseEvent(Interactive source, RoutedEventArgs e)
   at Avalonia.Interactivity.Interactive.RaiseEvent(RoutedEventArgs e)
   at Avalonia.Input.MouseDevice.MouseDown(IMouseDevice device, UInt64 timestamp, IInputElement root, Point p, PointerPointProperties properties, KeyModifiers inputModifiers, IInputElement hitTest)
   at Avalonia.Input.MouseDevice.ProcessRawEvent(RawPointerEventArgs e)
   at Avalonia.Input.InputManager.ProcessInput(RawInputEventArgs e)
   at Avalonia.Controls.TopLevel.HandleInput(RawInputEventArgs e)
   at Avalonia.Native.WindowBaseImpl.RawMouseEvent(AvnRawMouseEventType type, UInt64 timeStamp, AvnInputModifiers modifiers, AvnPoint point, AvnVector delta)
   at Avalonia.Native.Interop.Impl.__MicroComIAvnWindowBaseEventsVTable.RawMouseEvent(Void* this, AvnRawMouseEventType type, UInt64 timeStamp, AvnInputModifiers modifiers, AvnPoint point, AvnVector delta)
--- End of stack trace from previous location ---
   at Avalonia.Native.DispatcherImpl.RunLoop(CancellationToken token)
   at Avalonia.Threading.DispatcherFrame.Run(IControlledDispatcherImpl impl)
   at Avalonia.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at Avalonia.Threading.Dispatcher.MainLoop(CancellationToken cancellationToken)
   at Avalonia.Controls.ApplicationLifetimes.ClassicDesktopStyleApplicationLifetime.Start(String[] args)
   at Avalonia.ClassicDesktopStyleApplicationLifetimeExtensions.StartWithClassicDesktopLifetime(AppBuilder builder, String[] args, ShutdownMode shutdownMode)
   at AvaloniaApplication1.Program.Main(String[] args) in /Users/gagik/Downloads/RoutedViewHostInsideTabControl/RoutedViewHostInsideTabControl/Program.cs:line 13

Step to reproduce

Download the attached sample
Run the application
Change the tab to Employees
Change the tab back to Companies
Observe an app crash

Reproduction repository
https://github.com/kyurkchyan/RoutedViewHostInsideTabControl
Expected behavior
The tab switching should work seamlessly
Screenshots 🖼
No response
IDE
Rider macOS
Operating system
Mac OS 14.0 (23A344)
Version
Avalonia.ReactiveUI 11.0.5
Device
Mac
ReactiveUI Version
19.5.1
Additional information ℹ
No response

We've resolved this issue by copying the RoutedViewHost source code and adding the following inside the WhenActivated block
this.WhenActivated(disposables =>
            {
                ....

                Disposable.Create(() =>
                          {
                              Content = null;
                          })
                          .DisposeWith(disposables);
            });

This resolves the root cause of the issue. The problem is that once the view is reactivated, the same content is recreated through view location. However, that view is already attached to the parent. This means whenever the routed view host deactivates, we also need to clear its content. Otherwise, we are risking double-attaching the same view and causing this exception.

Probably worth raising this up with the Avalonia team. See if you can get the fix in.

@glennawatson  you are actually right. I've extended the sample I've attached to this bug report. And instead of using RoutedViewHost when using bare TransitioningContentControl through assigning the Content property the same issue occurs. I will raise this Avalonia.

Worth noting that AvaloniaUI own both the RoutedViewHost and the TransitioningContentControl
https://github.com/AvaloniaUI/Avalonia/blob/master/src/Avalonia.ReactiveUI/RoutedViewHost.cs
So bugs with that system aren't necessarily related directly with ReactiveUI.

@glennawatson thanks for the info, I actually didn't realize that. And the good news is the issue is already fixed in the latest CI beta release.

authors: glennawatson kyurkchyan

repo: reactiveui/ReactiveUI


text:
Cannot force to use Chakra engine instead of VroomJs

I have added the following code before app.UseReact(...)
var engineSwitcher = JsEngineSwitcher.Instance;
engineSwitcher.EngineFactories.Clear();
engineSwitcher.EngineFactories.AddChakraCore();
engineSwitcher.DefaultEngineName = ChakraCoreJsEngine.EngineName;

but still see Failed to initialise VroomJs error in logs.

I think you can just ignore that error, it should still be using Chakra.

I cannot ignore error as it is an unhandled exception in React.AspNet.BabelFileMiddleware and pipeline stops executing
An unhandled exception has occurred: Unable to resolve type: React.ReactEnvironment
React.TinyIoC.TinyIoCResolutionException: Unable to resolve type: React.ReactEnvironment ---> React.TinyIoC.TinyIoCResolutionException: Unable to resolve type: React.JavaScriptEngineFactory ---> React.Exceptions.VroomJsInitialisationException: Failed to initialise VroomJs.


text:
Translate: Fragments

Translate Fragments #4

We're closing this issue to reduce the noise in the repo. The place to claim an issue is #4
Thanks! 👍

authors: RamirezAlex alejandronanez


text:
[fixed] Ensure we don't check for hidden on Shadow DOM.

When inside a Shadow DOM, the loop will eventually reach the Shadow DOM element itself, which cannot be checked for visibility. We can continue our upwards check by skipping to the Shadow DOM host.
Changes proposed:

Skip the Shadow DOM element (rootNode when inside a Shadow DOM) when checking for visibility.

Acceptance Checklist:

[x] The commit message follows the guidelines in CONTRIBUTING.md.
[x] Documentation (README.md) and examples have been updated as needed.
[x] If this is a code change, a spec testing the functionality has been added.
[x] If the commit message has [changed] or [removed], there is an upgrade path above.

@diasbruno I added some specs to this to verify the functionality.

@stevematney Look really good! Bom trabalho. I'll do my best to review this ASAP.

Cool! Thank you!

@diasbruno we recently discovered that simply using document.activeElement does not work in Safari with Web Components inside Modals that have Shadow DOM attached. For this instance, you have to drill down through (potentially) nested shadowRoot elements to find the actual element that is active. Without this drilling down, scopeTab thinks that elements inside a Shadow DOM are not visible within the modal, even though that's not the case. This breaks tabbing, either redirecting focus to the Modal itself, or to the first non-Web-Component item within the Modal.
This is an active bug for us, so the sooner we can get these changes into a new react-modal version, the better. I appreciate all your help on this!

Will getActiveElement do the job for this case?

Will getActiveElement do the job in this case?

I think you're asking if the new getActiveElement function in these changes will solve the problem of finding the activeElement within Shadow DOM. If that is what you're asking, then yes. It will recurse through nested activeElement until it finds the one that does not have a shadowRoot.
https://github.com/reactjs/react-modal/blob/3aa914fbb14c4011911d4c2167ab1015d0598f03/src/helpers/scopeTab.js#L3-L7

Nice! Released version 3.14.4.

Nice! Released version 3.14.4. 🎉

@diasbruno thanks so much for jumping on that quickly!

Nah..no problem, bro!
Let me know if something happens in this release so we can rollback.

authors: diasbruno stevematney

repo: reactjs/react-modal


text:
Typo

Hey guys,
I wanna use this opportunity and thank you personally for this amazing lib + this amazing doc. I loved it. Especially those challenges at the end of each section. Good job.
I also found this small typo here: https://github.com/reactjs/react.dev/blob/eb174dd932613fb0784a78ee2d9360554538cc08/src/content/reference/rsc/server-components.md?plain=1#L291C23-L291C31
All the best
Mohammad Jawad

commment should be comment


text:
fix wrong quotes around inline codes

related PR:

#6522

The root cause is fixing on remark-smartypants: here
But It's hard to tell when it gets merged so in the meanwhile this typo fix can be helpful.

I think no need to merge this PR, let's wait to fix it in the upstream package https://github.com/silvenon/remark-smartypants/pull/80

@dimaMachina Yes, It's merging in no time. I will just change this PR to update dependency after new version releases 😋

@dimaMachina I just found it they don't rely on silvenon/remark-smartypants.
the remark-smartypants here is implemented itself. Sorry for confusing 🥲. I can refer to your work to fix this.

@2wheeh thank you of course you can refer 👍

@2wheeh thanks for fixing this! I'm still seeing it broken in the preview deployment, could you take a look?

@2wheeh thanks for fixing this! I'm still seeing it broken in the preview deployment, could you take a look?

@rickhanlonii Have you checked they are cached ?

Ah, can you increment the cache key here: https://github.com/reactjs/react.dev/blob/main/src/utils/prepareMDX.js#L10

Ah, can you increment the cache key here: https://github.com/reactjs/react.dev/blob/main/src/utils/prepareMDX.js#L10

@rickhanlonii done it: 1c6d531
and it looks fine in preview now.
except in search bar :

Awesome, thanks! The search should update the index after deploy.

authors: 2wheeh dimaMachina rickhanlonii


text:
"Here" as the title for link has no semantics

A page could have 50 links, every one with the link text "Here" and it doesn't mean anything.
Search engines rely on the fact that the link text says something about the link. The text "Here" doesn't mean anything to search engines.  Using "Here" as link text has no semantic value.

Search engines aside, it's helpful for screen readers to have more descriptive link content. The link text here is a bit long but let's go with it.

authors: KennethKinLum alexkrolick


text:
Improve ESLint

I replaced next with next/core-web-vitals because it's stricter and better in my opinion. (https://nextjs.org/docs/basic-features/eslint)
I also added a rule that warns about unused variables. I think this is essential. When I ran yarn lint, I saw many unused variables. I'll fix them later.

Yes, only no-unused-vars.


text:
Терминология: Contibuting

Выражения из Codebase Overview, но встречаются и в других главах из CONTRIBUTING.
Codebase - код (не могу придумать, как вставить сюда base, чтобы не получилось длинное словосочетание);
(to) contribute - участвовать в разработке (внести вклад еще переводят, но мне больше первый вариант нравится, к тому же это в документации, а не в меню).

guide - руководство или гайд? Гайд, на мой, взляд, достаточно устоявшеся слово.

utilities - утилиты или вспомогательные функции?

@Heegiiny давайте сделаем по issue на термин, чтобы обсуждение было максимально ясным https://github.com/reactjs/ru.reactjs.org/issues/155

Codebase:
кодовая база и база кода? Например, в вашей базе кода... Или обзор кодовой базы

Хорошо.

@Heegiiny
contribute:
содействие [в разработке]
делать вклад

Сам раздел мы перевели как Участие в проекте, для перевода главы How to Contribute я бы предпочтёл использовать более общий перевод - Как внести свой вклад (поскольку много встречается в рунете) или Как поучаствовать (но не нравится из-за некоторого повтора названия главы), а уже в самом тексте можно использовать участвовать в разработке (например здесь уместнее).

authors: Heegiiny another-guy lex111


text:
Интеграция со сторонними библиотеками

@vvscode спасибо, а также @ntishkevich и @another-guy за ревью!


text:
🛑 Bellshade Website is down

In b4ca896, Bellshade Website (https://bellshade.org) was down:

HTTP code: 0
Response time: 0 ms

Resolved: Bellshade Website is back up in bc7d84e.


text:
Add tests for double watchers to be ignored

This tests the current behavior. I think the behavior should be changed to throw an exception instead of silently ignoring those callables or just call both callables.

@clue Not sure whether it should be an exception or just call all callbacks.

@kelunik Both would be valid options IMHO. Do you feel like filing an issue or preparing a PR so we can discuss this and its implications? :+1:

Done via #87.

authors: clue kelunik

repo: reactphp/event-loop


text:
Provide Interfaces

Would you be open to programming React Against a set of interfaces?
That way I can use other PSR-7 HTTP and embed the react interface in an extension of an already existing PSR-7 http object.

What kind of interfaces are you looking for? IMO we should focus our efforts on providing native PSR-7 support (see #28) instead of providing our own set of interfaces.

Honestly I think PSR-7 is the way to go, you've done great work coming up with solutions regarding that on the client side @clue :+1:

I believe this has been answered, see #28 for more details.
I'll close this for now, please come back with more details if this problem persists and we can reopen this :+1:

authors: WyriHaximus clue geggleto

repo: reactphp/http


text:
✨ [Feature request]:  Dev jokes javascript to typescript

Is your feature request related to a problem? Please describe.
This feature is not related to any problem it's modification of Dev jokes from javascript to typescript
Describe the solution you'd like
Converting jsx to tsx 🛠

hey @atapas  can you assign this to me..

repo: reactplay/react-play


text:
UncontrolledTooltips do not position correctly if the wrapper has an overflow: auto

Issue description

components: UncontrolledTooltip
reactstrap version ^6.1.0
react version ^16.4.0
bootstrap version ^4.1.1

What is happening?
The title says it all: UncontrolledTooltips do not position correctly if the wrapper has an overflow: auto.
After a lot of searching, I landed on this popper.js issue which is exactly the problem I am reporting for Reactstrap.
What should be happening?
UncontrolledTooltip should be placed correctly on the target DOM element.
Steps to reproduce issue

Create a div and wrap it in another div with the CSS (or the React style) overflow: auto.
Create an UncontrolledTooltip and set as target this div.

Error message in console
No error in console, just UX.
Code
Check the following section.
A solution I found
By looking at the issue I pointed at previously, seems like the problem is the following:

It's the correct behavior, the preventOverflow modifier uses by default, as boundariesElement, the scrollParent, you can change it to viewport or window or anything else supported.

So, I resolved the issue by adding the modifiers prop to the UncontrolledTooltip:
 <UncontrolledTooltip modifiers={{preventOverflow: {boundariesElement: 'window'}}} autohide={false} delay={{ show: 200, hide: 5 }} placement='left' target={${id}_${j}}> ... </UncontrolledTooltip>

Looks like bootstrap exposes an easy way to set the boundary (also documented. We should probably expose a boundary prop which sets the preventOverflow.boundariesElement in the same way.

@TheSharpieOne - I think the boundariesElement can also apply to the Dropdown/UncontrolledDropdown, should a new issue be created for that?

Nice solution with the modifiers prop, works great now!

authors: Muntaner TheSharpieOne pachuka tarik-besic

repo: reactstrap/reactstrap


text:
i have an issue while initializing readium js viewer

here is error log
0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'run', 'prepare' ]
2 info using npm@2.7.4
3 info using node@v0.12.2
4 verbose stack Error: ENOENT, open '/home/theta-1-linux/Desktop/working/readium/readium-js-viewer/package.json'
4 verbose stack     at Error (native)
5 verbose cwd /home/theta-1-linux/Desktop/working/readium/readium-js-viewer
6 error Linux 3.19.0-30-generic
7 error argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "prepare"
8 error node v0.12.2
9 error npm  v2.7.4
10 error path /home/theta-1-linux/Desktop/working/readium/readium-js-viewer/package.json
11 error code ENOENT
12 error errno -2
13 error enoent ENOENT, open '/home/theta-1-linux/Desktop/working/readium/readium-js-viewer/package.json'
13 error enoent This is most likely not a problem with npm itself
13 error enoent and is related to npm not being able to find a file.
14 verbose exit [ -2, true ]

On your filesystem, does this file exist?
/home/theta-1-linux/Desktop/working/readium/readium-js-viewer/package.json

If not, what are the permissions in the containing folder?
Could you try again after moving readium-js-viewer into your home folder?

Hey Daniel
Thanks, it works for me
Thanks & Regards
Rohan M.
rohan@thetatechnolabs.com
www.thetatechnolabs.com
This message and any files attached to it are intended for the use of the
addressee only and may contain private and confidential material, the
disclosure of which is prohibited by law. If you are not the intended
recipient, please note that disclosure, distribution or copying of this
message and any attachments is strictly prohibited.
On Tue, Nov 3, 2015 at 12:05 AM, Daniel Weck notifications@github.com
wrote:

If not, what are the permissions in the containing folder?
Could you try again after moving readium-js-viewer into your home folder?
—
Reply to this email directly or view it on GitHub
https://github.com/readium/readium-js-viewer/issues/429#issuecomment-153118664
.

authors: danielweck rohanmashiyava

repo: readium/readium-js-viewer


text:
Hypothes.is / Annotation example integration

Was talking with @rkwright today at the Hacking the Codex hackathon, and we talked about what would be needed for a Hypothesis integration (many people have asked us for one!).
There are a couple ways we could integrate. The simplest approach could be injecting JavaScript in the iframe, a guest annotator that can communicate with a host in the parent document. This is largely to be able to get selection data and draw highlights. Will we be able to do this with the upcoming work on plugins?
If this will not work there are other possibilities, for example, a highlight and getSelection API. We need to be able to listen for selection events in the iframe and get more selection data than merely the CFI (for example, if there are PDF versions of the same document we would like to be able to migrate annotations between them). We also need to be able to create highlights where annotations exist.
It will be easiest if we can inject our guest script. Thoughts?

I can see this being a plugin, yes. We would need to develop a better facility to inject scripts into the iframes. What we have now (but not in master/develop yet) is this:
reader.getLoadedContentFrames()

returns an array of tuples <Iframe, spineItem>
This is an array because depending on the page spread, or scroll view we could have multiple iframes  being displayed. Right now to inject JS, it is up to you to include script tags, and so on once you have the iframe reference.

Managing the injection and state from the iframes is probably going to be the biggest challenge.
If the host of the annotator can handle multiple guests then this will be easier.

We should take care not to expose the iframe to plugins. There is a known security issue caused by Readium's reliance on direct iframe access. I had the impression that we planned on fixing it one day. If we allow plugin developers direct access, it will exacerbate the problem by potentially breaking plugin compatibility if we ever decide to fix it.
My suggestion would be to expose an opaque API for injecting scripts. Under the hood it could use direct iframe access.

@JakeHartnell
How does Hypothes.is/Annotator render the highlights? Do you guys do span element wrapping of the text? One of my concerns with highlighting + EPUB docs is to not disrupt the integrity of the original DOM. This is to avoid CFI invalidation.
With highlighting what we have tries is to not insert spans and instead use range info + absolutely positioned divs to indirectly render highlights.
In some unavoidable cases (mathjax integration), when we have to do DOM manipulation we mark certain element nodes and their subtrees as "blacklisted" areas. Unfortunately with what we have now this is not ideal for highlights because essentially every time you create a highlight you are removing that area of text away from the CFI resolution.
I personally think using spans and having the ability to modify the DOM without the CFI worry will be the best, both in ease of development and end user experience. But in order to have this we need to spend some development time into something like this:
https://github.com/readium/readium-cfi-js/pull/19

@ryanackley
Yea, the opaque API is a good solution. I want the plugins API to head towards this direction, with what we have now everything is a direct access to the Reader view API. I want to stress this to others that this issue with breaking plugin compatibility on changes applies to more than just the iframe security issue.

I think we have reached a point where a brief telecon would be helpful and more efficient. I'll propose something.

Doesn't this exist now? Should this issue be closed then?

@jccr are you happy closing this? (I certainly am)

Yes. Let's close this.

authors: JCCR JakeHartnell coler-j danielweck jccr rkwright ryanackley

repo: readium/readium-js


text:
Can we have search result section wise in sphinx rtd theme?

Problem
Give details on your issue.
I have some sections in the project, and I need that if someone searches then the search page will give section-wise results.
Reproducible Project
Please give a link to a public reproducible project or provide an example of the Restructured Text that gives an issue.
Place RST code here (if any).

Error Logs/Results
Place any images or error logs that might be able to help solve the issue here.
Expected Results
Please describe how this should work properly.
Environment Info

Python Version:
Sphinx Version:
RTD Theme Version:

@rahulsrivastava1 can you write a bit more about your use-case?'
It might be solved for projects hosted on Read the Docs since it uses RTD's own server side search and client for displaying search results. This doesn't relate to sphinx-rtd-theme.
Otherwise, Sphinx has its own search function and your feature would have to be requested on Sphinx. You can read about search options here: https://www.sphinx-doc.org/en/master/usage/configuration.html

Hi @benjaoming, I have some sections in my project, and I have some pages under that section. I want that if someone to search by any keyword then the search page will appear section-wise. Right now, it is showing only the page name not section name.

@rahulsrivastava1 this works differently with projects hosted on Read the Docs, try for instance the search function here: https://docs.readthedocs.io/

@benjaoming
I have hosted on Azure App service.

@rahulsrivastava1 you would have to use Read the Docs to have the Read the Docs search extensions available. It seems to support the feature you are asking for.
If you want a new feature for Sphinx, you should post it in the Sphinx repo: https://github.com/sphinx-doc/sphinx


text:
Typo in creating-a-cache.mdx

Typo import -> important

 Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.You have signed the CLA already but the status is still pending? Let us recheck it.

authors: CLAassistant quidryan

repo: readysettech/docs


text:
failed to build with "error MSB8066"

I am getting an error while building in windows
C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(254,5): e
rror MSB8066: Custom build for 'C:\Users\USER1\Desktop\Work\new\simple-binary-encoding\sbe-samples\src\main\cpp\cppbuil
d\Debug\CMakeFiles\6666cd76f96956469e7be39d750cc7d9\baseline.rule;C:\Users\USER1\Desktop\Work\new\simple-binary-encodin
g\sbe-samples\src\main\cpp\cppbuild\Debug\CMakeFiles\0d32063f0a28c99e1e03b1788321f1ed\examples_codecs.rule;C:\Users\USE
R1\Desktop\Work\new\simple-binary-encoding\sbe-samples\src\main\cpp\CMakeLists.txt' exited with code 1. [C:\Users\USER1
\Desktop\Work\new\simple-binary-encoding\sbe-samples\src\main\cpp\cppbuild\Debug\examples_codecs.vcxproj]
I took the following steps:-
1.git clone https://github.com/real-logic/simple-binary-encoding.git
2.cd simple-binary-encoding\sbe-samples\src\main\cpp
3.mkdir -p cppbuild/Debug
4. cd cppbuild/Debug
5.cmake ../..
6. cmake --build . --clean-first
7. ctest
But I got the above error after executing the step 6

Try the following:

git clone https://github.com/real-logic/simple-binary-encoding.git

cd simple-binary-encoding

Run cppbuild/cppbuild.cmd

This is what we run in CI.

authors: SafalKumar vyazelenko

repo: real-logic/simple-binary-encoding


text:
🛑 Whole Minded Health is down

In 420fd32, Whole Minded Health (https://wholemindedhealth.com) was down:

HTTP code: 0
Response time: 0 ms

Resolved: Whole Minded Health is back up in ff113ed after 10 minutes.

repo: realewie/uptime


text:
Weekly Review (2017/01/19)

A list of issues assigned to nobody.
ansible-role-cbsd

[ ] issue 2: support VIMAGE

ansible-role-editors

[x] issue 6: Can't find vim--no_x11 on OpenBSD 6.0

ansible-role-example

[ ] issue 37: Using proxy in Jenkins environment
[x] issue 36: Creating more Jenkins slaves
[x] issue 35: Make Jenkins stages parallel (dividing kitchen test stage and integration tests to multiple jobs so that multiple Jenkins slave can perform tasks in parallel)
[x] issue 34: Jenkins slave is not managed by ansible
[ ] issue 33: Update sysutils/ansible in Jenkins slave to 2.2.0 or newer
[ ] issue 32: Jenkins test is slow
[x] issue 31: Weekly Review (2016/12/26)

ansible-role-freebsd-repos

[ ] issue 9: the role does not support multiple package URLs

ansible-role-java

[x] issue 13: Java package version for OpenBSD is hard-coded
[x] issue 9: the role does not set wxallowed mount(8) option on OpenBSD
[x] issue 7: fix linuxism in specinfra

ansible-role-jenkins-master

[x] issue 4: the role does not support OpenBSD

ansible-role-logstash

[x] issue 7: fix linuxism in specinfra
[ ] issue 6: needs to update root certificates

ansible-role-nsd

[ ] issue 24: the role does not support external data
[x] issue 22: missing test case when chroot is enabled

ansible-role-postfix

[ ] issue 13: Update ansible that supports OpenBSD's "pkgname%branch" syntax
[x] issue 11: the role does not validate main.cf or master.cf
[ ] issue 7: periodic tasks for sendmail are not disabled in FreeBSD
[ ] issue 4: the role does not have an integration test

ansible-role-poudriere

[ ] issue 8: Create minimal ports tree for the test

close the weekly review in the last week.

repo: reallyenglish/ansible-role-example

license: isc


text:
Realm addNotificationBlock returning error

Goals
I am trying to instantiate a NotificationToken to listen to changes in a specific property of my Realm objects. The goal is to display every object matching the query in viewController.
Expected Results
The variable called 'location' in my Realm objects is changed by a helper method which is triggered by a Timer instance. When 'location' property is changed to value 2, I expect the Realm to notify the notificationToken object about the change allowing me to push the new result to viewController.
Actual Results
Immediately after launching the app, addNotificationBlock method returns the following error:
Error Domain=io.realm Code=1 "std::exception" UserInfo={NSLocalizedDescription=std::exception, Error Code=1}
Notifications are not listened after this. (Which is of course the way this enumeration is supposed to work.) I opened a thread on StackOverflow and based on given instructions managed to setup a breakpoint which pointed to method called void RealmCoordinator::pin_version(VersionID versionid)
Steps to Reproduce
It is difficult to say how to reproduce this error since I am (as far as I'm concerned) using the addNotificationBlock as instructed and not trying to accomplish anything complicated. I am happy to deliver the full Xcode workspace if necessary.
Code Sample
The contents of my viewController:
import UIKit
import RealmSwift

class PatientCell: UITableViewCell {

    @IBOutlet weak var hetu: UITextView!
    @IBOutlet weak var name: UITextView!
    @IBOutlet weak var photo: UITextView!

}

class PäivystyslistaVC: UIViewController, UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource, UIPopoverControllerDelegate {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet var patientPopupView: UIView!

    var patients: Results<Patient2>!
    var realm = try! Realm()
    var timer: Timer!
    var notificationToken: NotificationToken? = nil

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self
        let realm = try! Realm()
        patients = realm.objects(Patient2.self).filter("location = 2")

        print("Patients on the ER: \(patients)")

        notificationToken = patients.addNotificationBlock { (changes: RealmCollectionChange) in
            switch changes {
            case .initial:
                print("From initial")
                break
            case .update:
                print("From update")
                break
            case .error(let err):
                print("Error occured \(err)")
                break
            }
        }

        timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(self.addPatient), userInfo: nil, repeats: true)
    }

    func addPatient() {
        print("")
        print("Timer launched")
        print("Patients on the ER: \(patients.count)")
        sendPatientToER()
        print("")
        tableView.reloadData()
    }

    // MARK: TableView:n hallinta
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return patients.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "patient", for: indexPath) as! PatientCell

        let patient = patients[indexPath.row]
        cell.hetu?.text = patient.hetu
        cell.name?.text = patient.fullName
        cell.photo?.text = patient.photo

        return cell

    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let potilastiedotVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PotilastiedotVC")
        self.present(potilastiedotVC, animated: true, completion: nil)

        tableView.deselectRow(at: indexPath, animated: true)
    }

    func tableView(_ tableView: UITableView, editActionsForRowAt: IndexPath) -> [UITableViewRowAction]? {
        let kotiuta = UITableViewRowAction(style: .normal, title: "Kotiuta") { action, index in
            try! self.realm.write {
                self.realm.create(Patient2.self, value: ["id": index.row, "location": 1], update: true)
            }
            self.tableView.deleteRows(at: [index], with: .left)

        }
        kotiuta.backgroundColor = UIColor.vihreä

        let osastolle = UITableViewRowAction(style: .normal, title: "Osastolle") { action, index in
            try! self.realm.write {
                self.realm.create(Patient2.self, value: ["id": index.row, "location": 3], update: true)
            }
            self.tableView.deleteRows(at: [index], with: .top)
        }
        osastolle.backgroundColor = UIColor.oranssi

        let lähetä = UITableViewRowAction(style: .normal, title: "Lähetä") { action, index in
            try! self.realm.write {
                self.realm.create(Patient2.self, value: ["id": index.row, "location": 3], update: true)
            }
            self.tableView.deleteRows(at: [index], with: .top)
        }
        lähetä.backgroundColor = UIColor.vaaleansininen

        return [kotiuta, lähetä, osastolle]
    }

In addition I have a helper method in another file:
import UIKit
import RealmSwift

func sendPatientToER() {
    let realm = try! Realm()
    let count = realm.objects(Patient2.self).filter("location == 1").count
    print("Count of patients waiting at home: \(count)")
    let randomId = Int(arc4random_uniform(UInt32(count)))
    print("Random id generated: \(randomId)")
    realm.beginWrite()
    realm.create(Patient2.self, value: ["id": randomId, "location": 2], update: true)
    try! realm.commitWrite()
}

Thank you in advance.
Version of Realm and Tooling
Realm version: 2.4.2
Xcode version: 8.2.1
iOS/OSX version: 10.12.3
Dependency manager + version:  Cocoapods 1.1.1

Hi @EmilOsvald. Thanks for reaching out about this. My apologies for the delay in getting back to you. I'll have one of the engineers look at this and follow-up with a solution or additional questions.

Hi @tgoyne, thank you for your input and sorry for the delay.  I cleared the decks and everything works in my refactored project like a charm. I suppose the problem was that I had done some rookie mistake in my code (as I had suspected). Would you nevertheless like to see the original version?

Yes, that'd still be helpful. Even if you did only hit problems due to a mistake on your end, you still hit a case where Realm isn't behaving properly and it'd be good to be able to fix that.

Hey @EmilOsvald! Just checking in on this issue. Would you be able to provide us with a copy of the original version of your project for us to analyse? Thanks a lot!

Hi @TimOliver. I went through all my previous app versions on Git but unfortunately the version of interest seems to be lost. I am sorry.

@EmilOsvald Ahh okay. No problems then! It can't be helped. If you do manage to find the issue again, please let us know! Thanks!

I know this issues quite old and probably not interesting anymore, I was struggling however with the same problem for quite a while now and I'd like to share my findings.
In my case it happened after a bulk delete. Whenever a user does a logout I have to clear some of my tables
- (void)deleteSecureContent:(RLMRealm *)realm {
    NSError *error;
    NSArray *array = [realm.schema.objectSchema valueForKey:@"className"];
    [realm transactionWithBlock:^{
        for(NSString *className in array){
            Class<VLProtectedEntity> realmClass = NSClassFromString(className);
            if(realmClass && [[realmClass class] respondsToSelector:@selector(isProtectedEntity)]){
                BOOL protected = [[realmClass class] isProtectedEntity];
                if(protected){
                    [realm deleteObjects:[[realmClass class] allObjectsInRealm:realm]];
                }
            }
        }
    } error: &error];
    [realm refresh];
    if (error) {
        DDLogError(@"error %@ deleteSecureContent",error);
        [[Crashlytics sharedInstance] recordError:error];
    }
}

This is already the working version of the code. The important row in this case was the call to refresh the realm. Without that I had exactly the same error.
It's probably important to say that I'm working with two realms in this project one is persistent and one is in-memory and only the latter, so the in-memory instance did suffer from this problem.
I'm on Realm (3.18.0)

repo: realm/realm-cocoa


text:
Resolving "realm-cocoa"

I use the tool swift package that comes with xcode to integrate, but it gets stuck in Resolving "realm-cocoa". How can I solve this?

That step is where spm downloads the repository from github.

authors: sysbol tgoyne


text:
List and Results should support access by IndexSet

Goals
Swift's Array type offers an API to return all indexes in a given IndexSet:
let objects: [Any] = someArray.objects(at: someIndexSet)

Currently, Realm's collection types do not support this API. This is inconvenient because NSTableView extensively uses IndexSet. If I want to translate the selected rows in the table to an Array of objects on which I can act, I can't just pass the IndexSet returned by selectedRowIndexes to the Realm collection. Instead, I must manually loop through the indexes.
Additionally, because IndexSet is heavily optimized for its task, I assume the objects(at:) API is more performant than the naive for-loop approach.
Expected Results
Realm collection types should support accessing objects by IndexSet.
Actual Results
Realm collection types do not support IndexSet.
Steps for others to Reproduce
N/A
Code Sample
N/A
Version of Realm and Tooling
Realm framework version: 10.7.2
Xcode version: 13.0 Beta 1
iOS/OSX version: macOS 11.4
Dependency manager + version: SPM

There isn't really much room for us to do anything significantly faster; skipping some redundant checks might make it 5-10% faster but there isn't a lot of unnecessary overhead to begin with. A convenience helper would be easy to add, though.

The convenience method would make interfacing with NSTableView much nicer, for sure.

authors: bdkjones tgoyne


text:
Give RLMNotVersioned a consistent value in 32- and 64-bit

Fixes #1957.

Updated to address @tgoyne's feedback.
/cc @simonask

If the actual value in RLMNotVersioned is never actually persisted in the Realm file, this should be good. Otherwise, we should probably also check for the old 32-bit value. Theoretically, you could end up with an app that crashed before getting to the initial schema-creating transaction, but after persisting 0xffffffff as the schema version number, which then has Realm updated with this change, and then suddenly thinks that 2^32-1 is a valid version number.
I'm unsure if that scenario is actually realistic, or if it's something we want to even care about maintaining pre-1.0. :-)

An app which crashes before committing the initial transaction will not have persisted a schema version at all, because that's set during the initial transaction.

@tgoyne, it seems to me that the value of RLMNotVersioned is persisted the the Realm file. If it was not, then it would not have have caused a problem for us in connection with sync. As a temporary workaround, we compare changesets from the initial schema creating transactions, and can only proceed if they are strict equal. Before @simonask fix, they were not equal accoss a 32/64 bit barrier.
What did I miss?

The schema version is set to RLMNotVersioned, the tables are created, and then the schema version is set to the actual version all within a single write transaction. It shows up in the transaction log, but a write transaction is never committed while the version is RLMNotVersioned.

Ah, alright :-)

Other than my feedback, :+1:.

:+1:

authors: bdash jpsim kspangsege simonask tgoyne


text:
update ObjC model template comment to use ObjC generics

Since we no longer support Xcode 6, might as well encourage the use of ObjC generics.

:+1:

authors: colasbd jpsim