Skip to content

Commit

Permalink
Fix to only localize the primary localization and not the fall-throug… (
Browse files Browse the repository at this point in the history
#856)

* Fix to only localize the primary localization and not the fall-through localizations
  • Loading branch information
sosthoff authored and macdrevx committed Dec 2, 2021
1 parent 927ed06 commit a3737b0
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
18 changes: 17 additions & 1 deletion Sources/MapboxMaps/Style/Style+Localization.swift
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ extension Style {

if var stringExpression = String(data: try JSONEncoder().encode(symbolLayer.textField), encoding: .utf8),
stringExpression != "null" {
stringExpression.updateExpression(replacement: replacement, regex: expressionCoalesce)
stringExpression.updateOnceExpression(replacement: replacement, regex: expressionCoalesce)
stringExpression.updateExpression(replacement: replacement, regex: expressionAbbr)

// Turn the new json string back into an Expression
Expand Down Expand Up @@ -113,4 +113,20 @@ extension String {
range: range,
withTemplate: replacement)
}

/// Updates string once using the first occurrence of a regex
/// - Parameters:
/// - replacement: New string to replace the matched pattern
/// - regex: The regex pattern that will be matched for replacement
internal mutating func updateOnceExpression(replacement: String, regex: NSRegularExpression) {
var range = NSRange(location: 0, length: NSString(string: self).length)
range = regex.rangeOfFirstMatch(in: self, options: [], range: range)
if range.lowerBound == NSNotFound {
return
}
self = regex.stringByReplacingMatches(in: self,
options: [],
range: range,
withTemplate: replacement)
}
}
48 changes: 48 additions & 0 deletions Tests/MapboxMapsTests/Style/Style+LocalizationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,52 @@ final class StyleLocalizationTests: MapViewIntegrationTestCase {

XCTAssertThrowsError(try style.localizeLabels(into: Locale(identifier: "tlh")))
}

func testOnlyLocalizesFirstLocalization() throws {
var source = GeoJSONSource()
source.data = .feature(Feature(geometry: Point(CLLocationCoordinate2D(latitude: 0, longitude: 0))))
try style.addSource(source, id: "a")

var symbolLayer = SymbolLayer(id: "a")
symbolLayer.source = "a"
symbolLayer.textField = .expression(
Exp(.format) {
Exp(.coalesce) {
Exp(.get) {
"name_en"
}
Exp(.get) {
"name_fr"
}
Exp(.get) {
"name"
}
}
FormatOptions()
}
)

try style.addLayer(symbolLayer)

try style.localizeLabels(into: Locale(identifier: "de"))

let updatedLayer = try style.layer(withId: "a", type: SymbolLayer.self)

XCTAssertEqual(updatedLayer.textField, .expression(
Exp(.format) {
Exp(.coalesce) {
Exp(.get) {
"name_de"
}
Exp(.get) {
"name_fr"
}
Exp(.get) {
"name"
}
}
FormatOptions()
}
))
}
}

0 comments on commit a3737b0

Please sign in to comment.